Monday 21 December 2015

Calling Function in v7 and v8

   


  def cancel_confirmed(self, cr, uid, ids, context=None):
        obj = self.browse(cr,uid,ids,context)
        active_id = int(obj.active_id)
        active_model = obj.active_model
        reason = obj.reason

     
        if active_model == 'purchase.order':

            self.pool.get('purchase.order').action_cancel(cr,uid,[active_id],context)
            self.pool.get('purchase.order').write(cr,uid,[active_id],{'od_cancel_reason':reason},context)

        elif active_model == 'stock.picking':

            self.pool.get('stock.picking').action_cancel(cr,uid,[active_id],context)
            self.pool.get('stock.picking').write(cr,uid,[active_id],{'od_cancel_reason':reason},context)

        elif active_model == 'sale.order':

            self.pool.get('sale.order').action_cancel(cr, uid, [active_id], context)
            self.pool.get('sale.order').write(cr,uid,[active_id],{'od_cancel_reason':reason},context)

        elif active_model == 'account.voucher':
            self.pool.get('account.voucher').cancel_voucher(cr,uid,[active_id],context)

            self.pool.get('account.voucher').write(cr,uid,[active_id],{'od_cancel_reason':reason},context)


     
        return True


#account invoice written in new api
    @api.multi
    def action_cancel_for_invoice(self):
        active_id = int(self.active_id)
        reason= self.reason
        acco = self.env['account.invoice'].browse(active_id)
        acco.action_cancel()
        acco.write({'od_cancel_reason': reason})
        return True

Wizard Creation

Python

from openerp import models, fields, api
from openerp.tools.translate import _
import openerp.addons.decimal_precision as dp
from datetime import datetime

class od_cancellation_wizard(models.TransientModel):
    _name = 'od.cancellation.wizard'
    _description = 'Cancellation Wizard'

    reason = fields.Text(string='Reason',required="1")
    active_id = fields.Char(string='Form ID')
    active_model = fields.Char(string='Model')
    state = fields.Char('State')

    def default_get(self, cr, uid, fields, context=None):
        res = super(od_cancellation_wizard, self).default_get(cr, uid, fields, context=context)
        active_id = context.get('active_ids', [])
        state = ''
        active_model = context.get('active_model')
        if active_model == 'sale.order':
            state = self.pool.get('sale.order').browse(cr,uid,active_id,context).state
            res.update({'active_id': active_id,'active_model':active_model,'state':state})

        elif active_model == 'purchase.order':
            state = self.pool.get('purchase.order').browse(cr,uid,active_id,context).state
            res.update({'active_id': active_id,'active_model':active_model,'state':state})

        elif active_model == 'stock.picking':
            state = self.pool.get('stock.picking').browse(cr,uid,active_id,context).state
            res.update({'active_id': active_id,'active_model':active_model,'state':state})

        elif active_model == 'account.invoice':

            state = self.pool.get('account.invoice').browse(cr,uid,active_id,context).state
            res.update({'active_id': active_id,'active_model':active_model,'state':state})


        elif active_model == 'account.voucher':

            state = self.pool.get('account.voucher').browse(cr,uid,active_id,context).state
            res.update({'active_id': active_id,'active_model':active_model,'state':state})



     
        return res
    def cancel(self, cr, uid, ids, context=None):
        obj = self.browse(cr,uid,ids,context)
        active_id = int(obj.active_id)
        active_model = obj.active_model
        reason = obj.reason
        if active_model == 'sale.order':
            self.pool.get('sale.order').write(cr,uid,[active_id],{'state':'cancel','od_cancel_reason':reason},context)

        elif active_model == 'purchase.order':

            self.pool.get('purchase.order').action_cancel(cr,uid,[active_id],context)
            self.pool.get('purchase.order').write(cr,uid,[active_id],{'od_cancel_reason':reason},context)
        elif active_model == 'stock.picking':

            self.pool.get('stock.picking').action_cancel(cr,uid,[active_id],context)
            self.pool.get('stock.picking').write(cr,uid,[active_id],{'od_cancel_reason':reason},context)


        elif active_model == 'account.voucher':
            self.pool.get('account.voucher').cancel_voucher(cr,uid,[active_id],context)

            self.pool.get('account.voucher').write(cr,uid,[active_id],{'od_cancel_reason':reason},context)


     
        return True
    def cancel_confirmed(self, cr, uid, ids, context=None):
        obj = self.browse(cr,uid,ids,context)
        active_id = int(obj.active_id)
        active_model = obj.active_model
        reason = obj.reason

     
        if active_model == 'purchase.order':

            self.pool.get('purchase.order').action_cancel(cr,uid,[active_id],context)
            self.pool.get('purchase.order').write(cr,uid,[active_id],{'od_cancel_reason':reason},context)

        elif active_model == 'stock.picking':

            self.pool.get('stock.picking').action_cancel(cr,uid,[active_id],context)
            self.pool.get('stock.picking').write(cr,uid,[active_id],{'od_cancel_reason':reason},context)

        elif active_model == 'sale.order':

            self.pool.get('sale.order').action_cancel(cr, uid, [active_id], context)
            self.pool.get('sale.order').write(cr,uid,[active_id],{'od_cancel_reason':reason},context)

        elif active_model == 'account.voucher':
            self.pool.get('account.voucher').cancel_voucher(cr,uid,[active_id],context)

            self.pool.get('account.voucher').write(cr,uid,[active_id],{'od_cancel_reason':reason},context)


     
        return True



    @api.multi
    def action_cancel_for_invoice(self):
        active_id = int(self.active_id)
        reason= self.reason
        acco = self.env['account.invoice'].browse(active_id)
        acco.action_cancel()
        acco.write({'od_cancel_reason': reason})
        return True


