Ir al contenido
Odoo Menú
  • Iniciar sesión
  • Pruébalo gratis
  • Aplicaciones
    Finanzas
    • Contabilidad
    • Facturación
    • Gastos
    • Hoja de cálculo (BI)
    • Documentos
    • Firma electrónica
    Ventas
    • CRM
    • Ventas
    • PdV para tiendas
    • PdV para restaurantes
    • Suscripciones
    • Alquiler
    Sitios web
    • Creador de sitios web
    • Comercio electrónico
    • Blog
    • Foro
    • Chat en vivo
    • eLearning
    Cadena de suministro
    • Inventario
    • Manufactura
    • PLM
    • Compras
    • Mantenimiento
    • Calidad
    Recursos humanos
    • Empleados
    • Reclutamiento
    • Vacaciones
    • Evaluaciones
    • Referencias
    • Flotilla
    Marketing
    • Redes sociales
    • Marketing por correo
    • Marketing por SMS
    • Eventos
    • Automatización de marketing
    • Encuestas
    Servicios
    • Proyectos
    • Registro de horas
    • Servicio externo
    • Soporte al cliente
    • Planeación
    • Citas
    Productividad
    • Conversaciones
    • Aprobaciones
    • IoT
    • VoIP
    • Artículos
    • WhatsApp
    Aplicaciones externas Studio de Odoo Plataforma de Odoo en la nube
  • Industrias
    Venta minorista
    • Librería
    • Tienda de ropa
    • Mueblería
    • Tienda de abarrotes
    • Ferretería
    • Juguetería
    Alimentos y hospitalidad
    • Bar y pub
    • Restaurante
    • Comida rápida
    • Casa de huéspedes
    • Distribuidora de bebidas
    • Hotel
    Bienes inmuebles
    • Agencia inmobiliaria
    • Estudio de arquitectura
    • Construcción
    • Gestión de bienes inmuebles
    • Jardinería
    • Asociación de propietarios
    Consultoría
    • Firma contable
    • Partner de Odoo
    • Agencia de marketing
    • Bufete de abogados
    • Adquisición de talentos
    • Auditorías y certificaciones
    Manufactura
    • Textil
    • Metal
    • Muebles
    • Comida
    • Cervecería
    • Regalos corporativos
    Salud y ejercicio
    • Club deportivo
    • Óptica
    • Gimnasio
    • Especialistas en bienestar
    • Farmacia
    • Peluquería
    Trades
    • Personal de mantenimiento
    • Hardware y soporte de TI
    • Sistemas de energía solar
    • Zapateros y fabricantes de calzado
    • Servicios de limpieza
    • Servicios de calefacción, ventilación y aire acondicionado
    Otros
    • Organización sin fines de lucro
    • Agencia para la protección del medio ambiente
    • Alquiler de anuncios publicitarios
    • Fotografía
    • Alquiler de bicicletas
    • Distribuidor de software
    Descubre todas las industrias
  • Odoo Community
    Aprende
    • Tutoriales
    • Documentación
    • Certificaciones
    • Capacitación
    • Blog
    • Podcast
    Fortalece la educación
    • Programa educativo
    • Scale Up! El juego empresarial
    • Visita Odoo
    Obtén el software
    • Descargar
    • Compara ediciones
    • Versiones
    Colabora
    • GitHub
    • Foro
    • Eventos
    • Traducciones
    • Conviértete en partner
    • Servicios para partners
    • Registra tu firma contable
    Obtén servicios
    • Encuentra un partner
    • Encuentra un contador
    • Contacta a un consultor
    • Servicios de implementación
    • Referencias de clientes
    • Soporte
    • Actualizaciones
    GitHub YouTube Twitter LinkedIn Instagram Facebook Spotify
    +1 (650) 691-3277
    Solicita una demostración
  • Precios
  • Ayuda

Odoo is the world's easiest all-in-one management software.
It includes hundreds of business apps:

  • CRM
  • e-Commerce
  • Contabilidad
  • Inventario
  • PoS
  • Proyectos
  • MRP
All apps
Debe estar registrado para interactuar con la comunidad.
Todas las publicaciones Personas Insignias
Etiquetas (Ver todo)
odoo accounting v14 pos v15
Acerca de este foro
Debe estar registrado para interactuar con la comunidad.
Todas las publicaciones Personas Insignias
Etiquetas (Ver todo)
odoo accounting v14 pos v15
Acerca de este foro
Ayuda

