Thursday, 10 December 2015

Kivy_odoo Integration

Hi,am explaining how to connect kivi with Odoo.



main.py


from kivy.app import App
from kivy.graphics import Color, Rectangle
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.properties import NumericProperty
from kivy.lang import Builder
import xmlrpclib
from kivy.storage.jsonstore import JsonStore
#store = JsonStore('hello.json')
Builder.load_string('''
#:import JsonStore kivy.storage.jsonstore
#:import random random.random
#:import SlideTransition kivy.uix.screenmanager.SlideTransition
#:import SwapTransition kivy.uix.screenmanager.SwapTransition
#:import WipeTransition kivy.uix.screenmanager.WipeTransition
#:import FadeTransition kivy.uix.screenmanager.FadeTransition
#:import RiseInTransition kivy.uix.screenmanager.RiseInTransition
#:import FallOutTransition kivy.uix.screenmanager.FallOutTransition
#:import NoTransition kivy.uix.screenmanager.NoTransition
<FirstBox>:
 
 
    BoxLayout:
        orientation:'vertical'
        BoxLayout:
            size_hint_y:None
            height:70
            Label:
                text:'Odoo App By Jamshi...'
        TextInput:
            id:ip
            border:[16,16,16,4]
            hint_text:'server ip'
            size_hint_y:None
            height:70
        TextInput:
            id:db
            hint_text:'database'
            size_hint_y:None
            height:70
        TextInput:
            id:port
            hint_text:'port'
            size_hint_y:None
            height:70
        TextInput:
            id:user
            hint_text:'username'
            size_hint_y:None
            height:70
        TextInput:
            id:passwd
            hint_text:'password'
            password:True
            size_hint_y:None
            height:70
        BoxLayout:
            orientation:'horizontal'
            Button:
                text:'login'
                background_color:[0,1,0,1]
                on_release:root.login()
            Button:
                text:'Quit'
                background_color:[0,0,1,1]
                on_release:App.on_stop()
     
        Label:
            id:status
            text:'Not Logged in...'
 
<MainMenu>:
    BoxLayout:
        orientation:'vertical'
        Button:
            text:'Create Customer'
            on_release:root.go_to_customer()
        Button:
            text:'Create Supplier'
            on_release:root.go_to_supplier()
        Button:
            text:'Creat Users'
            on_release:root.manager.current = 'user'
        Button:
            text:'Create Company'
            on_release:root.manager.current = 'company'
        Button:
            text:'Create Sale Order'
        Button:
            text:'Create Purchase Order'
        Button:
            text:'Quit'
            on_release:App.on_stop()
<Customer>:
 
    BoxLayout:
        orientation:'vertical'
        TextInput:
            id:name
            hint_text:'Customer Name'
            size_hint_y:None
            height:70
        TextInput:
            id:mobile
            hint_text:'Mobile'
            size_hint_y:None
            height:70
        TextInput:
            id:email
            hint_text:'email'
            size_hint_y:None
            height:70
         
        Button:
            text:'Create'
            on_release:root.create_customer()
        Button:
            text:'Main Menu'
            on_release:root.manager.current = 'main_menu'
        Button:
            text:'Quit'
            on_release:App.on_stop()
     
        Label:
            id:message
            text:'Enter Details to Add customer'
        Label:
            id:contact
            text:'Contact: +91 9744 894950'
        Label:
            text:'jamshu.mkd@gmail.com'
        Label:
            id:status
            text:'Not Created'

<Supplier>:
 
    BoxLayout:
        orientation:'vertical'
        TextInput:
            id:name
            hint_text:'Supplier Name'
            size_hint_y:None
            height:70
        TextInput:
            id:mobile
            hint_text:'Mobile'
            size_hint_y:None
            height:70
        TextInput:
            id:email
            hint_text:'email'
            size_hint_y:None
            height:70
         
        Button:
            text:'Create'
            on_release:root.create_supplier()
        Button:
            text:'Main Menu'
            on_release:root.manager.current = 'main_menu'
        Button:
            text:'Quit'
            on_release:App.on_stop()
     
        Label:
            id:message
            text:'Enter Details to Add customer'
        Label:
            id:contact
            text:'Contact: +91 9744 894950'
        Label:
            text:'jamshu.mkd@gmail.com'
        Label:
            id:status
            text:'Not Created'
<User>:
 
    BoxLayout:
        orientation:'vertical'
        TextInput:
            id:name
            hint_text:'User Name'
            size_hint_y:None
            height:70
        TextInput:
            id:login
            hint_text:'login'
            size_hint_y:None
            height:70
        TextInput:
            id:password
            hint_text:'password'
            size_hint_y:None
            height:70
        TextInput:
            id:email
            hint_text:'email'
            size_hint_y:None
            height:70
             
        Button:
            text:'Create'
            on_release:root.create_user()
        Button:
            text:'Main Menu'
            on_release:root.manager.current = 'main_menu'
        Button:
            text:'Quit'
            on_release:App.on_stop()
     
        Label:
            id:message
            text:'Enter Details to Add User'
     
        Label:
            id:status
            text:'Not Created'

<Company>:
 
    BoxLayout:
        orientation:'vertical'
        TextInput:
            id:name
            hint_text:'Company Name'
            size_hint_y:None
            height:70
     
             
        Button:
            text:'Create'
            on_release:root.create_company()
        Button:
            text:'Main Menu'
            on_release:root.manager.current = 'main_menu'
        Button:
            text:'Quit'
            on_release:App.on_stop()
     
        Label:
            id:message
            text:'Enter Details to Add Company'
     
        Label:
            id:status
            text:'Not Created'
''')

