How to copy purchase order value to account.invoice in odoo11 - python

I have created a custom field in the purchase order and another in account.invoice with the same name budget_id, when I create a purchase order and create a bill from this order I would like to copy the value of budget_id in the purchase order to the budget_id in the bill.
I have overridden the smart button method "action_view_invoice" in purchase.order and added my code but nothing happen. Are there other ways to do that?
Thanks in advance!
my code
#api.multi
def action_view_invoice(self):
action = self.env.ref('account.action_invoice_tree2')
result = action.read()[0]
result['context'] = {'type': 'in_invoice', 'default_purchase_id': self.id}
if not self.invoice_ids:
# Choose a default account journal in the same currency in case a new invoice is created
journal_domain = [
('type', '=', 'purchase'),
('company_id', '=', self.company_id.id),
('currency_id', '=', self.currency_id.id),
]
default_journal_id = self.env['account.journal'].search(journal_domain, limit=1)
if default_journal_id:
result['context']['default_journal_id'] = default_journal_id.id
else:
# Use the same account journal than a previous invoice
result['context']['default_journal_id'] = self.invoice_ids[0].journal_id.id
# choose the view_mode accordingly
if len(self.invoice_ids) != 1:
result['domain'] = "[('id', 'in', " + str(self.invoice_ids.ids) + ")]"
elif len(self.invoice_ids) == 1:
res = self.env.ref('account.invoice_supplier_form', False)
result['views'] = [(res and res.id or False, 'form')]
result['res_id'] = self.invoice_ids.id
result['context']['default_origin'] = self.name
result['context']['default_reference'] = self.partner_ref
result['context']['default_budget_id'] = self.budget_id.id # my code here
return result

The account.invoice object has the field purchase_id which is a link with purchase.order.
So in the account.invoice you can get any of the way(like in the vendor bill creation best approch) the purchase order budget_id field value into account.invoice budget_id field.
Code link - Purchase link In Invoice

Related

Adding a constraint for a field in Odoo

This is what I have to do:
"Add a field for registering children to the employee object. It is possible to enter several children and enter the first and last name and date of birth for each of them. Show the field on the form view, in the Private information tab, below the field for the number of children (children). Show the field only if the number of children is greater than 0."
I have done this:
#api.onchange('children', 'name_child', 'date_of_birth')
def onchange_usage(self):
if self.children > 0:
self.name_child = True
self.date_of_birth = True
else:
self.name_child = False
self.date_of_birth = False
children = fields.Integer(string='Children')
name_child = fields.Char(string='Name of the Child')
date_of_birth = fields.Date(string='Date of Birth')
Does anybody know what is wrong with this code? Thank u.
You can simply add invisible for the fields name_child and date_of_birth
attrs="{'invisible':[('children', '=', 0)]}"

Django filters - I want to sort the previous query and not the entire model

When I filter the table by city, for example, it works;
but if I want to sort by date or price using the multiple choices menu, django-filter sorts the entire model by the selected value and not only the cities.
How can I fix this problem?
import django_filters
from django_filters import DateFilter
from .models import ModelName
class SortFilter(django_filters.FilterSet):
SORT_BY_DATE_AND_PRICE = (
('date_asc', 'Date ascending'),
('date_desc', 'Date descending'),
('price_asc', 'Price ascending'),
('price_desc', 'Price descending')
)
sort = django_filters.ChoiceFilter(label='Order by:', choices=SORT_BY_DATE_AND_PRICE, method='filter_by_date_and_price')
class Meta:
model = ModelName
fields = ['city', 'destination']
def filter_by_date_and_price(self, queryset, name, value):
if value == 'date_asc':
sort = 'date'
elif value == 'date_desc':
sort = '-date'
elif value == 'price_asc':
sort = 'price'
elif value == 'pret_desc':
sort = '-price'
return queryset.order_by(sort)
Entry.objects.filter(value="Value").filter(another_value="Another value")
I think you're looking for something like this. I was going to leave it as a comment but I'm writing to answer because my rep score is not enough.
https://www.youtube.com/watch?v=G-Rct7Na0UQ

add many2many and one2many record through python code -Odoo 12 / Python 3.7