XML



<?xml version="1.0" encoding="UTF-8"?>
<openerp>
    <data>
        <record id="od_view_cancellation_wizard_form" model="ir.ui.view">
            <field name="name">Cancellation Reason</field>
            <field name="model">od.cancellation.wizard</field>
            <field name="arch" type="xml">
                <form string="Transfer details" >

                <p style="color:blue;font-size:10pt;">
                    Enter the cancellation reason for this document.
                </p>
                <group>
                    <field name="reason" nolabel="1" placeholder="Type Here...."/>
                    <field name="active_id" invisible="1"/>
                    <field name="active_model" invisible="1"/>
                    <field name="state" invisible="1"/>
                </group>
                    <footer>
                <p style="color:red;font-size:10pt;">
                    Are you sure you want to cancel this document?
           
                        <button name="cancel" string="Yes" type="object"  attrs="{'invisible': ['|',('state', '!=', 'draft'),('active_model', '=', 'account.invoice')]}" class="oe_link"/>
                        <button name="cancel_confirmed" string="Yes" type="object" class="oe_link" attrs="{'invisible': ['|',('state', '=', 'draft'),('active_model', '=', 'account.invoice')]}" />

                        <button name="action_cancel_for_invoice" string="Yes" type="object"  attrs="{'invisible': [('active_model','!=','account.invoice')]}" class="oe_link"/>

                        or
                        <button string="No"  class="oe_link" special="cancel"/>

                   </p>
                    </footer>


                 
               
                </form>
            </field>
        </record>




        <record id="action_od_view_cancellation_wizard" model="ir.actions.act_window">
            <field name="name">Cancellation Reason</field>
            <field name="type">ir.actions.act_window</field>
            <field name="res_model">od.cancellation.wizard</field>
            <field name="view_type">form</field>
            <field name="view_mode">form</field>
            <field name="view_id" ref="od_view_cancellation_wizard_form"/>
            <field name="target">new</field>
        </record>





    </data>

</openerp>


Button

       <button name="%(action_od_view_cancellation_wizard)d" states="manual,progress" string="Cancel Order" type="action" groups="base.group_user"/>


    def action_add(self, cr, uid, ids, context=None):
        context['mo_id'] = ids[0]


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


 <button name="action_add" string="Consumption" icon="STOCK_ADD" type="object"/>

Sunday 20 December 2015