val = {}
class Customer(Screen):
     
    def create_customer(self,*agrs):
        if val.get('ip'):
         
            ip=val.get('ip')
            db=val.get('db')
            port =val.get('port')
            user=val.get('user')
            passwd=val.get('passwd')
            sock_common = xmlrpclib.ServerProxy ('http://'+ip+':'+port+'/xmlrpc/common', allow_none=True)
            uid = sock_common.login(db, user, passwd)
            sock= xmlrpclib.ServerProxy('http://'+ip+':'+port+'/xmlrpc/object', allow_none=True)
            customer_name =self.ids.name.text
            mobile = self.ids.mobile.text
            email=self.ids.email.text
            c_vals ={'name':customer_name,
                    'mobile':mobile,
                    'email':email,
                    'customer':True}
            if customer_name != '':
                sock.execute(db, uid, passwd, 'res.partner', 'create', c_vals)
                self.ids.status.text = 'Customer Created Successfuly'
     
class Supplier(Screen):
    def create_supplier(self,*args):
        if val.get('ip'):
         
            ip=val.get('ip')
            db=val.get('db')
            port =val.get('port')
            user=val.get('user')
            passwd=val.get('passwd')
            sock_common = xmlrpclib.ServerProxy ('http://'+ip+':'+port+'/xmlrpc/common', allow_none=True)
            uid = sock_common.login(db, user, passwd)
            sock= xmlrpclib.ServerProxy('http://'+ip+':'+port+'/xmlrpc/object', allow_none=True)
            customer_name =self.ids.name.text
            mobile = self.ids.mobile.text
            email=self.ids.email.text
            c_vals ={'name':customer_name,
                    'mobile':mobile,
                    'email':email,
                    'supplier':True }
            if customer_name != '':
                sock.execute(db, uid, passwd, 'res.partner', 'create', c_vals)
                self.ids.status.text = 'Supplier Created Successfuly'

class User(Screen):
    def create_user(self,*args):
        if val.get('ip'):
         
            ip=val.get('ip')
            db=val.get('db')
            port =val.get('port')
            user=val.get('user')
            passwd=val.get('passwd')
            sock_common = xmlrpclib.ServerProxy ('http://'+ip+':'+port+'/xmlrpc/common', allow_none=True)
            uid = sock_common.login(db, user, passwd)
            sock= xmlrpclib.ServerProxy('http://'+ip+':'+port+'/xmlrpc/object', allow_none=True)
            name =self.ids.name.text
            login = self.ids.login.text
            email=self.ids.email.text
            password=self.ids.password.text
            c_vals ={'name':name,
                    'login':login,
                    'email':email,
                    'password':password}
            if name != '':
                sock.execute(db, uid, passwd, 'res.users', 'create', c_vals)
                self.ids.status.text = 'User Created Successfuly'

class Company(Screen):
    def create_company(self,*args):
        if val.get('ip'):
             
                ip=val.get('ip')
                db=val.get('db')
                port =val.get('port')
                user=val.get('user')
                passwd=val.get('passwd')
                sock_common = xmlrpclib.ServerProxy ('http://'+ip+':'+port+'/xmlrpc/common', allow_none=True)
                uid = sock_common.login(db, user, passwd)
                sock= xmlrpclib.ServerProxy('http://'+ip+':'+port+'/xmlrpc/object', allow_none=True)
                name =self.ids.name.text
             
                c_vals ={'name':name}
                if name != '':
                    sock.execute(db, uid, passwd, 'res.company', 'create', c_vals)
                    self.ids.status.text = 'Company Created Successfuly'
     