i am stuck since a couple of days in some many2many and one2many field i am trying to add value to through code. The idea is to consume a web service to get some data from a third party website and re-use these same data in my odoo 12 modules. I was able to parse the JSON request and create entities using model.Models. However, for fields using one2many or many2many i was unable to add their values and link them to my models. Here is my python code. What i want to achieve is after the creation of a record "book.db" i want to also create its category in the same time and link it to the current record. However everytime i run the code only the "book.db" model is created. The category model is never made nor linked. Can someone point me to the right direction or correct my code if possible. Thanks alot.
from odoo import models, fields, api
from . import prestashopproduct
import requests
import json
class Book(models.Model):
_name = "book.db"
prestashop_id = fields.Integer('Prestashop ID')
title = fields.Char(string="book title")
ean13_code = fields.Char(string="EAN13")
author = fields.Char(string="book author")
released = fields.Date(string="Date de publication")
type = fields.Selection([('Numérique', 'Numérique'), ('Papier', 'Papier')], string="type")
catalog = fields.Char(string="catalogue")
collection = fields.Char(string="collection")
isbn = fields.Char(string="Numero ISBN")
description = fields.Html("Description")
distributeur = fields.Char(string="Distribiteur")
code_distribiture = fields.Char(string="Code distribiteur")
code_collection = fields.Char(string="Code collection")
code_dispo = fields.Char(string="Code dispo")
code_tva1 = fields.Integer("Code tva1")
code_tva2 = fields.Integer("Code tva2")
presentation = fields.Html("Presentation")
type_produit = fields.Char(string="Type de produit")
theme_edilectre = fields.Char(string="Type de produit")
categorie = fields.Html("categorie")
poid = fields.Float("Poid en Gramme")
prix = fields.Float("Prix")
largeur = fields.Float("Largeur en MM")
epaisseur = fields.Float("Epaisseur en MM")
hauteur = fields.Float("Hauteur en MM")
image = fields.One2many('product.images', 'product_id', string='Imags du produit')
cate = fields.Many2many('product.cetegorie', 'product_id', string='Imags du produit')
image_product = fields.Char("Image")
#api.one
def get_books(self):
jso = prestashopproduct.Product.get_full_stock(self=prestashopproduct.Product())
for j in jso['products']:
if self.check_unicity(j['id']):
book = [{'title': j['name'][1]['value'],
'ean13_code': j['ean13'],
'isbn': j['isbn'],
'epaisseur': j['width'],
'largeur': j['depth'],
'hauteur': j['height'],
'poid': j['weight'],
'prestashop_id': j['id'],
'description': j['description'][1]['value'],
'presentation': j['description_short'][1]['value'],
'categorie': j['description_short'][1]['value']}]
record = self.create(book)
print (self.id)
record.cate.create({'cate': [{'product_id': record.id, 'name': 'absc'}]})
def check_unicity(self, id):
if self.search_count([('prestashop_id', '=', id)]) > 0:
return False
else:
return True
class Image(models.Model):
_name = 'product.images'
product_id = fields.Many2many('book.db', string='Prestashop ID')
product_image = fields.Binary('Image du produit')
product_image_url = fields.Char("product_image")
def donload_product_image(self, product_id, image_id):
image = prestashopproduct.Product.get_product_image(prestashopproduct.Product(), id_product=product_id,
id_image=image_id)
return image
class Categories(models.Model):
_name = 'product.cetegorie'
product_id = fields.Many2many('book.db', string="Categories")
nb_products_recursive = fields.Integer("nb_products_recursive")
name = fields.Char("Descriptif")
#api.one
def new_record(self, product_id):
self.create([{'product_id': product_id, 'name': 'a'}])
#api.model
def _repare_cate_list(self, cates=[]):
post_cates = []
existing_add = []
for cate_name in cates:
cate_ids = self.env['product.cetegorie'].search([('name', '=', cate_name)])
if cate_ids:
existing_add.append(int(cate_ids[0]))
else:
post_cates.append((0, 0, {'name': cate_name}))
post_cates.insert(0, [6, 0, existing_add])
return post_cates
#api.one
def get_books(self):
jso = prestashopproduct.Product.get_full_stock(self=prestashopproduct.Product())
for j in jso['products']:
if self.check_unicity(j['id']):
cate_vals = self._repare_cate_list(['absc'])
book = [{'title': j['name'][1]['value'],
'ean13_code': j['ean13'],
'isbn': j['isbn'],
'epaisseur': j['width'],
'largeur': j['depth'],
'hauteur': j['height'],
'poid': j['weight'],
'prestashop_id': j['id'],
'description': j['description'][1]['value'],
'presentation': j['description_short'][1]['value'],
'categorie': j['description_short'][1]['value'],
'cate':cate_vals
}]
record = self.create(book)
Also remove line product_id = fields.Many2many('book.db', string="Categories") from the 'product.cetegorie' model its not needed. As Many to many is using separate table to link categories to save them.
Whenever you want to edit, update or delete One2many or Many2many field(s) please refer below lines.
(0, 0, {values}) link to a new record that needs to be created with
the given values ​​dictionary
(1, ID, {values}) update the linked record with id = ID (write values
​​on it)
(2, ID) remove and delete the linked record with id = ID (calls unlink
on ID, that will delete the object completely, and the link to it as
well)
(3, ID) cut the link to the linked record with id = ID (delete the
relationship between the two objects but does not delete the target
object itself)
(4, ID) link to existing record with id = ID (adds a relationship)
(5) unlink all (like using (3, ID) for all linked records)
(6, 0, [IDs]) replace the list of linked IDs (like using (5) then (4,
ID) for each ID in the list of IDs)