How to defaultly create invoice at the time of transferring





class stock_picking(models.Model):
    _inherit = "stock.picking"




    @api.cr_uid_ids_context
    def do_transfer(self, cr, uid, picking_ids, context=None):
        res = super(stock_picking,self).do_transfer(cr, uid, picking_ids, context)
        inv_type = ''
        picking_pool = self.pool.get('stock.picking')
        pickings = picking_pool.browse(cr, uid, picking_ids[0], context=context)
        pick = pickings and pickings[0]
        if not pick or not pick.move_lines:
            return 'sale'
        type = pick.picking_type_id.code
        usage = pick.move_lines[0].location_id.usage if type == 'incoming' else pick.move_lines[0].location_dest_id.usage

        journal_type = JOURNAL_TYPE_MAP.get((type, usage), ['sale'])[0] or 'out_invoice'
        if journal_type == 'sale':
            inv_type = 'out_invoice'
        elif journal_type == 'purchase':
            inv_type = 'in_invoice'

        elif journal_type == 'sale_refund':
            inv_type = 'out_refund'
        else:
            inv_type = 'in_refund'
                               
        journal_obj = self.pool.get('account.journal')
        journals = journal_obj.search(cr, uid, [('type', '=', journal_type)])
        journal_id = journals and journals[0]
        picking_pool.action_invoice_create(cr, uid, picking_ids,
              journal_id = journal_id,
              group = False,
              type = inv_type,
              context=context)
   
        return res

Thursday 17 December 2015

Sending Mail Functionality When Clicking Button





   

def od_discount_approved(self, cr, uid, ids, context=None):
         self.write(cr,uid,ids,{'od_sales_man_discount_ctrl':False},context)
                               self.od_send_mail(cr,uid,ids,'rso_disc_approved_mail_to_salesperson',context=context)
        return True



    def od_send_mail(self,cr,uid,ids,template,context=None):
       
        ir_model_data = self.pool['ir.model.data']
        email_obj = self.pool.get('email.template')
        template_id = ir_model_data.get_object_reference(cr,uid,'orchid_rso', template)[1]
        sale_id = self.browse(cr,uid,ids,context) and self.browse(cr,uid,ids,context).id
        email_obj.send_mail(cr,uid,template_id,sale_id, force_send=True)
        return True



Through default data loading technic,you can create a template.



<record id="task_reviewer_mail" model="email.template">
            <field name="name">Task Reviewer Mail</field>
            <field name="email_from">${(user.email or '')|safe}</field>
            <field name="subject">Task</field>
            <field name="email_to">${object.reviewer_id.email}</field>
            <field name="model_id" ref="project.model_project_task"/>
          
            <field name="body_html"><![CDATA[
                <div style="font-family: 'Lucica Grande', Ubuntu, Arial, Verdana, sans-serif; font-size: 12px; color: rgb(34, 34, 34); background-color: #FFF; ">
                    <p>Dear ${object.reviewer_id.name or 'Reviewer'},</p>
                    <p>Please Check The task</p>
                  
                    <p>Thank You</p>
                   
                </div>           
            ]]></field>
        </record>
       
       
        <record id="task_creation_auto_mail_customer" model="email.template">
            <field name="name">Task Customer Mail</field>
            <field name="email_from">${(user.email or '')|safe}</field>
            <field name="subject">Task To Customer</field>
            <field name="email_to">${object.partner_id.email}</field>
            <field name="model_id" ref="project.model_project_task"/>
          
            <field name="body_html"><![CDATA[
                <div style="font-family: 'Lucica Grande', Ubuntu, Arial, Verdana, sans-serif; font-size: 12px; color: rgb(34, 34, 34); background-color: #FFF; ">
                    <p>Dear ${object.partner_id.name or 'Customer'},</p>
                    <p>Please Check</p>
                  
                    <p>Thank You</p>
                   
                </div>           
            ]]></field>
        </record>
       

        <record id="lead_to_opportunity_mail" model="email.template">
            <field name="name">Lead To Opportunity Mail</field>
            <field name="email_from">${(user.email or '')|safe}</field>
            <field name="subject">Lead To Opportunity</field>
            <field name="email_to">test@gmail.com</field>
            <field name="model_id" ref="crm.model_crm_lead"/>
          
            <field name="body_html"><![CDATA[
                <div style="font-family: 'Lucica Grande', Ubuntu, Arial, Verdana, sans-serif; font-size: 12px; color: rgb(34, 34, 34); background-color: #FFF; ">
                    <p>Dear ,</p>
                    <p>Please Check The task</p>
                  
                    <p>Thank You</p>
                   
                </div>           
            ]]></field>
        </record>





        <record id="disc_approved_mail_to_salesperson" model="email.template">
            <field name="name">Disc Approved Mail to Salesman</field>
            <field name="email_from">${(user.email or '')|safe}</field>
            <field name="subject">Discount Approved</field>
            <field name="email_to">test@gmail.com</field>
            <field name="model_id" ref="sale.model_sale_order"/>
          
            <field name="body_html"><![CDATA[
                <div style="font-family: 'Lucica Grande', Ubuntu, Arial, Verdana, sans-serif; font-size: 12px; color: rgb(34, 34, 34); background-color: #FFF; ">
                    <p>$Dear ${object.user_id.name or 'Salesman'},</p>
                    <p>Quotation No:${object.name or 'Quotation'}</p>
                  
                    <p>Thank You</p>
                   
                </div>           
            ]]></field>
        </record

