← Back to team overview

avanzosc team mailing list archive

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

 

Review: Needs Fixing code review

Una pequeña cosa sobre un código espaguetti que hay y ya está.

Diff comments:

> === modified file 'dos_production_lots_import/__init__.py'
> --- dos_production_lots_import/__init__.py	2014-06-11 10:23:47 +0000
> +++ dos_production_lots_import/__init__.py	2014-06-24 15:12:15 +0000
> @@ -19,6 +19,6 @@
>  #
>  ##############################################################################
>  
> -import wizard
> +from . import wizard
>  
>  # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
> 
> === modified file 'dos_production_lots_import/__openerp__.py'
> --- dos_production_lots_import/__openerp__.py	2014-06-11 10:23:47 +0000
> +++ dos_production_lots_import/__openerp__.py	2014-06-24 15:12:15 +0000
> @@ -21,19 +21,14 @@
>  
>  
>  {
> -    "name" : "DOS Production Lots Import",
> -    "version" : "1.0",
> -    "author" : "DOS",
> -    "category" : "Production,Sale,Stock",
> -    "website" : "www.dos-sl.es",
> -    "description": "This module allows you import lots of production from a csv file.",
> -    "depends" : ["sale", "stock", "product"],
> -    "init_xml" : [],
> -    "update_xml" : [
> -		'wizard/production_lots_import_view.xml',
> -	],
> -    "active": False,
> +    "name": "DOS Production Lots Import",
> +    "version": "1.0",
> +    "author": "DOS",
> +    "category": "Production,Sale,Stock",
> +    "website": "www.dos-sl.es",
> +    "description": ("This module allows you import "
> +                    "lots of production from a csv file."),
> +    "depends": ["sale", "stock", "product"],
> +    "data": ['wizard/production_lots_import_view.xml'],
>      "installable": True
>  }
> -
> -
> 
> === modified file 'dos_production_lots_import/wizard/__init__.py'
> --- dos_production_lots_import/wizard/__init__.py	2014-06-11 10:23:47 +0000
> +++ dos_production_lots_import/wizard/__init__.py	2014-06-24 15:12:15 +0000
> @@ -19,8 +19,6 @@
>  #
>  ##############################################################################
>  
> -import production_lots_import
> +from . import production_lots_import
>  
>  # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
> -
> -
> 
> === modified file 'dos_production_lots_import/wizard/production_lots_import.py'
> --- dos_production_lots_import/wizard/production_lots_import.py	2014-06-11 10:23:47 +0000
> +++ dos_production_lots_import/wizard/production_lots_import.py	2014-06-24 15:12:15 +0000
> @@ -19,17 +19,16 @@
>  #
>  ##############################################################################
>  
> -import tools
>  import base64
>  import logging
> -import pooler
>  import csv
>  import time
> -from tools.translate import _
> +from openerp.tools.translate import _
>  from tempfile import TemporaryFile
> -from osv import osv, fields
> -
> -class production_lots_import(osv.osv_memory):
> +from openerp.orm import orm, fields
> +
> +
> +class ProductionLotsImport(orm.TransientModel):
>      """ Production Lots Import """
>  
>      _name = "production.lots.import"
> @@ -37,80 +36,68 @@
>      _inherit = "ir.wizard.screen"
>  
>      _columns = {
> -        'product_type': fields.selection([('sim', 'Tarjeta SIM'), ('enlace', 'Enlace')], 'Product type'),
> +        'product_type': fields.selection([('sim', 'Tarjeta SIM'),
> +                                          ('enlace', 'Enlace')],
> +                                         'Product type'),
>          'data': fields.binary('File', required=True),
> -    }
> -    
> -    
> +        }
> +
>      def is_date(self, date):
>          try:
> -          if date != '':
> -              valid_date = time.strptime(date, '%Y-%m-%d')
> -          return True
> -      
> +            if date != '':
> +                valid_date = time.strptime(date, '%Y-%m-%d')
> +            return True
>          except ValueError:
> -          return False
> -        
> +            return False
> +
>      def verify_line(self, dic):
> -
>          if not ('icc' in dic and 'telefono' in dic):
>              return False
> -            
>          if 'fecha_alta' in dic and not self.is_date(dic['fecha_alta']):
>              return False
> -
> -        if 'fecha_activacion' in dic and not self.is_date(dic['fecha_activacion']):
> +        if ('fecha_activacion' in dic
> +                and not self.is_date(dic['fecha_activacion'])):
>              return False
> -           
>          return True
> -    
> -    
> -    def get_production_lot_id(self, cr, uid, dic, location_id, location_dest_id):
> -        
> -        db_name = cr.dbname
> -        pool = pooler.get_pool(db_name)
> -        production_lot_obj = pool.get('stock.production.lot')
> -        stock_move_obj = pool.get('stock.move')
> +
> +    def get_production_lot_id(self, cr, uid, dic, location_id,
> +                              location_dest_id):
> +        production_lot_obj = self.pool['stock.production.lot']
> +        stock_move_obj = self.pool['stock.move']
>          name = None
>          result = None
> -        
>          if 'icc' in dic and dic['icc']:
>              name = dic['icc']
> -
>          if name:
> -            product_lot_ids = production_lot_obj.search(cr, uid, [('name', '=', name), ('stock_available', '>', 0)])
> -            
> +            lot_info = [('name', '=', name), ('stock_available', '>', 0)]
> +            product_lot_ids = production_lot_obj.search(cr, uid, lot_info,
> +                                                        context=context)
>              if product_lot_ids:
>                  product_lot_id = product_lot_ids[0]
> -                
> -                #Comprobamos que el lote seleccionado no se haya traspasado de ubicación
> -                stock_move_ids = stock_move_obj.search(cr, uid, [('prodlot_id', '=', product_lot_id), ('location_id', '=', location_id), ('location_dest_id', '=', location_dest_id)])
> -                
> +                # Comprobamos que el lote seleccionado
> +                # no se haya traspasado de ubicación
> +                move_info = [('prodlot_id', '=', product_lot_id),
> +                             ('location_id', '=', location_id),
> +                             ('location_dest_id', '=', location_dest_id)]
> +                stock_move_ids = stock_move_obj.search(cr, uid, move_info,
> +                                                       context=context)
>                  if not stock_move_ids:
>                      result = product_lot_id
> -                    
>          return result
> -        
> -        
> -    def load_data(self, cr, fileobj, fileformat, header_line_columns, context):
> -        
> +
> +    def load_data(self, cr, fileobj, fileformat, header_line_columns,
> +                  context):
>          """Read file and save"""
>          logger = logging.getLogger('production_lot_import')
> -
>          if context is None:
>              context = {}
> -            
> -        db_name = cr.dbname
> -        pool = pooler.get_pool(db_name)
> -        stock_warehouse_obj = pool.get('stock.warehouse')
> -        stock_picking_obj = pool.get('stock.picking')
> -        stock_move_obj = pool.get('stock.move')
> -        stock_prod_lot_obj = pool.get('stock.production.lot')
> -        product_obj = pool.get('product.product')
> -        
> +        stock_warehouse_obj = self.pool['stock.warehouse']
> +        stock_picking_obj = self.pool['stock.picking']
> +        stock_move_obj = self.pool['stock.move']
> +        stock_prod_lot_obj = self.pool['stock.production.lot']
> +        product_obj = self.pool['product.product']
>          try:
>              uid = 1
> -
>              # Empezamos a leer fichero
>              fileobj.seek(0)
>              if fileformat == 'csv':
> @@ -120,122 +107,122 @@
>              else:
>                  logger.error('Bad file format: %s', fileformat)
>                  raise Exception(_('Bad file format'))
> -    
> -    
> -            #Comprobamos que hay al menos un almacen definido
> +            # 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):
> +            for warehouse in stock_warehouse_obj.browse(cr, uid,
> +                                                        stock_warehouse_ids,
> +                                                        context):
>                  stock_warehouse = warehouse

