rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
date_done = self.browse(cr, uid, ids[0]).date_done if (date_done > time.strftime('%Y-%m-%d %H:%M:%S')): raise osv.except_osv("Error", "Segment cannot be closed before end date")
def state_done_set(self, cr, uid, ids, *args): date_done = self.browse(cr, uid, ids[0]).date_done if (date_done > time.strftime('%Y-%m-%d %H:%M:%S')): raise osv.except_osv("Error", "Segment cannot be closed before end date")
[('state', 'in', ['inprogress', 'todo']), ('segment_id', '=', ids[0])]) if wi_ids : raise osv.except_osv("Error", "Segment cannot be done before all workitems are processed") self.write(cr, uid, ids, {'state': 'done'})
[('state', '=', 'todo'), ('segment_id', 'in', ids)]) self.pool.get("marketing.campaign.workitem").write(cr, uid, wi_ids, {'state':'cancelled'}) self.write(cr, uid, ids, {'state': 'done','date_done': time.strftime('%Y-%m-%d %H:%M:%S')})
def state_done_set(self, cr, uid, ids, *args): date_done = self.browse(cr, uid, ids[0]).date_done if (date_done > time.strftime('%Y-%m-%d %H:%M:%S')): raise osv.except_osv("Error", "Segment cannot be closed before end date")
self.write(cr, uid, ids, {'state': 'cancelled'}) return True
wi_ids = self.pool.get("marketing.campaign.workitem").search(cr, uid, [('state', '=', 'todo'), ('segment_id', 'in', ids)]) self.pool.get("marketing.campaign.workitem").write(cr, uid, wi_ids, {'state':'cancelled'}) self.write(cr, uid, ids, {'state': 'cancelled','date_done': time.strftime('%Y-%m-%d %H:%M:%S')}) return True
def state_cancel_set(self, cr, uid, ids, *args): self.write(cr, uid, ids, {'state': 'cancelled'}) return True
self.process_segment(cr, uid, {'segment_ids' : ids})
self.process_segment(cr, uid, ids)
def synchroniz(self, cr, uid, ids, *args): self.process_segment(cr, uid, {'segment_ids' : ids}) return True
def process_segment(self, cr, uid, context={}): last_action_date = '' if 'segment_ids' in context: segment_ids = context['segment_ids'] last_action_date = (datetime.now() + _intervalTypes['days'](-1) \ ).strftime('%Y-%m-%d %H:%M:%S') else : segment_ids = self.search(cr, uid, [('state', '=', 'running')])
def process_segment(self, cr, uid, segment_ids=None, context={}): if not segment_ids: segment_ids = self.search(cr, uid, [('state', '=', 'running')], context=context)
def process_segment(self, cr, uid, context={}): last_action_date = '' if 'segment_ids' in context: segment_ids = context['segment_ids'] last_action_date = (datetime.now() + _intervalTypes['days'](-1) \ ).strftime('%Y-%m-%d %H:%M:%S')
for segment in self.browse(cr, uid, segment_ids):
for segment in self.browse(cr, uid, segment_ids, context=context):
def process_segment(self, cr, uid, context={}): last_action_date = '' if 'segment_ids' in context: segment_ids = context['segment_ids'] last_action_date = (datetime.now() + _intervalTypes['days'](-1) \ ).strftime('%Y-%m-%d %H:%M:%S')
uid, [('start', '=', True), ('campaign_id', '=', segment.campaign_id.id)]) if (segment.sync_last_date and \ segment.sync_last_date <= action_date )\ or not segment.sync_last_date : model_obj = self.pool.get(segment.object_id.model) criteria = [(segment.sync_mode, '<=', action_date)] if last_action_date : criteria.append((segment.sync_mode, '>=', last_action_date)) object_ids = model_obj.search(cr, uid, criteria) for o_ids in model_obj.read(cr, uid, object_ids) : partner_id = 'partner_id' in o_ids and o_ids['partner_id'] \ or False if partner_id: for act_id in act_ids: wi_vals = {'segment_id': segment.id, 'activity_id': act_id, 'date': action_date, 'partner_id': partner_id[0], 'state': 'todo', } self.pool.get('marketing.campaign.workitem').create( cr, uid, wi_vals) self.write(cr, uid, segment.id, {'sync_last_date':action_date}) return True marketing_campaign_segment() class marketing_campaign_activity(osv.osv):
uid, [('start', '=', True), ('campaign_id', '=', segment.campaign_id.id)]) model_obj = self.pool.get(segment.object_id.model) criteria = [] if segment.sync_last_date: criteria += [(segment.sync_mode, '>', segment.sync_last_date)] if segment.ir_filter_id: criteria += segment.ir_filter_id.domain object_ids = model_obj.search(cr, uid, criteria) for o_ids in model_obj.browse(cr, uid, object_ids, context=context) : for act_id in act_ids: wi_vals = { 'segment_id': segment.id, 'activity_id': act_id, 'date': action_date, 'partner_id': o_ids.partner_id and o_ids.partner_id.id or False, 'state': 'todo', 'res_id': o_ids.id } self.pool.get('marketing.campaign.workitem').create(cr, uid, wi_vals) self.write(cr, uid, segment.id, {'sync_last_date':action_date}) return True marketing_campaign_segment() class marketing_campaign_activity(osv.osv):
def process_segment(self, cr, uid, context={}): last_action_date = '' if 'segment_ids' in context: segment_ids = context['segment_ids'] last_action_date = (datetime.now() + _intervalTypes['days'](-1) \ ).strftime('%Y-%m-%d %H:%M:%S')
'start': fields.boolean('Start',help= "Its necessary to start activity \ before running campaign"),
'start': fields.boolean('Start',help= "This activity is launched when the campaign starts."),
def process_segment(self, cr, uid, context={}): last_action_date = '' if 'segment_ids' in context: segment_ids = context['segment_ids'] last_action_date = (datetime.now() + _intervalTypes['days'](-1) \ ).strftime('%Y-%m-%d %H:%M:%S')
help="It is simple python condition that is to \ be tested before action is executed. Eg : revenue > 10"),
help="Python condition to know if the activity can be launched"),
def process_segment(self, cr, uid, context={}): last_action_date = '' if 'segment_ids' in context: segment_ids = context['segment_ids'] last_action_date = (datetime.now() + _intervalTypes['days'](-1) \ ).strftime('%Y-%m-%d %H:%M:%S')
mct_obj = self.pool.get('marketing.campaign.transition') process_to_id = mct_obj.search(cr,uid, [ ('activity_from_id','=', workitem.activity_id.id)]) for mct_id in mct_obj.browse(cr, uid, process_to_id):
for mct_id in workitem.activity_id.to_ids: launch_date = time.strftime('%Y-%m-%d %H:%M:%S')
def process_chain(self, cr, uid, workitem_id, context={}): workitem = self.browse(cr, uid, workitem_id) mct_obj = self.pool.get('marketing.campaign.transition') process_to_id = mct_obj.search(cr,uid, [ ('activity_from_id','=', workitem.activity_id.id)]) for mct_id in mct_obj.browse(cr, uid, process_to_id): if mct_id.interval_type and mct_id.interval_nbr : launch_date = (datetime.now() + _intervalTypes[ \ mct_id.interval_type](mct_id.interval_nbr) \ ).strftime('%Y-%m-%d %H:%M:%S') launch_date = time.strftime('%Y-%m-%d %H:%M:%S') workitem_vals = {'segment_id': workitem.segment_id.id, 'activity_id': mct_id.activity_to_id.id, 'date': launch_date, 'partner_id': workitem.partner_id.id, 'state': 'todo', } self.create(cr, uid, workitem_vals)
launch_date = time.strftime('%Y-%m-%d %H:%M:%S') workitem_vals = {'segment_id': workitem.segment_id.id, 'activity_id': mct_id.activity_to_id.id, 'date': launch_date, 'partner_id': workitem.partner_id.id, 'state': 'todo', }
workitem_vals = { 'segment_id': workitem.segment_id.id, 'activity_id': mct_id.activity_to_id.id, 'date': launch_date, 'partner_id': workitem.partner_id.id, 'res_id': workitem.res_id, 'state': 'todo', }
def process_chain(self, cr, uid, workitem_id, context={}): workitem = self.browse(cr, uid, workitem_id) mct_obj = self.pool.get('marketing.campaign.transition') process_to_id = mct_obj.search(cr,uid, [ ('activity_from_id','=', workitem.activity_id.id)]) for mct_id in mct_obj.browse(cr, uid, process_to_id): if mct_id.interval_type and mct_id.interval_nbr : launch_date = (datetime.now() + _intervalTypes[ \ mct_id.interval_type](mct_id.interval_nbr) \ ).strftime('%Y-%m-%d %H:%M:%S') launch_date = time.strftime('%Y-%m-%d %H:%M:%S') workitem_vals = {'segment_id': workitem.segment_id.id, 'activity_id': mct_id.activity_to_id.id, 'date': launch_date, 'partner_id': workitem.partner_id.id, 'state': 'todo', } self.create(cr, uid, workitem_vals)
res = self.pool.get('marketing.campaign.activity').process( cr, uid, wi.activity_id.id, wi.id, context) if res : self.write(cr, uid, wi.id, {'state': 'done'}) self.process_chain(cr, uid, wi.id, context) else : self.write(cr, uid, wi.id, {'state': 'exception', 'error_msg': res['error_msg']})
if wi.campaign_id.mode in ('manual','active'): self.pool.get('marketing.campaign.activity').process( cr, uid, wi.activity_id.id, wi.id, context) self.write(cr, uid, wi.id, {'state': 'done'}) self.process_chain(cr, uid, wi.id, context)
def process(self, cr, uid, workitem_ids, context={}): for wi in self.browse(cr, uid, workitem_ids): if wi.state == 'todo':# we searched the wi which are in todo state #then y v keep this filter again eval_context = { 'pool': self.pool, 'cr': cr, 'uid': uid, 'wi': wi, 'object': wi.activity_id, 'transition': wi.activity_id.to_ids } expr = eval(str(wi.activity_id.condition), eval_context) if expr: try : res = self.pool.get('marketing.campaign.activity').process( cr, uid, wi.activity_id.id, wi.id, context) if res : self.write(cr, uid, wi.id, {'state': 'done'}) self.process_chain(cr, uid, wi.id, context) else : self.write(cr, uid, wi.id, {'state': 'exception', 'error_msg': res['error_msg']}) except Exception,e: self.write(cr, uid, wi.id, {'state': 'exception'}) else : self.write(cr, uid, wi.id, {'state': 'cancelled'})
workitem_ids = self.search(cr, uid, [('state', '=', 'todo'),
camp_obj = self.pool.get('marketing.campaign') camp_ids = camp_obj.search(cr, uid, [('state','=','running')], context=context) for camp in camp_obj.browse(cr, uid, camp_ids, context=context): if camp.mode in ('test_realtime','active'): workitem_ids = self.search(cr, uid, [('state', '=', 'todo'),
def process_all(self, cr, uid, context={}): workitem_ids = self.search(cr, uid, [('state', '=', 'todo'), ('date','<=', time.strftime('%Y-%m-%d %H:%M:%S'))]) if workitem_ids: self.process(cr, uid, workitem_ids, context)
res= super(stock_invoice_onshipping, self).view_init(cr, uid, fields_list, context=context) pick_obj=self.pool.get('stock.picking') count=0 for pick in pick_obj.browse(cr, uid,context.get('active_ids', False)):
res = super(stock_invoice_onshipping, self).view_init(cr, uid, fields_list, context=context) pick_obj = self.pool.get('stock.picking') count = 0 active_ids = context.get('active_ids',[]) for pick in pick_obj.browse(cr, uid, active_ids):
def view_init(self, cr, uid, fields_list, context=None): if context is None: context = {} res= super(stock_invoice_onshipping, self).view_init(cr, uid, fields_list, context=context) pick_obj=self.pool.get('stock.picking') count=0 for pick in pick_obj.browse(cr, uid,context.get('active_ids', False)): if pick.invoice_state != '2binvoiced': count=count+1 if len(context.get('active_ids'))==1 and count==1: raise osv.except_osv(_('Warning !'),'This picking list does not require invoicing.') if len(context.get('active_ids'))==count: raise osv.except_osv(_('Warning !'),'None of these picking lists require invoicing.') return res
count=count+1 if len(context.get('active_ids'))==1 and count==1: raise osv.except_osv(_('Warning !'),'This picking list does not require invoicing.') if len(context.get('active_ids'))==count: raise osv.except_osv(_('Warning !'),'None of these picking lists require invoicing.')
count += 1 if len(active_ids) == 1 and count: raise osv.except_osv(_('Warning !'), _('This picking list does not require invoicing.')) if len(active_ids) == count: raise osv.except_osv(_('Warning !'), _('None of these picking lists require invoicing.'))
def view_init(self, cr, uid, fields_list, context=None): if context is None: context = {} res= super(stock_invoice_onshipping, self).view_init(cr, uid, fields_list, context=context) pick_obj=self.pool.get('stock.picking') count=0 for pick in pick_obj.browse(cr, uid,context.get('active_ids', False)): if pick.invoice_state != '2binvoiced': count=count+1 if len(context.get('active_ids'))==1 and count==1: raise osv.except_osv(_('Warning !'),'This picking list does not require invoicing.') if len(context.get('active_ids'))==count: raise osv.except_osv(_('Warning !'),'None of these picking lists require invoicing.') return res
def _get_type(self, cr, uid, context=None): """ To get invoice type. @param self: The object pointer. @param cr: A database cursor @param uid: ID of the user currently logged in @param ids: The ID or list of IDs if we want more than one @param context: A standard dictionary @return: Invoice type """
def _get_type(self, pick): src_usage = dest_usage = None pick_type = None if pick.invoice_state=='2binvoiced': if pick.move_lines: src_usage = pick.move_lines[0].location_id.usage dest_usage = pick.move_lines[0].location_dest_id.usage if pick.type == 'out' and dest_usage == 'supplier': pick_type = 'in_refund' elif pick.type == 'out' and dest_usage == 'customer': pick_type = 'out_invoice' elif pick.type == 'in' and src_usage == 'supplier': pick_type = 'in_invoice' elif pick.type == 'in' and src_usage == 'customer': pick_type = 'out_refund' else: pick_type = 'out_invoice' return pick_type def create_invoice(self, cr, uid, ids, context=None):
def view_init(self, cr, uid, fields_list, context=None): if context is None: context = {} res= super(stock_invoice_onshipping, self).view_init(cr, uid, fields_list, context=context) pick_obj=self.pool.get('stock.picking') count=0 for pick in pick_obj.browse(cr, uid,context.get('active_ids', False)): if pick.invoice_state != '2binvoiced': count=count+1 if len(context.get('active_ids'))==1 and count==1: raise osv.except_osv(_('Warning !'),'This picking list does not require invoicing.') if len(context.get('active_ids'))==count: raise osv.except_osv(_('Warning !'),'None of these picking lists require invoicing.') return res
picking_obj = self.pool.get('stock.picking') src_usage = dest_usage = None for pick in picking_obj.browse(cr, uid, context['active_ids'], context=context): if pick.invoice_state=='2binvoiced': if pick.move_lines: src_usage = pick.move_lines[0].location_id.usage dest_usage = pick.move_lines[0].location_dest_id.usage if pick.type == 'out' and dest_usage == 'supplier': type = 'in_refund' elif pick.type == 'out' and dest_usage == 'customer': type = 'out_invoice' elif pick.type == 'in' and src_usage == 'supplier': type = 'in_invoice' elif pick.type == 'in' and src_usage == 'customer': type = 'out_refund' else: type = 'out_invoice' return type _defaults = { 'type': _get_type, } def create_invoice(self, cr, uid, ids, context): """ To create invoice @param self: The object pointer. @param cr: A database cursor @param uid: ID of the user currently logged in @param ids: the ID or list of IDs if we want more than one @param context: A standard dictionary @return: Invoice ids """
def _get_type(self, cr, uid, context=None): """ To get invoice type. @param self: The object pointer. @param cr: A database cursor @param uid: ID of the user currently logged in @param ids: The ID or list of IDs if we want more than one @param context: A standard dictionary @return: Invoice type """ if context is None: context = {} picking_obj = self.pool.get('stock.picking') src_usage = dest_usage = None for pick in picking_obj.browse(cr, uid, context['active_ids'], context=context): if pick.invoice_state=='2binvoiced': if pick.move_lines: src_usage = pick.move_lines[0].location_id.usage dest_usage = pick.move_lines[0].location_dest_id.usage if pick.type == 'out' and dest_usage == 'supplier': type = 'in_refund' elif pick.type == 'out' and dest_usage == 'customer': type = 'out_invoice' elif pick.type == 'in' and src_usage == 'supplier': type = 'in_invoice' elif pick.type == 'in' and src_usage == 'customer': type = 'out_refund' else: type = 'out_invoice' return type
mod_obj = self.pool.get('ir.model.data') act_obj = self.pool.get('ir.actions.act_window') for onshipdata_obj in self.read(cr, uid, ids, ['journal_id', 'group', 'type', 'invoice_date']): if context.get('new_picking', False): onshipdata_obj[id] = onshipdata_obj.new_picking onshipdata_obj[ids] = onshipdata_obj.new_picking
onshipdata_obj = self.read(cr, uid, ids[0], ['journal_id', 'group', 'invoice_date']) if context.get('new_picking', False): onshipdata_obj['id'] = onshipdata_obj.new_picking onshipdata_obj[ids] = onshipdata_obj.new_picking
def create_invoice(self, cr, uid, ids, context): """ To create invoice @param self: The object pointer. @param cr: A database cursor @param uid: ID of the user currently logged in @param ids: the ID or list of IDs if we want more than one @param context: A standard dictionary @return: Invoice ids """ result = [] picking_obj = self.pool.get('stock.picking') mod_obj = self.pool.get('ir.model.data') act_obj = self.pool.get('ir.actions.act_window') for onshipdata_obj in self.read(cr, uid, ids, ['journal_id', 'group', 'type', 'invoice_date']): if context.get('new_picking', False): onshipdata_obj[id] = onshipdata_obj.new_picking onshipdata_obj[ids] = onshipdata_obj.new_picking
type = onshipdata_obj['type'] context['date_inv'] = onshipdata_obj['invoice_date'] res = picking_obj.action_invoice_create(cr, uid,context['active_ids'], journal_id = onshipdata_obj['journal_id'], group=onshipdata_obj['group'], type=type, context=context) invoice_ids = res.values() if not invoice_ids: raise osv.except_osv(_('Error'), _('Invoice is not created'))
context['date_inv'] = onshipdata_obj['invoice_date'] invoice_ids = [] for picking in picking_obj.browse(cr, uid, context.get('active_ids', []), context=context): if picking.invoice_state == '2binvoiced': res = picking_obj.action_invoice_create(cr, uid, [picking.id], journal_id = onshipdata_obj['journal_id'], group=onshipdata_obj['group'], type=self._get_type(picking), context=context) invoice_ids.extend(res.values()) if not invoice_ids: raise osv.except_osv(_('Error'), _('No invoice were created'))
def create_invoice(self, cr, uid, ids, context): """ To create invoice @param self: The object pointer. @param cr: A database cursor @param uid: ID of the user currently logged in @param ids: the ID or list of IDs if we want more than one @param context: A standard dictionary @return: Invoice ids """ result = [] picking_obj = self.pool.get('stock.picking') mod_obj = self.pool.get('ir.model.data') act_obj = self.pool.get('ir.actions.act_window') for onshipdata_obj in self.read(cr, uid, ids, ['journal_id', 'group', 'type', 'invoice_date']): if context.get('new_picking', False): onshipdata_obj[id] = onshipdata_obj.new_picking onshipdata_obj[ids] = onshipdata_obj.new_picking
'views': False,
def create_invoice(self, cr, uid, ids, context): """ To create invoice @param self: The object pointer. @param cr: A database cursor @param uid: ID of the user currently logged in @param ids: the ID or list of IDs if we want more than one @param context: A standard dictionary @return: Invoice ids """ result = [] picking_obj = self.pool.get('stock.picking') mod_obj = self.pool.get('ir.model.data') act_obj = self.pool.get('ir.actions.act_window') for onshipdata_obj in self.read(cr, uid, ids, ['journal_id', 'group', 'type', 'invoice_date']): if context.get('new_picking', False): onshipdata_obj[id] = onshipdata_obj.new_picking onshipdata_obj[ids] = onshipdata_obj.new_picking
'ca_theorical': fields.function(_analysis_all, method=True, multi='analytic_analysis', type='float', string='Theorical Revenue',
'ca_theorical': fields.function(_analysis_all, method=True, multi='analytic_analysis', type='float', string='Theoretical Revenue',
def _theorical_margin_calc(self, cr, uid, ids, name, arg, context=None): res = {} for account in self.browse(cr, uid, ids, context=context): res[account.id] = account.ca_theorical + account.total_cost for id in ids: res[id] = round(res.get(id, 0.0),2) return res
'theorical_margin': fields.function(_theorical_margin_calc, method=True, type='float', string='Theorical Margin',
'theorical_margin': fields.function(_theorical_margin_calc, method=True, type='float', string='Theoretical Margin',
def _theorical_margin_calc(self, cr, uid, ids, name, arg, context=None): res = {} for account in self.browse(cr, uid, ids, context=context): res[account.id] = account.ca_theorical + account.total_cost for id in ids: res[id] = round(res.get(id, 0.0),2) return res
'state': fields.char('Current state', size=32, readonly=True),
'state': fields.related('emp_id', 'state', string='Current state', type='char', required=True, readonly=True),
def sign_out_result(self, cr, uid, ids, context=None): if context is None: context = {} emp_obj = self.pool.get('hr.employee') for data in self.browse(cr, uid, ids, context=context): emp_id = data.emp_id.id emp_obj.attendance_action_change(cr, uid, [emp_id], type='action', dt=data.date) self._write(cr, uid, data, emp_id, context=context) return {}
in_out = res == 'sign_out' and 'out' or 'in'
in_out = (res == 'sign_out') and 'in' or 'out'
def check_state(self, cr, uid, ids, context=None): obj_model = self.pool.get('ir.model.data') if context is None: context = {} emp_id = self.default_get(cr, uid, context)['emp_id'] # get the latest action (sign_in or out) for this employee cr.execute('select action from hr_attendance where employee_id=%s and action in (\'sign_in\',\'sign_out\') order by name desc limit 1', (emp_id,)) res = (cr.fetchone() or ('sign_out',))[0] in_out = res == 'sign_out' and 'out' or 'in' #TODO: invert sign_in et sign_out model_data_ids = obj_model.search(cr,uid,[('model','=','ir.ui.view'),('name','=','view_hr_timesheet_sign_%s' % in_out)], context=context) resource_id = obj_model.read(cr, uid, model_data_ids, fields=['res_id'], context=context)[0]['res_id'] return { 'name': 'Sign in / Sign out', 'view_type': 'form', 'view_mode': 'tree,form', 'res_model': 'hr.sign.%s.project' % in_out, 'views': [(False,'tree'), (resource_id,'form')], 'type': 'ir.actions.act_window', 'target': 'new' }
if isinstance(type,dict): type = type.get('type','action')
def attendance_action_change(self, cr, uid, ids, type='action', context={}, dt=False, *args): id = False warning_sign = 'sign' if type == 'sign_in': warning_sign = "Sign In" elif type == 'sign_out': warning_sign = "Sign Out" for emp in self.read(cr, uid, ids, ['id'], context=context): if not self._action_check(cr, uid, emp['id'], dt, context): raise osv.except_osv(_('Warning'), _('You tried to %s with a date anterior to another event !\nTry to contact the administrator to correct attendances.')%(warning_sign,)) res = {'action' : type, 'employee_id' : emp['id']} if dt: res['name'] = dt id = self.pool.get('hr.attendance').create(cr, uid, res, context=context) if type != 'action': return id return True
product_context.update(uom=line.product_uom.id)
product_context.update(uom=line.product_uom.id,date=inv.date)
def action_confirm(self, cr, uid, ids, context=None): """ Confirm the inventory and writes its finished date @return: True """ if context is None: context = {} # to perform the correct inventory corrections we need analyze stock location by # location, never recursively, so we use a special context product_context = dict(context, compute_child=False)
'date': inv.date,
def action_confirm(self, cr, uid, ids, context=None): """ Confirm the inventory and writes its finished date @return: True """ if context is None: context = {} # to perform the correct inventory corrections we need analyze stock location by # location, never recursively, so we use a special context product_context = dict(context, compute_child=False)
def on_change_product_id(self, cr, uid, ids, location_id, product, uom=False):
def on_change_product_id(self, cr, uid, ids, location_id, product, uom=False, to_date=False):
def on_change_product_id(self, cr, uid, ids, location_id, product, uom=False): """ Changes UoM and name if product_id changes. @param location_id: Location id @param product: Changed product_id @param uom: UoM product @return: Dictionary of changed values """ if not product: return {} if not uom: prod = self.pool.get('product.product').browse(cr, uid, [product], {'uom': uom})[0] uom = prod.uom_id.id amount = self.pool.get('stock.location')._product_get(cr, uid, location_id, [product], {'uom': uom})[product] result = {'product_qty': amount, 'product_uom': uom} return {'value': result}
amount = self.pool.get('stock.location')._product_get(cr, uid, location_id, [product], {'uom': uom})[product]
amount = self.pool.get('stock.location')._product_get(cr, uid, location_id, [product], {'uom': uom, 'to_date': to_date})[product]
def on_change_product_id(self, cr, uid, ids, location_id, product, uom=False): """ Changes UoM and name if product_id changes. @param location_id: Location id @param product: Changed product_id @param uom: UoM product @return: Dictionary of changed values """ if not product: return {} if not uom: prod = self.pool.get('product.product').browse(cr, uid, [product], {'uom': uom})[0] uom = prod.uom_id.id amount = self.pool.get('stock.location')._product_get(cr, uid, location_id, [product], {'uom': uom})[product] result = {'product_qty': amount, 'product_uom': uom} return {'value': result}
params = right[:]
params = right and right[:] or []
def __leaf_to_sql(self, leaf, table): if leaf == self.__DUMMY_LEAF: return ('(1=1)', []) left, operator, right = leaf
else: if operator == 'in': query = '(%s.%s IS NULL)' % (table._table, left) else: query = '(%s.%s IS NOT NULL)' % (table._table, left)
def __leaf_to_sql(self, leaf, table): if leaf == self.__DUMMY_LEAF: return ('(1=1)', []) left, operator, right = leaf
query = obj+".state <> 'draft' AND "+obj+".period_id IN (SELECT id FROM account_period WHERE fiscalyear_id IN (%s) OR id IN (%s)) %s %s" % (fiscalyear_clause, periods, where_move_state, where_move_lines_by_date)
query = obj+".state <> 'draft' AND "+obj+".period_id IN (SELECT id FROM account_period WHERE fiscalyear_id IN (%s) AND id IN (%s)) %s %s" % (fiscalyear_clause, periods, where_move_state, where_move_lines_by_date)
def _query_get(self, cr, uid, obj='l', context=None): fiscalyear_obj = self.pool.get('account.fiscalyear') fiscalperiod_obj = self.pool.get('account.period') account_obj = self.pool.get('account.account') fiscalyear_ids = [] if context is None: context = {} initial_bal = context.get('initial_bal', False) company_clause = " " if context.get('company_id', False): company_clause = " AND " +obj+".company_id = %s" % context.get('company_id', False) if not context.get('fiscalyear', False): fiscalyear_ids = fiscalyear_obj.search(cr, uid, [('state', '=', 'draft')]) else: #for initial balance as well as for normal query, we check only the selected FY because the best practice is to generate the FY opening entries fiscalyear_ids = [context['fiscalyear']]
'inventory_line_id': fields.one2many('stock.inventory.line', 'inventory_id', 'Inventories', readonly=True, states={'draft': [('readonly', False)]}),
'inventory_line_id': fields.one2many('stock.inventory.line', 'inventory_id', 'Inventories', states={'draft': [('readonly', False)]}),
def unlink(self, cr, uid, ids, context=None): for move in self.browse(cr, uid, ids, context=context): if move.state != 'draft': raise osv.except_osv(_('UserError'), _('You can only delete draft moves.')) return super(stock_move, self).unlink( cr, uid, ids, context=context)
dict = self.style_properties_dict[(s.getAttribute("style:name")).encode("latin-1")] or {}
dict = self.style_properties_dict[(s.getAttribute("style:name")).encode("utf-8")] or {}
def normalizeStyleProperties(self): """Transfer all style:style-properties attributes from the self.style_properties_hierarchical dict to the automatic-styles from content.xml. Use this function to preprocess content.xml for XSLT transformations etc.Do not try to implement this function with XSlT - believe me, it's a terrible task...""" styles_styles = self.styles_dom.getElementsByTagName("style:style") automatic_styles = self.content_dom.getElementsByTagName("office:automatic-styles")[0] for s in styles_styles: automatic_styles.appendChild(s.cloneNode(deep=1)) content_styles = self.content_dom.getElementsByTagName("style:style") # these are the content_styles with styles_styles added!!! for s in content_styles: c = self.findChildrenByName(s,"style:properties") if c == []: # some derived automatic styles do not have "style:properties": temp = self.content_dom.createElement("style:properties") s.appendChild(temp) c = self.findChildrenByName(s,"style:properties") c = c[0] dict = self.style_properties_dict[(s.getAttribute("style:name")).encode("latin-1")] or {} for attribute in dict.keys(): c.setAttribute(self.openOfficeStringUtf8(attribute),self.openOfficeStringUtf8(dict[attribute]))
name = s.getAttribute("style:name").encode("latin-1")
name = s.getAttribute("style:name").encode("utf-8")
def buildStyleDict(self): """Store all style:style-nodes from content.xml and styles.xml in self.style_dict. Caution: in this dict the nodes from two dom apis are merged!""" for st in (self.styles_dom,self.content_dom): for s in st.getElementsByTagName("style:style"): name = s.getAttribute("style:name").encode("latin-1") self.style_dict[name] = s return True
parent = self.style_dict[style_name].getAttribute("style:parent-style-name").encode("latin-1")
parent = self.style_dict[style_name].getAttribute("style:parent-style-name").encode("utf-8")
def getStylePropertiesDict(self,style_name): res = {}
res[attr] = c.getAttribute(attr).encode("latin-1")
res[attr] = c.getAttribute(attr).encode("utf-8")
def getStylePropertiesDict(self,style_name): res = {}
domain=[('type','=','cr')], context={'default_type':'cr'}),
domain=[('type','=','cr')], context={'default_type':'cr'}, readonly=True, states={'draft':[('readonly',False)]}),
def _get_currency(self, cr, uid, context): user = self.pool.get('res.users').browse(cr, uid, uid) if user.company_id: return user.company_id.currency_id.id return False
domain=[('type','=','dr')], context={'default_type':'dr'}),
domain=[('type','=','dr')], context={'default_type':'dr'}, readonly=True, states={'draft':[('readonly',False)]}),
def _get_currency(self, cr, uid, context): user = self.pool.get('res.users').browse(cr, uid, uid) if user.company_id: return user.company_id.currency_id.id return False
['invoice', 'delivery', 'contact'])
['default', 'invoice', 'delivery', 'contact'])
def makeOrder(self, cr, uid, ids, context=None): """ This function create Quotation on given case. @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 make sale' ids @param context: A standard dictionary for contextual values @return : Dictionary value of created sale order. """ if not context: context = {}
'close': 1
def _get_shop_id(self, cr, uid, ids, context=None): if context is None: context = {} cmpny_id = self.pool.get('res.users')._get_company(cr, uid, context=context) shop = self.pool.get('sale.shop').search(cr, uid, [('company_id', '=', cmpny_id)]) return shop and shop[0] or False
if ids: cr.execute('select number_of_days_temp from hr_holidays where id in ('+','.join(map(str, ids))+')') res = cr.fetchall() if res and res[0][0] < 0:
for rec in self.read(cr, uid, ids, ['number_of_days','date_from','date_to']): if rec['number_of_days'] < 0:
def _check_date(self, cr, uid, ids): if ids: cr.execute('select number_of_days_temp from hr_holidays where id in ('+','.join(map(str, ids))+')') res = cr.fetchall() if res and res[0][0] < 0: return False return True
return True _constraints = [(_check_date, 'Start date should not be larger than end date! ', ['number_of_days'])]
date_from = time.strptime(rec['date_from'], '%Y-%m-%d %H:%M:%S') date_to = time.strptime(rec['date_to'], '%Y-%m-%d %H:%M:%S') if date_from > date_to: return False return True _constraints = [(_check_date, 'Start date should not be larger than end date!\nNumber of Days should be greater than 1!', ['number_of_days'])]
def _check_date(self, cr, uid, ids): if ids: cr.execute('select number_of_days_temp from hr_holidays where id in ('+','.join(map(str, ids))+')') res = cr.fetchall() if res and res[0][0] < 0: return False return True
total_amount = 0.0 if inv.tax_amount: total_amount = inv.amount + inv.tax_amount
total_amount = inv.amount
def action_move_line_create(self, cr, uid, ids, *args): journal_pool = self.pool.get('account.journal') sequence_pool = self.pool.get('ir.sequence') move_pool = self.pool.get('account.move') move_line_pool = self.pool.get('account.move.line') analytic_pool = self.pool.get('account.analytic.line') currency_pool = self.pool.get('res.currency') invoice_pool = self.pool.get('account.invoice') for inv in self.browse(cr, uid, ids): if inv.move_id: continue
'sum_debit': self._sum_debit, 'sum_credit': self._sum_credit,
def __init__(self, cr, uid, name, context=None): super(third_party_ledger, self).__init__(cr, uid, name, context=context) self.localcontext.update({ 'time': time, 'lines': self.lines, 'sum_debit_partner': self._sum_debit_partner, 'sum_credit_partner': self._sum_credit_partner, 'sum_debit': self._sum_debit, 'sum_credit': self._sum_credit, 'get_currency': self._get_currency, 'comma_me' : self.comma_me, 'get_start_period': self.get_start_period, 'get_end_period': self.get_end_period, 'get_account': self._get_account, 'get_filter': self._get_filter, 'get_start_date': self._get_start_date, 'get_end_date': self._get_end_date, 'get_fiscalyear': self._get_fiscalyear, 'get_start_date':self._get_start_date, 'get_end_date': self._get_end_date, 'get_journal': self._get_journal, 'get_partners':self._get_partners, 'get_intial_balance':self._get_intial_balance, 'display_initial_balance':self._display_initial_balance, 'display_currency':self._display_currency, 'get_target_move': self._get_target_move, })
return result_tmp
return result_tmp + result_init
def _sum_debit_partner(self, partner): move_state = ['draft','posted'] if self.target_move == 'posted': move_state = ['posted']
return result_tmp def _sum_debit(self): move_state = ['draft','posted'] if self.target_move == 'posted': move_state = ['posted'] if not self.ids: return 0.0 result_tmp = 0.0 result_init = 0.0 if self.reconcil : RECONCILE_TAG = " " else: RECONCILE_TAG = "AND reconcile_id IS NULL" if self.initial_balance: self.cr.execute( "SELECT sum(debit) " \ "FROM account_move_line AS l, " \ "account_move AS m " "WHERE partner_id IN %s" \ "AND m.id = l.move_id " \ "AND m.state IN %s " "AND account_id IN %s" \ "AND reconcile_id IS NULL " \ "AND " + self.init_query + " ", (tuple(self.partner_ids), tuple(move_state), tuple(self.account_ids))) contemp = self.cr.fetchone() if contemp != None: result_init = contemp[0] or 0.0 else: result_init = result_tmp + 0.0 self.cr.execute( "SELECT sum(debit) " \ "FROM account_move_line AS l, " \ "account_move AS m " "WHERE partner_id IN %s" \ "AND m.id = l.move_id " \ "AND m.state IN %s " "AND account_id IN %s" \ " " + RECONCILE_TAG + " " \ "AND " + self.query + " " , (tuple(self.partner_ids), tuple(move_state) ,tuple(self.account_ids),)) contemp = self.cr.fetchone() if contemp != None: result_tmp = contemp[0] or 0.0 else: result_tmp = result_tmp + 0.0
def _sum_credit_partner(self, partner): move_state = ['draft','posted'] if self.target_move == 'posted': move_state = ['posted']
def _sum_credit(self): move_state = ['draft','posted'] if self.target_move == 'posted': move_state = ['posted'] if not self.ids: return 0.0 result_tmp = 0.0 result_init = 0.0 if self.reconcil : RECONCILE_TAG = " " else: RECONCILE_TAG = "AND reconcile_id IS NULL" if self.initial_balance: self.cr.execute( "SELECT sum(credit) " \ "FROM account_move_line AS l, " \ "account_move AS m " "WHERE partner_id IN %s" \ "AND m.id = l.move_id " \ "AND m.state IN %s " "AND account_id IN %s" \ "AND reconcile_id IS NULL " \ "AND " + self.init_query + " ", (tuple(self.partner_ids), tuple(move_state), tuple(self.account_ids))) contemp = self.cr.fetchone() if contemp != None: result_init = contemp[0] or 0.0 else: result_init = result_tmp + 0.0 self.cr.execute( "SELECT sum(credit) " \ "FROM account_move_line AS l, " \ "account_move AS m " "WHERE partner_id IN %s" \ "AND m.id = l.move_id " \ "AND m.state IN %s " "AND account_id IN %s" \ " " + RECONCILE_TAG + " " \ "AND " + self.query + " " , (tuple(self.partner_ids), tuple(move_state), tuple(self.account_ids),)) contemp = self.cr.fetchone() if contemp != None: result_tmp = contemp[0] or 0.0 else: result_tmp = result_tmp + 0.0 return result_tmp + result_init
def _sum_credit(self): move_state = ['draft','posted'] if self.target_move == 'posted': move_state = ['posted']
reference = obj_inv.reference or ''
reference = obj_inv.reference or number or ''
def action_number(self, cr, uid, ids, *args): #TODO: not correct fix but required a frech values before reading it. self.write(cr, uid, ids, {})
'title': _('Bad Lot Assignation !'),
'title': _('Insufficient Stock in Lot !'),
def onchange_lot_id(self, cr, uid, ids, prodlot_id=False, product_qty=False, loc_id=False, product_id=False, context=None): """ On change of production lot gives a warning message. @param prodlot_id: Changed production lot id @param product_qty: Quantity of product @param loc_id: Location id @param product_id: Product id @return: Warning message """ if not prodlot_id or not loc_id: return {} ctx = context and context.copy() or {} ctx['location_id'] = loc_id prodlot = self.pool.get('stock.production.lot').browse(cr, uid, prodlot_id, ctx) location = self.pool.get('stock.location').browse(cr, uid, loc_id) warning = {} if (location.usage == 'internal') and (product_qty > (prodlot.stock_available or 0.0)): warning = { 'title': _('Bad Lot Assignation !'), 'message': _('You are moving %.2f products but only %.2f available in this lot.') % (product_qty, prodlot.stock_available or 0.0) } return {'warning': warning}
if (pick.type == 'in'):
if (pick.type == 'in') and 'purchase_id' in pick._columns.keys():
def default_get(self, cr, uid, fields, context=None): """ To get default values for the object. @param self: The object pointer. @param cr: A database cursor @param uid: ID of the user currently logged in @param fields: List of fields for which we want default values @param context: A standard dictionary @return: A dictionary which of fields with values. """
if (pick.type == 'out'):
if (pick.type == 'out') and 'sale_id' in pick._columns.keys():
def default_get(self, cr, uid, fields, context=None): """ To get default values for the object. @param self: The object pointer. @param cr: A database cursor @param uid: ID of the user currently logged in @param fields: List of fields for which we want default values @param context: A standard dictionary @return: A dictionary which of fields with values. """
ids = self.search(cr, user, [('code', operator, name.split()[0]), ('name', operator, name.split()[1])]+ args, limit=limit)
operand1,operand2 = name.split(' ',1) ids = self.search(cr, user, [('code', operator, operand1), ('name', operator, operand2)]+ args, limit=limit)
def name_search(self, cr, user, name, args=None, operator='ilike', context=None, limit=100): if not args: args = [] if not context: context = {} args = args[:] ids = [] try: if name and str(name).startswith('partner:'): part_id = int(name.split(':')[1]) part = self.pool.get('res.partner').browse(cr, user, part_id, context) args += [('id', 'in', (part.property_account_payable.id, part.property_account_receivable.id))] name = False if name and str(name).startswith('type:'): type = name.split(':')[1] args += [('type', '=', type)] name = False except: pass if name: ids = self.search(cr, user, [('code', '=like', name+"%")]+args, limit=limit) if not ids: ids = self.search(cr, user, [('shortcut', '=', name)]+ args, limit=limit) if not ids: ids = self.search(cr, user, [('name', operator, name)]+ args, limit=limit) if not ids and len(name.split()) >= 2: ids = self.search(cr, user, [('code', operator, name.split()[0]), ('name', operator, name.split()[1])]+ args, limit=limit) else: ids = self.search(cr, user, args, context=context, limit=limit) return self.name_get(cr, user, ids, context=context)
'fiscal_position': fpos
'fiscal_position': fpos,
def _makeOrder(self, cr, uid, data, context): pool = pooler.get_pool(cr.dbname) case_obj = pool.get('crm.case') sale_obj = pool.get('sale.order') partner_obj = pool.get('res.partner') sale_line_obj = pool.get('sale.order.line')
if journal.currency: result = {'value': { 'currency_id': journal.currency.id
currency_id = journal.currency and journal.currency.id or journal.company_id.currency_id.id result = {'value': { 'currency_id': currency_id,
def onchange_journal_id(self, cr, uid, ids, journal_id): if journal_id: journal = self.pool.get('account.journal').browse(cr, uid, journal_id) if journal.currency: result = {'value': { 'currency_id': journal.currency.id } } return result user_company = self.pool.get('res.users').browse(cr, uid, [uid])[0].company_id result = {'value': { 'currency_id': user_company.currency_id.id } } return result
return result user_company = self.pool.get('res.users').browse(cr, uid, [uid])[0].company_id result = {'value': { 'currency_id': user_company.currency_id.id } }
def onchange_journal_id(self, cr, uid, ids, journal_id): if journal_id: journal = self.pool.get('account.journal').browse(cr, uid, journal_id) if journal.currency: result = {'value': { 'currency_id': journal.currency.id } } return result user_company = self.pool.get('res.users').browse(cr, uid, [uid])[0].company_id result = {'value': { 'currency_id': user_company.currency_id.id } } return result
def name_search(self, cr, user, name, args=None, operator='ilike', context={}, limit=100):
def name_search(self, cr, user, name, args=None, operator='ilike', context=None, limit=100):
def name_search(self, cr, user, name, args=None, operator='ilike', context={}, limit=100): if not args: args = [] ids = [] if context.get('journal_type', False): args += [('type','=',context.get('journal_type'))]
ids = self.search(cr, user, [('name', operator, name)]+ args, limit=limit, context=context)
ids = self.search(cr, user, [('name', 'ilike', name)]+ args, limit=limit, context=context)
def name_search(self, cr, user, name, args=None, operator='ilike', context={}, limit=100): if not args: args = [] ids = [] if context.get('journal_type', False): args += [('type','=',context.get('journal_type'))]
import libxslt import libxml2
from lxml import etree from StringIO import StringIO
def sxw2rml(sxw_file, xsl, output='.', save_pict=False): import libxslt import libxml2 tool = PyOpenOffice(output, save_pict = save_pict) res = tool.unpackNormalize(sxw_file) styledoc = libxml2.parseDoc(xsl) style = libxslt.parseStylesheetDoc(styledoc) doc = libxml2.parseMemory(res,len(res)) result = style.applyStylesheet(doc, None) root = result.xpathEval("/document/stylesheet") if root: root=root[0] images = libxml2.newNode("images") for img in tool.images: node = libxml2.newNode('image') node.setProp('name', img) node.setContent( base64.encodestring(tool.images[img])) images.addChild(node) root.addNextSibling(images) try: xml = style.saveResultToString(result) return xml except: return result
styledoc = libxml2.parseDoc(xsl) style = libxslt.parseStylesheetDoc(styledoc) doc = libxml2.parseMemory(res,len(res)) result = style.applyStylesheet(doc, None) root = result.xpathEval("/document/stylesheet")
f = StringIO(xsl) styledoc = etree.parse(f) style = etree.XSLT(styledoc) f = StringIO(res) doc = etree.parse(f) result = style(doc) root = etree.XPathEvaluator(result)("/document/stylesheet")
def sxw2rml(sxw_file, xsl, output='.', save_pict=False): import libxslt import libxml2 tool = PyOpenOffice(output, save_pict = save_pict) res = tool.unpackNormalize(sxw_file) styledoc = libxml2.parseDoc(xsl) style = libxslt.parseStylesheetDoc(styledoc) doc = libxml2.parseMemory(res,len(res)) result = style.applyStylesheet(doc, None) root = result.xpathEval("/document/stylesheet") if root: root=root[0] images = libxml2.newNode("images") for img in tool.images: node = libxml2.newNode('image') node.setProp('name', img) node.setContent( base64.encodestring(tool.images[img])) images.addChild(node) root.addNextSibling(images) try: xml = style.saveResultToString(result) return xml except: return result
images = libxml2.newNode("images")
images = etree.Element("images")
def sxw2rml(sxw_file, xsl, output='.', save_pict=False): import libxslt import libxml2 tool = PyOpenOffice(output, save_pict = save_pict) res = tool.unpackNormalize(sxw_file) styledoc = libxml2.parseDoc(xsl) style = libxslt.parseStylesheetDoc(styledoc) doc = libxml2.parseMemory(res,len(res)) result = style.applyStylesheet(doc, None) root = result.xpathEval("/document/stylesheet") if root: root=root[0] images = libxml2.newNode("images") for img in tool.images: node = libxml2.newNode('image') node.setProp('name', img) node.setContent( base64.encodestring(tool.images[img])) images.addChild(node) root.addNextSibling(images) try: xml = style.saveResultToString(result) return xml except: return result
node = libxml2.newNode('image') node.setProp('name', img) node.setContent( base64.encodestring(tool.images[img])) images.addChild(node) root.addNextSibling(images)
node = etree.Element('image', name=img) node.text = base64.encodestring(tool.images[img]) images.append(node) root.append(images)
def sxw2rml(sxw_file, xsl, output='.', save_pict=False): import libxslt import libxml2 tool = PyOpenOffice(output, save_pict = save_pict) res = tool.unpackNormalize(sxw_file) styledoc = libxml2.parseDoc(xsl) style = libxslt.parseStylesheetDoc(styledoc) doc = libxml2.parseMemory(res,len(res)) result = style.applyStylesheet(doc, None) root = result.xpathEval("/document/stylesheet") if root: root=root[0] images = libxml2.newNode("images") for img in tool.images: node = libxml2.newNode('image') node.setProp('name', img) node.setContent( base64.encodestring(tool.images[img])) images.addChild(node) root.addNextSibling(images) try: xml = style.saveResultToString(result) return xml except: return result
xml = style.saveResultToString(result)
xml = str(result)
def sxw2rml(sxw_file, xsl, output='.', save_pict=False): import libxslt import libxml2 tool = PyOpenOffice(output, save_pict = save_pict) res = tool.unpackNormalize(sxw_file) styledoc = libxml2.parseDoc(xsl) style = libxslt.parseStylesheetDoc(styledoc) doc = libxml2.parseMemory(res,len(res)) result = style.applyStylesheet(doc, None) root = result.xpathEval("/document/stylesheet") if root: root=root[0] images = libxml2.newNode("images") for img in tool.images: node = libxml2.newNode('image') node.setProp('name', img) node.setContent( base64.encodestring(tool.images[img])) images.addChild(node) root.addNextSibling(images) try: xml = style.saveResultToString(result) return xml except: return result
f = StringIO.StringIO(file(fname).read())
f = fname
def sxw2rml(sxw_file, xsl, output='.', save_pict=False): import libxslt import libxml2 tool = PyOpenOffice(output, save_pict = save_pict) res = tool.unpackNormalize(sxw_file) styledoc = libxml2.parseDoc(xsl) style = libxslt.parseStylesheetDoc(styledoc) doc = libxml2.parseMemory(res,len(res)) result = style.applyStylesheet(doc, None) root = result.xpathEval("/document/stylesheet") if root: root=root[0] images = libxml2.newNode("images") for img in tool.images: node = libxml2.newNode('image') node.setProp('name', img) node.setContent( base64.encodestring(tool.images[img])) images.addChild(node) root.addNextSibling(images) try: xml = style.saveResultToString(result) return xml except: return result
if quantity_rest <= 0:
if quantity_rest < 0:
def split(self, cr, uid, ids, move_ids, context=None): """ To split stock moves into production lot @param self: The object pointer. @param cr: A database cursor @param uid: ID of the user currently logged in @param ids: the ID or list of IDs if we want more than one @param move_ids: the ID or list of IDs of stock move we want to split @param context: A standard dictionary @return: """ prodlot_obj = self.pool.get('stock.production.lot') ir_sequence_obj = self.pool.get('ir.sequence') move_obj = self.pool.get('stock.move') new_move = [] for data in self.browse(cr, uid, ids): for move in move_obj.browse(cr, uid, move_ids): move_qty = move.product_qty quantity_rest = move.product_qty uos_qty_rest = move.product_uos_qty new_move = [] for line in data.line_ids: quantity = line.quantity
current_move = move_obj.copy(cr, uid, move.id, default_val) new_move.append(current_move)
if quantity_rest > 0: current_move = move_obj.copy(cr, uid, move.id, default_val) new_move.append(current_move) if quantity_rest == 0: current_move = move.id
def split(self, cr, uid, ids, move_ids, context=None): """ To split stock moves into production lot @param self: The object pointer. @param cr: A database cursor @param uid: ID of the user currently logged in @param ids: the ID or list of IDs if we want more than one @param move_ids: the ID or list of IDs of stock move we want to split @param context: A standard dictionary @return: """ prodlot_obj = self.pool.get('stock.production.lot') ir_sequence_obj = self.pool.get('ir.sequence') move_obj = self.pool.get('stock.move') new_move = [] for data in self.browse(cr, uid, ids): for move in move_obj.browse(cr, uid, move_ids): move_qty = move.product_qty quantity_rest = move.product_qty uos_qty_rest = move.product_uos_qty new_move = [] for line in data.line_ids: quantity = line.quantity
if 'analytic_account_id' in vals and vals['analytic_account_id']:
if vals.get('analytic_account_id',False):
def create(self, cr, uid, vals, context=None, check=True): if not context: context={} account_obj = self.pool.get('account.account') tax_obj=self.pool.get('account.tax') if ('account_id' in vals) and not account_obj.read(cr, uid, vals['account_id'], ['active'])['active']: raise osv.except_osv(_('Bad account!'), _('You can not use an inactive account!')) if 'journal_id' in vals and 'journal_id' not in context: context['journal_id'] = vals['journal_id'] if 'period_id' in vals and 'period_id' not in context: context['period_id'] = vals['period_id'] if ('journal_id' not in context) and ('move_id' in vals) and vals['move_id']: m = self.pool.get('account.move').browse(cr, uid, vals['move_id']) context['journal_id'] = m.journal_id.id context['period_id'] = m.period_id.id
'partner_id': fields.many2one('res.partner', 'Partner', select=1),
'partner_id': fields.many2one('res.partner', 'Partner', select=1, ondelete='restrict'),
def _get_move_lines(self, cr, uid, ids, context=None): result = [] for move in self.pool.get('account.move').browse(cr, uid, ids, context=context): for line in move.line_id: result.append(line.id) return result
att_ids = []
def create_record(msg): if hasattr(model_pool, 'message_new'): res_id = model_pool.message_new(cr, uid, msg, context) else: data = { 'name': msg.get('subject'), 'email_from': msg.get('from'), 'email_cc': msg.get('cc'), 'user_id': False, 'description': msg.get('body'), 'state' : 'draft', } data.update(self.get_partner(cr, uid, msg.get('from'), context=context)) res_id = model_pool.create(cr, uid, data, context=context)
body = tools.html2plaintext(content)
body = tools.ustr(tools.html2plaintext(content))
def create_record(msg): if hasattr(model_pool, 'message_new'): res_id = model_pool.message_new(cr, uid, msg, context) else: data = { 'name': msg.get('subject'), 'email_from': msg.get('from'), 'email_cc': msg.get('cc'), 'user_id': False, 'description': msg.get('body'), 'state' : 'draft', } data.update(self.get_partner(cr, uid, msg.get('from'), context=context)) res_id = model_pool.create(cr, uid, data, context=context)
body = content
body = tools.ustr(content)
def create_record(msg): if hasattr(model_pool, 'message_new'): res_id = model_pool.message_new(cr, uid, msg, context) else: data = { 'name': msg.get('subject'), 'email_from': msg.get('from'), 'email_cc': msg.get('cc'), 'user_id': False, 'description': msg.get('body'), 'state' : 'draft', } data.update(self.get_partner(cr, uid, msg.get('from'), context=context)) res_id = model_pool.create(cr, uid, data, context=context)
res = tools.ustr(res)
res = tools.ustr(res, encoding)
def create_record(msg): if hasattr(model_pool, 'message_new'): res_id = model_pool.message_new(cr, uid, msg, context) else: data = { 'name': msg.get('subject'), 'email_from': msg.get('from'), 'email_cc': msg.get('cc'), 'user_id': False, 'description': msg.get('body'), 'state' : 'draft', } data.update(self.get_partner(cr, uid, msg.get('from'), context=context)) res_id = model_pool.create(cr, uid, data, context=context)
for line in self.browse(cr, uid, ids): if line.journal_id.internal_sequence: seq_no = obj_sequence.get_id(cr, uid, line.journal_id.internal_sequence.id, context=context)
for move in self.browse(cr, uid, ids, context): if move.journal_id.internal_sequence_id: seq_no = obj_sequence.get_id(cr, uid, move.journal_id.internal_sequence_id.id, context=context)
def post(self, cr, uid, ids, context=None): obj_sequence = self.pool.get('ir.sequence') res = super(account_move, self).post(cr, uid, ids, context=context) seq_no = False for line in self.browse(cr, uid, ids): if line.journal_id.internal_sequence: seq_no = obj_sequence.get_id(cr, uid, line.journal_id.internal_sequence.id, context=context) if seq_no: self.write(cr, uid, [line.id], {'internal_sequence_number': seq_no}) return res
self.write(cr, uid, [line.id], {'internal_sequence_number': seq_no})
self.write(cr, uid, [move.id], {'internal_sequence_number': seq_no})
def post(self, cr, uid, ids, context=None): obj_sequence = self.pool.get('ir.sequence') res = super(account_move, self).post(cr, uid, ids, context=context) seq_no = False for line in self.browse(cr, uid, ids): if line.journal_id.internal_sequence: seq_no = obj_sequence.get_id(cr, uid, line.journal_id.internal_sequence.id, context=context) if seq_no: self.write(cr, uid, [line.id], {'internal_sequence_number': seq_no}) return res
'References':"%s" % (message_id)
x_headers['References'] = "%s" % (message_id)
def action_send(self, cr, uid, ids, context=None): """ This sends an email to ALL the addresses of the selected partners. """
res['value'].update({'purchase_price': purchase_price})
price = self.pool.get('res.currency').compute(cr, uid, frm_cur, to_cur, purchase_price, round=False) res['value'].update({'purchase_price': price})
def product_id_change(self, cr, uid, ids, pricelist, product, qty=0, uom=False, qty_uos=0, uos=False, name='', partner_id=False, lang=False, update_tax=True, date_order=False, packaging=False, fiscal_position=False, flag=False): res = super(sale_order_line, self).product_id_change(cr, uid, ids, pricelist, product, qty=qty, uom=uom, qty_uos=qty_uos, uos=uos, name=name, partner_id=partner_id, lang=lang, update_tax=update_tax, date_order=date_order, packaging=packaging, fiscal_position=fiscal_position, flag=flag) if product: purchase_price = self.pool.get('product.product').browse(cr, uid, product).standard_price res['value'].update({'purchase_price': purchase_price}) return res
'company_id': fields.related('voucher_id','company_id', relation='res.company', string='Company', store=True),
'company_id': fields.related('voucher_id','company_id', relation='res.company', type='many2one', string='Company', store=True),
def _compute_balance(self, cr, uid, ids, name, args, context=None): currency_pool = self.pool.get('res.currency') rs_data = {} for line in self.browse(cr, uid, ids): res = {} company_currency = line.voucher_id.journal_id.company_id.currency_id.id voucher_currency = line.voucher_id.currency_id.id move_line = line.move_line_id or False
if move.product_id.track_production and location_id:
if (not move.prodlot_id.id) and (move.product_id.track_production and location_id):
def action_consume(self, cr, uid, ids, quantity, location_id=False, context=None): """ Consumed product with specific quatity from specific source location @param cr: the database cursor @param uid: the user id @param ids: ids of stock move object to be consumed @param quantity : specify consume quantity @param location_id : specify source location @param context: context arguments @return: Consumed lines """ if context is None: context = {} if quantity <= 0: raise osv.except_osv(_('Warning!'), _('Please provide Proper Quantity !'))
case.user_id.address_id.email) or tools.config.get('email_from',False)})
case.user_id.address_id.email and \ "%s <%s>" % (case.user_id.name, case.user_id.address_id.email)) or \ tools.config.get('email_from',False)})
def default_get(self, cr, uid, fields, context=None): """ This function gets default values """ if not context: context = {}
'date_due': fields.date('Due Date'),
'date_due': fields.date('Due Date', readonly=True, states={'draft':[('readonly',False)]}),
def _get_partner(self, cr, uid, context={}): return context.get('partner_id', False)
if line[1]: line_amount = voucher_line_pool.browse(cr, uid, line[1]).untax_amount else: line_amount = line[2].get('amount')
line_amount = line[2].get('amount')
def onchange_price(self, cr, uid, ids, line_ids, tax_id, partner_id=False, context={}): tax_pool = self.pool.get('account.tax') partner_pool = self.pool.get('res.partner') position_pool = self.pool.get('account.fiscal.position') voucher_line_pool = self.pool.get('account.voucher.line') res = { 'tax_amount':False, 'amount':False, } voucher_total_tax = 0.0 voucher_total = 0.0 voucher_line_ids = [] total = 0.0 total_tax = 0.0 for line in line_ids: line_amount = 0.0 if line[1]: line_amount = voucher_line_pool.browse(cr, uid, line[1]).untax_amount else: line_amount = line[2].get('amount') voucher_line_ids += [line[1]] voucher_total += line_amount total = voucher_total total_tax = 0.0 if tax_id: tax = [tax_pool.browse(cr, uid, tax_id)] if partner_id: partner = partner_pool.browse(cr, uid, partner_id) or False taxes = position_pool.map_tax(cr, uid, partner and partner.property_account_position or False, tax) tax = tax_pool.browse(cr, uid, taxes) if not tax[0].price_include: for tax_line in tax_pool.compute_all(cr, uid, tax, voucher_total, 1).get('taxes'): total_tax += tax_line.get('amount') total += total_tax res.update({ 'amount':total, 'tax_amount':total_tax })
'amount':total,
'amount':total or voucher_total,
def onchange_price(self, cr, uid, ids, line_ids, tax_id, partner_id=False, context={}): tax_pool = self.pool.get('account.tax') partner_pool = self.pool.get('res.partner') position_pool = self.pool.get('account.fiscal.position') voucher_line_pool = self.pool.get('account.voucher.line') res = { 'tax_amount':False, 'amount':False, } voucher_total_tax = 0.0 voucher_total = 0.0 voucher_line_ids = [] total = 0.0 total_tax = 0.0 for line in line_ids: line_amount = 0.0 if line[1]: line_amount = voucher_line_pool.browse(cr, uid, line[1]).untax_amount else: line_amount = line[2].get('amount') voucher_line_ids += [line[1]] voucher_total += line_amount total = voucher_total total_tax = 0.0 if tax_id: tax = [tax_pool.browse(cr, uid, tax_id)] if partner_id: partner = partner_pool.browse(cr, uid, partner_id) or False taxes = position_pool.map_tax(cr, uid, partner and partner.property_account_position or False, tax) tax = tax_pool.browse(cr, uid, taxes) if not tax[0].price_include: for tax_line in tax_pool.compute_all(cr, uid, tax, voucher_total, 1).get('taxes'): total_tax += tax_line.get('amount') total += total_tax res.update({ 'amount':total, 'tax_amount':total_tax })
master_line = move_line_pool.create(cr, uid, move_line)
if (debit == 0.0 or credit == 0.0 or debit+credit > 0) and (debit > 0.0 or credit > 0.0): master_line = move_line_pool.create(cr, uid, move_line)
def _get_payment_term_lines(term_id, amount): term_pool = self.pool.get('account.payment.term') if term_id and amount: terms = term_pool.compute(cr, uid, term_id, amount) return terms return False
if inv.tax_id:
if inv.tax_id and inv.type in ('sale', 'purchase'):
def _get_payment_term_lines(term_id, amount): term_pool = self.pool.get('account.payment.term') if term_id and amount: terms = term_pool.compute(cr, uid, term_id, amount) return terms return False
move_pool.post(cr, uid, [move_id], context={})
def _get_payment_term_lines(term_id, amount): term_pool = self.pool.get('account.payment.term') if term_id and amount: terms = term_pool.compute(cr, uid, term_id, amount) return terms return False
result['toolbar']['action'] = []
if result.get('toolbar', False): result['toolbar']['action'] = []
def fields_view_get(self, cr, uid, view_id=None, view_type='form', context={}, toolbar=False, submenu=False): journal_pool = self.pool.get('account.journal') result = super(osv.osv, self).fields_view_get(cr, uid, view_id, view_type, context, toolbar=toolbar, submenu=submenu) if view_type != 'tree': #Remove the toolbar from the form view if view_type == 'form': result['toolbar']['action'] = []
import random
def generate_phases(self, cr, uid, ids, *args): import random phase_obj = self.pool.get('document.change.process.phase') phase_type_obj = self.pool.get('document.change.process.phase.type') document_type_obj = self.pool.get('document.change.type') directory_obj = self.pool.get('document.directory') document_obj = self.pool.get('ir.attachment') new_doc_ids = [] for process in self.browse(cr, uid, ids): if process.process_model_id: directory_ids = directory_obj.search(cr, uid, [('parent_id','child_of',process.structure_id and process.structure_id.id)]) for phase_type_id in process.process_model_id.phase_type_ids: phase_value = { 'name' : '%s-%s' %(phase_type_id.name, process.name), 'phase_type_id': phase_type_id.id, 'process_id': process.id } phase_id = phase_obj.create(cr, uid, phase_value) cr.execute('select document_type_id from document_type_phase_type_rel where phase_type_id = %s' % phase_type_id.id) document_type_ids = map(lambda x: x[0], cr.fetchall()) document_ids = document_obj.search(cr, uid, [ ('parent_id','in',directory_ids), ('change_type_id','in',document_type_ids)]) for document_id in document_ids: vals = {'process_phase_id': phase_id} if process.pending_directory_id: vals.update({'parent_id':process.pending_directory_id.id}) new_doc_ids.append(document_obj.copy(cr, uid, document_id, vals)) phase_obj.write(cr, uid, [phase_id], {'phase_document_ids': [(6,0,document_ids)]}) self.write(cr, uid, [process.id],{'process_document_ids': [(6,0,new_doc_ids)]})
case_pool=pool.get('crm.case')
case_pool=pool.get(data['model'])
def _mass_mail_send(self, cr, uid, data, context): attach = filter(lambda x: x, [data['form']['doc1'], data['form']['doc2'], data['form']['doc3']]) attach = map(lambda x: x and ('Attachment'+str(attach.index(x)+1), base64.decodestring(x)), attach) pool = pooler.get_pool(cr.dbname) case_pool=pool.get('crm.case') case = case_pool.browse(cr,uid,data['ids'])[0] case_pool.write(cr, uid, [case.id], { 'som': False, 'canal_id': False, }) emails = [data['form']['to']] + (data['form']['cc'] or '').split(',') emails = filter(None, emails) body = data['form']['text'] if not case.user_id.address_id.email: raise wizard.except_wizard(_('Warning!'),_("Please specify user's email address !")) if case.user_id.signature: body += '\n\n%s' % (case.user_id.signature) case_pool._history(cr, uid, [case], _('Send'), history=True, email=False, details=body) flag = tools.email_send( case.user_id.address_id.email, emails, data['form']['subject'], body, case_pool.format_body(body), attach=attach, reply_to=case.section_id.reply_to, tinycrm=str(case.id) ) if flag: if data['form']['state'] == 'unchanged': pass elif data['form']['state'] == 'done': case_pool.case_close(cr, uid, data['ids']) elif data['form']['state'] == 'pending': case_pool.case_pending(cr, uid, data['ids']) cr.commit() else: raise wizard.except_wizard(_('Warning!'),_("Email not sent !")) return {}
case = pool.get('crm.lead').browse(cr, uid, data['id'])
case = pool.get(data['model']).browse(cr, uid, data['id'])
def _get_info(self, cr, uid, data, context): if not data['id']: return {} pool = pooler.get_pool(cr.dbname) case = pool.get('crm.lead').browse(cr, uid, data['id']) if not case.user_id: raise wizard.except_wizard(_('Error'),_('You must define a responsible user for this case in order to use this action!')) return { 'to': case.email_from, 'subject': case.name, 'cc': case.email_cc or '' }
def _equal_balance(self, cr, uid, ids, statement, context={}): if statement.balance_end != statement.balance_end_cash: return False else: return True def _user_allow(self, cr, uid, ids, statement, context={}): return True
def onchange_journal_id(self, cr, uid, statement_id, journal_id, context={}): """ Changes balance start and starting details if journal_id changes" @param statement_id: Changed statement_id @param journal_id: Changed journal_id @return: Dictionary of changed values """ cash_pool = self.pool.get('account.cashbox.line') statement_pool = self.pool.get('account.bank.statement')
if st.balance_end != st.balance_end_cash:
if not self._equal_balance(cr, uid, ids, st, context):
def button_confirm(self, cr, uid, ids, context={}): """ Check the starting and ending detail of statement @return: True """ done = [] res_currency_obj = self.pool.get('res.currency') res_users_obj = self.pool.get('res.users') account_move_obj = self.pool.get('account.move') account_move_line_obj = self.pool.get('account.move.line') account_bank_statement_line_obj = self.pool.get('account.bank.statement.line')
msg_txt = email.message_from_string(message)
def parse_message(self, message): #TOCHECK: put this function in mailgateway module msg_txt = email.message_from_string(message) message_id = msg_txt.get('message-id', False) msg = {} msg_txt = email.message_from_string(message) fields = msg_txt.keys() msg['id'] = message_id msg['message-id'] = message_id
msg_ids = msg_pool.search(cr, uid, [('message_id','=',message_id)])
msg_ids = []
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 = msg_pool.search(cr, uid, [('message_id','=',message_id)]) res = {} res_ids = [] if msg_ids and len(msg_ids): return 0
if msg_ids and len(msg_ids): return 0
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 = msg_pool.search(cr, uid, [('message_id','=',message_id)]) res = {} res_ids = [] if msg_ids and len(msg_ids): return 0
def allow_cancel(self, cr, uid, ids, context={}): for pick in self.browse(cr, uid, ids, context=context): if not pick.move_lines: return True for move in pick.move_lines: if move.state == 'done': return False return True
def test_cancel(self, cr, uid, ids, context=None): """ Test whether the move lines are canceled or not. @return: True or False """ for pick in self.browse(cr, uid, ids, context=context): if not pick.move_lines: return False for move in pick.move_lines: if move.state not in ('cancel',): return False return True
self.init_query = obj_move._query_get(self.cr, self.uid, obj='l', context=data['form'].get('used_context_initial_bal', {}))
ctx2 = data['form'].get('used_context',{}).copy() ctx2.update({'initial_bal': True}) self.init_query = obj_move._query_get(self.cr, self.uid, obj='l', context=ctx2)
def set_context(self, objects, data, ids, report_type=None): obj_move = self.pool.get('account.move.line') self.query = obj_move._query_get(self.cr, self.uid, obj='l', context=data['form'].get('used_context', {})) self.init_query = obj_move._query_get(self.cr, self.uid, obj='l', context=data['form'].get('used_context_initial_bal', {})) self.reconcil = data['form'].get('reconcil', True) self.initial_balance = data['form'].get('initial_balance', True) self.result_selection = data['form'].get('result_selection', 'customer') self.amount_currency = data['form'].get('amount_currency', False) self.target_move = data['form'].get('target_move', 'all') PARTNER_REQUEST = '' move_state = ['draft','posted'] if self.target_move == 'posted': move_state = ['posted']
pool.get(obj).read(cr, uid, [ids[0]]) cnt = cr.count pool.get(obj).read(cr, uid, [ids[0]]) code_base_complexity = cr.count - cnt
pool.get(obj).read(cr, uid, ids)
def run_test(self, cr, uid, module_path): pool = pooler.get_pool(cr.dbname) module_name = module_path.split('/')[-1] obj_list = self.get_objects(cr, uid, module_name)
pool.get(obj).read(cr, uid, ids[:size/2]) cnt = cr.count pool.get(obj).read(cr, uid, ids[:size/2]) code_half_complexity = cr.count - cnt
ccr.reset() pool.get(obj).read(ccr, uid, [ids[0]]) code_base_complexity = ccr.count
def run_test(self, cr, uid, module_path): pool = pooler.get_pool(cr.dbname) module_name = module_path.split('/')[-1] obj_list = self.get_objects(cr, uid, module_name)
pool.get(obj).read(cr, uid, ids) cnt = cr.count pool.get(obj).read(cr, uid, ids) code_size_complexity = cr.count - cnt
ccr.reset() pool.get(obj).read(ccr, uid, ids[:size/2]) code_half_complexity = ccr.count ccr.reset() pool.get(obj).read(ccr, uid, ids) code_size_complexity = ccr.count
def run_test(self, cr, uid, module_path): pool = pooler.get_pool(cr.dbname) module_name = module_path.split('/')[-1] obj_list = self.get_objects(cr, uid, module_name)
datetime.strptime(guarantee_limit, '%Y-%m-%d') < datetime.now()):
datetime.strptime(guarantee_limit, '%Y-%m-%d') < datetime.now())
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 } }