Wednesday 16 December 2015

Constriants In Odoo

SQL Constraints


_sql_constraints = [
('name_uniq', 'unique(name, company_id)', 'Order Reference must be unique per Company!'),
]


V7 Constriants


def _check_duration(self, cr, uid, ids, context=None):
obj_fy = self.browse(cr, uid, ids[0], context=context)
    if obj_fy.date_stop < obj_fy.date_start:
        return False
    return True

_constraints = [
(_check_duration, 'Error!\nThe start date of a fiscal year must precede its end date.', ['date_start','date_stop'])
    ]


V8 Constriants

Example1


@api.multi
@api.one
@api.constrains('stage_id','user_id')
def _check_constriant(self):
stage_id = self.stage_id
stage_type = stage_id.stage_type
stage_ids = self.env['od.project.task.stages'].search([('stage_type', '=', 'progress')])
project_task_ids = self.env['od.project.task'].search([('user_id', '=', self.user_id.id),('stage_id', 'in', [x.id for x in stage_ids])])
if len(project_task_ids) >1:
            raise Warning(_("Job already assigned, %s"))




@api.multi
@api.one
@api.constrains('stage_id','user_id')
def _check_constriant(self):
stage_id = self.stage_id
stage_type = stage_id.stage_type
stage_ids = self.env['od.project.task.stages'].search([('stage_type', '=', 'progress')])
project_task_ids = self.env['od.project.task'].search([('user_id', '=', self.user_id.id),('stage_id', 'in', [x.id for x in stage_ids])])
if len(project_task_ids) >1:
raise Warning(_("Job already assigned, %s"))


Example2

@api.multi
@api.one
@api.constrains('date_from','date_to','fiscalyear_id')
def _check_month(self):
fiscalyear_id = self.fiscalyear_id.id
fiscal_year_obj = self.env['account.fiscalyear'].browse(fiscalyear_id)
date_start = fiscal_year_obj.date_start
date_stop = fiscal_year_obj.date_stop
date_from = self.date_from
date_to = self.date_to
if date_start<= date_from <=date_stop and date_start<= date_to <=date_stop:
print "date_start"
else:
raise Warning(_("Date From or Date To Is Not In The Fiscal Year,Please Enter Proper Dates %s") % self.date_to,self.date_from)
date_from =str(date_from)
date_to = str(date_to)
date_from = datetime.datetime.strptime(date_from, '%Y-%m-%d')
date_to = datetime.datetime.strptime(date_to, "%Y-%m-%d")
diff = (12 * date_to.year + date_to.month) - (12 * date_from.year + date_from.month)
if diff == 0:
raise Warning(_("If You Want To Check Current Month Target,Please Put Date To As First Day Of Next Month %s") % self.date_to)
elif diff < 1:
            raise Warning(_("Invalid Date,Date To is Less Than Date From, %s") % self.date_to)  



