Thursday, 10 December 2015

XML view Description



Common Structure

View objects expose a number of fields, they are optional unless specified otherwise.
name (mandatory)
only useful as a mnemonic/description of the view when looking for one in a list of some sort
model
the model linked to the view, if applicable (it doesn't for QWeb views)
priority
client programs can request views by id, or by (model, type). For the latter, all the views for the right type and model will be searched, and the one with the lowest priority number will be returned (it is the "default view").
priority also defines the order of application during view inheritance.
arch
the description of the view's layout
groups_id
Many2many field to the groups allowed to view/use the current view
inherit_id
the current view's parent view, see Inheritance, unset by default
mode
inheritance mode, see Inheritance. If inherit_id is unset the mode can only be primary. If inherit_id is set,extension by default but can be explicitly set to primary
application
website feature defining togglable views. By default, views are always applied

Inheritance

View matching

  • if a view is requested by (model, type), the view with the right model and type, mode=primary and the lowest priority is matched
  • when a view is requested by id, if its mode is not primary its closest parent with mode primary is matched

View resolution

Resolution generates the final arch for a requested/matched primary view:
  1. if the view has a parent, the parent is fully resolved then the current view's inheritance specs are applied
  2. if the view has no parent, its arch is used as-is
  3. the current view's children with mode extension are looked up and their inheritance specs are applied depth-first (a child view is applied, then its children, then its siblings)
The result of applying children views yields the final arch

Inheritance specs

There are three types of inheritance specs:
  • An xpath element with an expr attribute. expr is an XPath expression2 applied to the current arch, the first node it finds is the match
  • a field element with a name attribute, matches the first field with the same name
  • any other element, the first element with the same name and identical attributes (ignoring position) is matched
The inheritance spec may have an optional position attribute specifying how the matched node should be altered:
inside (default)
the content of the inheritance spec is appended to the matched node
replace
the content of the inheritance spec replaces the matched node
after
the content of the inheritance spec is added to the matched node's parent, after the matched node
before
the content of the inheritance spec is added to the matched node's parent, before the matched node
attributes
the content of the inheritance spec should be attribute elements with a name attribute and an optional body:
  • if the attribute element has a body, a new attributed named after its name is created on the matched node with theattribute element's text as value
  • if the attribute element has no body, the attribute named after its name is removed from the matched node. If no such attribute exists, an error is raised
A view's specs are applied sequentially.

Lists

The root element of list views is <tree>3. The list view's root can have the following attributes:
editable
by default, selecting a list view's row opens the corresponding form view The editable attributes makes the list view itself editable in-place.
Valid values are top and bottom, making new records appear respectively at the top or bottom of the list.
The architecture for the inline form view is derived from the list view. Most attributes valid on a form view's fields and buttons are thus accepted by list views although they may not have any meaning if the list view is non-editable
default_order
overrides the ordering of the view, replacing the model's default order. The value is a comma-separated list of fields, postfixed by desc to sort in reverse order:
<tree default_order="sequence,name desc">
colors


allows changing the color of a row's text based on the corresponding record's attributes.
Defined as a mapping of colors to Python expressions. Values are of the form: color:expr[;...]. For each record, pairs are tested in order, the expression is evaluated for the record and if true the corresponding color is applied to the row. If no color matches, uses the default text color (black).
  • color can be any valid CSS color unit.
  • expr should be a Python expression evaluated with the current record's attributes as context values. Other context values are uid (the id of the current user) and current_date (the current date as a string of the form yyyy-MM-dd)
fonts
allows changing a row's font style based on the corresponding record's attributes.
The format is the same as for color, but the color of each pair is replaced by bold, italic or underline, the expression evaluating to true will apply the corresponding style to the row's text. Contrary to colors, multiple pairs can match each record
create, edit, delete
allows disabling the corresponding action in the view by setting the corresponding attribute to false
on_write
only makes sense on an editable list. Should be the name of a method on the list's model. The method will be called with the id of a record after having created or edited that record (in database).
The method should return a list of ids of other records to load or update.

Possible children elements of the list view are:
button
displays a button in a list cell
icon
icon to use to display the button
string
  • if there is no icon, the button's text
  • if there is an icon, alt text for the icon
type
type of button, indicates how it clicking it affects Odoo:
workflow (default)
sends a signal to a workflow. The button's name is the workflow signal, the row's record is passed as argument to the signal
object
call a method on the list's model. The button's name is the method, which is called with the current row's record id and the current context.
action
load an execute an ir.actions, the button's name is the database id of the action. The context is expanded with the list's model (as active_model), the current row's record (active_id) and all the records currently loaded in the list (active_ids, may be just a subset of the database records matching the current search)
name
see type
args
see type
attrs
dynamic attributes based on record values.
A mapping of attributes to domains, domains are evaluated in the context of the current row's record, if True the corresponding attribute is set on the cell.
Possible attributes are invisible (hides the button) and readonly (disables the button but still shows it)
states
shorthand for invisible attrs: a list of states, comma separated, requires that the model has a state field and that it is used in the view.
Makes the button invisible if the record is not in one of the listed states
context
merged into the view's context when performing the button's Odoo call
confirm
confirmation message to display (and for the user to accept) before performing the button's Odoo call
field
defines a column where the corresponding field should be displayed for each record. Can use the following attributes:
name
the name of the field to display in the current model. A given name can only be used once per view
string
the title of the field's column (by default, uses the string of the model's field)
invisible
fetches and stores the field, but doesn't display the column in the table. Necessary for fields which shouldn't be displayed but are used by e.g. @colors
groups
lists the groups which should be able to see the field
widget
alternate representations for a field's display. Possible list view values are:
progressbar
displays float fields as a progress bar.
many2onebutton
replaces the m2o field's value by a checkmark if the field is filled, and a cross if it is not
handle
for sequence fields, instead of displaying the field's value just displays a dra&drop icon
sum, avg
displays the corresponding aggregate at the bottom of the column. The aggregation is only computed on currently displayed records. The aggregation operation must match the corresponding field's group_operator
attrs
dynamic attributes based on record values. Only effects the current field, so e.g. invisible will hide the field but leave the same field of other records visible, it will not hide the column itself.

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