class FirstBox(Screen):
         
    def login(self,*args):
        ip = self.ids.ip.text
        db = self.ids.db.text
        port = self.ids.port.text
        user = self.ids.user.text
        passwd = self.ids.passwd.text
        global val
        val ={'ip':ip,'db':db,'port':port,'user':user,'passwd':passwd}
     
     
        try:
         
         
            sock_common = xmlrpclib.ServerProxy ('http://'+ip+':'+port+'/xmlrpc/common', allow_none=True)
            uid = sock_common.login(db, user, passwd)
            #store.put('tito', ip=ip, db=db,port=port,user=user,passwd=passwd)
            self.manager.current = 'main_menu'
        except Exception, e:
             self.ids.status.text='Login Failed Please Try Again'
     
class MainMenu(Screen):
    def go_to_customer(self,*args):
        self.manager.current = 'customer'
    def go_to_supplier(self,*args):
        self.manager.current = 'supplier'

class ScreenManagerApp(App):

    def build(self):
        self.title = 'OdooApp'
        root = ScreenManager()

        root.add_widget(FirstBox(name='first'))
        root.add_widget(MainMenu(name='main_menu'))
        root.add_widget(Customer(name='customer'))
        root.add_widget(Supplier(name='supplier'))
        root.add_widget(User(name='user'))
        root.add_widget(Company(name='company'))
        return root

if __name__ == '__main__':
    ScreenManagerApp().run()



file.json



{"tito": {"passwd": "admin", "ip": "localhost", "db": "kv_oct_26_local", "port": "8070", "user": "admin"}}

Wednesday, 9 December 2015

Sale Order Workflow

Workflow of sales order in Odoo


A sale order have 9 stages.
  • Draft Quotation
  • Quotation Sent
  • Cancelled
  • Waiting Schedule
  • Sales Order
  • Sale to Invoice
  • Invoice Exception
  • Done
At first we create a quotation.
  • Sales-> Quotation->Create
  • Select a customer 
  • Inside Order Lines tab click add an item
  • Select a Product. After that the systems fills the Unit Price and other related fields.
  • Now you can specify the quantity
  • In Other Information tab you an several fields like Shipping Policy and Create Invoice. you can specify it
  • Then save the form. Now your Quotation is Created
After creating a Quotation you can send it to the customer via Email. A pdf of your Quotation will attached in that email. This is not required.
Then you can confirm it as a sale order.
  • Remember after confirming a sale order you can’t change the important values of the order like(Customer, Product, Quantity..etc)
  • Now you have three options depends on your Create Invoice filed value.
    1. On Demand – You can Create Invoice or view Delivery Order of your Sales Order
    2. On Delivery Order – You can view the Delivery Order and deliver your product if it is available. Only after completing the Delivery process you can create invoice.
    3. Before Delivery – In this option, first you want to pay the invoice. after that you can deliver your product
  • Paid and Delivered Fields, inside the Other Information tab shows the status of invoice and delivery order
  • Shipping Policy
    1. Deliver Each Product when available.
    2. Deliver All Products at once.
After Completing these steps your Sale Order workflow is completed.



ORM Methods

_search()


Example 1:



def _search(self, cr, user, args, offset=0, limit=None, order=None, context=None, count=False, access_rights_uid=None):

        location_ids = []

        if context is not None and context.get('user_location'):

            ids = [loc.lot_stock_id.id for loc in \

            self.pool.get('res.users').browse(cr, user, user, context=context).od_warehouse_id if loc.lot_stock_id]

            args.append(['id', 'in', ids])

        return super(stock_location, self)._search(cr, user, args, offset=offset, limit=limit, order=order, context=context)


Example2:



#get sale orders in the selected roster date and order state in progress/manual only

    def _search(self, cr, user, args, offset=0, limit=None, order=None, context=None, count=False, access_rights_uid=None):

        if context is None:

            context={}

        so_ids=[]

        if context.get('roster') and not context.get('roster_date'):

            args.append(['id', 'in', so_ids])

        if context.get('roster') and context.get('roster_date'):

            date = context.get('roster_date')

            qry = """select id from sale_order where state in ('progress','manual') and date_order >= '%s' and date_order < ('%s'::date + '1 day'::interval)"""%(date,date)

            cr.execute(qry)

            res = cr.fetchall()

            if res:

                so_ids.extend([i[0] for i in res])

            args.append(['id', 'in', so_ids])

        return super(sale_order, self)._search(cr, user, args, offset=offset, limit=limit, order=order, context=context)


write()


    

    Example 1:


    def write(self, cr, uid, ids, vals, context=None):

        line_ids = []

        res = super(sale_order_line, self).write(cr, uid, ids, vals, context=context)

        rec = self.browse(cr, uid, ids, context)[0].order_id

        

        if vals.get('discount') > 10:

            

            self.pool.get('sale.order').write(cr,uid,[rec.id],{'od_sales_man_discount_ctrl':True},context)

        else:

            for obj in rec.order_line:

                if obj.discount > 10:

                    line_ids.append(obj.id)

            if len(line_ids) > 0:

                self.pool.get('sale.order').write(cr,uid,[rec.id],{'od_sales_man_discount_ctrl':True},context)

            else:

                self.pool.get('sale.order').write(cr,uid,[rec.id],{'od_sales_man_discount_ctrl':False},context)

      

        return res


