Tag: odoo

Odoo How to install or uninstall a Odoo module from command line or using python

cd /odoo-installed folder
python3 odoo-bin shell -d db-name--addons-path=/your-addons-path


Then run the bleow Python script
For Install
self.env['ir.module.module'].search([('name', '=', 'moule-name')]).button_immediate_install()
For Unistall
self.env['ir.module.module'].search([('name', '=', 'moule-name')]).button_immediate_uninstall()

Making Fields Visible and Invisible based on One2many field values in Odoo

Py File

from odoo import models, fields, api, _
from odoo.exceptions import UserError

class AccountPaymentRegister(models.TransientModel):
_inherit = ‘account.payment.register’

# == Inherit fields ==
cheque_date = fields.Date(String="Cheque Date", default=fields.Date.context_today)
cheque_no = fields.Char(String="Cheque No.")
rec_bank = fields.Char(String="Receive Bank")    
payment_method_code = fields.Char(String="Payment Method code")

is_bank_selected = fields.Boolean(string="is bank selected")
# Journal ID - Many2one 
# If Journal ID is Bank is is_bank_selected become TRUE.
@api.onchange('journal_id')
def _change_journal_id(self):
    if self.journal_id.name == 'Bank':
        self.is_bank_selected = True
    else:           
        self.is_bank_selected = False    

XML file

<?xml version="1.0" encoding="utf-8"?>
<odoo>
    <data>
        <record id="view_account_payment_register_mesco_inherit_form" model="ir.ui.view">
            <field name="name">account.payment.register.mesco.inherit.form</field>
            <field name="model">account.payment.register</field>
            <field name="inherit_id" ref="account.view_account_payment_register_form"/>
            <field name="arch" type="xml">
                <field name="communication" position="after">
                    <field name="is_bank_selected" invisible="1"/>
                    <field name="cheque_date" attrs="{'invisible': [('is_bank_selected', '!=', True)]}"/>
                    <field name="cheque_no" attrs="{'invisible': [('is_bank_selected', '!=', True)]}"/>
                    <field name="rec_bank" attrs="{'invisible': [('is_bank_selected', '!=', True)]}"/>
                </field>
            </field>
        </record>

    </data>
</odoo>

Hide or remove Fields from Odoo Filter(Add Custom Filter) and Group By(Add Custom Group).

    #You can easily hide or remove  fields from odoo filter by inheriting function fields_get()
    @api.model
    def fields_get(self, fields=None):
        show = ['file_name','partner_id','line_partner_ids','common_message','state','upload_type']
        group = ['partner_id','state','upload_type']
        res = super(SendDocument, self).fields_get()
        for field in res:
            res[field]['selectable'] = False
            res[field]['sortable'] = False
        for field in show:
            res[field]['selectable'] = True
        for field in group:
            res[field]['sortable'] = True
        return res

How to drop database(PostgreSQL) if there are active connections to it(PostgreSQL database is being accessed by other users)?

  1. PostgreSQL 9.2 and above:
SELECT pg_terminate_backend(pg_stat_activity.pid)
FROM pg_stat_activity
WHERE pg_stat_activity.datname = 'database_name' -- ← change this to your DB
AND pid <> pg_backend_pid();

OR

  1. PostgreSQL 9.1 and below:
SELECT pg_terminate_backend(pg_stat_activity.procpid)
FROM pg_stat_activity
WHERE pg_stat_activity.datname = 'database_name' -- ← change this to your DB
AND procpid <> pg_backend_pid();

sudo su postgres

psql

drop database database_name;

Odoo – Hide Cost Price and Sale Price of product from Product master form,tree and kanban views – for sales user.

<record id="ep_product_template_form_view" model="ir.ui.view">            
	<field name="inherit_id" ref="product.product_template_form_view"/>
	<field name="model">product.template</field>            
	<field name="arch" type="xml">
		<xpath expr="//field[@name='list_price']" position="attributes">
			<attribute name="groups">sales_team.group_sale_manager</attribute>		
			
		</xpath>
		<xpath expr="//label[@for='standard_price']" position="attributes">
			<attribute name="groups">sales_team.group_sale_manager</attribute>		
			
		</xpath>
		<xpath expr="//div[@name='standard_price_uom']" position="attributes">
			<attribute name="groups">sales_team.group_sale_manager</attribute>	
			
		</xpath>
		<xpath expr="//div[@name='standard_price_uom']" position="attributes">
			<attribute name="groups">sales_team.group_sale_manager</attribute>	
			
		</xpath>     
	</field>
</record> 

<record id="ep_product_template_tree_view_cost_price" model="ir.ui.view">			
	<field name="model">product.template</field>
	<field name="inherit_id" ref="product.product_template_tree_view" />
	<field name="arch" type="xml">
		<xpath expr="//field[@name='standard_price']" position="attributes">
			<attribute name="groups">sales_team.group_sale_manager</attribute>		
			
		</xpath>
	</field>