Custom Import method - how to ?

Suscribirse

Reciba una notificación cuando haya actividad en esta publicación

Se marcó esta pregunta
importcsvorder.linesodoo8.0
2 Respuestas
8730 Vistas
Avatar
Dr Obx

How to import csv file with multiple 'order_lines'?

Meantime I was doing some research and actually I found that I do not need to create import method but just add a condition which will check how many products is in the order.

Sales record numberUser id
name
email
item
price
1
Miriam234
Ted Butcher
tedbut@gmail.co

1



VW Polo
12345.00
1



Alloys 18"
4321.00
2
Fariam554
Frank Pitchka
pitchka@yahoo.jp
Pencil "Bravo"
1.20

So we have 2 orders with two different form. Order 1 is multiple and 2 is single.

Based on this how can I using API create a sale_order with multiple order_lines ?

Something like that ..

def order_sort(self):

records = self.env['iprodstep.log'].search([('state','=','draft')])

for record in records:

if record is False:

raise except_orm('Nothing to sort')

record.write({'image_url': ''.join(map(str,(record.item_id,'.jpg')))})

record.write({'item_id': record.item_id})

print ' '

print ' '

print ' '

print '== record ======================================================================'

print ' ',record.id

if record.sales_record_number:

a = 1

customer = self.env['res.partner'].search([('name','ilike',record.buyer_full_name)])

print ' '

print '.. Customer ....................................................................'

if not customer:

#if record.buyer_postcode:

postcode = "%s %s" %(record.buyer_postcode[:-3].strip(), record.buyer_postcode[-3:])

self.env['res.partner'].create({'name': record.buyer_full_name.title(), 'city': record.buyer_city.title(), 'zip': postcode.upper(),'email': record.buyer_email.lower(), 'phone': record.buyer_phone_number})

print record.buyer_full_name.title()

print record.buyer_email.lower()

print record.buyer_address_1.title()

print record.buyer_city.title()

print postcode.upper()

else:

#if record.buyer_postcode:

postcode = "%s %s" %(record.buyer_postcode[:-3].strip(), record.buyer_postcode[-3:])

print record.buyer_full_name.title()

print record.buyer_email.lower()

print record.buyer_address_1.title()

print record.buyer_city.title()

print postcode.upper()

items = self.env['iprodstep.log'].search([('sales_record_number','=',record.sales_record_number)])

print '.. order .......................................................................'

for item in items:

if item.item_id:

print ' ',a,'. ',item.item_id

a = a + 1

partner_id = self.env['res.partner'].search([['name', '=', record.buyer_full_name], ['zip','=', postcode]])

print '.. partner_id ..................................................................'

print ' ',partner_id.id

print '================================================================================'

0
Avatar
Descartar
Avatar
Pawan
Mejor respuesta

Rob,

please check the code below to import csv file to create Purchase Order, you can manipulate it to create Sale order s per your requirement:

try:

val=base64.decodestring(obj.file)

inp = cStringIO.StringIO(val)

reader = csv.DictReader(inp, quotechar='"', delimiter=',')

except Exception as e:

raise UserError(_('Invalid File!.\nPlease try using another file.'))

Now reader will contain the data from csv file in form of dictionary...... now use it as per your requirement

purchase_order = {}

po_pool = self.env['purchase.order']

po_line_pool = self.env['purchase.order.line']

ven_pool = self.env['res.partner']

part_pool = self.env['part.number']

product_pool = self.env['product.product']

try:

for row in reader:

vendor = row['Vendor Id'].strip()

po = row['PO Number'].strip()

if po not in purchase_order:

po_obj = po_pool.search([('name', '=ilike', po)])

if not po_obj:

po_data ={}

#create PO

vendor_obj = ven_pool.search([('supplier_code', '=ilike', vendor)], limit=1, order="id desc")

if not vendor:

raise UserError(_('''Vendor Id '%s' does not exist in the system''')%(vendor))

try:

cuttoff_date = datetime.datetime.strptime(row['PO Date'].strip(), "%d-%b-%y")

except ValueError:

raise ValidationError(_('''Date '%s' is not in correct format''')%(row['PO Date'].strip()))