Example2:



def write(self, cr, uid, ids, vals, context=None):

         od_route_shift_obj = self.browse(cr, uid, ids, context=None)

         update_pending_orders = od_route_shift_obj.update_pending_orders

         old_sale_person_id = od_route_shift_obj.sale_person_id.id

         sale_order_pool = self.pool.get('sale.order')

         sale_order_obj = sale_order_pool.browse(cr, uid, ids)

         sale_person_id = sale_order_obj.user_id

         sale_order_ids = sale_order_pool.search(cr, uid, [('od_delivered_user_id', '=', old_sale_person_id),('state', '=', 'draft')])

         if 'sale_person_id' in vals and 'update_pending_orders' in vals:

            if vals['update_pending_orders']:

                new_sale_person_id = vals['sale_person_id']

                if sale_order_ids:

                    sale_order_pool.write(cr, uid, sale_order_ids, {'od_delivered_user_id': new_sale_person_id})

         return super(od_route_shift, self).write(cr, uid, ids, vals, context=context)


  sale_order_pool.write(cr, uid, sale_order_ids, {'od_delivered_user_id': new_sale_person_id})


create()


Example1:


def create(self, cr, uid, vals, context=None):

        res = super(od_hr_expense_loans_description_line, self).create

    (cr, uid, vals, context=context)

        loan_data = self.browse(cr, uid,res)

        product_id = vals['product_id']

        od_hr_expense_loans_description_line_obj = self.pool.get

       ('od.hr.expense.loans.description.line')

        unit_quantity = vals['unit_quantity']

        product_obj = self.pool.get('product.product')

        next_date = vals['date_value']

        unit_amount = vals['unit_amount']

        next_date_strp = datetime.strptime(next_date, '%Y-%m-%d')

        next_date_strp_rel = relativedelta(next_date_strp)

        months = (12*(next_date_strp_rel.years) +(next_date_strp_rel.months+1))

        od_hr_loan_info_line_pool = self.pool.get('od.hr.loan.info.line')

        for i in range(0,unit_quantity):

            next_date_strp = next_date_strp + relativedelta(months=1)

            if product_id:

                salary_pool = self.pool.get('hr.salary.rule')

                salary_rule_ids =  self.pool.get('hr.salary.rule').search

              (cr,uid, [('od_product_id','=',product_id)])

                if salary_rule_ids:

                    salary_rule_data = salary_pool.browse

                 (cr, uid, salary_rule_ids, context=context)[0]

                    od_hr_loan_info_line_pool.create(cr, uid, {

                        'date_value': next_date_strp,

                        'amount': unit_amount,

                        'rule_id': salary_rule_data.id,

                        'hr_expense_loan_id':loan_data.loans_id and loan_data.loans_id.id ,

                })

        return res


Example2:


    def create(self, cr, uid, vals, context=None):

        if vals.get('discount') > 10 and vals.get('order_id'):

            self.pool.get('sale.order').write(cr,uid,[vals.get('order_id')],{'od_sales_man_discount_ctrl':True},context)

        return super(sale_order_line, self).create(cr, uid, vals, context=context)


unlink()


Example1:


@api.multi