Onchange We Can Create Lines

    In version 7.0 we cant create lines at the time of onchange,because we cant take the current form id,but 8.0 we can call it as self.id




    @api.multi
    def onchange_task_id(self, task_id):
        result = {}
        k =[]
        if task_id:
            obj =  self.env['project.task'].browse(task_id)
            for material in obj.lease_facilities_lines:
         
                vals = {
                        'order_id':self.id,
                        'product_id':material.product_id.id,
                        'name':material.product_id.name,
                        'price_unit':material.unit_price * material.hours,
                        'product_uom_qty':material.qty,
                        'od_date_from':material.from_date,
                        'od_date_to':material.to_date,
                        'product_uom':material.product_id.uom_id and material.product_id.uom_id.id,
                        'state': 'draft',
                        'od_month':material.hours
                }
                k.append(vals)

Saturday 12 December 2015

Some Useful Widgets in XML


Image

<field name="image" widget="image" class="oe_right" nolabel="1" img_width="150" img_height="200" width="150" height="300"/>


Two Fields In Same Line


                               <label for="readability"/>
                                <div>
                                    <field name="readability"
                                        on_change="onchange_accuracy_class_id(accuracy_class_id,                                                        readability,max_capacity)"
                                        class="oe_inline"/>
                                    <field name="uom_id" groups="product.group_uom" class="oe_inline" placeholder="UOM"/>

                                </div>

Many2many Widget


<field name="shift_ids" widget="many2many_tags"/>


Place holder


<field name="description" class="oe_inline" nolabel="1" placeholder="Put an internal note..."/>



Title Field




    <record model="ir.ui.view" id="od_hr_document_type_view_form">
        <field name="name">od.hr.document.type</field>
        <field name="model">od.hr.document.type</field>
        <field name="arch" type="xml">
            <form string="Hr Document Type">
           <sheet>
               <div class="oe_title">
                            <label for="name" class="oe_edit_only"/>
                            <h1>
                                <field name="name"/>
                             
                            </h1>
                        </div>
          <group col="4">
               <field name="code"/>
        </group>

          </sheet>
            </form>
      </field>

    </record>


Smart Buttons



<div class="oe_right oe_button_box">
                              <button class="oe_inline oe_stat_button" name="action_view_brand" string="Brand" type="object" icon="fa-strikethrough">
                               </button>

                              <button class="oe_inline oe_stat_button" name="action_view_product"                                         type="object"
                              icon="fa-refresh" string="Product"/>
                              <button class="oe_inline oe_stat_button" name="action_view_saleman"                                       type="object"
                              icon="fa-refresh" string="Saleman"/>
                              <button class="oe_inline oe_stat_button" name="action_view_category"                                       type="object"
                              icon="fa-refresh" string="Category"/>
                              <button class="oe_inline oe_stat_button" name="action_view_customer"                                     type="object"
                              icon="fa-refresh" string="Customer"/>
                              <button class="oe_inline oe_stat_button" name="action_view_supplier"                                       type="object"
                              icon="fa-refresh" string="Supplier"/>

  </div>


Tree Colour Giving


<tree string="Unit" colors="blue:status_date &gt;status_next_date ; red:status_date &gt; current_date and status_date &lt; status_next_date;">


Separator


<separator string="Allocation Method"/>


Action View Domain Giving



<record id="od_action_move_line" model="ir.actions.act_window">
            <field name="name">Stock Moves</field>
            <field name="res_model">stock.move</field>
            <field eval="30" name="priority"/>
            <field name="type">ir.actions.act_window</field>
            <field name="view_type">form</field>
            <field name="view_id" ref="od_view_move_picking_tree"/>
            <field name="context">{}</field>
            <field name="domain">[('raw_material_production_id','!=',False)]</field>
            <field name="help" type="html">
              <p class="oe_view_nocontent_create">
                Click to create a stock movement.
              </p><p>
                This menu gives you the full traceability of inventory
                operations on a specific product. You can filter on the product
                to see all the past or future movements for the product.
              </p>
            </field>

        </record>