</record>
<record id="ep_view_template_property_form" model="ir.ui.view">            
	<field name="model">product.supplierinfo</field>
	<field name="inherit_id" ref="product.product_supplierinfo_form_view"/>
	<field name="arch" type="xml">
		<xpath expr="//label[@for='price']" position="attributes">
			<attribute name="groups">sales_team.group_sale_manager</attribute>	
			
		</xpath>
			
	</field>
</record>
<record id="ep_product_supplierinfo_tree_view" model="ir.ui.view">            
	<field name="model">product.supplierinfo</field>
	<field name="inherit_id" ref="product.product_supplierinfo_tree_view"/>
	<field name="arch" type="xml">
		<xpath expr="//field[@name='price']" position="attributes">
			<attribute name="groups">sales_team.group_sale_manager</attribute>	
			
		</xpath>
			
	</field>
</record>
<record id="ep_product_template_kanban_view" model="ir.ui.view">            
	<field name="model">product.template</field>
	<field name="inherit_id" ref="product.product_template_kanban_view"/>
	<field name="arch" type="xml">
		<xpath expr="//div[@class='oe_kanban_details']/ul/li" position="attributes">
			<attribute name="groups">sales_team.group_sale_manager</attribute>                    
		</xpath>                    
	</field>
</record>

Change menu name and action name in Odoo

<!– Delete the Purchase Agreements –>
<delete model=”ir.ui.menu” id=”menu_purchase_requisition_pro_mgt” />
<!– Create the menu the Material Request –>
<menuitem
name=”Material Request” id=”menu_purchase_requisition_pro_mgt”
sequence=”10″
parent=”purchase.menu_procurement_management”
action=”purchase_requisition.action_purchase_requisition” />
<!– Update the action name Material Request –>
<record id=”purchase_requisition.action_purchase_requisition” model=”ir.actions.act_window”>
<field name=”name”>Material Request</field>
</record>aterial Request Material Request

Odoo Call python function from Javascript

Write below function inside odoo javascript page.

  this._rpc({
                    model: 'hr.employee',
                    method: 'default_events',
                    args: [this.res_id],
                }, {
                    shadow: true,
                });  

Write below function inside Odoo python file

@api.model
def default_events(self,emp_id):
up_ev_data = []
events_obj= self.env['upcoming.events']
leave_obj= self.env['hr.leave']
leaveline= leave_obj.search([('employee_id','=',emp_id),('state','=','validate')])
if(emp_id):
self.env['upcoming.events'].search([('employee_id','=',emp_id)]).unlink()
for leave in leaveline:
vals={
'name' : leave.holiday_status_id.name,
'employee_id': leave.employee_id.id,
'date_start': leave.request_date_from,
'date_end': leave.request_date_to,
'state':'validate',
}
up_ev_data.append((0,0,vals))
events_obj.create(vals)
return up_ev_data Write below function inside odoo javascript page.

this._rpc({
model: 'hr.employee',
method: 'default_events',
args: [this.res_id],
}, {
shadow: true,
});
Write below function inside Odoo python file

addons\employee_events\static\src\js\event_list.js

odoo.define('employee_events.event_list', function (require) {
     "use strict";
var FieldOne2Many = require('web.relational_fields').FieldOne2Many;
var fieldRegistry = require('web.field_registry');
var ListRenderer = require('web.ListRenderer');
// Function ListRenderer_extnd    
var ListRenderer_extnd = ListRenderer.extend({
    _renderRow: function (record, index) {
        var $row = this._super.apply(this, arguments);
        // Change on2many row's background colour based on event_type condition            
        if(record.data["event_type"]=='leave')
        {           
            this.$el.find('> table').removeClass('table-striped');     
            $row.addClass('events_leave');   
        }
        if(record.data["event_type"]=='calendar')
        {           
            this.$el.find('> table').removeClass('table-striped');     
            $row.addClass('events_calender');   
        }
        if(record.data["event_type"]=='activity')
        {           
            this.$el.find('> table').removeClass('table-striped');     
            $row.addClass('events_activity');   
        }            
        return $row;
    },

});
// Extending javascript one2many Render function 
var EventListFieldOne2Many = FieldOne2Many.extend({        
    _getRenderer: function () {
        console.log("My Message inside");
        if (this.view.arch.tag === 'tree') {                
            //Calling python funtion default_events(hr.employee) using _rpc             
            this._rpc({
                model: 'hr.employee',
                method: 'default_events',
                args: [this.res_id],
            }, {
                shadow: true,
            });
            // Return ListRenderer_extnd
            return ListRenderer_extnd;
        }
        return this._super.apply(this, arguments);
    },
});
console.log("My Event List End!!!");
fieldRegistry.add('Event_List_FieldOne2Many', EventListFieldOne2Many);
});

