Skip to Content
Odoo Menú
  • Registra entrada
  • Prova-ho gratis
  • Aplicacions
    Finances
    • Comptabilitat
    • Facturació
    • Despeses
    • Full de càlcul (IA)
    • Documents
    • Signatura
    Vendes
    • CRM
    • Vendes
    • Punt de venda per a botigues
    • Punt de venda per a restaurants
    • Subscripcions
    • Lloguer
    Imatges de llocs web
    • Creació de llocs web
    • Comerç electrònic
    • Blog
    • Fòrum
    • Xat en directe
    • Aprenentatge en línia
    Cadena de subministrament
    • Inventari
    • Fabricació
    • PLM
    • Compres
    • Manteniment
    • Qualitat
    Recursos humans
    • Empleats
    • Reclutament
    • Absències
    • Avaluacions
    • Recomanacions
    • Flota
    Màrqueting
    • Màrqueting Social
    • Màrqueting per correu electrònic
    • Màrqueting per SMS
    • Esdeveniments
    • Automatització del màrqueting
    • Enquestes
    Serveis
    • Projectes
    • Fulls d'hores
    • Servei de camp
    • Suport
    • Planificació
    • Cites
    Productivitat
    • Converses
    • Validacions
    • IoT
    • VoIP
    • Coneixements
    • WhatsApp
    Aplicacions de tercers Odoo Studio Plataforma d'Odoo al núvol
  • Sectors
    Comerç al detall
    • Llibreria
    • Botiga de roba
    • Botiga de mobles
    • Botiga d'ultramarins
    • Ferreteria
    • Botiga de joguines
    Food & Hospitality
    • Bar i pub
    • Restaurant
    • Menjar ràpid
    • Guest House
    • Distribuïdor de begudes
    • Hotel
    Immobiliari
    • Agència immobiliària
    • Estudi d'arquitectura
    • Construcció
    • Gestió immobiliària
    • Jardineria
    • Associació de propietaris de béns immobles
    Consultoria
    • Empresa comptable
    • Partner d'Odoo
    • Agència de màrqueting
    • Bufet d'advocats
    • Captació de talent
    • Auditoria i certificació
    Fabricació
    • Textile
    • Metal
    • Mobles
    • Menjar
    • Brewery
    • Regals corporatius
    Salut i fitness
    • Club d'esport
    • Òptica
    • Centre de fitness
    • Especialistes en benestar
    • Farmàcia
    • Perruqueria
    Trades
    • Servei de manteniment
    • Hardware i suport informàtic
    • Sistemes d'energia solar
    • Shoe Maker
    • Serveis de neteja
    • Instal·lacions HVAC
    Altres
    • Nonprofit Organization
    • Agència del medi ambient
    • Lloguer de panells publicitaris
    • Fotografia
    • Lloguer de bicicletes
    • Distribuïdors de programari
    Browse all Industries
  • Comunitat
    Aprèn
    • Tutorials
    • Documentació
    • Certificacions
    • Formació
    • Blog
    • Pòdcast
    Potenciar l'educació
    • Programa educatiu
    • Scale-Up! El joc empresarial
    • Visita Odoo
    Obtindre el programari
    • Descarregar
    • Comparar edicions
    • Novetats de les versions
    Col·laborar
    • GitHub
    • Fòrum
    • Esdeveniments
    • Traduccions
    • Converteix-te en partner
    • Services for Partners
    • Registra la teva empresa comptable
    Obtindre els serveis
    • Troba un partner
    • Troba un comptable
    • Contacta amb un expert
    • Serveis d'implementació
    • Referències del client
    • Suport
    • Actualitzacions
    Github Youtube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Programar una demo
  • Preus
  • Ajuda

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

  • CRM
  • e-Commerce
  • Comptabilitat
  • Inventari
  • PoS
  • Projectes
  • MRP
All apps
You need to be registered to interact with the community.
All Posts People Badges
Etiquetes (View all)
odoo accounting v14 pos v15
About this forum
You need to be registered to interact with the community.
All Posts People Badges
Etiquetes (View all)
odoo accounting v14 pos v15
About this forum
Ajuda

Custom Import method - how to ?

Subscriure's

Get notified when there's activity on this post

This question has been flagged
importcsvorder.linesodoo8.0
2 Respostes
8721 Vistes
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
Best Answer

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 :)

Enjoying the discussion? Don't just read, join in!

Create an account today to enjoy exclusive features and engage with our awesome community!

Registrar-se
Related Posts Respostes Vistes Activitat
Disable automatic follow when importing res.partner csv
import csv
Avatar
Avatar
Avatar
3
de juny 20
4866
Enable/disable import rights?
import csv
Avatar
Avatar
1
de nov. 18
10372
'utf8' codec can't decode byte error when importing a list of products as a CSV file Solved
import csv
Avatar
Avatar
Avatar
Avatar
Avatar
11
de febr. 17
64889
Import contacts through CSV Solved
import csv
Avatar
Avatar
2
de març 15
11969
Import csv file with related field other than id, external id, name
import csv importing data from excel file
Avatar
Avatar
Avatar
Avatar
4
de nov. 24
12732
Community
  • Tutorials
  • Documentació
  • Fòrum
Codi obert
  • Descarregar
  • GitHub
  • Runbot
  • Traduccions
Serveis
  • Allotjament a Odoo.sh
  • Suport
  • Actualització
  • Desenvolupaments personalitzats
  • Educació
  • Troba un comptable
  • Troba un partner
  • Converteix-te en partner
Sobre nosaltres
  • La nostra empresa
  • Actius de marca
  • Contacta amb nosaltres
  • Llocs de treball
  • Esdeveniments
  • Pòdcast
  • Blog
  • Clients
  • Informació legal • Privacitat
  • Seguretat
الْعَرَبيّة 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 és un conjunt d'aplicacions empresarials de codi obert que cobreix totes les necessitats de la teva empresa: CRM, comerç electrònic, comptabilitat, inventari, punt de venda, gestió de projectes, etc.

La proposta única de valor d'Odoo és ser molt fàcil d'utilitzar i estar totalment integrat, ambdues alhora.

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