Mismo código espaguetti que en varios sitios. Pregunta a Oihane cómo lo ha resuelto para poner en todos lo mismo.

>                  break
> -            
>              if not stock_warehouse:
> -                raise osv.except_osv(_('Stock Warehouse not defined !'), _('Stock Warehouse not defined.'))        
> -            
> -
> -            #Albaran interno por si hay traspasos de ubicacion
> +                raise orm.except_orm(_('Stock Warehouse not defined !'),
> +                                     _('Stock Warehouse not defined.'))
> +            # Albaran interno por si hay traspasos de ubicacion
>              stock_picking_id = None
> -            
>              # Leemos resto del fichero
>              line = 1
>              succesfull = True
> -            
>              for row in reader:
>                  line += 1
> -                # Leemos para cada línea todos sus valores y los almacenamos en un diccionario
> +                # Leemos para cada línea todos sus valores y
> +                # los almacenamos en un diccionario
>                  dic = {}
>                  for i in range(len(f)):
>                      # Descartamos columnas
> -                    #if f[i] in ('albaran_entrada',):
> +                    # if f[i] in ('albaran_entrada',):
>                      #    continue
> -                    
> -  
>                      # Formateamos fecha
>                      if f[i] in ('fecha_alta',):
>                          date = time.strptime(row[i], "%d/%m/%Y")
>                          dic[f[i]] = time.strftime("%Y-%m-%d", date)
> -                        
> -                        #Activamos el lote:
> +                        # Activamos el lote:
>                          #    SIM - Si la linea trae ICC y numero de telefono
>                          if 'icc' in dic and 'telefono' in dic:
> -                            dic['fecha_activacion'] = time.strftime("%Y-%m-%d", date)
> -                        
> +                            dic['fecha_activacion'] = time.strftime("%Y-%m-%d",
> +                                                                    date)
>                          continue
> -                    
>                      # Añadimos resto valores al diccionario
>                      if row[i] not in ('NULL', ''):
>                          dic[f[i]] = row[i]
> -    
>                  try:
> -                    #ACTIVACION DE SIM
> -                    #Actualizamos lotes de produccion sin movimientos de entrada
> -                    #y traspasamos lotes a la ubicación de stock definida en almacen
> -                    stock_prod_lot_id = self.get_production_lot_id(cr, uid, dic, stock_warehouse.lot_input_id.id, stock_warehouse.lot_stock_id.id)
> -                    
> -                    if stock_prod_lot_id and self.verify_line(dic):
> -                        
> +                    # ACTIVACION DE SIM
> +                    # Actualizamos lotes de produccion
> +                    # sin movimientos de entrada y traspasamos
> +                    # lotes a la ubicación de stock definida en almacen
> +                    input_id = stock_warehouse.lot_input_id.id
> +                    stock_id = stock_warehouse.lot_stock_id.id
> +                    prod_lot_id = self.get_production_lot_id(cr, uid, dic,
> +                                                             input_id,
> +                                                             stock_id)
> +                    if prod_lot_id and self.verify_line(dic):
>                          if not stock_picking_id:
> -                            #Creamos albaran interno para la actualizacion
> -                            vals = {
> -                                    'origin': 'IMP/' + time.strftime('%Y%m%d'),
> +                            # Creamos albaran interno para la actualizacion
> +                            vals = {'origin': 'IMP/' + time.strftime('%Y%m%d'),
>                                      'date': time.strftime('%Y-%m-%d %H:%M:%S'),
>                                      'move_type': 'direct',
>                                      'invoice_state': 'none',
>                                      'state': 'draft',
>                                      'auto_picking': False,
>                                      'type': 'internal',
> +                                    }
> +                            stock_picking_id = stock_picking_obj.create(cr,
> +                                                                        uid,
> +                                                                        vals)
> +                        # Actualizamos datos de lote de produccion
> +                        result = stock_prod_lot_obj.write(cr, uid,
> +                                                          [prod_lot_id],
> +                                                          dic)
> +                        # Traspaso de ubicación
> +                        stock_prod_lot = stock_prod_lot_obj.browse(cr, uid,
> +                                                                   prod_lot_id,
> +                                                                   context)
> +                        date_expected = time.strftime('%Y-%m-%d %H:%M:%S')
> +                        location_dest_id = stock_warehouse.lot_stock_id.id
> +                        vals = {
> +                            'picking_id': stock_picking_id,
> +                            'product_id': stock_prod_lot.product_id.id,
> +                            'name': ('[' +
> +                                     stock_prod_lot.product_id.default_code
> +                                     + '] '
> +                                     + stock_prod_lot.product_id.name),
> +                            'prodlot_id': prod_lot_id,
> +                            'product_qty': 1,
> +                            'product_uos_qty': 1,
> +                            'product_uom': 1,
> +                            'location_id': stock_warehouse.lot_input_id.id,
> +                            'location_dest_id': location_dest_id,
> +                            'date_expected': date_expected,
> +                            'date': time.strftime('%Y-%m-%d %H:%M:%S'),
> +                            'auto_validate': False,
> +                            'priority': '1',
> +                            'state': 'done',
>                              }
> -                
> -                            stock_picking_id = stock_picking_obj.create(cr, uid, vals)
> -                            
> -                        #Actualizamos datos de lote de produccion
> -                        result = stock_prod_lot_obj.write(cr, uid, [stock_prod_lot_id], dic)
> -
> -                        #Traspaso de ubicación
> -                        stock_prod_lot = stock_prod_lot_obj.browse(cr, uid, stock_prod_lot_id, context)
> -                        
> -                        vals = {
> -                                'picking_id': stock_picking_id,
> -                                'product_id': stock_prod_lot.product_id.id,
> -                                'name': '[' + stock_prod_lot.product_id.default_code + '] ' + stock_prod_lot.product_id.name,
> -                                'prodlot_id': stock_prod_lot_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_id = stock_move_obj.create(cr, uid, vals)
> -
>                      else:
>                          succesfull = False
> -                        filename = '[production_lot_import][format: %s]' % (fileformat)
> -                        logger.exception("Couldn't update production lot line %s of file %s", str(line), filename)                       
> +                        filename = ('[production_lot_import][format: %s]'
> +                                    % (fileformat))
> +                        logger.exception("Couldn't update production lot line"
> +                                         " %s of file %s", str(line), filename)
>                  except:
>                      succesfull = False
> -                    filename = '[production_lot_import][format: %s]' % (fileformat)
> -                    logger.exception("Couldn't update production lot line %s of file %s", str(line), filename)
> -    
> -            #Validamos albaran interno si se han traspasado lotes
> +                    filename = ('[production_lot_import][format: %s]' %
> +                                (fileformat))
> +                    logger.exception("Couldn't update production lot line"
> +                                     " %s of file %s", str(line), filename)
> +            # Validamos albaran interno si se han traspasado lotes
>              if stock_picking_id:
> -                stock_picking_obj.write(cr, uid, [stock_picking_id], {'state': 'done'})
> -            
> -
> +                stock_picking_obj.write(cr, uid, [stock_picking_id],
> +                                        {'state': 'done'})
>              if succesfull:
>                  logger.info("import file loaded succesfully")
>              else:
>                  logger.info("import file loaded with errors")
>          except IOError:
>              filename = '[production_lot_import][format: %s]' % (fileformat)
> -            logger.exception("Couldn't update production lot file %s", filename)
> -
> +            logger.exception("Couldn't update production lot file %s",
> +                             filename)
>  
>      def import_file(self, cr, uid, ids, context):
>          """
> @@ -245,30 +232,24 @@
>              @param ids: the ID or list of IDs
>              @param context: A standard dictionary
>          """
> -
>          import_data = self.browse(cr, uid, ids)[0]
>          fileobj = TemporaryFile('w+')
>          fileobj.write(base64.decodestring(import_data.data))
> -
>          # now we determine the file format
>          fileobj.seek(0)
> -        first_line = fileobj.readline().strip().replace('"', '').replace(' ', '')
> +        line = fileobj.readline()
> +        first_line = line.strip().replace('"', '').replace(' ', '')
>          columns = first_line.split(';')
>          num_columns = len(columns)
> -        
>          if num_columns == 8:
> -            #Fichero SIM
> -            header_line_columns = "icc;telefono;pin;puk;fecha_alta;operador;descripcion;albaran_entrada"
> +            # Fichero SIM
> +            header_line_columns = ("icc;telefono;pin;puk;fecha_alta;operador;"
> +                                   "descripcion;albaran_entrada")
>              fileformat = 'csv'
>          else:
>              header_line_columns = ""
>              file_format = 'no_csv'
> -        
>          fileobj.seek(0)
> -
>          self.load_data(cr, fileobj, fileformat, header_line_columns, context)
> -
>          fileobj.close()
>          return {}
> -
> -production_lots_import()
> 
> === modified file 'dos_production_lots_import/wizard/production_lots_import_view.xml'
> --- dos_production_lots_import/wizard/production_lots_import_view.xml	2014-06-11 10:23:47 +0000
> +++ dos_production_lots_import/wizard/production_lots_import_view.xml	2014-06-24 15:12:15 +0000
> @@ -5,7 +5,6 @@
>          <record id="view_production_lots_import" model="ir.ui.view">
>              <field name="name">Activation of SIM Importer</field>
>              <field name="model">production.lots.import</field>
> -            <field name="type">form</field>
>              <field name="arch" type="xml">
>                  <form string="Activation of SIM Importer">
>                      <group col="8">
> 


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


References