def unlink(self):

    for invoice in self:

        if invoice.state not in ('draft', 'cancel'):

            raise Warning(_('You cannot delete an invoice which is not draft or cancelled. You should refund it instead.'))

        elif invoice.internal_number:

            raise Warning(_('You cannot 

delete an invoice after it has been validated (and received a number). You can set it back to "Draft" state and modify its content, then re-confirm it.'))

    return super(account_invoice, self).unlink()


Example2:


@api.multi

def unlink(self):

    for target in self:

        if target.state not in ('draft'):

            raise Warning(_('You cannot delete it,it is not in draft.'))

        return super(od_sales_target, self).unlink()


Example3:


def unlink(self, cr, uid, ids, context=None):

     od_production_planning_obj = self.read(cr, uid, ids, ['manufacturer_line'], context=context)

     unlink_ids = []

     for production in od_production_planning_obj:

        for product in production['manufacturer_line']:

            raise osv.except_osv(_('Invalid Action!'), _('You cannot Delete it,Manufacturing Order Still Existing'))

        unlink_ids.append(production['id'])

    return osv.osv.unlink(self, cr, uid, unlink_ids, context=context)


Example4:


def unlink(self, cr, uid, ids, context=None):

    sale_orders = self.read(cr, uid, ids, ['state'], context=context)

    unlink_ids = []

    for s in sale_orders:

        if s['state'] in ['draft', 'cancel']:

            unlink_ids.append(s['id'])

        else:

            raise osv.except_osv(_('Invalid Action!'), _('In order to delete a confirmed sales order, you must cancel it before!'))


        return osv.osv.unlink(self, cr, uid, unlink_ids, context=context)


Example5:



#For lines Exisisting lines unlink at the time of line generation(v7)




def compute_sheet(self, cr, uid, ids, context=None): 
        slip_line_pool = self.pool.get('hr.payslip.line') 
        sequence_obj = self.pool.get('ir.sequence') 
        self._od_generate_ot_details(cr, uid, ids,context=context) 
        for payslip in self.browse(cr, uid, ids, context=context): 
            number = payslip.number or sequence_obj.get(cr, uid, 'salary.slip') 
            #delete old payslip lines 
            old_slipline_ids = slip_line_pool.search(cr, uid, [('slip_id', '=', payslip.id)], context=context) 
#            old_slipline_ids 
            if old_slipline_ids: 
                slip_line_pool.unlink(cr, uid, old_slipline_ids, context=context) 
            if payslip.contract_id: 
                #set the list of contract for which the rules have to be applied 
                contract_ids = [payslip.contract_id.id] 
            else: 
                #if we don't give the contract, then the rules to apply should be for all current contracts of the employee 
                contract_ids = self.get_contract(cr, uid, payslip.employee_id, payslip.date_from, payslip.date_to, context=context) 
            lines = [(0,0,line) for line in self.pool.get('hr.payslip').get_payslip_lines(cr, uid, contract_ids, payslip.id, context=context)] 
            self.write(cr, uid, [payslip.id], {'line_ids': lines, 'number': number,}, context=context) 
        return True


Example6



    @api.multi 
    def search_product(self): 
        for obj in self: 
            enquiry_line = obj.enquiry_line 
            enquiry_line.unlink() 
        stock_quant_ids = self.env['stock.quant'].search([('product_id', '=', self.product_id.id)]) 
        for quant in stock_quant_ids: 
            if quant.location_id.usage == 'internal': 
                vals = {'enquiry_id':self.id, 
                        'product_id':quant.product_id.id, 
                        #'batch_no':quant.od_batch_no, 
                        'product_uom_qty':quant.qty, 
                        'location_id':quant.location_id.id, 
                        'package_id':quant.package_id.id, 
                        'unit_price':quant.cost, 
                        'in_date':quant.in_date, 
                        'inventory_value':quant.inventory_value, 
                        'lot_id': quant.lot_id and quant.lot_id.id or '' 
                      } 
                self.env['od.product.enquiry.line'].create(vals) 

        return { 
            'name': _('Product Enquiry'), 
            'view_type': 'form', 
            'view_mode': 'form', 
            'res_model': 'od.product.enquiry', 
            'res_id': self.id, 
            'target': 'new', 
            'type': 'ir.actions.act_window', 
        }


search()


Example1:


journal = self.env['account.analytic.journal'].search([('type', '=', journal_type)], limit=1)



Example2:


journal_ids = self.pool.get('account.journal').search(cr, uid,
            [('type', '=', 'sale'), ('company_id', '=', order.company_id.id)],
            limit=1)


browse()


Example1:


prod = product_obj.browse(cr, uid, line[2]['product_id'], context=context)


Example2:


p = self.env['res.partner'].browse(partner_id)



name_get()


Example1:



    def name_get(self, cr, uid, ids, context=None):
        res = []
        for id in ids:
            elmt = self.browse(cr, uid, id, context=context)
            name = "["+str(elmt.code)+"]"+" "+elmt.name
            res.append((id, name))
        return res



Thursday, 3 December 2015

V8 and V7 Field Difference


Here am explaining the field differences between version 7.0 and 8.0

Field in Version8.0


Image



    @api.depends('image')
    def _get_medium_image(self):
        self.image_medium =\
            tools.image_get_resized_images(self.image)['image_medium']

    @api.one
    @api.depends('image')
    def _get_small_image(self):
        self.image_small =\
            tools.image_get_resized_images(self.image)['image_small']

    @api.one
    def _set_image_from_medium(self):
        self.image = tools.image_resize_image_big(self.image_medium)

    @api.one
    def _set_image_from_small(self):
        self.write({'image': tools.image_resize_image_big(self.image_small)})


        image = fields.Binary(string="Image",)    
        image_medium = fields.Binary(compute='_get_medium_image',                                                                            inverse='_set_image_from_medium',
                                 string="Medium-sized image", store=True)
        image_small = fields.Binary(compute='_get_small_image',                                                                                  inverse='_set_image_from_small',
                                string="Small-sized image", type="binary",
                                store=True)



Related Field


Eg:-commercial_partner_id = fields.Many2one('res.partner',string='Partner',related='partner_id.commercial_partner_id',store=True,readonly=True)

Eg:-number = fields.Char(related='move_id.name', store=True, readonly=True,)

Eg:-company_id = fields.Many2one('res.company', string='Company',related='invoice_id.company_id', store=True, readonly=True)

Eg:-is_brand = fields.Boolean(related='sale_product_target_id.is_brand',string='Is Brand',store=True)


Eg:-eccentricity_uom_id = fields.Many2one('product.uom',string="Ref Unit",related='uom_id',readonly=True,)


Eg:-image = fields.Binary(string="Image",related='support_id.image',readonly=True,)
    image_medium = fields.Binary(compute='_get_medium_image',                                                                                inverse='_set_image_from_medium',
                                 string="Medium-sized image", store=True)
    image_small = fields.Binary(compute='_get_small_image', inverse='_set_image_from_small',
                                string="Small-sized image", type="binary",
                                store=True)


     for making an image field as relational field then we have to define normal image field,and          just put the relation in image field only,otherwise no difference.


Functional Field


Example1:



    @api.one

    @api.depends('price_unit', 'discount', 'invoice_line_tax_id', 'quantity',
        'product_id', 'invoice_id.partner_id', 'invoice_id.currency_id')
    def _compute_price(self):
        price = self.price_unit * (1 - (self.discount or 0.0) / 100.0)
        taxes = self.invoice_line_tax_id.compute_all(price, self.quantity, product=self.product_id, partner=self.invoice_id.partner_id)
        self.price_subtotal = taxes['total']
        if self.invoice_id:
            self.price_subtotal = self.invoice_id.currency_id.round(self.price_subtotal)


    price_subtotal = fields.Float(string='Amount', digits= dp.get_precision('Account'),
        store=True, readonly=True, compute='_compute_price')



Example2:



 @api.one

 @api.depends('brand_line.amount','category_line.amount','product_line.amount','saleman_line.amount',
   'customer_line.amount','supplier_line.amount')
    def _compute_amount(self):
        array = []
        self.total_brand_amount = sum((line.p1_amount + line.p2_amount + line.p3_amount + line.p4_amount +
         line.p5_amount + line.p6_amount +line.p7_amount + line.p8_amount + line.p9_amount + line.p10_amount +
        line.p11_amount + line.p12_amount) for line in self.brand_line)
        array.append(self.total_brand_amount)
        array.append(self.total_category_amount)
        array.append(self.total_product_amount)
        array.append(self.total_saleman_amount)
        array.append(self.total_customer_amount)
        array.append(self.total_supplier_amount)
        largest = max(array)
        self.planned_target = largest
        length = len(array)
        largest = array[0]
        for i in range(0,length):
           if array[i] > largest:
             largest = array[i]
             self.planned_target = largest
    total_brand_amount = fields.Float(string='Amount Brand',
        store=True, readonly=True, compute='_compute_amount')



Example3:



    @api.one
    @api.depends(
        'move_id.line_id.account_id',
        'move_id.line_id.reconcile_id.line_id',
        'move_id.line_id.reconcile_partial_id.line_partial_ids',
    )
    def _compute_move_lines(self):
        # Give Journal Items related to the payment reconciled to this invoice.
        # Return partial and total payments related to the selected invoice.
        self.move_lines = self.env['account.move.line']
        if not self.move_id:
            return
        data_lines = self.move_id.line_id.filtered(lambda l: l.account_id == self.account_id)
        partial_lines = self.env['account.move.line']
        for data_line in data_lines:
            if data_line.reconcile_id:
                lines = data_line.reconcile_id.line_id
            elif data_line.reconcile_partial_id:
                lines = data_line.reconcile_partial_id.line_partial_ids
            else:
                lines = self.env['account.move.line']
            partial_lines += data_line
            self.move_lines = lines - partial_lines



    ##many2many functional field
    move_lines = fields.Many2many('account.move.line', string='Entry Lines',
        compute='_compute_move_lines')




    @api.model
    def _default_account(self):
        if self._context.get('type') in ('out_invoice', 'out_refund'):
            return self.env['ir.property'].get('property_account_income_categ', 'product.category')
        else:
            return self.env['ir.property'].get('property_account_expense_categ', 'product.category')

    #Many2one functional field
    account_id = fields.Many2one('account.account', string='Account',
        required=True, domain=[('type', 'not in', ['view', 'closed'])],
        default=_default_account,
        )


Many2many



    invoice_line_tax_id = fields.Many2many('account.tax',
        'account_invoice_line_tax', 'invoice_line_id', 'tax_id',
        string='Taxes', domain=[('parent_id', '=', False)])
    product_ids = fields.Many2many('product.product',string='Products',)


Many2one


    period_id = fields.Many2one('account.period', string='Force Period',
        domain=[('state', '!=', 'done')], copy=False,
        readonly=True, states={'draft': [('readonly', False)]})


One2many


invoice_ids = fields.One2many('account.invoice', 'partner_id', string='Invoices',
        readonly=True, copy=False)

Boolean Field


    sent = fields.Boolean(readonly=True, default=False, copy=False,
        help="It indicates that the invoice has been sent.")

Date field


    date_invoice = fields.Date(string='Invoice Date')


Text


        note =fields.Text(string='Terms and conditions'),

Char


        name = fields.Char(string='Order Reference',)





Field in Version7.0

Image


    def _get_image(self, cr, uid, ids, name, args, context=None):
        result = dict.fromkeys(ids, False)
        for obj in self.browse(cr, uid, ids, context=context):
            result[obj.id] = tools.image_get_resized_images(obj.image, avoid_resize_medium=True)
        return result

    def _set_image(self, cr, uid, id, name, value, args, context=None):
        return self.write(cr, uid, [id], {'image': tools.image_resize_image_big(value)}, context=context)


    _columns = {
        'image': fields.binary("Image",help="This field holds the image used as image for the facility, limited to 1024x1024px."),
        'image_medium': fields.function(_get_image, fnct_inv=_set_image,
            string="Medium-sized image", type="binary", multi="_get_image",
            store={
                'od.property': (lambda self, cr, uid, ids, c={}: ids, ['image'], 10),
            },
            help="Medium-sized image of the Facility. It is automatically "\
                 "resized as a 128x128px image, with aspect ratio preserved, "\
                 "only when the image exceeds one of those sizes. Use this field in form views or some kanban views."),
        'image_small': fields.function(_get_image, fnct_inv=_set_image,
            string="Small-sized image", type="binary", multi="_get_image",
            store={
                'od.property': (lambda self, cr, uid, ids, c={}: ids, ['image'], 10),
            },
            help="Small-sized image of the Facility. It is automatically "\
                 "resized as a 64x64px image, with aspect ratio preserved. "\
                 "Use this field anywhere a small image is required."),
   }






Related Field


Eg:od_shop_id':fields.related('session_id','config_id',type='many2one',relation='pos.config',string='Shop',store=True,)
Eg:-'exchange_rate':fields.related('currency_id','rate',type='float',string='Exchange Rate',),
Eg:-'fiscalyear_id':fields.related('period_id','fiscalyear_id',string='Fiscal Year',type='many2one',relation='account.fiscalyear'),
Eg:-'company_id': fields.related('journal_id','company_id',type='many2one',relation='res.company',string='Company',store=True,readonly=True)



Functional Field


Example1:

    def _od_shipping_count(self, cr, uid, ids, field_name, arg, context=None):
        res ={}
        for obj in self.browse(cr, uid, ids, context):
            shipment_ids = self.pool.get('od.shipping.doc').search(cr, uid, [('purchar_order_id', '=', obj.id)])
            if shipment_ids:
                res[obj.id] = len(shipment_ids)
        return res


    _columns = {
        'od_shipping_count':fields.function(_od_shipping_count,string='Docs',type='integer'),
    }


Example2:


    def _get_management_line(self, cr, uid, ids, field_name,arg,context=None):
       line_ids = []

       for rec in self.browse(cr, uid, ids, context=context):
            deposit_id = rec.id
            fdr_line_ids = self.pool.get('od.facility.management.fdr.line').search(cr,uid,[('deposit_id', '=', deposit_id)])
            if fdr_line_ids:
                for line in fdr_line_ids:
                    line_obj = self.pool.get('od.facility.management.fdr.line').browse(cr,uid,line,context=context)
                    management_id = line_obj.fdr_line_id and line_obj.fdr_line_id.id
                    allocated_amount = line_obj.allocated_amount
                    line_id = self.pool.get('od.deposit.management.line').create(cr,uid,{'management_id':management_id,'amount':allocated_amount})
                    line_ids.append(line_id)

       return dict([(id,line_ids) for id in ids])

    _columns = {
 #One2many              'management_line':fields.function(_get_management_line,type='one2many',relation="od.deposit.management.line"),
    }


Example3:


    def _get_lines_salary_rule_category(self, cr, uid, ids, field_names, arg=None, context=None):

        result = {}
        if not ids: return result
        for id in ids:
            result.setdefault(id, [])
        cr.execute('''SELECT pl.slip_id, pl.id FROM hr_payslip_line AS pl \
                    LEFT JOIN hr_salary_rule_category AS sh on (pl.category_id = sh.id) \
                    WHERE pl.slip_id in %s \
                    GROUP BY pl.slip_id, pl.sequence, pl.id ORDER BY pl.sequence''',(tuple(ids),))
        res = cr.fetchall()
        for r in res:
            result[r[0]].append(r[1])
        return result



    #One2many
    _columns = {
'details_by_salary_rule_category': fields.function(_get_lines_salary_rule_category, method=True, type='one2many', relation='hr.payslip.line', string='Details by Salary Rule Category'),
    }



Example4:




    def _get_latest_contract(self, cr, uid, ids, field_name, args, context=None):

        res = {}
        obj_contract = self.pool.get('hr.contract')
        for emp in self.browse(cr, uid, ids, context=context):
            contract_ids = obj_contract.search(cr, uid, [('employee_id','=',emp.id),], order='date_start', context=context)
            if contract_ids:
                res[emp.id] = contract_ids[-1:][0]
            else:
                res[emp.id] = False
        return res


        #many2one
        'contract_id': fields.function(_get_latest_contract, string='Contract', type='many2one', relation="hr.contract", help='Latest contract of the employee'),


Example5:


    def _sheet(self, cursor, user, ids, name, args, context=None):
        sheet_obj = self.pool.get('hr_timesheet_sheet.sheet')
        res = {}.fromkeys(ids, False)
        for ts_line in self.browse(cursor, user, ids, context=context):
            sheet_ids = sheet_obj.search(cursor, user,
                [('date_to', '>=', ts_line.date), ('date_from', '<=', ts_line.date),
                 ('employee_id.user_id', '=', ts_line.user_id.id),
                 ('state', 'in', ['draft', 'new'])],
                context=context)
            if sheet_ids:
            # [0] because only one sheet possible for an employee between 2 dates
                res[ts_line.id] = sheet_obj.name_get(cursor, user, sheet_ids, context=context)[0]
        return res



        'sheet_id': fields.function(_sheet, string='Sheet',
            type='many2one', relation='hr_timesheet_sheet.sheet',
         
            )



Many2many


'shift_ids':fields.many2many('od.time.slot','od_route_shift_detail_time_slot_relation',
'detail_id','time_slot_id','Shift'),



'promo_products': fields.many2many('product.product', 'callcenter_product_rel','product_id',

'callcenter_id', 'Call Center'),



Many2one



        'user_id': fields.many2one('res.users', 'Salesperson', states={'draft': [('readonly', False)], 'sent': [('readonly', False)]}, select=True, track_visibility='onchange'),



One2many


        'order_line': fields.one2many('sale.order.line', 'order_id', 'Order Lines', readonly=True, states={'draft': [('readonly', False)], 'sent': [('readonly', False)]}, copy=True),


Boolean Field


    'sent':fields.boolean(string='Sent')

Date field


    'date_invoice':fields.date(string='Invoice Date')

Text


        'note': fields.text('Terms and conditions'),

Char


        'name': fields.char('Order Reference', required=True, copy=False,
            readonly=True, states={'draft': [('readonly', False)], 'sent': [('readonly', False)]}, select=True),



        

Saturday, 1 August 2015

XML-RPC Example

Hi All,
    Here am explaining how to use xml-rpc.

    Ex:suppose we need to create a partner


import xmlrpclib
username = 'admin' #the user
pwd = '******'      #the password of the user
dbname = 'db123'    #the database

# Get the uid
sock_common = xmlrpclib.ServerProxy ('http://localhost:1212/xmlrpc/common')
uid = sock_common.login(dbname, username, pwd)

#replace localhost with the address of the server
sock = xmlrpclib.ServerProxy('http://localhost:1212/xmlrpc/object')


values = {
    'name':"Partner1",

    
    }

sock.execute(dbname, uid, pwd, 'res.partner', 'create', values)

Example For Server Action

    Hi all,
         Here am explaining how to trigger an automatic email to immediate manager,while an employee submitting  his/her leave request.


Step1.

 

     Configure out going mail server(already explained in my previous post).


step2.

 

   *)Create a Template for mail

 

    name:template_leave_email
    Applies to:Leave
    subject:Leave Request from [[ object.employee_id.name ]]
    Message:Dear [[object.employee_id.parent_id.name]],
            You have one Leave Request from [[ object.employee_id.name ]].Please see that one.
            Thanking You.
    from:${object.employee_id.work_email}
    To(emails):${object.employee_id.parent_id.work_email}
    Language:${object.partner_id and object.partner_id.lang or ''}
    Outgoing mail server:(localhost)

























   *)Create a server action

 

     Action Name:leave_request_manager
     Base Model:Leave
     Action To Do:Send Email
     Condition:True
     Sequence:5
     Email Template:template_leave_email(select the template we are already created)


step3:Customize the workflow

 

      Setting->Workflows->Workflows->hr.wkf.holidays
      take the confirm button
      and attach our new server action with it.