odoo\addons\employee_events\models\hr_employee.py

import datetime
from odoo import api, fields, models, _

# inherit employee module
class Employee(models.Model):
    _inherit = 'hr.employee'  
         
    event_ids = fields.One2many('upcoming.events', 'employee_id', string='Upcoming Events',copy=True)
    # creating upcoming events from Leaves,Calender and Activity
    # Function from  event_list.js
    @api.model
    def default_events(self,emp_id):          
        up_ev_data = []
        events_obj= self.env['upcoming.events']
        cal_obj= self.env['calendar.event']
        emp_obj= self.env['hr.employee']
        act_obj= self.env['mail.activity']
        leave_obj= self.env['hr.leave']
        if(emp_id):
            # Clearing existing upcoming event lines 
            self.env['upcoming.events'].search([('employee_id','=',emp_id)]).unlink()
            # creating upcoming events from Leaves  
            leaveline= leave_obj.search([('employee_id','=',emp_id),('state','=','validate'),('request_date_to','>',datetime.datetime.utcnow().date())])            
            for leave in leaveline:                
                vals={
                    'name' : leave.holiday_status_id.name,
                    'employee_id': leave.employee_id.id, 
                    'date_start': leave.request_date_from,
                    'date_end': leave.request_date_to,
                    'state':'validate',
                    'event_type':'leave',          
                }               
                up_ev_data.append(vals) 
            # creating upcoming events from Calendar events              
            employee= emp_obj.search([('id','=',emp_id)])
            if(employee):                
                event_line=cal_obj.search([('partner_ids','in',employee.user_id.partner_id.id),('privacy','=','public'),('stop_date','>=',datetime.datetime.utcnow().date())]) 
                for event in event_line:
                    vals={
                        'name' : event.name,
                        'employee_id': emp_id, 
                        'date_start': event.start_date,
                        'date_end': event.stop_date,
                        'state':'validate',
                        'event_type':'calendar',            
                    }
                    up_ev_data.append(vals)                   
            # creating upcoming events from Activity
            if(employee):               
                act_line=act_obj.search([('res_id','=',employee.id),('res_model_id','=','hr.employee'),('date_deadline','>=',datetime.datetime.utcnow().date())]) 
                for act in act_line:
                    vals={
                        'name' : act.summary,
                        'employee_id': emp_id, 
                        'date_start': act.date_deadline,
                        'date_end': act.date_deadline,
                        'state':'validate',
                        'event_type':'activity',            
                    }
                    up_ev_data.append(vals)
            # Sort based on the date                
            up_ev_data_new=sorted(up_ev_data, key = lambda i: i['date_start'])   
            # Creating upcoming event lines   
            events_obj.create(up_ev_data_new)            
        return up_ev_data        
   
   

# upcoming.events module
class UpcomingEvents(models.Model):
    _name = 'upcoming.events'
    name = fields.Char('Events')
    employee_id = fields.Many2one('hr.employee', string='Employee')
    date_start = fields.Date('Start Date', default=fields.Date.today,
        help="Start date of the event.")
    date_end = fields.Date('End Date', default=fields.Date.today,
        help="End date of the event.")
    event_type=fields.Selection([
            ('leave', 'Leave'),
            ('calendar', 'Calendar'),
            ('activity', 'Activity'),           
        ], string='Type', default='calendar')
    state = fields.Selection([
            ('draft', 'New'),
            ('confirm', 'Waiting Approval'),
            ('refuse', 'Refused'),
            ('validate1', 'Waiting Second Approval'),
            ('validate', 'Approved'),
            ('cancel', 'Cancelled')
        ], string='Status', default='draft')

from odoo import api, fields, models, _
class Employee(models.Model):
     _inherit = 'hr.employee'  
event_ids = fields.One2many('upcoming.events', 'employee_id', string='Upcoming Events',copy=True)

@api.model
def default_events(self,emp_id):          
    up_ev_data = []
    events_obj= self.env['upcoming.events']
    leave_obj= self.env['hr.leave']
    leaveline= leave_obj.search([('employee_id','=',emp_id),('state','=','validate')])      

    if(emp_id):
        self.env['upcoming.events'].search([('employee_id','=',emp_id)]).unlink()
        for leave in leaveline:                
            vals={
                'name' : leave.holiday_status_id.name,
                'employee_id': leave.employee_id.id, 
                'date_start': leave.request_date_from,
                'date_end': leave.request_date_to,
                'state':'validate',            
            }                
            up_ev_data.append((0,0,vals))
            events_obj.create(vals)                
    return up_ev_data