po_data = {

'name': po,

'partner_id': vendor_obj.id,

'partner_ref': vendor_obj.supplier_code,

'cuttoff_date': cuttoff_date

}

po_obj = po_pool.create(po_data)

purchase_order[po] = [po_obj, [], []]

line_data = {}

part_number = row['Part Number']

part_obj = part_pool.search([('name', '=ilike', part_number)], limit=1, order="id desc")

if not part_obj:

raise ValidationError(_('''Part '%s' does not exist in the system''')%(part_number))

product_obj = product_pool.search(['|', ('part_number', '=', part_obj.id), ('alt_pt_no_ids', 'in', part_obj.id)], limit=1, order="id desc")

if not product_obj:

raise ValidationError(_('''No product is tagged to part '%s' ''')%(part_number))

line_data.update({

'part_no': part_obj.id,

'product': product_obj.id,

'price_unit': row['Unit Price'].strip(),

'product_qty': 1,

'product_uom': product_obj.uom_id.id,

})

purchase_order[po][1].append((0, 0, line_data))

purchase_order[po][2].append(part_obj)

for key, order in purchase_order.iteritems():

po = order[0]

lines = order[1]

po.write({

'order_line': lines,

'state': 'done',

})

for pno in order[2]:

lines = po_line_pool.search([('order_id', '=', po.id), ('part_no', '=', pno.id)])

history = []

for line in lines:

history.append((4, line.id))

pno.write({'po_history_ids': history})

except Exception as e:

raise UserError(_('%s'%str(e)))

return True

0
Avatar
Descartar
Dr Obx
Autor

I was thinking about it a lot and in conclusion I decided to change it completely. Because my module was working on own table which is good on one hand but on the other hand if I can use sale_order/order_lines instead ..... I think it should be better. Why ? Because I can/will have more than one source of orders (webstore, ebay, orders created by sale department) so module will load and operate on one/global list of orders. However import method will be required :)

Dr Obx
Autor

Thank you Pawan :)

¿Le interesa esta conversación? ¡Participe en ella!

Cree una cuenta para poder utilizar funciones exclusivas e interactuar con la comunidad.

Registrarse
Publicaciones relacionadas Respuestas Vistas Actividad
Disable automatic follow when importing res.partner csv
import csv
Avatar
Avatar
Avatar
3
jun 20
4869
Enable/disable import rights?
import csv
Avatar
Avatar
1
nov 18
10373
'utf8' codec can't decode byte error when importing a list of products as a CSV file Resuelto
import csv
Avatar
Avatar
Avatar
Avatar
Avatar
11
feb 17
64892
Import contacts through CSV Resuelto
import csv
Avatar
Avatar
2
mar 15
11973
Import csv file with related field other than id, external id, name
import csv importing data from excel file
Avatar
Avatar
Avatar
Avatar
4
nov 24
12740
Comunidad
  • Tutoriales
  • Documentación
  • Foro
Código abierto
  • Descargar
  • GitHub
  • Runbot
  • Traducciones
Servicios
  • Alojamiento en Odoo.sh
  • Soporte
  • Actualizaciones del software
  • Desarrollos personalizados
  • Educación
  • Encuentra un contador
  • Encuentra un partner
  • Conviértete en partner
Sobre nosotros
  • Nuestra empresa
  • Activos de marca
  • Contáctanos
  • Empleos
  • Eventos
  • Podcast
  • Blog
  • Clientes
  • Legal • Privacidad
  • Seguridad
الْعَرَبيّة Català 简体中文 繁體中文 (台灣) Čeština Dansk Nederlands English Suomi Français Deutsch हिंदी Bahasa Indonesia Italiano 日本語 한국어 (KR) Lietuvių kalba Język polski Português (BR) română русский язык Slovenský jazyk slovenščina Español (América Latina) Español ภาษาไทย Türkçe українська Tiếng Việt

Odoo es un conjunto de aplicaciones de código abierto que cubren todas las necesidades de tu empresa: CRM, comercio electrónico, contabilidad, inventario, punto de venta, gestión de proyectos, etc.

La propuesta única de valor de Odoo es ser muy fácil de usar y estar totalmente integrado.

Website made with

Odoo Experience on YouTube

1. Use the live chat to ask your questions.
2. The operator answers within a few minutes.

Live support on Youtube
Watch now