rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
'res_id': res_id,
'domain' : "[('id','=',%d)]"%(res_id),
def open_document(self, cr, uid, ids, context): """ To Open Document @param self: The object pointer. @param cr: A database cursor @param uid: ID of the user currently logged in @param ids: the ID of messages @param context: A standard dictionary """ action_data = False if ids: message_id = ids[0] mailgate_data = self.browse(cr, uid, message_id) model = mailgate_data.model res_id = mailgate_data.res_id
tax_ids = self.pool.get('account.tax').search(cr, uid, [('company_id', '=', company_id)])
def product_id_change(self, cr, uid, ids, product, uom, qty=0, name='', type='out_invoice', partner_id=False, fposition_id=False, price_unit=False, address_invoice_id=False, currency_id=False, context=None): if context is None: context = {} company_id = context.get('company_id',False) if not partner_id: raise osv.except_osv(_('No Partner Defined !'),_("You must first select a partner !") ) if not product: if type in ('in_invoice', 'in_refund'): return {'value': {'categ_id': False}, 'domain':{'product_uom':[]}} else: return {'value': {'price_unit': 0.0, 'categ_id': False}, 'domain':{'product_uom':[]}} part = self.pool.get('res.partner').browse(cr, uid, partner_id) fpos_obj = self.pool.get('account.fiscal.position') fpos = fposition_id and fpos_obj.browse(cr, uid, fposition_id) or False
taxes = res.taxes_id and res.taxes_id or (a and self.pool.get('account.account').browse(cr, uid, a).tax_ids or False) tax_id = fpos_obj.map_tax(cr, uid, fpos, taxes)
def_sale_taxes = map(lambda x: x.id, res.taxes_id) sale_tax_list = [tax for tax in tax_ids if tax in def_sale_taxes] sale_tax_id = self.pool.get('account.tax').browse(cr, uid, sale_tax_list) sale_taxes = sale_tax_id and sale_tax_id or (a and self.pool.get('account.account').browse(cr, uid, a).tax_ids or False) tax_id = fpos_obj.map_tax(cr, uid, fpos, sale_taxes)
def product_id_change(self, cr, uid, ids, product, uom, qty=0, name='', type='out_invoice', partner_id=False, fposition_id=False, price_unit=False, address_invoice_id=False, currency_id=False, context=None): if context is None: context = {} company_id = context.get('company_id',False) if not partner_id: raise osv.except_osv(_('No Partner Defined !'),_("You must first select a partner !") ) if not product: if type in ('in_invoice', 'in_refund'): return {'value': {'categ_id': False}, 'domain':{'product_uom':[]}} else: return {'value': {'price_unit': 0.0, 'categ_id': False}, 'domain':{'product_uom':[]}} part = self.pool.get('res.partner').browse(cr, uid, partner_id) fpos_obj = self.pool.get('account.fiscal.position') fpos = fposition_id and fpos_obj.browse(cr, uid, fposition_id) or False
taxes = res.supplier_taxes_id and res.supplier_taxes_id or (a and self.pool.get('account.account').browse(cr, uid, a).tax_ids or False) tax_id = fpos_obj.map_tax(cr, uid, fpos, taxes)
def_pur_taxes = map(lambda x: x.id, res.supplier_taxes_id) pur_tax_list = [tax for tax in tax_ids if tax in def_pur_taxes] pur_tax_id = self.pool.get('account.tax').browse(cr, uid, pur_tax_list) pur_taxes = pur_tax_id and pur_tax_id or (a and self.pool.get('account.account').browse(cr, uid, a).tax_ids or False) tax_id = fpos_obj.map_tax(cr, uid, fpos, pur_taxes)
def product_id_change(self, cr, uid, ids, product, uom, qty=0, name='', type='out_invoice', partner_id=False, fposition_id=False, price_unit=False, address_invoice_id=False, currency_id=False, context=None): if context is None: context = {} company_id = context.get('company_id',False) if not partner_id: raise osv.except_osv(_('No Partner Defined !'),_("You must first select a partner !") ) if not product: if type in ('in_invoice', 'in_refund'): return {'value': {'categ_id': False}, 'domain':{'product_uom':[]}} else: return {'value': {'price_unit': 0.0, 'categ_id': False}, 'domain':{'product_uom':[]}} part = self.pool.get('res.partner').browse(cr, uid, partner_id) fpos_obj = self.pool.get('account.fiscal.position') fpos = fposition_id and fpos_obj.browse(cr, uid, fposition_id) or False
'padding': 3
'padding': 3, 'company_id': company_id.id
def generate_configurable_chart(self, cr, uid, ids, context=None): obj_acc = self.pool.get('account.account') obj_acc_tax = self.pool.get('account.tax') obj_journal = self.pool.get('account.journal') obj_acc_tax_code = self.pool.get('account.tax.code') obj_acc_template = self.pool.get('account.account.template') obj_acc_tax_template = self.pool.get('account.tax.code.template') obj_fiscal_position_template = self.pool.get('account.fiscal.position.template') obj_fiscal_position = self.pool.get('account.fiscal.position') analytic_journal_obj = self.pool.get('account.analytic.journal') obj_acc_chart_template = self.pool.get('account.chart.template') obj_acc_journal_view = self.pool.get('account.journal.view') mod_obj = self.pool.get('ir.model.data') obj_sequence = self.pool.get('ir.sequence') property_obj = self.pool.get('ir.property') fields_obj = self.pool.get('ir.model.fields') obj_tax_fp = self.pool.get('account.fiscal.position.tax') obj_ac_fp = self.pool.get('account.fiscal.position.account')
'analytic_journal_id': analitical_journal_sale
'analytic_journal_id': analitical_journal_sale, 'company_id': company_id.id
def generate_configurable_chart(self, cr, uid, ids, context=None): obj_acc = self.pool.get('account.account') obj_acc_tax = self.pool.get('account.tax') obj_journal = self.pool.get('account.journal') obj_acc_tax_code = self.pool.get('account.tax.code') obj_acc_template = self.pool.get('account.account.template') obj_acc_tax_template = self.pool.get('account.tax.code.template') obj_fiscal_position_template = self.pool.get('account.fiscal.position.template') obj_fiscal_position = self.pool.get('account.fiscal.position') analytic_journal_obj = self.pool.get('account.analytic.journal') obj_acc_chart_template = self.pool.get('account.chart.template') obj_acc_journal_view = self.pool.get('account.journal.view') mod_obj = self.pool.get('ir.model.data') obj_sequence = self.pool.get('ir.sequence') property_obj = self.pool.get('ir.property') fields_obj = self.pool.get('ir.model.fields') obj_tax_fp = self.pool.get('account.fiscal.position.tax') obj_ac_fp = self.pool.get('account.fiscal.position.account')
'analytic_journal_id': analitical_journal_purchase
'analytic_journal_id': analitical_journal_purchase, 'company_id': company_id.id
def generate_configurable_chart(self, cr, uid, ids, context=None): obj_acc = self.pool.get('account.account') obj_acc_tax = self.pool.get('account.tax') obj_journal = self.pool.get('account.journal') obj_acc_tax_code = self.pool.get('account.tax.code') obj_acc_template = self.pool.get('account.account.template') obj_acc_tax_template = self.pool.get('account.tax.code.template') obj_fiscal_position_template = self.pool.get('account.fiscal.position.template') obj_fiscal_position = self.pool.get('account.fiscal.position') analytic_journal_obj = self.pool.get('account.analytic.journal') obj_acc_chart_template = self.pool.get('account.chart.template') obj_acc_journal_view = self.pool.get('account.journal.view') mod_obj = self.pool.get('ir.model.data') obj_sequence = self.pool.get('ir.sequence') property_obj = self.pool.get('ir.property') fields_obj = self.pool.get('ir.model.fields') obj_tax_fp = self.pool.get('account.fiscal.position.tax') obj_ac_fp = self.pool.get('account.fiscal.position.account')
acc = l.product_id.product_tmpl_id.property_account_expense.id
acc = l.product_id.product_tmpl_id.property_account_expense
def action_invoice_create(self, cr, uid, ids): res = False invoice_obj = self.pool.get('account.invoice') for exp in self.browse(cr, uid, ids): lines = [] for l in exp.line_ids: tax_id = [] if l.product_id: acc = l.product_id.product_tmpl_id.property_account_expense.id if not acc: acc = l.product_id.categ_id.property_account_expense_categ.id tax_id = [x.id for x in l.product_id.supplier_taxes_id] else: acc = self.pool.get('ir.property').get(cr, uid, 'property_account_expense_categ', 'product.category') if not acc: raise osv.except_osv(_('Error !'), _('Please configure Default Expanse account for Product purchase, `property_account_expense_categ`'))
acc = l.product_id.categ_id.property_account_expense_categ.id
acc = l.product_id.categ_id.property_account_expense_categ
def action_invoice_create(self, cr, uid, ids): res = False invoice_obj = self.pool.get('account.invoice') for exp in self.browse(cr, uid, ids): lines = [] for l in exp.line_ids: tax_id = [] if l.product_id: acc = l.product_id.product_tmpl_id.property_account_expense.id if not acc: acc = l.product_id.categ_id.property_account_expense_categ.id tax_id = [x.id for x in l.product_id.supplier_taxes_id] else: acc = self.pool.get('ir.property').get(cr, uid, 'property_account_expense_categ', 'product.category') if not acc: raise osv.except_osv(_('Error !'), _('Please configure Default Expanse account for Product purchase, `property_account_expense_categ`'))
freq='' if freq == 'None':
freq=datas.get('rrule_type') if freq == 'none':
def compute_rule_string(self, cr, uid, datas, context=None, *args): """ Compute rule string according to value type RECUR of iCalendar from the values given. @param self: the object pointer @param cr: the current row, from the database cursor, @param uid: the current user’s ID for security checks, @param datas: dictionary of freq and interval value. @param context: A standard dictionary for contextual values @return: String value of the format RECUR of iCalendar """
if datas.get('rrule_type')=='daily_working': freq ='weekly' else: freq=datas.get('rrule_type')
def compute_rule_string(self, cr, uid, datas, context=None, *args): """ Compute rule string according to value type RECUR of iCalendar from the values given. @param self: the object pointer @param cr: the current row, from the database cursor, @param uid: the current user’s ID for security checks, @param datas: dictionary of freq and interval value. @param context: A standard dictionary for contextual values @return: String value of the format RECUR of iCalendar """
['date', 'rdates', 'rrule', 'exdate']):
['date', 'rrule', 'exdate']):
def unlink(self, cr, uid, ids, context=None): for id in ids: if len(str(id).split('-')) > 1: date_new = time.strftime("%Y-%m-%d %H:%M:%S", \ time.strptime(str(str(id).split('-')[1]), "%Y%m%d%H%M%S")) for record in self.read(cr, uid, [common.caldevIDs2readIDs(id)], \ ['date', 'rdates', 'rrule', 'exdate']): if record['rrule']: exdate = (record['exdate'] and (record['exdate'] + ',' ) or '') + \ ''.join((re.compile('\d')).findall(date_new)) + 'Z' if record['date'] == date_new: self.write(cr, uid, [common.caldevIDs2readIDs(id)], {'exdate' : exdate}) else: ids = map(lambda x:common.caldevIDs2readIDs(x), ids) return super(crm_meeting, self).unlink(cr, uid, common.caldevIDs2readIDs(ids)) else: return super(crm_meeting, self).unlink(cr, uid, ids)
if partner.membership_state != 'canceled': res[partner.id] = False else:
res[partner.id] = False if partner.membership_state == 'canceled':
def _membership_cancel(self, cr, uid, ids, name, args, context=None): '''Return the cancel date of membership''' res = {} member_line_obj = self.pool.get('membership.membership_line') for partner in self.browse(cr, uid, ids, context=context): if partner.membership_state != 'canceled': res[partner.id] = False else: line_id = member_line_obj.search(cr, uid, [('partner', '=', partner.id)],limit=1, order='date_cancel') if line_id: res[partner.id] = member_line_obj.read(cr, uid, line_id[0],['date_cancel'])['date_cancel'] else: res[partner.id] = False return res
else: res[partner.id] = False
def _membership_cancel(self, cr, uid, ids, name, args, context=None): '''Return the cancel date of membership''' res = {} member_line_obj = self.pool.get('membership.membership_line') for partner in self.browse(cr, uid, ids, context=context): if partner.membership_state != 'canceled': res[partner.id] = False else: line_id = member_line_obj.search(cr, uid, [('partner', '=', partner.id)],limit=1, order='date_cancel') if line_id: res[partner.id] = member_line_obj.read(cr, uid, line_id[0],['date_cancel'])['date_cancel'] else: res[partner.id] = False return res
'account.invoice':(_get_invoice_partner,['state'], 10),
'account.invoice':(_get_invoice_partner,['state'], 11),
def _get_partners(self, cr, uid, ids, context={}): ids2 = ids while ids2: ids2 = self.search(cr, uid, [('associate_member','in',ids2)], context=context) ids+=ids2 return ids
'sale':[('type','in',['sale','purchase_refund'])], 'purchase':[('type','in',['purchase','sale_refund'])],
'sale':[('type','in',['sale','sale_refund'])], 'purchase':[('type','in',['purchase','purchase_refund'])],
def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False, submenu=False): """ Returns views and fields for current model where view will depend on {view_type}. @param view_id: list of fields, which required to read signatures @param view_type: defines a view type. it can be one of (form, tree, graph, calender, gantt, search, mdx) @param context: context arguments, like lang, time zone @param toolbar: contains a list of reports, wizards, and links related to current model @return: Returns a dict that contains definition for fields, views, and toolbars """ data_pool = self.pool.get('ir.model.data') journal_pool = self.pool.get('account.journal') voucher_type = { 'sale':'view_sale_receipt_form', 'purchase':'view_purchase_receipt_form', 'payment':'view_vendor_payment_form', 'receipt':'view_vendor_receipt_form' } if view_type == 'form': tview = voucher_type.get(context.get('type')) tview = tview or 'view_voucher_form' result = data_pool._get_id(cr, uid, 'account_voucher', tview) view_id = data_pool.browse(cr, uid, result, context=context).res_id res = super(account_voucher, self).fields_view_get(cr, uid, view_id, view_type, context, toolbar, submenu) #Restrict the list of journal view in search view if view_type == 'search': type_search = { 'bank':[('type','in',['bank','cash'])], 'cash':[('type','in',['bank','cash'])], 'sale':[('type','in',['sale','purchase_refund'])], 'purchase':[('type','in',['purchase','sale_refund'])], 'expense':[('type','in',['purchase'])], 'sale_refund':[('type','in',['sale','purchase_refund'])], 'purchase_refund':[('type','in',['purchase','sale_refund'])] } domain = type_search.get(context.get('journal_type')) journal_list = journal_pool.name_search(cr, uid, '', domain) res['fields']['journal_id']['selection'] = journal_list return res
'sale_refund':[('type','in',['sale','purchase_refund'])], 'purchase_refund':[('type','in',['purchase','sale_refund'])]
'sale_refund':[('type','in',['sale','sale_refund'])], 'purchase_refund':[('type','in',['purchase','purchase_refund'])]
def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False, submenu=False): """ Returns views and fields for current model where view will depend on {view_type}. @param view_id: list of fields, which required to read signatures @param view_type: defines a view type. it can be one of (form, tree, graph, calender, gantt, search, mdx) @param context: context arguments, like lang, time zone @param toolbar: contains a list of reports, wizards, and links related to current model @return: Returns a dict that contains definition for fields, views, and toolbars """ data_pool = self.pool.get('ir.model.data') journal_pool = self.pool.get('account.journal') voucher_type = { 'sale':'view_sale_receipt_form', 'purchase':'view_purchase_receipt_form', 'payment':'view_vendor_payment_form', 'receipt':'view_vendor_receipt_form' } if view_type == 'form': tview = voucher_type.get(context.get('type')) tview = tview or 'view_voucher_form' result = data_pool._get_id(cr, uid, 'account_voucher', tview) view_id = data_pool.browse(cr, uid, result, context=context).res_id res = super(account_voucher, self).fields_view_get(cr, uid, view_id, view_type, context, toolbar, submenu) #Restrict the list of journal view in search view if view_type == 'search': type_search = { 'bank':[('type','in',['bank','cash'])], 'cash':[('type','in',['bank','cash'])], 'sale':[('type','in',['sale','purchase_refund'])], 'purchase':[('type','in',['purchase','sale_refund'])], 'expense':[('type','in',['purchase'])], 'sale_refund':[('type','in',['sale','purchase_refund'])], 'purchase_refund':[('type','in',['purchase','sale_refund'])] } domain = type_search.get(context.get('journal_type')) journal_list = journal_pool.name_search(cr, uid, '', domain) res['fields']['journal_id']['selection'] = journal_list return res
where = [('collection_id','=',self.dir_id)]
where = [('collection_id','=',self.dir_id)] ext = False if name: res = name.split('.ics') if len(res) > 1: name = res[0] ext = '.ics'
def _child_get(self, cr, name=False, parent_id=False, domain=None): dirobj = self.context._dirobj uid = self.context.uid ctx = self.context.context.copy() ctx.update(self.dctx) where = [('collection_id','=',self.dir_id)] if name: where.append(('name','=',name)) if not domain: domain = [] where = where + domain fil_obj = dirobj.pool.get('basic.calendar') ids = fil_obj.search(cr,uid,where,context=ctx) res = [] for calender in fil_obj.browse(cr, uid, ids, context=ctx): res.append(node_calendar(calender.name, self, self.context, calender)) return res
res.append(node_calendar(calender.name, self, self.context, calender))
if not ext: res.append(node_calendar(calender.name, self, self.context, calender)) else: res.append(res_node_calendar(name, self, self.context, calender))
def _child_get(self, cr, name=False, parent_id=False, domain=None): dirobj = self.context._dirobj uid = self.context.uid ctx = self.context.context.copy() ctx.update(self.dctx) where = [('collection_id','=',self.dir_id)] if name: where.append(('name','=',name)) if not domain: domain = [] where = where + domain fil_obj = dirobj.pool.get('basic.calendar') ids = fil_obj.search(cr,uid,where,context=ctx) res = [] for calender in fil_obj.browse(cr, uid, ids, context=ctx): res.append(node_calendar(calender.name, self, self.context, calender)) return res
def __init__(self,path, parent, context, res_obj, res_model, res_id=None): super(res_node_calendar,self).__init__(path, parent, context) self.calendar_id = parent.calendar_id
def __init__(self,path, parent, context, res_obj, res_model=None, res_id=None): super(res_node_calendar,self).__init__(path, parent, context)
def __init__(self,path, parent, context, res_obj, res_model, res_id=None): super(res_node_calendar,self).__init__(path, parent, context) self.calendar_id = parent.calendar_id self.mimetype = 'text/calendar' self.create_date = parent.create_date self.write_date = parent.write_date or parent.create_date if res_obj: self.create_date = res_obj.create_date self.write_date = res_obj.write_date or res_obj.create_date self.displayname = res_obj.name
return '%s_%d' % (self.model, self.res_id)
res = False if self.model and self.res_id: res = '%s_%d' % (self.model, self.res_id) elif self.calendar_id: res = '%d' % (self.calendar_id) return res
def _get_ttag(self,cr): return '%s_%d' % (self.model, self.res_id)
if not real_event_id in new_ids:
if real_event_id and not real_event_id in new_ids:
def write(self, cr, uid, ids, vals, context=None, check=True, update_check=True): """ Overrides orm write method. @param self: the object pointer @param cr: the current row, from the database cursor, @param uid: the current user’s ID for security checks, @param ids: List of crm meeting's ids @param vals: Dictionary of field value. @param context: A standard dictionary for contextual values @return: True """ if not context: context = {} if isinstance(ids, (str, int, long)): select = [ids] else: select = ids new_ids = [] for event_id in select: if len(str(event_id).split('-')) > 1: data = self.read(cr, uid, event_id, ['date', 'date_deadline', \ 'rrule', 'duration']) real_event_id = base_calendar_id2real_id(event_id) if data.get('rrule'): vals.update({ 'recurrent_uid': real_event_id, 'recurrent_id': data.get('date'), 'rrule_type': 'none', 'rrule': '' }) new_id = self.copy(cr, uid, real_event_id, default=vals, context=context) context.update({'active_id': new_id, 'active_ids': [new_id]}) continue if not real_event_id in new_ids: new_ids.append(real_event_id)
res = super(calendar_event, self).write(cr, uid, new_ids, vals, context=context)
if new_ids: res = super(calendar_event, self).write(cr, uid, new_ids, vals, context=context)
def write(self, cr, uid, ids, vals, context=None, check=True, update_check=True): """ Overrides orm write method. @param self: the object pointer @param cr: the current row, from the database cursor, @param uid: the current user’s ID for security checks, @param ids: List of crm meeting's ids @param vals: Dictionary of field value. @param context: A standard dictionary for contextual values @return: True """ if not context: context = {} if isinstance(ids, (str, int, long)): select = [ids] else: select = ids new_ids = [] for event_id in select: if len(str(event_id).split('-')) > 1: data = self.read(cr, uid, event_id, ['date', 'date_deadline', \ 'rrule', 'duration']) real_event_id = base_calendar_id2real_id(event_id) if data.get('rrule'): vals.update({ 'recurrent_uid': real_event_id, 'recurrent_id': data.get('date'), 'rrule_type': 'none', 'rrule': '' }) new_id = self.copy(cr, uid, real_event_id, default=vals, context=context) context.update({'active_id': new_id, 'active_ids': [new_id]}) continue if not real_event_id in new_ids: new_ids.append(real_event_id)
avg(100.0 * (l.price_unit*l.product_qty*u.factor) / (t.standard_price*l.product_qty*u.factor))::decimal(16,2) as negociation,
avg(100.0 * (l.price_unit*l.product_qty*u.factor) / NULLIF(t.standard_price*l.product_qty*u.factor, 0.0))::decimal(16,2) as negociation,
def init(self, cr): tools.sql.drop_view_if_exists(cr, 'purchase_report') cr.execute(""" create or replace view purchase_report as ( select min(l.id) as id, s.date_order as date, to_char(s.date_order, 'YYYY') as name, to_char(s.date_order, 'MM') as month, to_char(s.date_order, 'YYYY-MM-DD') as day, s.state, s.date_approve, date_trunc('day',s.minimum_planned_date) as expected_date, s.partner_address_id, s.dest_address_id, s.pricelist_id, s.validator, s.warehouse_id as warehouse_id, s.partner_id as partner_id, s.create_uid as user_id, s.company_id as company_id, l.product_id, t.categ_id as category_id, l.product_uom as product_uom, s.location_id as location_id, sum(l.product_qty*u.factor) as quantity, extract(epoch from age(s.date_approve,s.date_order))/(24*60*60)::decimal(16,2) as delay, extract(epoch from age(l.date_planned,s.date_order))/(24*60*60)::decimal(16,2) as delay_pass, count(*) as nbr, (l.price_unit*l.product_qty*u.factor)::decimal(16,2) as price_total, avg(100.0 * (l.price_unit*l.product_qty*u.factor) / (t.standard_price*l.product_qty*u.factor))::decimal(16,2) as negociation, sum(t.standard_price*l.product_qty*u.factor)::decimal(16,2) as price_standard, (sum(l.product_qty*l.price_unit)/sum(l.product_qty*u.factor))::decimal(16,2) as price_average from purchase_order s left join purchase_order_line l on (s.id=l.order_id) left join product_product p on (l.product_id=p.id) left join product_template t on (p.product_tmpl_id=t.id) left join product_uom u on (u.id=l.product_uom) where l.product_id is not null group by s.company_id, s.create_uid, s.partner_id, l.product_qty, u.factor, s.location_id, l.price_unit, s.date_approve, l.date_planned, l.product_uom, date_trunc('day',s.minimum_planned_date), s.partner_address_id, s.pricelist_id, s.validator, s.dest_address_id, l.product_id, t.categ_id, s.date_order, to_char(s.date_order, 'YYYY'), to_char(s.date_order, 'MM'), to_char(s.date_order, 'YYYY-MM-DD'), s.state, s.warehouse_id ) """)
(sum(l.product_qty*l.price_unit)/sum(l.product_qty*u.factor))::decimal(16,2) as price_average
(sum(l.product_qty*l.price_unit)/NULLIF(sum(l.product_qty*u.factor),0.0))::decimal(16,2) as price_average
def init(self, cr): tools.sql.drop_view_if_exists(cr, 'purchase_report') cr.execute(""" create or replace view purchase_report as ( select min(l.id) as id, s.date_order as date, to_char(s.date_order, 'YYYY') as name, to_char(s.date_order, 'MM') as month, to_char(s.date_order, 'YYYY-MM-DD') as day, s.state, s.date_approve, date_trunc('day',s.minimum_planned_date) as expected_date, s.partner_address_id, s.dest_address_id, s.pricelist_id, s.validator, s.warehouse_id as warehouse_id, s.partner_id as partner_id, s.create_uid as user_id, s.company_id as company_id, l.product_id, t.categ_id as category_id, l.product_uom as product_uom, s.location_id as location_id, sum(l.product_qty*u.factor) as quantity, extract(epoch from age(s.date_approve,s.date_order))/(24*60*60)::decimal(16,2) as delay, extract(epoch from age(l.date_planned,s.date_order))/(24*60*60)::decimal(16,2) as delay_pass, count(*) as nbr, (l.price_unit*l.product_qty*u.factor)::decimal(16,2) as price_total, avg(100.0 * (l.price_unit*l.product_qty*u.factor) / (t.standard_price*l.product_qty*u.factor))::decimal(16,2) as negociation, sum(t.standard_price*l.product_qty*u.factor)::decimal(16,2) as price_standard, (sum(l.product_qty*l.price_unit)/sum(l.product_qty*u.factor))::decimal(16,2) as price_average from purchase_order s left join purchase_order_line l on (s.id=l.order_id) left join product_product p on (l.product_id=p.id) left join product_template t on (p.product_tmpl_id=t.id) left join product_uom u on (u.id=l.product_uom) where l.product_id is not null group by s.company_id, s.create_uid, s.partner_id, l.product_qty, u.factor, s.location_id, l.price_unit, s.date_approve, l.date_planned, l.product_uom, date_trunc('day',s.minimum_planned_date), s.partner_address_id, s.pricelist_id, s.validator, s.dest_address_id, l.product_id, t.categ_id, s.date_order, to_char(s.date_order, 'YYYY'), to_char(s.date_order, 'MM'), to_char(s.date_order, 'YYYY-MM-DD'), s.state, s.warehouse_id ) """)
return result and result[0] or False return result
return ids and ids[0] or False return ids
def get_recurrent_ids(self, cr, uid, select, base_start_date, base_until_date, limit=100): if not limit: limit = 100 if isinstance(select, (str, int, long)): ids = [select] else: ids = select result = [] if ids and (base_start_date or base_until_date): cr.execute("select m.id, m.rrule, c.date, m.exdate from crm_meeting m\ join crm_case c on (c.id=m.inherit_case_id) \ where m.id in ("+ ','.join(map(lambda x: str(x), ids))+")")
elif type == 'out_refund':
elif inv.type == 'out_refund':
def compute_refund(self, cr, uid, ids, mode, context=None): """ @param cr: the current row, from the database cursor, @param uid: the current user’s ID for security checks, @param ids: the account invoice refund’s ID or list of IDs
self.email_send(cr, uid, obj, emails, action.act_mail_body, emailfrom=email_from)
def to_email(text): return re.findall(r'([^ ,<@]+@[^> ,]+)', text or '') emails = to_email(','.join(filter(None, emails))) email_froms = to_email(email_from) if email_froms: self.email_send(cr, uid, obj, emails, action.act_mail_body, emailfrom=email_froms[0])
def do_action(self, cr, uid, action, model_obj, obj, context=None): """ Do Action @param self: The object pointer @param cr: the current row, from the database cursor, @param uid: the current user’s ID for security checks, @param action: pass action @param model_obj: pass Model object @param context: A standard dictionary for contextual values """ if context is None: context = {}
def get_real_price(res_dict, product_id, pricelist):
def get_real_price(res_dict, product_id, qty, uom, pricelist):
def get_real_price(res_dict, product_id, pricelist): item_obj = self.pool.get('product.pricelist.item') price_type_obj = self.pool.get('product.price.type') product_obj = self.pool.get('product.product') template_obj = self.pool.get('product.template') field_name = 'list_price'
product_tmpl_id = product_obj.browse(cr, uid, product_id, context).product_tmpl_id.id
product = product_obj.browse(cr, uid, product_id, context) product_tmpl_id = product.product_tmpl_id.id
def get_real_price(res_dict, product_id, pricelist): item_obj = self.pool.get('product.pricelist.item') price_type_obj = self.pool.get('product.price.type') product_obj = self.pool.get('product.product') template_obj = self.pool.get('product.template') field_name = 'list_price'
return product_read[field_name]
factor = 1.0 if uom and uom != product.uom_id.id: product_uom_obj = self.pool.get('product.uom') uom_data = product_uom_obj.browse(cr, uid, product.uom_id.id) factor = uom_data.factor return product_read[field_name] * factor
def get_real_price(res_dict, product_id, pricelist): item_obj = self.pool.get('product.pricelist.item') price_type_obj = self.pool.get('product.price.type') product_obj = self.pool.get('product.product') template_obj = self.pool.get('product.template') field_name = 'list_price'
new_list_price = get_real_price(list_price, product.id, pricelist)
new_list_price = get_real_price(list_price, product.id, qty, uom, pricelist)
def get_real_price(res_dict, product_id, pricelist): item_obj = self.pool.get('product.pricelist.item') price_type_obj = self.pool.get('product.price.type') product_obj = self.pool.get('product.product') template_obj = self.pool.get('product.template') field_name = 'list_price'
real_price = get_real_price(price_unit_res, product.id, pricelist)
real_price = get_real_price(price_unit_res, product.id, qty, uom, pricelist)
def get_real_price(res_dict, product_id, pricelist): item_obj = self.pool.get('product.pricelist.item') price_type_obj = self.pool.get('product.price.type') product_obj = self.pool.get('product.product') template_obj = self.pool.get('product.template') field_name = 'list_price'
p_obj = self.pool.get('product.product').browse(cr,uid,product_id).list_price
p_obj = self.pool.get('product.product').browse(cr,uid,[product_id])[0] uom_id=p_obj.uom_po_id.id
def price_by_product(self, cr, uid, ids, pricelist, product_id, qty=0, partner_id=False): if not product_id: return 0.0 if not pricelist: raise osv.except_osv(_('No Pricelist !'), _('You have to select a pricelist in the sale form !\n' \ 'Please set one before choosing a product.')) p_obj = self.pool.get('product.product').browse(cr,uid,product_id).list_price price = self.pool.get('product.pricelist').price_get(cr, uid, [pricelist], product_id, qty or 1.0, partner_id)[pricelist] # Todo need to check
[pricelist], product_id, qty or 1.0, partner_id)[pricelist] return price or p_obj
[pricelist], product_id, qty or 1.0, partner_id,{'uom': uom_id})[pricelist] if price is False: raise osv.except_osv(_('No valid pricelist line found !'), _("Couldn't find a pricelist line matching this product" \ " and quantity.\nYou have to change either the product," \ " the quantity or the pricelist.")) return price
def price_by_product(self, cr, uid, ids, pricelist, product_id, qty=0, partner_id=False): if not product_id: return 0.0 if not pricelist: raise osv.except_osv(_('No Pricelist !'), _('You have to select a pricelist in the sale form !\n' \ 'Please set one before choosing a product.')) p_obj = self.pool.get('product.product').browse(cr,uid,product_id).list_price price = self.pool.get('product.pricelist').price_get(cr, uid, [pricelist], product_id, qty or 1.0, partner_id)[pricelist] # Todo need to check
lang=self.pool.get('res.partner').read(cr, uid, partner_id)['lang']
lang=self.pool.get('res.partner').read(cr, uid, partner_id, ['lang'])['lang']
def product_id_change(self, cr, uid, ids, pricelist, product, qty, uom, partner_id, date_order=False, fiscal_position=False, date_planned=False, name=False, price_unit=False, notes=False): if not pricelist: raise osv.except_osv(_('No Pricelist !'), _('You have to select a pricelist or a supplier in the purchase form !\nPlease set one before choosing a product.')) if not partner_id: raise osv.except_osv(_('No Partner!'), _('You have to select a partner in the purchase form !\nPlease set one partner before choosing a product.')) if not product: return {'value': {'price_unit': price_unit or 0.0, 'name': name or '', 'notes': notes or'', 'product_uom' : uom or False}, 'domain':{'product_uom':[]}} prod= self.pool.get('product.product').browse(cr, uid,product) lang=False if partner_id: lang=self.pool.get('res.partner').read(cr, uid, partner_id)['lang'] context={'lang':lang} context['partner_id'] = partner_id
'write_date': fields.datetime('Modifided Date', readonly=True), 'description': fields.text("description"),
'write_date': fields.datetime('Write Date', readonly=True), 'description': fields.text("Description"),
def import_cal(self, cr, uid, content, data_id=None, context=None): """ Import Calendar @param self: The object pointer @param cr: the current row, from the database cursor, @param uid: the current user’s ID for security checks, @param data_id: Get Data’s ID or False @param context: A standard dictionary for contextual values """
'fn': lambda *a: 'field',
'fn': 'field',
def create(self, cr, uid, vals, context=None): """ create calendar's line @param self: The object pointer @param cr: the current row, from the database cursor, @param uid: the current user’s ID for security checks, @param vals: Get the Values @param context: A standard dictionary for contextual values """
seconds = child.value.seconds days = child.value.days diff = (days * 86400) + seconds interval = 'days' related = 'before'
if isinstance(child.value, timedelta): seconds = child.value.seconds days = child.value.days diff = (days * 86400) + seconds interval = 'days' related = 'before' elif isinstance(child.value, datetime): raise NotImplementedError("we cannot parse absolute triggers")
def import_cal(self, cr, uid, ical_data, context=None): """ Import Calendar @param self: The object pointer @param cr: the current row, from the database cursor, @param uid: the current user’s ID for security checks, @param ical_data: Get calendar's Data @param context: A standard dictionary for contextual values """
fields['field'+str(i)] = models[f.field_id.model][f.field_id.name] i+=1
if f.field_id.model: fields['field'+str(i)] = models[f.field_id.model][f.field_id.name] i+=1 else: fields['column_count'] = {'readonly': True, 'type': 'integer', 'string': 'Count', 'size': 64, 'name': 'column_count'}
def fields_get(self, cr, user, fields=None, context=None): if (not context) or 'report_id' not in context: return super(report_creator, self).fields_get(cr, user, fields, context) report = self.browse(cr, user, context['report_id']) models = {} for model in report.model_ids: models[model.model] = self.pool.get(model.model).fields_get(cr, user, context=context) fields = {} i = 0 for f in report.field_ids: fields['field'+str(i)] = models[f.field_id.model][f.field_id.name] i+=1 return fields
fields['field'+str(i)] = models[f.field_id.model][f.field_id.name] i+=1
if f.field_id.model: fields['field'+str(i)] = models[f.field_id.model][f.field_id.name] i+=1 else: fields['column_count'] = {'readonly': True, 'type': 'integer', 'string': 'Count', 'size': 64, 'name': 'column_count'}
def fields_view_get(self, cr, user, view_id=None, view_type='form', context=None, toolbar=False): if (not context) or 'report_id' not in context: return super(report_creator, self).fields_view_get(cr, user, view_id, view_type, context, toolbar) report = self.browse(cr, user, context['report_id']) models = {} for model in report.model_ids: models[model.model] = self.pool.get(model.model).fields_get(cr, user, context=context) fields = {} i = 0 for f in report.field_ids: fields['field'+str(i)] = models[f.field_id.model][f.field_id.name] i+=1 arch = '<?xml version="1.0" encoding="utf-8"?>\n' if view_type=='graph': arch +='<graph string="%s" type="%s" orientation="%s">' % (report.name, report.view_graph_type,report.view_graph_orientation) for val in ('x','y'): i = 0 for f in report.field_ids: if f.graph_mode==val: arch += '<field name="%s" select="1"/>' % ('field'+str(i),) i+=1 elif view_type=='calendar': required_types = ['date_start','date_delay','color'] set_dict = {'view_type':view_type,'string':report.name} temp_list = [] i=0 for f in report.field_ids: if f.calendar_mode and f.calendar_mode in required_types: set_dict[f.calendar_mode] = 'field'+str(i) i+=1 del required_types[required_types.index(f.calendar_mode)] else: temp_list.append('''<field name="%(name)s" select="1"/>''' % {'name':'field'+str(i)}) i+=1 arch += '''<%(view_type)s string="%(string)s" date_start="%(date_start)s" ''' %set_dict if set_dict.get('date_delay',False): arch +=''' date_delay="%(date_delay)s" '''%set_dict if set_dict.get('date_stop',False): arch +=''' date_stop="%(date_stop)s" '''%set_dict if set_dict.get('color',False): arch +=''' color="%(color)s"'''%set_dict arch += '''>''' arch += ''.join(temp_list) else: arch += '<%s string="%s">\n' % (view_type, report.name) i = 0 for f in report.field_ids: arch += '<field name="%s" select="1"/>' % ('field'+str(i),) i+=1 arch += '</%s>' % (view_type,) result = { 'arch': arch, 'fields': fields } result['toolbar'] = { 'print': [], 'action': [], 'relate': [] } return result
arch += '<field name="%s" select="1"/>' % ('field'+str(i),) i+=1
if f.field_id.model: arch += '<field name="%s" select="1"/>' % ('field'+str(i),) i+=1 else: arch += '<field name="%s" select="1"/>' % ('column_count',)
def fields_view_get(self, cr, user, view_id=None, view_type='form', context=None, toolbar=False): if (not context) or 'report_id' not in context: return super(report_creator, self).fields_view_get(cr, user, view_id, view_type, context, toolbar) report = self.browse(cr, user, context['report_id']) models = {} for model in report.model_ids: models[model.model] = self.pool.get(model.model).fields_get(cr, user, context=context) fields = {} i = 0 for f in report.field_ids: fields['field'+str(i)] = models[f.field_id.model][f.field_id.name] i+=1 arch = '<?xml version="1.0" encoding="utf-8"?>\n' if view_type=='graph': arch +='<graph string="%s" type="%s" orientation="%s">' % (report.name, report.view_graph_type,report.view_graph_orientation) for val in ('x','y'): i = 0 for f in report.field_ids: if f.graph_mode==val: arch += '<field name="%s" select="1"/>' % ('field'+str(i),) i+=1 elif view_type=='calendar': required_types = ['date_start','date_delay','color'] set_dict = {'view_type':view_type,'string':report.name} temp_list = [] i=0 for f in report.field_ids: if f.calendar_mode and f.calendar_mode in required_types: set_dict[f.calendar_mode] = 'field'+str(i) i+=1 del required_types[required_types.index(f.calendar_mode)] else: temp_list.append('''<field name="%(name)s" select="1"/>''' % {'name':'field'+str(i)}) i+=1 arch += '''<%(view_type)s string="%(string)s" date_start="%(date_start)s" ''' %set_dict if set_dict.get('date_delay',False): arch +=''' date_delay="%(date_delay)s" '''%set_dict if set_dict.get('date_stop',False): arch +=''' date_stop="%(date_stop)s" '''%set_dict if set_dict.get('color',False): arch +=''' color="%(color)s"'''%set_dict arch += '''>''' arch += ''.join(temp_list) else: arch += '<%s string="%s">\n' % (view_type, report.name) i = 0 for f in report.field_ids: arch += '<field name="%s" select="1"/>' % ('field'+str(i),) i+=1 arch += '</%s>' % (view_type,) result = { 'arch': arch, 'fields': fields } result['toolbar'] = { 'print': [], 'action': [], 'relate': [] } return result
set_dict[f.calendar_mode] = 'field'+str(i) i+=1
if f.field_id.model: field_cal = 'field'+str(i) i+=1 else: field_cal = 'column_count' set_dict[f.calendar_mode] = field_cal
def fields_view_get(self, cr, user, view_id=None, view_type='form', context=None, toolbar=False): if (not context) or 'report_id' not in context: return super(report_creator, self).fields_view_get(cr, user, view_id, view_type, context, toolbar) report = self.browse(cr, user, context['report_id']) models = {} for model in report.model_ids: models[model.model] = self.pool.get(model.model).fields_get(cr, user, context=context) fields = {} i = 0 for f in report.field_ids: fields['field'+str(i)] = models[f.field_id.model][f.field_id.name] i+=1 arch = '<?xml version="1.0" encoding="utf-8"?>\n' if view_type=='graph': arch +='<graph string="%s" type="%s" orientation="%s">' % (report.name, report.view_graph_type,report.view_graph_orientation) for val in ('x','y'): i = 0 for f in report.field_ids: if f.graph_mode==val: arch += '<field name="%s" select="1"/>' % ('field'+str(i),) i+=1 elif view_type=='calendar': required_types = ['date_start','date_delay','color'] set_dict = {'view_type':view_type,'string':report.name} temp_list = [] i=0 for f in report.field_ids: if f.calendar_mode and f.calendar_mode in required_types: set_dict[f.calendar_mode] = 'field'+str(i) i+=1 del required_types[required_types.index(f.calendar_mode)] else: temp_list.append('''<field name="%(name)s" select="1"/>''' % {'name':'field'+str(i)}) i+=1 arch += '''<%(view_type)s string="%(string)s" date_start="%(date_start)s" ''' %set_dict if set_dict.get('date_delay',False): arch +=''' date_delay="%(date_delay)s" '''%set_dict if set_dict.get('date_stop',False): arch +=''' date_stop="%(date_stop)s" '''%set_dict if set_dict.get('color',False): arch +=''' color="%(color)s"'''%set_dict arch += '''>''' arch += ''.join(temp_list) else: arch += '<%s string="%s">\n' % (view_type, report.name) i = 0 for f in report.field_ids: arch += '<field name="%s" select="1"/>' % ('field'+str(i),) i+=1 arch += '</%s>' % (view_type,) result = { 'arch': arch, 'fields': fields } result['toolbar'] = { 'print': [], 'action': [], 'relate': [] } return result
temp_list.append('''<field name="%(name)s" select="1"/>''' % {'name':'field'+str(i)}) i+=1
if f.field_id.model: temp_list.append('''<field name="%(name)s" select="1"/>''' % {'name':'field'+str(i)}) i+=1 else: temp_list.append('''<field name="%(name)s" select="1"/>''' % {'name':'column_count'})
def fields_view_get(self, cr, user, view_id=None, view_type='form', context=None, toolbar=False): if (not context) or 'report_id' not in context: return super(report_creator, self).fields_view_get(cr, user, view_id, view_type, context, toolbar) report = self.browse(cr, user, context['report_id']) models = {} for model in report.model_ids: models[model.model] = self.pool.get(model.model).fields_get(cr, user, context=context) fields = {} i = 0 for f in report.field_ids: fields['field'+str(i)] = models[f.field_id.model][f.field_id.name] i+=1 arch = '<?xml version="1.0" encoding="utf-8"?>\n' if view_type=='graph': arch +='<graph string="%s" type="%s" orientation="%s">' % (report.name, report.view_graph_type,report.view_graph_orientation) for val in ('x','y'): i = 0 for f in report.field_ids: if f.graph_mode==val: arch += '<field name="%s" select="1"/>' % ('field'+str(i),) i+=1 elif view_type=='calendar': required_types = ['date_start','date_delay','color'] set_dict = {'view_type':view_type,'string':report.name} temp_list = [] i=0 for f in report.field_ids: if f.calendar_mode and f.calendar_mode in required_types: set_dict[f.calendar_mode] = 'field'+str(i) i+=1 del required_types[required_types.index(f.calendar_mode)] else: temp_list.append('''<field name="%(name)s" select="1"/>''' % {'name':'field'+str(i)}) i+=1 arch += '''<%(view_type)s string="%(string)s" date_start="%(date_start)s" ''' %set_dict if set_dict.get('date_delay',False): arch +=''' date_delay="%(date_delay)s" '''%set_dict if set_dict.get('date_stop',False): arch +=''' date_stop="%(date_stop)s" '''%set_dict if set_dict.get('color',False): arch +=''' color="%(color)s"'''%set_dict arch += '''>''' arch += ''.join(temp_list) else: arch += '<%s string="%s">\n' % (view_type, report.name) i = 0 for f in report.field_ids: arch += '<field name="%s" select="1"/>' % ('field'+str(i),) i+=1 arch += '</%s>' % (view_type,) result = { 'arch': arch, 'fields': fields } result['toolbar'] = { 'print': [], 'action': [], 'relate': [] } return result
fields['field'+str(i)] = (f.field_id.model, f.field_id.name) i+=1
if f.field_id.model: fields['field'+str(i)] = (f.field_id.model, f.field_id.name) i+=1 else: fields['column_count'] = (False, 'Count')
def search(self, cr, user, args, offset=0, limit=None, order=None, context=None, count=False): if (not context) or 'report_id' not in context: return super(report_creator, self).search(cr, user, args, offset, limit, order, context, count) report = self.browse(cr, user, context['report_id']) i = 0 fields = {} for f in report.field_ids: fields['field'+str(i)] = (f.field_id.model, f.field_id.name) i+=1 newargs = [] newargs2 = [] for a in args: res = self.pool.get(fields[a[0]][0])._where_calc(cr, user, [[fields[a[0]][1],a[1],a[2]]], active_test=False, context=context) newargs+=res[0] newargs2+=res[1] ctx = context or {} ctx['getid'] = True report = self._sql_query_get(cr, user, [context['report_id']], 'sql_query', None, ctx, where_plus=newargs, limit=limit, offset=offset) query = report[context['report_id']] cr.execute(query, newargs2) result = cr.fetchall() return map(lambda x: x[0], result)
res = self.pool.get(fields[a[0]][0])._where_calc(cr, user, [[fields[a[0]][1],a[1],a[2]]], active_test=False, context=context) newargs+=res[0] newargs2+=res[1]
if fields[a[0]][0]: res = self.pool.get(fields[a[0]][0])._where_calc(cr, user, [[fields[a[0]][1],a[1],a[2]]], active_test=False, context=context) newargs+=res[0] newargs2+=res[1] else: newargs += [("count(*) " + a[1] +" " + str(a[2]))]
def search(self, cr, user, args, offset=0, limit=None, order=None, context=None, count=False): if (not context) or 'report_id' not in context: return super(report_creator, self).search(cr, user, args, offset, limit, order, context, count) report = self.browse(cr, user, context['report_id']) i = 0 fields = {} for f in report.field_ids: fields['field'+str(i)] = (f.field_id.model, f.field_id.name) i+=1 newargs = [] newargs2 = [] for a in args: res = self.pool.get(fields[a[0]][0])._where_calc(cr, user, [[fields[a[0]][1],a[1],a[2]]], active_test=False, context=context) newargs+=res[0] newargs2+=res[1] ctx = context or {} ctx['getid'] = True report = self._sql_query_get(cr, user, [context['report_id']], 'sql_query', None, ctx, where_plus=newargs, limit=limit, offset=offset) query = report[context['report_id']] cr.execute(query, newargs2) result = cr.fetchall() return map(lambda x: x[0], result)
groupby.append(t+'.'+f.field_id.name)
def _sql_query_get(self, cr, uid, ids, prop, unknow_none, context, where_plus=[], limit=None, offset=None): result = {} for obj in self.browse(cr, uid, ids): fields = [] groupby = [] i = 0 for f in obj.field_ids: t = self.pool.get(f.field_id.model_id.model)._table if f.group_method == 'group': fields.append('\t'+t+'.'+f.field_id.name+' as field'+str(i)) groupby.append(t+'.'+f.field_id.name) else: fields.append('\t'+f.group_method+'('+t+'.'+f.field_id.name+')'+' as field'+str(i)) i+=1 models = self._path_get(cr, uid, obj.model_ids, obj.filter_ids) check = self._id_get(cr, uid, ids[0], context) if check<>False: fields.insert(0,(check+' as id')) if models: result[obj.id] = """select
week_wh[ldt.date().weekday()] = week_wh.get(ldt.date().weekday(), 0) + (dt - ldt).hours
week_wh[ldt.date().weekday()] = week_wh.get(ldt.date().weekday(), 0) + ((dt - ldt).seconds/3600)
def create_xml(self, cr, uid, ids, datas, context=None): obj_emp = pooler.get_pool(cr.dbname).get('hr.employee') start_date = datetime.strptime(datas['form']['init_date'], '%Y-%m-%d') end_date = datetime.strptime(datas['form']['end_date'], '%Y-%m-%d') first_monday = start_date - relativedelta(days=start_date.date().weekday()) last_monday = end_date + relativedelta(days=7 - end_date.date().weekday()) if last_monday < first_monday: first_monday, last_monday = last_monday, first_monday
date_and_hours_by_cal = [(op.production_id.date_planned, op.hour, op.workcenter_id.calendar_id.id) for op in ops]
date_and_hours_by_cal = [] for op in ops: date_planned = op.production_id.date_planned and op.date_planned if date_planned: date_and_hours_by_cal.append((date_planned, op.hour, op.workcenter_id.calendar_id.id))
def _get_date_end(self, cr, uid, ids, field_name, arg, context): """ Finds ending date. @return: Dictionary of values. """ ops = self.browse(cr, uid, ids, context=context) date_and_hours_by_cal = [(op.production_id.date_planned, op.hour, op.workcenter_id.calendar_id.id) for op in ops] intervals = self.pool.get('resource.calendar').interval_get_multi(cr, uid, date_and_hours_by_cal)
if op.date_planned: i = intervals[(op.date_planned, op.hour, op.workcenter_id.calendar_id.id)]
date_planned = op.production_id.date_planned and op.date_planned if date_planned: i = intervals[(date_planned, op.hour, op.workcenter_id.calendar_id.id)]
def _get_date_end(self, cr, uid, ids, field_name, arg, context): """ Finds ending date. @return: Dictionary of values. """ ops = self.browse(cr, uid, ids, context=context) date_and_hours_by_cal = [(op.production_id.date_planned, op.hour, op.workcenter_id.calendar_id.id) for op in ops] intervals = self.pool.get('resource.calendar').interval_get_multi(cr, uid, date_and_hours_by_cal)
_timers = {}
__tasks = [] __tasks_by_db = {}
def shutdown(self): logging.shutdown()
__logger = logging.getLogger('timer') def setAlarm(self, fn, dt, db_name, *args, **kwargs): wait = dt - time.time() if wait > 0: self.__logger.debug("Job scheduled in %.3g seconds for %s.%s" % (wait, fn.im_class.__name__, fn.func_name)) timer = threading.Timer(wait, fn, args, kwargs) timer.start() self._timers.setdefault(db_name, []).append(timer) for db in self._timers: for timer in self._timers[db]: if not timer.isAlive(): self._timers[db].remove(timer)
@classmethod def setAlarm(cls, function, timestamp, db_name, *args, **kwargs): task = [timestamp, db_name, function, args, kwargs] heapq.heappush(cls.__tasks, task) cls.__tasks_by_db.setdefault(db_name, []).append(task)
def shutdown(self): logging.shutdown()
for db in cls._timers: if db_name is None or db == db_name: for timer in cls._timers[db]: timer.cancel()
if db_name is None: cls.__tasks, cls.__tasks_by_db = [], {} else: if db_name in cls.__tasks_by_db: for task in cls.__tasks_by_db[db_name]: task[0] = 0
def cancel(cls, db_name): """Cancel all timers for a given database. If None passed, all timers are cancelled""" for db in cls._timers: if db_name is None or db == db_name: for timer in cls._timers[db]: timer.cancel()
partner_id, date_order=False, fiscal_position=False):
partner_id, date_order=False, fiscal_position=False, date_planned=False, name=False, price_unit=False, notes=False):
def product_id_change(self,cr, uid, ids, pricelist, product, qty, uom, partner_id, date_order=False, fiscal_position=False): warning = {} if not product: return {'value': {'price_unit': 0.0, 'name':'','notes':'', 'product_uom' : False}, 'domain':{'product_uom':[]}} product_obj = self.pool.get('product.product') product_info = product_obj.browse(cr, uid, product) title = False message = False
l.company_id company_id
l.company_id as company_id
def init(self, cr): tools.drop_view_if_exists(cr, 'account_followup_stat_by_partner') cr.execute(""" create or replace view account_followup_stat_by_partner as ( SELECT l.partner_id AS id, l.partner_id AS partner_id, min(l.date) AS date_move, max(l.date) AS date_move_last, max(l.followup_date) AS date_followup, max(l.followup_line_id) AS max_followup_id, sum(l.debit - l.credit) AS balance, l.company_id company_id FROM account_move_line l LEFT JOIN account_account a ON (l.account_id = a.id) WHERE a.active AND a.type = 'receivable' AND l.reconcile_id is NULL AND l.partner_id IS NOT NULL GROUP BY l.partner_id, l.company_id )""")
res = super(product_product,self).get_product_accounts(cr, uid, product_id, context)
def get_product_accounts(self, cr, uid, product_id, context={}): """ To get the stock input account, stock output account and stock journal related to product. @param product_id: product id @return: dictionary which contains information regarding stock input account, stock output account and stock journal """ product_obj = self.pool.get('product.product').browse(cr, uid, product_id, False) stock_input_acc = product_obj.property_stock_account_input and product_obj.property_stock_account_input.id or False if not stock_input_acc: stock_input_acc = product_obj.categ_id.property_stock_account_input_categ and product_obj.categ_id.property_stock_account_input_categ.id or False stock_output_acc = product_obj.property_stock_account_output and product_obj.property_stock_account_output.id or False if not stock_output_acc: stock_output_acc = product_obj.categ_id.property_stock_account_output_categ and product_obj.categ_id.property_stock_account_output_categ.id or False
res = {}
def get_product_accounts(self, cr, uid, product_id, context={}): """ To get the stock input account, stock output account and stock journal related to product. @param product_id: product id @return: dictionary which contains information regarding stock input account, stock output account and stock journal """ product_obj = self.pool.get('product.product').browse(cr, uid, product_id, False) stock_input_acc = product_obj.property_stock_account_input and product_obj.property_stock_account_input.id or False if not stock_input_acc: stock_input_acc = product_obj.categ_id.property_stock_account_input_categ and product_obj.categ_id.property_stock_account_input_categ.id or False stock_output_acc = product_obj.property_stock_account_output and product_obj.property_stock_account_output.id or False if not stock_output_acc: stock_output_acc = product_obj.categ_id.property_stock_account_output_categ and product_obj.categ_id.property_stock_account_output_categ.id or False
self.result_sum_dr += self.res_bl['balance']
self.result_sum_dr += self.res_bl['balance']*-1
def sum_dr(self): if self.res_bl['type'] == 'Net Profit': self.result_sum_dr += self.res_bl['balance'] return self.result_sum_dr
self.result_sum_dr += abs(account.debit - account.credit)
self.result_sum_dr += account.balance
def get_data(self,data): cr, uid = self.cr, self.uid db_pool = pooler.get_pool(self.cr.dbname)
self.result_sum_cr += abs(account.debit - account.credit)
self.result_sum_cr += account.balance
def get_data(self,data): cr, uid = self.cr, self.uid db_pool = pooler.get_pool(self.cr.dbname)
tools.debug(ret)
def login(self, db, login, password): ret = super(users,self).login(db, login, password) tools.debug(ret) if ret: return ret pool = pooler.get_pool(db) cr = pooler.get_db(db).cursor() action_obj = pool.get('ir.actions.actions') cr.execute(""" SELECT id, company, ldap_server, ldap_server_port, ldap_binddn, ldap_password, ldap_filter, ldap_base, "user", create_user FROM res_company_ldap WHERE ldap_server != '' and ldap_binddn != '' ORDER BY sequence""") for res_company_ldap in cr.dictfetchall(): tools.debug(res_company_ldap) try: l = ldap.open(res_company_ldap['ldap_server'], res_company_ldap['ldap_server_port']) if l.simple_bind_s(res_company_ldap['ldap_binddn'], res_company_ldap['ldap_password']): base = res_company_ldap['ldap_base'] scope = ldap.SCOPE_SUBTREE filter = filter_format(res_company_ldap['ldap_filter'], (login,)) retrieve_attributes = None result_id = l.search(base, scope, filter, retrieve_attributes) timeout = 60 result_type, result_data = l.result(result_id, timeout) if not result_data: continue if result_type == ldap.RES_SEARCH_RESULT and len(result_data) == 1: dn = result_data[0][0] tools.debug(dn) name = result_data[0][1]['cn'][0] if l.bind_s(dn, password): l.unbind() cr.execute("SELECT id FROM res_users WHERE login=%s",(tools.ustr(login),)) res = cr.fetchone() tools.debug(res) if res: cr.close() return res[0] if not res_company_ldap['create_user']: continue action_id = action_obj.search(cr, 1, [('usage', '=', 'menu')])[0] if res_company_ldap['user']: res = self.copy(cr, 1, res_company_ldap['user'], default={'active': True}) self.write(cr, 1, res, { 'name': name, 'login': login.encode('utf-8'), 'company_id': res_company_ldap['company'], }) else: res = self.create(cr, 1, { 'name': name, 'login': login.encode('utf-8'), 'company_id': res_company_ldap['company'], 'action_id': action_id, 'menu_id': action_id, }) cr.commit() cr.close() return res l.unbind() except Exception, e: tools.debug(e) continue cr.close() return False
tools.debug(res_company_ldap)
logger.debug(res_company_ldap)
def login(self, db, login, password): ret = super(users,self).login(db, login, password) tools.debug(ret) if ret: return ret pool = pooler.get_pool(db) cr = pooler.get_db(db).cursor() action_obj = pool.get('ir.actions.actions') cr.execute(""" SELECT id, company, ldap_server, ldap_server_port, ldap_binddn, ldap_password, ldap_filter, ldap_base, "user", create_user FROM res_company_ldap WHERE ldap_server != '' and ldap_binddn != '' ORDER BY sequence""") for res_company_ldap in cr.dictfetchall(): tools.debug(res_company_ldap) try: l = ldap.open(res_company_ldap['ldap_server'], res_company_ldap['ldap_server_port']) if l.simple_bind_s(res_company_ldap['ldap_binddn'], res_company_ldap['ldap_password']): base = res_company_ldap['ldap_base'] scope = ldap.SCOPE_SUBTREE filter = filter_format(res_company_ldap['ldap_filter'], (login,)) retrieve_attributes = None result_id = l.search(base, scope, filter, retrieve_attributes) timeout = 60 result_type, result_data = l.result(result_id, timeout) if not result_data: continue if result_type == ldap.RES_SEARCH_RESULT and len(result_data) == 1: dn = result_data[0][0] tools.debug(dn) name = result_data[0][1]['cn'][0] if l.bind_s(dn, password): l.unbind() cr.execute("SELECT id FROM res_users WHERE login=%s",(tools.ustr(login),)) res = cr.fetchone() tools.debug(res) if res: cr.close() return res[0] if not res_company_ldap['create_user']: continue action_id = action_obj.search(cr, 1, [('usage', '=', 'menu')])[0] if res_company_ldap['user']: res = self.copy(cr, 1, res_company_ldap['user'], default={'active': True}) self.write(cr, 1, res, { 'name': name, 'login': login.encode('utf-8'), 'company_id': res_company_ldap['company'], }) else: res = self.create(cr, 1, { 'name': name, 'login': login.encode('utf-8'), 'company_id': res_company_ldap['company'], 'action_id': action_id, 'menu_id': action_id, }) cr.commit() cr.close() return res l.unbind() except Exception, e: tools.debug(e) continue cr.close() return False
tools.debug(dn)
logger.debug(dn)
def login(self, db, login, password): ret = super(users,self).login(db, login, password) tools.debug(ret) if ret: return ret pool = pooler.get_pool(db) cr = pooler.get_db(db).cursor() action_obj = pool.get('ir.actions.actions') cr.execute(""" SELECT id, company, ldap_server, ldap_server_port, ldap_binddn, ldap_password, ldap_filter, ldap_base, "user", create_user FROM res_company_ldap WHERE ldap_server != '' and ldap_binddn != '' ORDER BY sequence""") for res_company_ldap in cr.dictfetchall(): tools.debug(res_company_ldap) try: l = ldap.open(res_company_ldap['ldap_server'], res_company_ldap['ldap_server_port']) if l.simple_bind_s(res_company_ldap['ldap_binddn'], res_company_ldap['ldap_password']): base = res_company_ldap['ldap_base'] scope = ldap.SCOPE_SUBTREE filter = filter_format(res_company_ldap['ldap_filter'], (login,)) retrieve_attributes = None result_id = l.search(base, scope, filter, retrieve_attributes) timeout = 60 result_type, result_data = l.result(result_id, timeout) if not result_data: continue if result_type == ldap.RES_SEARCH_RESULT and len(result_data) == 1: dn = result_data[0][0] tools.debug(dn) name = result_data[0][1]['cn'][0] if l.bind_s(dn, password): l.unbind() cr.execute("SELECT id FROM res_users WHERE login=%s",(tools.ustr(login),)) res = cr.fetchone() tools.debug(res) if res: cr.close() return res[0] if not res_company_ldap['create_user']: continue action_id = action_obj.search(cr, 1, [('usage', '=', 'menu')])[0] if res_company_ldap['user']: res = self.copy(cr, 1, res_company_ldap['user'], default={'active': True}) self.write(cr, 1, res, { 'name': name, 'login': login.encode('utf-8'), 'company_id': res_company_ldap['company'], }) else: res = self.create(cr, 1, { 'name': name, 'login': login.encode('utf-8'), 'company_id': res_company_ldap['company'], 'action_id': action_id, 'menu_id': action_id, }) cr.commit() cr.close() return res l.unbind() except Exception, e: tools.debug(e) continue cr.close() return False
tools.debug(res)
logger.debug(res)
def login(self, db, login, password): ret = super(users,self).login(db, login, password) tools.debug(ret) if ret: return ret pool = pooler.get_pool(db) cr = pooler.get_db(db).cursor() action_obj = pool.get('ir.actions.actions') cr.execute(""" SELECT id, company, ldap_server, ldap_server_port, ldap_binddn, ldap_password, ldap_filter, ldap_base, "user", create_user FROM res_company_ldap WHERE ldap_server != '' and ldap_binddn != '' ORDER BY sequence""") for res_company_ldap in cr.dictfetchall(): tools.debug(res_company_ldap) try: l = ldap.open(res_company_ldap['ldap_server'], res_company_ldap['ldap_server_port']) if l.simple_bind_s(res_company_ldap['ldap_binddn'], res_company_ldap['ldap_password']): base = res_company_ldap['ldap_base'] scope = ldap.SCOPE_SUBTREE filter = filter_format(res_company_ldap['ldap_filter'], (login,)) retrieve_attributes = None result_id = l.search(base, scope, filter, retrieve_attributes) timeout = 60 result_type, result_data = l.result(result_id, timeout) if not result_data: continue if result_type == ldap.RES_SEARCH_RESULT and len(result_data) == 1: dn = result_data[0][0] tools.debug(dn) name = result_data[0][1]['cn'][0] if l.bind_s(dn, password): l.unbind() cr.execute("SELECT id FROM res_users WHERE login=%s",(tools.ustr(login),)) res = cr.fetchone() tools.debug(res) if res: cr.close() return res[0] if not res_company_ldap['create_user']: continue action_id = action_obj.search(cr, 1, [('usage', '=', 'menu')])[0] if res_company_ldap['user']: res = self.copy(cr, 1, res_company_ldap['user'], default={'active': True}) self.write(cr, 1, res, { 'name': name, 'login': login.encode('utf-8'), 'company_id': res_company_ldap['company'], }) else: res = self.create(cr, 1, { 'name': name, 'login': login.encode('utf-8'), 'company_id': res_company_ldap['company'], 'action_id': action_id, 'menu_id': action_id, }) cr.commit() cr.close() return res l.unbind() except Exception, e: tools.debug(e) continue cr.close() return False
tools.debug(e)
logger.warning("Cannot auth", exc_info=True)
def login(self, db, login, password): ret = super(users,self).login(db, login, password) tools.debug(ret) if ret: return ret pool = pooler.get_pool(db) cr = pooler.get_db(db).cursor() action_obj = pool.get('ir.actions.actions') cr.execute(""" SELECT id, company, ldap_server, ldap_server_port, ldap_binddn, ldap_password, ldap_filter, ldap_base, "user", create_user FROM res_company_ldap WHERE ldap_server != '' and ldap_binddn != '' ORDER BY sequence""") for res_company_ldap in cr.dictfetchall(): tools.debug(res_company_ldap) try: l = ldap.open(res_company_ldap['ldap_server'], res_company_ldap['ldap_server_port']) if l.simple_bind_s(res_company_ldap['ldap_binddn'], res_company_ldap['ldap_password']): base = res_company_ldap['ldap_base'] scope = ldap.SCOPE_SUBTREE filter = filter_format(res_company_ldap['ldap_filter'], (login,)) retrieve_attributes = None result_id = l.search(base, scope, filter, retrieve_attributes) timeout = 60 result_type, result_data = l.result(result_id, timeout) if not result_data: continue if result_type == ldap.RES_SEARCH_RESULT and len(result_data) == 1: dn = result_data[0][0] tools.debug(dn) name = result_data[0][1]['cn'][0] if l.bind_s(dn, password): l.unbind() cr.execute("SELECT id FROM res_users WHERE login=%s",(tools.ustr(login),)) res = cr.fetchone() tools.debug(res) if res: cr.close() return res[0] if not res_company_ldap['create_user']: continue action_id = action_obj.search(cr, 1, [('usage', '=', 'menu')])[0] if res_company_ldap['user']: res = self.copy(cr, 1, res_company_ldap['user'], default={'active': True}) self.write(cr, 1, res, { 'name': name, 'login': login.encode('utf-8'), 'company_id': res_company_ldap['company'], }) else: res = self.create(cr, 1, { 'name': name, 'login': login.encode('utf-8'), 'company_id': res_company_ldap['company'], 'action_id': action_id, 'menu_id': action_id, }) cr.commit() cr.close() return res l.unbind() except Exception, e: tools.debug(e) continue cr.close() return False
except:
except ExceptionNoTb:
def check(self, db, uid, passwd): try: return super(users,self).check(db, uid, passwd) except: # AccessDenied pass cr = pooler.get_db(db).cursor() user = self.browse(cr, 1, uid) if user and user.company_id.ldaps: for res_company_ldap in user.company_id.ldaps: try: l = ldap.open(res_company_ldap.ldap_server, res_company_ldap.ldap_server_port) if l.simple_bind_s(res_company_ldap.ldap_binddn, res_company_ldap.ldap_password): base = res_company_ldap.ldap_base scope = ldap.SCOPE_SUBTREE filter = filter_format(res_company_ldap.ldap_filter, (user.login,)) retrieve_attributes = None result_id = l.search(base, scope, filter, retrieve_attributes) timeout = 60 result_type, result_data = l.result(result_id, timeout) if result_data and result_type == ldap.RES_SEARCH_RESULT and len(result_data) == 1: dn = result_data[0][0] if l.bind_s(dn, passwd): l.unbind() self._uid_cache.setdefault(db, {})[uid] = passwd cr.close() return True l.unbind() except Exception, e: tools.debug(e) pass cr.close() raise security.ExceptionNoTb('AccessDenied')
tools.debug(e)
logger.warning('cannot check', exc_info=True)
def check(self, db, uid, passwd): try: return super(users,self).check(db, uid, passwd) except: # AccessDenied pass cr = pooler.get_db(db).cursor() user = self.browse(cr, 1, uid) if user and user.company_id.ldaps: for res_company_ldap in user.company_id.ldaps: try: l = ldap.open(res_company_ldap.ldap_server, res_company_ldap.ldap_server_port) if l.simple_bind_s(res_company_ldap.ldap_binddn, res_company_ldap.ldap_password): base = res_company_ldap.ldap_base scope = ldap.SCOPE_SUBTREE filter = filter_format(res_company_ldap.ldap_filter, (user.login,)) retrieve_attributes = None result_id = l.search(base, scope, filter, retrieve_attributes) timeout = 60 result_type, result_data = l.result(result_id, timeout) if result_data and result_type == ldap.RES_SEARCH_RESULT and len(result_data) == 1: dn = result_data[0][0] if l.bind_s(dn, passwd): l.unbind() self._uid_cache.setdefault(db, {})[uid] = passwd cr.close() return True l.unbind() except Exception, e: tools.debug(e) pass cr.close() raise security.ExceptionNoTb('AccessDenied')
help="Number of iterations this workcenter has to do in the specified operation of the routing."), 'hour_nbr': fields.float('Number of Hours', required=True, help="Time in hours for this workcenter to achieve the operation of the specified routing."),
help="Number of iterations this work Center has to do in the specified operation of the routing."), 'hour_nbr': fields.float('Number of Hours', required=True, help="Time in hours for this work Center to achieve the operation of the specified routing."),
def on_change_product_cost(self, cr, uid, ids, product_id, context=None): if context is None: context = {} value = {}
if guarantee_limit and date.today() > datetime.strptime(guarantee_limit, '%Y-%m-%d'):
if guarantee_limit and datetime.strptime(date.today().strftime('%Y-%m-%d'), '%Y-%m-%d') > datetime.strptime(guarantee_limit, '%Y-%m-%d'):
def onchange_operation_type(self, cr, uid, ids, type, guarantee_limit): """ On change of operation type it sets source location, destination location and to invoice field. @param product: Changed operation type. @param guarantee_limit: Guarantee limit of current record. @return: Dictionary of values. """ if not type: return {'value': { 'location_id': False, 'location_dest_id': False } } produc_id = self.pool.get('stock.location').search(cr, uid, [('name','=','Production')])[0] if type == 'add': stock_id = self.pool.get('stock.location').search(cr, uid, [('name','=','Stock')])[0] to_invoice = False if guarantee_limit and date.today() > datetime.strptime(guarantee_limit, '%Y-%m-%d'): to_invoice=True return {'value': { 'to_invoice': to_invoice, 'location_id': stock_id, 'location_dest_id': produc_id } } return {'value': { 'to_invoice': False, 'location_id': produc_id, 'location_dest_id': False } }
msg_txt += '\n\t'.join(message.description.split('\n')[:3]) + '...'
msg_txt += self.truncate_data(cr, uid, message.description, context=context)
def _get_display_text(self, cr, uid, ids, name, arg, context=None): if context is None: context = {} tz = context.get('tz') result = {} for message in self.browse(cr, uid, ids, context=context): msg_txt = '' if message.history: msg_txt += (message.email_from or '/') + _(' wrote on ') + format_date_tz(message.date, tz) + ':\n\t' if message.description: msg_txt += '\n\t'.join(message.description.split('\n')[:3]) + '...' else: msg_txt = (message.user_id.name or '/') + _(' on ') + format_date_tz(message.date, tz) + ':\n\t' if message.name == _('Opportunity'): msg_txt += _("Converted to Opportunity") else: msg_txt += _("Changed Status to: ") + message.name result[message.id] = msg_txt return result
def _hours_get(self, cr, uid, ids, field_names, args, context):
def _hours_get(self, cr, uid, ids, field_names, args, context=None): res = {}
def _hours_get(self, cr, uid, ids, field_names, args, context): cr.execute("SELECT task_id, COALESCE(SUM(hours),0) FROM project_task_work WHERE task_id =ANY(%s) GROUP BY task_id",(ids,)) hours = dict(cr.fetchall()) res = {} for task in self.browse(cr, uid, ids, context=context): res[task.id] = {} res[task.id]['effective_hours'] = hours.get(task.id, 0.0) res[task.id]['total_hours'] = task.remaining_hours + hours.get(task.id, 0.0) if (task.remaining_hours + hours.get(task.id, 0.0)): res[task.id]['progress'] = round(min(100.0 * hours.get(task.id, 0.0) / res[task.id]['total_hours'], 100),2) else: res[task.id]['progress'] = 0.0 if task.state in ('done','cancel'): res[task.id]['progress'] = 100.0 res[task.id]['delay_hours'] = res[task.id]['total_hours'] - task.planned_hours return res
res = {}
def _hours_get(self, cr, uid, ids, field_names, args, context): cr.execute("SELECT task_id, COALESCE(SUM(hours),0) FROM project_task_work WHERE task_id =ANY(%s) GROUP BY task_id",(ids,)) hours = dict(cr.fetchall()) res = {} for task in self.browse(cr, uid, ids, context=context): res[task.id] = {} res[task.id]['effective_hours'] = hours.get(task.id, 0.0) res[task.id]['total_hours'] = task.remaining_hours + hours.get(task.id, 0.0) if (task.remaining_hours + hours.get(task.id, 0.0)): res[task.id]['progress'] = round(min(100.0 * hours.get(task.id, 0.0) / res[task.id]['total_hours'], 100),2) else: res[task.id]['progress'] = 0.0 if task.state in ('done','cancel'): res[task.id]['progress'] = 100.0 res[task.id]['delay_hours'] = res[task.id]['total_hours'] - task.planned_hours return res
res[task.id] = {} res[task.id]['effective_hours'] = hours.get(task.id, 0.0) res[task.id]['total_hours'] = task.remaining_hours + hours.get(task.id, 0.0)
res[task.id] = {'effective_hours': hours.get(task.id, 0.0), 'total_hours': task.remaining_hours + hours.get(task.id, 0.0)}
def _hours_get(self, cr, uid, ids, field_names, args, context): cr.execute("SELECT task_id, COALESCE(SUM(hours),0) FROM project_task_work WHERE task_id =ANY(%s) GROUP BY task_id",(ids,)) hours = dict(cr.fetchall()) res = {} for task in self.browse(cr, uid, ids, context=context): res[task.id] = {} res[task.id]['effective_hours'] = hours.get(task.id, 0.0) res[task.id]['total_hours'] = task.remaining_hours + hours.get(task.id, 0.0) if (task.remaining_hours + hours.get(task.id, 0.0)): res[task.id]['progress'] = round(min(100.0 * hours.get(task.id, 0.0) / res[task.id]['total_hours'], 100),2) else: res[task.id]['progress'] = 0.0 if task.state in ('done','cancel'): res[task.id]['progress'] = 100.0 res[task.id]['delay_hours'] = res[task.id]['total_hours'] - task.planned_hours return res
res[task.id]['progress'] = round(min(100.0 * hours.get(task.id, 0.0) / res[task.id]['total_hours'], 100),2)
if hours.get(task.id, 0.0) > res[task.id]['total_hours']: res[task.id]['progress'] = round(100 - (max(100.0 * hours.get(task.id, 0.0) / res[task.id]['total_hours'], 100)) % 100, 2) else: res[task.id]['progress'] = round(min(100.0 * hours.get(task.id, 0.0) / res[task.id]['total_hours'], 100),2)
def _hours_get(self, cr, uid, ids, field_names, args, context): cr.execute("SELECT task_id, COALESCE(SUM(hours),0) FROM project_task_work WHERE task_id =ANY(%s) GROUP BY task_id",(ids,)) hours = dict(cr.fetchall()) res = {} for task in self.browse(cr, uid, ids, context=context): res[task.id] = {} res[task.id]['effective_hours'] = hours.get(task.id, 0.0) res[task.id]['total_hours'] = task.remaining_hours + hours.get(task.id, 0.0) if (task.remaining_hours + hours.get(task.id, 0.0)): res[task.id]['progress'] = round(min(100.0 * hours.get(task.id, 0.0) / res[task.id]['total_hours'], 100),2) else: res[task.id]['progress'] = 0.0 if task.state in ('done','cancel'): res[task.id]['progress'] = 100.0 res[task.id]['delay_hours'] = res[task.id]['total_hours'] - task.planned_hours return res
if (not src_acct.currency_id) or src_acct.currency_id.id == reference_currency_id:
if (not dest_acct.currency_id) or dest_acct.currency_id.id == reference_currency_id:
def _create_account_move_line(self, cr, uid, move, src_account_id, dest_account_id, reference_amount, reference_currency_id, context=None): """ Generate the account.move.line values to post to track the stock valuation difference due to the processing of the given stock move. """ # prepare default values considering that the destination accounts have the reference_currency_id as their main currency partner_id = (move.picking_id.address_id and move.picking_id.address_id.partner_id and move.picking_id.address_id.partner_id.id) or False debit_line_vals = { 'name': move.name, 'product_id': move.product_id and move.product_id.id or False, 'quantity': move.product_qty, 'ref': move.picking_id and move.picking_id.name or False, 'date': time.strftime('%Y-%m-%d') , 'partner_id': partner_id, 'debit': reference_amount, 'account_id': dest_account_id, } credit_line_vals = { 'name': move.name, 'product_id': move.product_id and move.product_id.id or False, 'quantity': move.product_qty, 'ref': move.picking_id and move.picking_id.name or False, 'date': time.strftime('%Y-%m-%d') , 'partner_id': partner_id, 'credit': reference_amount, 'account_id': src_account_id, }
partner = picking.address_id.partner_id
partner = picking.purchase_id.partner_id
def _get_address_invoice(self, cr, uid, picking): """ Gets invoice address of a partner @return {'contact': address, 'invoice': address} for invoice """ partner_obj = self.pool.get('res.partner') partner = picking.address_id.partner_id
def name_get(self, cr, uid, ids, context={}): if not len(ids): return [] reads = self.browse(cr, uid, ids, context) res = [] for record in reads: name = record.plan_id.name res.append((record['id'], name)) return res
def create(self, cr, uid, vals, context={}): id = super(hr_employee, self).create(cr, uid, vals, context=context) if vals.get('evaluation_plan_id', False): self.pool.get("hr_evaluation.evaluation").create(cr, uid, {'employee_id' : id, 'plan_id': vals['evaluation_plan_id']}, context=context) return id
self.write(cr, uid, ids, { 'state' : 'done'})
def survey_req_done(self, cr, uid, ids, context=None): if context is None: context = {} self.write(cr, uid, ids, { 'state' : 'done'}) hr_eval_obj = self.pool.get('hr_evaluation.evaluation') for id in self.browse(cr, uid, ids, context=context): flag = False wating_id = 0 tot_done_req = 0 records = hr_eval_obj.browse(cr, uid, [id.evaluation_id.id],context=context)[0].survey_request_ids for child in records: if child.state == "draft" : wating_id = child.id continue if child.state != "done": flag = True else : tot_done_req += 1 if not flag and wating_id: self.survey_req_waiting_answer(cr, uid, [wating_id], context) hr_eval_obj.write(cr, uid, [id.evaluation_id.id], {'progress' :tot_done_req * 100 / len(records)}, context=context)
res += [(user_email, case.email_from, case.email_cc, getattr(case,'priority') and case.priority or False)]
res += [(user_email, case.email_from, case.email_cc or False, getattr(case,'priority') and case.priority or False)]
def emails_get(self, cr, uid, ids, context={}):
if message_id: msg_ids = msg_pool.search(cr, uid, [('message_id','=',message_id)]) if msg_ids and len(msg_ids): return 0
def history_message(self, cr, uid, vals): dictcreate = dict(vals) ref_ids = str(dictcreate.get('ref_ids')).split(';') msg = dictcreate.get('message') msg = self.pool.get('email.server.tools').parse_message(msg) server_tools_pool = self.pool.get('email.server.tools') message_id = msg.get('message-id', False) msg_pool = self.pool.get('mailgate.message') msg_ids = [] res = {} res_ids = [] if message_id: msg_ids = msg_pool.search(cr, uid, [('message_id','=',message_id)]) if msg_ids and len(msg_ids): return 0 for ref_id in ref_ids: msg_new = dictcreate.get('message') ref = ref_id.split(',') model = ref[0] res_id = int(ref[1]) if message_id: msg_ids = msg_pool.search(cr, uid, [('message_id','=',message_id),('res_id','=',res_id),('model','=',model)]) if msg_ids and len(msg_ids): continue server_tools_pool.history_message(cr, uid, model, res_id, msg_new) res_ids.append(res_id) return len(res_ids)
self.write(cr, uid, ids, {'state': 'done', 'date': time.strftime('%Y-%m-%d %H:%M:%S')}) wf_service = netsvc.LocalService("workflow") for id in ids: wf_service.trg_trigger(uid, 'stock.move', id, cr)
if move_ids: self.write(cr, uid, move_ids, {'state': 'done', 'date_planned': time.strftime('%Y-%m-%d %H:%M:%S')}) wf_service = netsvc.LocalService("workflow") for id in move_ids: wf_service.trg_trigger(uid, 'stock.move', id, cr)
def action_done(self, cr, uid, ids, context=None): """ Makes the move done and if all moves are done, it will finish the picking. @return: """ partial_datas='' picking_ids = [] partial_obj=self.pool.get('stock.partial.picking') partial_id=partial_obj.search(cr,uid,[]) if partial_id: partial_datas=partial_obj.read(cr,uid,partial_id)[0] if context is None: context = {}
'date' : lambda *a: (parser.parse(datetime.date.today().strftime('%Y-%m-%d')) + relativedelta(months =+ 1)).strftime('%Y-%m-%d'),
'date' : lambda *a: (parser.parse(datetime.now().strftime('%Y-%m-%d')) + relativedelta(months =+ 1)).strftime('%Y-%m-%d'),
def create(self, cr, uid, vals, context=None): if context is None: context = {} id = super(hr_employee, self).create(cr, uid, vals, context=context) if vals.get('evaluation_plan_id', False): self.pool.get('hr_evaluation.evaluation').create(cr, uid, {'employee_id' : id, 'plan_id': vals['evaluation_plan_id']}, context=context) return id
'date_deadline': (parser.parse(datetime.date.today().strftime('%Y-%m-%d')) + relativedelta(months =+ 1)).strftime('%Y-%m-%d'),
'date_deadline': (parser.parse(datetime.now().strftime('%Y-%m-%d')) + relativedelta(months =+ 1)).strftime('%Y-%m-%d'),
def button_plan_in_progress(self, cr, uid, ids, context=None): hr_eval_inter_obj = self.pool.get('hr.evaluation.interview') if context is None: context = {} apprai_id = [] for evaluation in self.browse(cr, uid, ids, context=context): wait = False for phase in evaluation.plan_id.phase_ids: childs = [] if phase.action == "bottom-up": childs = evaluation.employee_id.child_ids elif phase.action in ("top-down", "final"): if evaluation.employee_id.parent_id: childs = [evaluation.employee_id.parent_id] elif phase.action == "self": childs = [evaluation.employee_id] for child in childs:
planning.id::varchar(32) || '-' || COALESCE(users.id,0)::varchar(32) AS id,
(1000*(planning.id) + users.id)::integer AS id,
def init(self, cr): cr.execute(""" CREATE OR REPLACE VIEW report_account_analytic_planning_user AS ( SELECT planning.id AS planning_id, planning.id::varchar(32) || '-' || COALESCE(users.id,0)::varchar(32) AS id, planning.business_days, users.id AS user_id, (SELECT sum(line1.amount_in_base_uom) FROM report_account_analytic_planning_line line1 WHERE ( SELECT COUNT(1) FROM project_task task WHERE task.planning_line_id = line1.id ) > 0 AND line1.user_id = users.id AND line1.planning_id = planning.id )AS plan_tasks, (SELECT SUM(line1.amount_in_base_uom) FROM report_account_analytic_planning_line line1 WHERE ( SELECT COUNT(1) FROM project_task task WHERE task.planning_line_id = line1.id ) = 0 AND line1.user_id = users.id AND line1.planning_id = planning.id ) AS plan_open, (SELECT -(SUM(holidays.number_of_days)) FROM hr_holidays holidays WHERE holidays.employee_id IN ( SELECT emp.id FROM hr_employee emp, resource_resource res WHERE emp.resource_id = res.id and res.user_id = users.id ) AND holidays.state IN ('validate') AND holidays.type = 'remove' AND holidays.date_from >= planning.date_from AND holidays.date_to <= planning.date_to ) AS holiday
planning.id::varchar(32) || '-' || '0' AS id,
(1000*(planning.id) - 1)::integer AS id,
def init(self, cr): cr.execute(""" CREATE OR REPLACE VIEW report_account_analytic_planning_user AS ( SELECT planning.id AS planning_id, planning.id::varchar(32) || '-' || COALESCE(users.id,0)::varchar(32) AS id, planning.business_days, users.id AS user_id, (SELECT sum(line1.amount_in_base_uom) FROM report_account_analytic_planning_line line1 WHERE ( SELECT COUNT(1) FROM project_task task WHERE task.planning_line_id = line1.id ) > 0 AND line1.user_id = users.id AND line1.planning_id = planning.id )AS plan_tasks, (SELECT SUM(line1.amount_in_base_uom) FROM report_account_analytic_planning_line line1 WHERE ( SELECT COUNT(1) FROM project_task task WHERE task.planning_line_id = line1.id ) = 0 AND line1.user_id = users.id AND line1.planning_id = planning.id ) AS plan_open, (SELECT -(SUM(holidays.number_of_days)) FROM hr_holidays holidays WHERE holidays.employee_id IN ( SELECT emp.id FROM hr_employee emp, resource_resource res WHERE emp.resource_id = res.id and res.user_id = users.id ) AND holidays.state IN ('validate') AND holidays.type = 'remove' AND holidays.date_from >= planning.date_from AND holidays.date_to <= planning.date_to ) AS holiday
'work_phone': fields.related('address_id', 'phone', type='char', string='Work Phone', readonly=True),
'work_phone': fields.related('address_id', 'phone', type='char', size=32, string='Work Phone', readonly=True),
def job_open(self, cr, uid, ids, *args): self.write(cr, uid, ids, {'state': 'open'}) return True
return {}
if not journal_id: return False journal_pool = self.pool.get('account.journal') journal = journal_pool.browse(cr, uid, journal_id) account_id = journal.default_credit_account_id or journal.default_debit_account_id tax_id = False if account_id and account_id.tax_ids: tax_id = account_id.tax_ids[0].id return {'value':{'tax_id':tax_id}}
def onchange_journal(self, cr, uid, ids, journal_id): return {}
</form>""" % (str(journal), str(period))
</form>""" % (tools.ustr(journal), tools.ustr(period))
def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False, submenu=False): """ Returns views and fields for current model where view will depend on {view_type}. @param cr: A database cursor @param user: ID of the user currently logged in @param view_id: list of fields, which required to read signatures @param view_type: defines a view type. it can be one of (form, tree, graph, calender, gantt, search, mdx) @param context: context arguments, like lang, time zone @param toolbar: contains a list of reports, wizards, and links related to current model
self.cr.execute("select name from account_invoice as ac where id = %d" %(inv_id)) res = self.cr.fetchone() if res:
if inv_id: self.cr.execute("select name from account_invoice as ac where id = %d" %(inv_id)) res = self.cr.fetchone()
def _get_invoice(self,inv_id,user): res={} self.cr.execute("select name from account_invoice as ac where id = %d" %(inv_id)) res = self.cr.fetchone() if res: return res[0] else: return ''
partner_id, date_order=False):
partner_id, date_order=False,fiscal_position=False):
def product_uom_change(self, cr, uid, ids, pricelist, product, qty, uom, partner_id, date_order=False): res = self.product_id_change(cr, uid, ids, pricelist, product, qty, uom, partner_id, date_order=date_order) if 'product_uom' in res['value']: del res['value']['product_uom'] if not uom: res['value']['price_unit'] = 0.0 return res
partner_id, date_order=date_order)
partner_id, date_order=date_order,fiscal_position=fiscal_position)
def product_uom_change(self, cr, uid, ids, pricelist, product, qty, uom, partner_id, date_order=False): res = self.product_id_change(cr, uid, ids, pricelist, product, qty, uom, partner_id, date_order=date_order) if 'product_uom' in res['value']: del res['value']['product_uom'] if not uom: res['value']['price_unit'] = 0.0 return res
return rset1._iter()
return list(rset1._iter())
def todate(date): val = parser.parse(''.join((re.compile('\d')).findall(date))) return val
'delay': fields.float('Delivery Lead Time', required=True, help="Number of days between the order confirmation the the shipping of the products to the customer", readonly=True, states={'draft': [('readonly', False)]}),
'delay': fields.float('Delivery Lead Time', required=True, help="Number of days between the order confirmation the shipping of the products to the customer", readonly=True, states={'draft': [('readonly', False)]}),
def _number_packages(self, cr, uid, ids, field_name, arg, context=None): if context is None: context = {} res = {} for line in self.browse(cr, uid, ids, context=context): try: res[line.id] = int((line.product_uom_qty+line.product_packaging.qty-0.0001) / line.product_packaging.qty) except: res[line.id] = 1 return res
result = s.exp_list()
result = s.exp_list(document=True)
def db_list(self): #return pooler.pool_dic.keys() s = netsvc.ExportService.getService('db') result = s.exp_list() self.db_name_list = [] for db_name in result: db, cr = None, None try: try: db = pooler.get_db_only(db_name) cr = db.cursor() cr.execute("SELECT 1 FROM pg_class WHERE relkind = 'r' AND relname = 'ir_module_module'") if not cr.fetchone(): continue cr.execute("select id from ir_module_module where name like 'document%' and state='installed' ") res = cr.fetchone() if res and len(res): self.db_name_list.append(db_name) cr.commit() except Exception, e: log(e) finally: if cr is not None: cr.close() #if db is not None: # pooler.close_db(db_name) return self.db_name_list
cr.execute("UPDATE %s set freq='',interval=0,count=0,end_date=Null,\
cr.execute("UPDATE %s set freq='None',interval=0,count=0,end_date=Null,\
def _set_rrulestring(self, cr, uid, id, name, value, arg, context): """ Set rule string. @param self: The object pointer @param cr: the current row, from the database cursor, @param id: List of calendar event's ids. @param context: A standard dictionary for contextual values @return: dictionary of rrule value. """ cr.execute("UPDATE %s set freq='',interval=0,count=0,end_date=Null,\ mo=False,tu=False,we=False,th=False,fr=False,sa=False,su=False,\ day=0,select1=False,month_list=0 ,byday=False where id=%s" % (self._table, id)) if not value: return True val = {} for part in value.split(';'): if part.lower().__contains__('freq') and len(value.split(';')) <=2: rrule_type = part.lower()[5:] break else: rrule_type = 'custom' break ans = value.split(';') for i in ans: val[i.split('=')[0].lower()] = i.split('=')[1].lower() if int(val.get('interval')) > 1: #If interval is other than 1 rule is custom rrule_type = 'custom'
day=0,select1=False,month_list=0 ,byday=False where id=%s" % (self._table, id))
day=0,select1='date',month_list=Null ,byday=Null where id=%s" % (self._table, id))
def _set_rrulestring(self, cr, uid, id, name, value, arg, context): """ Set rule string. @param self: The object pointer @param cr: the current row, from the database cursor, @param id: List of calendar event's ids. @param context: A standard dictionary for contextual values @return: dictionary of rrule value. """ cr.execute("UPDATE %s set freq='',interval=0,count=0,end_date=Null,\ mo=False,tu=False,we=False,th=False,fr=False,sa=False,su=False,\ day=0,select1=False,month_list=0 ,byday=False where id=%s" % (self._table, id)) if not value: return True val = {} for part in value.split(';'): if part.lower().__contains__('freq') and len(value.split(';')) <=2: rrule_type = part.lower()[5:] break else: rrule_type = 'custom' break ans = value.split(';') for i in ans: val[i.split('=')[0].lower()] = i.split('=')[1].lower() if int(val.get('interval')) > 1: #If interval is other than 1 rule is custom rrule_type = 'custom'
if int(val.get('interval')) > 1:
if not val.get('interval'): rrule_type = 'custom' elif int(val.get('interval')) > 1:
def _set_rrulestring(self, cr, uid, id, name, value, arg, context): """ Set rule string. @param self: The object pointer @param cr: the current row, from the database cursor, @param id: List of calendar event's ids. @param context: A standard dictionary for contextual values @return: dictionary of rrule value. """ cr.execute("UPDATE %s set freq='',interval=0,count=0,end_date=Null,\ mo=False,tu=False,we=False,th=False,fr=False,sa=False,su=False,\ day=0,select1=False,month_list=0 ,byday=False where id=%s" % (self._table, id)) if not value: return True val = {} for part in value.split(';'): if part.lower().__contains__('freq') and len(value.split(';')) <=2: rrule_type = part.lower()[5:] break else: rrule_type = 'custom' break ans = value.split(';') for i in ans: val[i.split('=')[0].lower()] = i.split('=')[1].lower() if int(val.get('interval')) > 1: #If interval is other than 1 rule is custom rrule_type = 'custom'
new_val['byday'] = d[:1] new_val['week_list'] = d[1:].upper()
if '-' in d: new_val['byday'] = d[:2] new_val['week_list'] = d[2:4].upper() else: new_val['byday'] = d[:1] new_val['week_list'] = d[1:3].upper()
def _set_rrulestring(self, cr, uid, id, name, value, arg, context): """ Set rule string. @param self: The object pointer @param cr: the current row, from the database cursor, @param id: List of calendar event's ids. @param context: A standard dictionary for contextual values @return: dictionary of rrule value. """ cr.execute("UPDATE %s set freq='',interval=0,count=0,end_date=Null,\ mo=False,tu=False,we=False,th=False,fr=False,sa=False,su=False,\ day=0,select1=False,month_list=0 ,byday=False where id=%s" % (self._table, id)) if not value: return True val = {} for part in value.split(';'): if part.lower().__contains__('freq') and len(value.split(';')) <=2: rrule_type = part.lower()[5:] break else: rrule_type = 'custom' break ans = value.split(';') for i in ans: val[i.split('=')[0].lower()] = i.split('=')[1].lower() if int(val.get('interval')) > 1: #If interval is other than 1 rule is custom rrule_type = 'custom'
if datas.get('interval') < 1: raise osv.except_osv(_('Error!'), ("Please select proper Interval"))
interval_srting = datas.get('interval') and (';INTERVAL=' + str(datas.get('interval'))) or ''
def compute_rule_string(self, cr, uid, datas, context=None, *args): """ Compute rule string. @param self: the object pointer @param cr: the current row, from the database cursor, @param uid: the current user’s ID for security checks, @param datas: dictionary of freq and interval value. @return: string value which compute FREQILY;INTERVAL """
rrule_string = 'FREQ=' + freq.upper() + weekstring + ';INTERVAL=' + \ str(datas.get('interval')) + enddate + monthstring + yearstring
rrule_string = 'FREQ=' + freq.upper() + weekstring + interval_srting \ + enddate + monthstring + yearstring
def compute_rule_string(self, cr, uid, datas, context=None, *args): """ Compute rule string. @param self: the object pointer @param cr: the current row, from the database cursor, @param uid: the current user’s ID for security checks, @param datas: dictionary of freq and interval value. @return: string value which compute FREQILY;INTERVAL """