Attrs


<field name="p9_amount" attrs="{'invisible': [('period_type','in',('half','yearly'))]}"/>


<field name="p1_qty" attrs="{'invisible': ['|',('distribution_type','in',
('brand','category','saleman','customer','supplier')),('period_type','in',
('quaterly','half','yearly'))]}"/>


Color For A Field


<field name=”your_field_name” style=”color:green;font-size:28pt;”/>


                <p style="color:red;font-size:10pt;">
                    Are you sure you want to cancel this document?
             
                        <button name="cancel" string="Yes" type="object"  attrs="{'invisible': ['|',('state', '!=', 'draft'),('active_model', '=', 'account.invoice')]}" class="oe_link"/>
                        <button name="cancel_confirmed" string="Yes" type="object" class="oe_link" attrs="{'invisible': ['|',('state', '=', 'draft'),('active_model', '=', 'account.invoice')]}" />

                        <button name="action_cancel_for_invoice" string="Yes" type="object"  attrs="{'invisible': [('active_model','!=','account.invoice')]}" class="oe_link"/>

                        or
                        <button string="No"  class="oe_link" special="cancel"/>

                   </p>


Color For State Field


                   <header>
                    <field name="state" widget="statusbar" statusbar_visible="draft,confirm,done" statusbar_colors='{"cancel":"red","draft":"blue"}'/>
                    </header>


Double Inheriting Procedure


           <record id="od_office_project_view_inherited_from_orchid_rso" model="ir.ui.view">
            <field name="name">project.task.orchid.inherited</field>
            <field name="model">project.task</field>
            <field name="inherit_id" ref="orchid_office.view_task_form_in_orchid_office"/>
            <field name="arch" type="xml">
                               <xpath expr="//field[@name='od_task_type']" position="replace">
                      <field name="od_task_type" required="1"/>
                </xpath>
            </field>

            </record>


Footer

       <footer>
                <button string="Generate" name="action_move_create" type="object" class="oe_highlight"/> or
                <button string="Cancel" class="oe_link" special="cancel" />

       </footer>


Xpath


Example1:


<xpath expr="/form/sheet/notebook/page[@string='Order Lines']/field[@name='order_line']/tree/field[@name='price_unit']" position="after">


Example2:



 <xpath expr="/form[@string='Produce']/group[@string='To Consume']/field[@name='consume_lines']/tree[@string='Consume Lines']/field[@name='product_id']" position="after">
                <field name="product_uom"/>
                </xpath>

Example3:


 <xpath expr="/form[@string='Produce']/group[@string='To Consume']/field[@name='consume_lines']/tree[@string='Consume Lines']/field[@name='product_qty']" position="after">
                  <field name="location_id"/>
                  <field name="cost_price"/>

                </xpath>

Red Color for Button

class="oe_highlight"


Default Value For Field


<field name="category_line" context="{'default_distribution_type':'category'}">


Footer Right Setting


<group>
     <group class="oe_subtotal_footer oe_right">
           <field name="od_sub_total"/>
           <field name="od_discount"/>
           <field name="od_total"/>
     </group>
</group>


Graph View Default Measure



<field name="net_salary" type="measure"/>

Hide Create Button and Edit Button


<form string="Target Brand" version="7.0" create="false" edit="false">


Group Arrangements


<group>
       <group>
                <label for="name" class="oe_edit_only"/>
                <h2><field name="name"/></h2>
                             
                         
                 <label for="code"/>
                 <h2><field name="code"/></h2>
       </group>
     

        <group></group>
                 

</group>


Iframe Adding

                        <page string="openerp">
  <iframe marginheight="0" marginwidth="0" frameborder = "0"
                src="https://www.odoo.com/forum/help-1/question/adding-i-frame-in-openerp-34242" width="100%" height="1000"/>
                            </page>


Readonly Class

class="oe_read_only"