how to get value from odoo purchase lines order to stock.picking lines?

i'am added analytic account field on stock move model, I need as the stock move lines get quantity form PO lines to get analytic account field form lines when I confirm the order,
how can I do that
class StockMove(models.Model):
_inherit = "stock.move"
analytic_account_id = fields.Many2one(string='Analytic Account',comodel_name='account.analytic.account',)
any help will be appreciated
Override _prepare_stock_moves method which prepares the stock moves data for one order line and returns a list of dictionary ready to be used in stock.move's create().
class PurchaseOrderLine(models.Model):
_inherit = 'purchase.order.line'
#api.multi
def _prepare_stock_moves(self, picking):
res = super(PurchaseOrderLine, self)._prepare_stock_moves(picking)
res[0]['analytic_account_id'] = self.account_analytic_id.id
return res
To get field values from purchase order use the inverse_name order_id.
res[0]['analytic_account_id'] = self.order_id.account_analytic_id.id
Edit:
To use the same logic on production orders, you can set the account when you mark the order as done:
class ManufacturingOrder(models.Model):
_inherit = 'mrp.production'
analytic_account_id = fields.Many2one(string='Analytic Account', comodel_name='account.analytic.account')
#api.multi
def button_mark_done(self):
for order in self:
for move in order.move_finished_ids:
move.analytic_account_id = order.analytic_account_id
res = super(ManufacturingOrder, self).button_mark_done()
return res

Odoo10 : How can I automatically get the value for partner when customer number is given?

I am creating a module something like call log. In that i need to search the customer number and get the Partner information or have to link the partner automatically.
the following are the codes, somebody please help me.
class model_call(models.Model):
_inherit = 'res.partner'
_name = 'model.call'
_description = 'call logs'
""" *************** Base Fields ******************* """
name = fields.Char(string='Topic')
customer_number = fields.Char(string='Customer Number', track_visiility='onchange', onchange='get_partner(customer_number)')
#-------------------------------------------------
# apis
#-------------------------------------------------
#api.onchange('customer_number')
def get_partner(self, customer_number):
if customer_number:
customer = self.env['res.partner'].search([('customer_number', '=', record.phone)])
return customer
#------------------------------------------------------
customer = fields.Many2one('res.partner', string='Customer', track_visibility='onchange',index=True, help="Linked partner (optional). Usually created when converting the lead.",)
Your onchange isn't correct. You don't need parameters and have to return a dictionary or nothing. The dictionary is only needed for field filtering changes and warning messages. Value changes like yours are made "directly":
#api.onchange('customer_number')
def get_partner(self):
if self.customer_number:
customer = self.env['res.partner'].search(
[('customer_number', '=', self.phone)]) # shouldn't it be self.customer_number?
self.customer = customer
And try to stick to the Odoo Guidelines and change the field customer to customer_id.

Categories

Resources