rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
'res_id': fields.integer('Resource ID', select=1),
'res_id': fields.integer('Resource ID', select=1, readonly=1),
def _res_name_get(self, cr, uid, ids, field_name, arg, context=None): res = {} for obj in self.browse(cr, uid, ids, context=context): if obj.res_id: try: res[obj.id] = self.pool.get(obj.object_id.model).name_get(cr, uid, [obj.res_id], context=context)[0][1] except: res[obj.id] = '/' else: res[obj.id] = '/' return res
if account_id and (not line or (line and not line[0].amount)):
if account_id and (not line or (line and not line[0].amount)) and not context.get('amount', False):
def onchange_partner_id(self, cursor, user, line_id, partner_id, type, currency_id, context=None): res_users_obj = self.pool.get('res.users') res_currency_obj = self.pool.get('res.currency') res = {'value': {}} obj_partner = self.pool.get('res.partner') if context is None: context = {} if not partner_id: return res account_id = False line = self.browse(cursor, user, line_id) if not line or (line and not line[0].account_id): part = obj_partner.browse(cursor, user, partner_id, context=context) if type == 'supplier': account_id = part.property_account_payable.id else: account_id = part.property_account_receivable.id res['value']['account_id'] = account_id
'date': fields.datetime('Date Planned', required=True, help="Scheduled date for the movement of the products or real date if the move is done."),
'date': fields.datetime('Date ', required=True, help="Scheduled date for the movement of the products or real date if the move is done."),
def _check_product_lot(self, cr, uid, ids): """ Checks whether move is done or not and production lot is assigned to that move. @return: True or False """ for move in self.browse(cr, uid, ids): if move.prodlot_id and move.state == 'done' and (move.prodlot_id.product_id.id != move.product_id.id): return False return True
entry['name'] = model.name%{'year':time.strftime('%Y'), 'month':time.strftime('%m'), 'date':time.strftime('%d')}
entry['name'] = model.name%{'year':time.strftime('%Y'), 'month':time.strftime('%m'), 'date':time.strftime('%Y-%m')}
def generate(self, cr, uid, ids, datas={}, context={}): move_ids = [] entry = {} account_move_obj = self.pool.get('account.move') account_move_line_obj = self.pool.get('account.move.line') pt_obj = self.pool.get('account.payment.term')
if not exp.employee_id.address_id: raise osv.except_osv(_('Error !'), _('The employee must have a working address')) acc = exp.employee_id.address_id.partner_id.property_account_payable.id payment_term_id = exp.employee_id.address_id.partner_id.property_payment_term.id
if not exp.employee_id.address_home_id: raise osv.except_osv(_('Error !'), _('The employee must have a Home address')) acc = exp.employee_id.address_home_id.partner_id.property_account_payable.id payment_term_id = exp.employee_id.address_home_id.partner_id.property_payment_term.id
def action_invoice_create(self, cr, uid, ids): res = False invoice_obj = self.pool.get('account.invoice') property_obj = self.pool.get('ir.property') sequence_obj = self.pool.get('ir.sequence') analytic_journal_obj = self.pool.get('account.analytic.journal') account_journal = self.pool.get('account.journal') 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 if not acc: acc = l.product_id.categ_id.property_account_expense_categ tax_id = [x.id for x in l.product_id.supplier_taxes_id] else: acc = property_obj.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`'))
'partner_id': exp.employee_id.address_id.partner_id.id, 'address_invoice_id': exp.employee_id.address_id.id, 'address_contact_id': exp.employee_id.address_id.id,
'partner_id': exp.employee_id.address_home_id.partner_id.id, 'address_invoice_id': exp.employee_id.address_home_id.id, 'address_contact_id': exp.employee_id.address_home_id.id,
def action_invoice_create(self, cr, uid, ids): res = False invoice_obj = self.pool.get('account.invoice') property_obj = self.pool.get('ir.property') sequence_obj = self.pool.get('ir.sequence') analytic_journal_obj = self.pool.get('account.analytic.journal') account_journal = self.pool.get('account.journal') 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 if not acc: acc = l.product_id.categ_id.property_account_expense_categ tax_id = [x.id for x in l.product_id.supplier_taxes_id] else: acc = property_obj.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`'))
'fiscal_position': exp.employee_id.address_id.partner_id.property_account_position.id
'fiscal_position': exp.employee_id.address_home_id.partner_id.property_account_position.id
def action_invoice_create(self, cr, uid, ids): res = False invoice_obj = self.pool.get('account.invoice') property_obj = self.pool.get('ir.property') sequence_obj = self.pool.get('ir.sequence') analytic_journal_obj = self.pool.get('account.analytic.journal') account_journal = self.pool.get('account.journal') 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 if not acc: acc = l.product_id.categ_id.property_account_expense_categ tax_id = [x.id for x in l.product_id.supplier_taxes_id] else: acc = property_obj.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`'))
self.log(cr, uid, id, message)
self.log(cr, uid, case.id, message)
def case_open(self, cr, uid, ids, *args): """Overrides cancel for crm_case for setting Open Date @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 case's Ids @param *args: Give Tuple Value """ old_state = self.read(cr, uid, ids, ['state'])[0]['state'] old_stage_id = self.read(cr, uid, ids, ['stage_id'])[0]['stage_id'] res = super(crm_lead, self).case_open(cr, uid, ids, *args) if old_state == 'draft': value = {} if not old_stage_id: stage_id = super(crm_lead, self).stage_next(cr, uid, ids, *args) if stage_id: value.update({'stage_id': stage_id}) value.update(self.onchange_stage_id(cr, uid, ids, stage_id, context={})['value']) value.update({'date_open': time.strftime('%Y-%m-%d %H:%M:%S')}) self.write(cr, uid, ids, value)
self.log(cr, uid, id, message)
self.log(cr, uid, case.id, message)
def case_close(self, cr, uid, ids, *args): """Overrides close for crm_case for setting close date @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 case Ids @param *args: Tuple Value for additional Params """ res = super(crm_lead, self).case_close(cr, uid, ids, args) self.write(cr, uid, ids, {'date_closed': time.strftime('%Y-%m-%d %H:%M:%S')}) for case in self.browse(cr, uid, ids): n = { 'lead': _('The lead'), 'opportunity': _('The opportunity') }.get(case.type, _('The case')) message = n +" '" + case.name + "' "+ _("has been closed.") self.log(cr, uid, id, message) return res
if r['product_id']== move.product_id.id: move_lines_obj.write(cr, uid,move.id, {'product_qty' : r['product_qty']})
if r['product_id'] == move.product_id.id: move_lines_obj.write(cr, uid, [move.id], {'product_qty' : r['product_qty']})
def change_prod_qty(self, cr, uid, ids, context): """ Changes the Quantity of Product. @param self: The object pointer. @param cr: A database cursor @param uid: ID of the user currently logged in @param ids: List of IDs selected @param context: A standard dictionary @return: """ record_id = context and context.get('active_id',False) assert record_id, _('Active Id is not found') prod_obj = self.pool.get('mrp.production') product_lines_obj = self.pool.get('mrp.production.product.line') bom_obj = self.pool.get('mrp.bom') for wiz_qty in self.browse(cr, uid, ids): prod = prod_obj.browse(cr, uid,record_id) prod_obj.write(cr, uid,prod.id, {'product_qty': wiz_qty.product_qty}) prod_obj.action_compute(cr, uid, [prod.id]) move_lines_obj = self.pool.get('stock.move') for move in prod.move_lines: bom_point = prod.bom_id bom_id = prod.bom_id.id if not bom_point: bom_id = bom_obj._bom_find(cr, uid, prod.product_id.id, prod.product_uom.id) if not bom_id: raise osv.except_osv(_('Error'), _("Couldn't find bill of material for product")) prod_obj.write(cr, uid, [prod.id], {'bom_id': bom_id}) bom_point = bom_obj.browse(cr, uid, [bom_id])[0] if not bom_id: raise osv.except_osv(_('Error'), _("Couldn't find bill of material for product")) factor = prod.product_qty * prod.product_uom.factor / bom_point.product_uom.factor res = bom_obj._bom_explode(cr, uid, bom_point, factor / bom_point.product_qty, []) for r in res[0]: if r['product_id']== move.product_id.id: move_lines_obj.write(cr, uid,move.id, {'product_qty' : r['product_qty']}) for m in prod.move_created_ids: move_lines_obj.write(cr, uid,m.id, {'product_qty': wiz_qty.product_qty}) return {}
move_lines_obj.write(cr, uid,m.id, {'product_qty': wiz_qty.product_qty})
move_lines_obj.write(cr, uid, [m.id], {'product_qty': wiz_qty.product_qty})
def change_prod_qty(self, cr, uid, ids, context): """ Changes the Quantity of Product. @param self: The object pointer. @param cr: A database cursor @param uid: ID of the user currently logged in @param ids: List of IDs selected @param context: A standard dictionary @return: """ record_id = context and context.get('active_id',False) assert record_id, _('Active Id is not found') prod_obj = self.pool.get('mrp.production') product_lines_obj = self.pool.get('mrp.production.product.line') bom_obj = self.pool.get('mrp.bom') for wiz_qty in self.browse(cr, uid, ids): prod = prod_obj.browse(cr, uid,record_id) prod_obj.write(cr, uid,prod.id, {'product_qty': wiz_qty.product_qty}) prod_obj.action_compute(cr, uid, [prod.id]) move_lines_obj = self.pool.get('stock.move') for move in prod.move_lines: bom_point = prod.bom_id bom_id = prod.bom_id.id if not bom_point: bom_id = bom_obj._bom_find(cr, uid, prod.product_id.id, prod.product_uom.id) if not bom_id: raise osv.except_osv(_('Error'), _("Couldn't find bill of material for product")) prod_obj.write(cr, uid, [prod.id], {'bom_id': bom_id}) bom_point = bom_obj.browse(cr, uid, [bom_id])[0] if not bom_id: raise osv.except_osv(_('Error'), _("Couldn't find bill of material for product")) factor = prod.product_qty * prod.product_uom.factor / bom_point.product_uom.factor res = bom_obj._bom_explode(cr, uid, bom_point, factor / bom_point.product_qty, []) for r in res[0]: if r['product_id']== move.product_id.id: move_lines_obj.write(cr, uid,move.id, {'product_qty' : r['product_qty']}) for m in prod.move_created_ids: move_lines_obj.write(cr, uid,m.id, {'product_qty': wiz_qty.product_qty}) return {}
a = self.pool.get('ir.property').get(cr, uid,
prop = self.pool.get('ir.property').get(cr, uid,
def _get_line_uom(line): if (line.order_id.invoice_quantity=='order') or not line.procurement_id: if line.product_uos: return line.product_uos.id return line.product_uom.id else: return self.pool.get('procurement.order').uom_get(cr, uid, line.procurement_id.id, context=context)
context=context).id
context=context) a = prop and prop.id or False
def _get_line_uom(line): if (line.order_id.invoice_quantity=='order') or not line.procurement_id: if line.product_uos: return line.product_uos.id return line.product_uom.id else: return self.pool.get('procurement.order').uom_get(cr, uid, line.procurement_id.id, context=context)
if context is None: context = {}
def _check_recursion(self, cr, uid, ids, context=None): if context is None: context = {} level = 100 while len(ids): cr.execute('select distinct parent_id from hr_employee where id IN %s',(tuple(ids),)) ids = filter(None, map(lambda x:x[0], cr.fetchall())) if not level: return False level -= 1 return True
cr.execute('select distinct parent_id from hr_employee where id IN %s',(tuple(ids),))
cr.execute('SELECT DISTINCT parent_id FROM hr_employee WHERE id IN %s AND parent_id!=id',(tuple(ids),))
def _check_recursion(self, cr, uid, ids, context=None): if context is None: context = {} level = 100 while len(ids): cr.execute('select distinct parent_id from hr_employee where id IN %s',(tuple(ids),)) ids = filter(None, map(lambda x:x[0], cr.fetchall())) if not level: return False level -= 1 return True
line_domain = eval(line.domain)
line_domain = eval(line.domain or '[]')
def get_calendar_objects(self, cr, uid, ids, parent=None, domain=None, context=None): if not context: context = {} if not domain: domain = [] res = [] ctx_res_id = context.get('res_id', None) ctx_model = context.get('model', None) for cal in self.browse(cr, uid, ids): for line in cal.line_ids: if ctx_model and ctx_model != line.object_id.model: continue if line.name in ('valarm', 'attendee'): continue line_domain = eval(line.domain) line_domain += domain if ctx_res_id: line_domain += [('id','=',ctx_res_id)] mod_obj = self.pool.get(line.object_id.model) data_ids = mod_obj.search(cr, uid, line_domain, context=context) for data in mod_obj.browse(cr, uid, data_ids, context): ctx = parent and parent.context or None node = res_node_calendar('%s.ics' %data.id, parent, ctx, data, line.object_id.model, data.id) res.append(node) return res
domain = eval(line.domain)
domain = eval(line.domain or '[]')
def export_cal(self, cr, uid, ids, vobj='vevent', context=None): """ Export Calendar @param ids: List of calendar’s IDs @param vobj: the type of object to export @return the ical data. """ if not context: context = {} ctx_model = context.get('model', None) ctx_res_id = context.get('res_id', None) ical = vobject.iCalendar() for cal in self.browse(cr, uid, ids): for line in cal.line_ids: if ctx_model and ctx_model != line.object_id.model: continue if line.name in ('valarm', 'attendee'): continue domain = eval(line.domain) if ctx_res_id: domain += [('id','=',ctx_res_id)] mod_obj = self.pool.get(line.object_id.model) data_ids = mod_obj.search(cr, uid, domain, context=context) datas = mod_obj.read(cr, uid, data_ids, context=context) context.update({'model': line.object_id.model, 'calendar_id': cal.id }) self.__attribute__ = get_attribute_mapping(cr, uid, line.name, context) self.create_ics(cr, uid, datas, line.name, ical, context=context) return ical.serialize()
'company_id': fields.related('journal_id', 'company_id', type='many2one', relation='res.company', string='Company', store=True, required=True),
'company_id': fields.related('journal_id', 'company_id', type='many2one', relation='res.company', string='Company', store=True),
def _currency(self, cursor, user, ids, name, args, context=None): res = {} res_currency_obj = self.pool.get('res.currency') res_users_obj = self.pool.get('res.users') default_currency = res_users_obj.browse(cursor, user, user, context=context).company_id.currency_id for statement in self.browse(cursor, user, ids, context=context): currency = statement.journal_id.currency if not currency: currency = default_currency res[statement.id] = currency.id currency_names = {} for currency_id, currency_name in res_currency_obj.name_get(cursor, user, [x for x in res.values()], context=context): currency_names[currency_id] = currency_name for statement_id in res.keys(): currency_id = res[statement_id] res[statement_id] = (currency_id, currency_names[currency_id]) return res
'company_id': fields.related('statement_id', 'company_id', type='many2one', relation='res.company', string='Company', store=True, required=True),
'company_id': fields.related('statement_id', 'company_id', type='many2one', relation='res.company', string='Company', store=True),
def _reconcile_amount(self, cursor, user, ids, name, args, context=None): if not ids: return {} res_currency_obj = self.pool.get('res.currency') res_users_obj = self.pool.get('res.users')
to_update[str(id)]= {'level': fups[followup_line_id][1], 'partner_id': partner_id}
to_update[partner_id] = {} to_update[partner_id].update({id: fups[followup_line_id][1],})
def _get_partners_followp(self, cr, uid, ids, context=None): data = {} if context is None: context = {} if ids: data = self.read(cr, uid, ids, [])[0] cr.execute( "SELECT l.partner_id, l.followup_line_id,l.date_maturity, l.date, l.id "\ "FROM account_move_line AS l "\ "LEFT JOIN account_account AS a "\ "ON (l.account_id=a.id) "\ "WHERE (l.reconcile_id IS NULL) "\ "AND (a.type='receivable') "\ "AND (l.state<>'draft') "\ "AND (l.partner_id is NOT NULL) "\ "AND (a.active) "\ "AND (l.debit > 0) "\ "ORDER BY l.date") move_lines = cr.fetchall() old = None fups = {} fup_id = 'followup_id' in context and context['followup_id'] or data['followup_id'] date = 'date' in context and context['date'] or data['date']
'name': _('Follwoup Summary'),
'name': _('Followup Summary'),
def do_mail(self ,cr, uid, ids, context=None): mod_obj = self.pool.get('ir.model.data') move_obj = self.pool.get('account.move.line') user_obj = self.pool.get('res.users') line_obj = self.pool.get('account_followup.stat')
res = self._get_partners_followp(cr, uid, ids, context)['to_update'] to_update = res data['followup_id'] = 'followup_id' in context and context['followup_id'] or False date = 'date' in context and context['date'] or data['date'] for id in to_update.keys(): if to_update[id]['partner_id'] in data['partner_ids']: cr.execute( "UPDATE account_move_line "\ "SET followup_line_id=%s, followup_date=%s "\ "WHERE id=%s", (to_update[id]['level'], date, int(id),))
res = self._get_partners_followp(cr, uid, ids, context) self._update_partners(cr, uid, res, context=context)
def do_print(self, cr, uid, ids, context=None): if context is None: context = {} data = self.read(cr, uid, ids, [])[0] res = self._get_partners_followp(cr, uid, ids, context)['to_update'] to_update = res data['followup_id'] = 'followup_id' in context and context['followup_id'] or False date = 'date' in context and context['date'] or data['date'] for id in to_update.keys(): if to_update[id]['partner_id'] in data['partner_ids']: cr.execute( "UPDATE account_move_line "\ "SET followup_line_id=%s, followup_date=%s "\ "WHERE id=%s", (to_update[id]['level'], date, int(id),))
'state': fields.selection([('draft', 'Request for Quotation'), ('wait', 'Waiting'), ('confirmed', 'Waiting Supplier Ack'), ('approved', 'Approved'),('except_picking', 'Shipping Exception'), ('except_invoice', 'Invoice Exception'), ('done', 'Done'), ('cancel', 'Cancelled')], 'State', readonly=True, help="The state of the purchase order or the quotation request. A quotation is a purchase order in a 'Draft' state. Then the order has to be confirmed by the user, the state switch to 'Confirmed'. Then the supplier must confirm the order to change the state to 'Approved'. When the purchase order is paid and received, the state becomes 'Done'. If a cancel action occurs in the invoice or in the reception of goods, the state becomes in exception.", select=True),
'state': fields.selection(STATE_SELECTION, 'State', readonly=True, help="The state of the purchase order or the quotation request. A quotation is a purchase order in a 'Draft' state. Then the order has to be confirmed by the user, the state switch to 'Confirmed'. Then the supplier must confirm the order to change the state to 'Approved'. When the purchase order is paid and received, the state becomes 'Done'. If a cancel action occurs in the invoice or in the reception of goods, the state becomes in exception.", select=True),
def _invoiced(self, cursor, user, ids, name, arg, context=None): res = {} for purchase in self.browse(cursor, user, ids, context=context): if purchase.invoice_id.reconciled: res[purchase.id] = purchase.invoice_id.reconciled else: res[purchase.id] = False return res
state_dict = {'wait':'Waiting','confirmed':'Confirmed','approved':'Approved','except_picking': 'Shipping Exception','except_invoice': 'Invoice Exception','done': 'Done'} raise osv.except_osv(_('Invalid action !'), _('Cannot delete Purchase Order(s) which are in %s State!') %_(eval(s['state'],state_dict)))
raise osv.except_osv(_('Invalid action !'), _('Cannot delete Purchase Order(s) which are in %s State!') % _(dict(purchase_order.STATE_SELECTION).get(s['state'])))
def unlink(self, cr, uid, ids, context=None): purchase_orders = self.read(cr, uid, ids, ['state']) unlink_ids = [] for s in purchase_orders: if s['state'] in ['draft','cancel']: unlink_ids.append(s['id']) else: state_dict = {'wait':'Waiting','confirmed':'Confirmed','approved':'Approved','except_picking': 'Shipping Exception','except_invoice': 'Invoice Exception','done': 'Done'} raise osv.except_osv(_('Invalid action !'), _('Cannot delete Purchase Order(s) which are in %s State!') %_(eval(s['state'],state_dict)))
def write(self, cr, uid, ids,vals, *args, **kwargs): if 'date' in vals and vals['date']:
def write(self, cr, uid, ids, vals, *args, **kwargs): if isinstance(ids, (int, long)): ids = [ids] if vals.get('date', False):
def write(self, cr, uid, ids,vals, *args, **kwargs): if 'date' in vals and vals['date']: data_project = self.browse(cr, uid, ids) for prj in data_project: new_end_date = date(*time.strptime(vals['date'],'%Y-%m-%d')[:3]) if prj.date: old_end_date = date(*time.strptime(prj.date,'%Y-%m-%d')[:3]) for task in prj.tasks: if task.date_start: start_dt = (date(*time.strptime(str(task.date_start),'%Y-%m-%d %H:%M:%S')[:3])+(new_end_date-old_end_date)).strftime('%Y-%m-%d %H:%M:%S') if task.date_deadline: deadline_dt = (datetime(*time.strptime(str(task.date_deadline),'%Y-%m-%d')[:3])+(new_end_date-old_end_date)).strftime('%Y-%m-%d') self.pool.get('project.task').write(cr, uid, task.id, {'date_start':start_dt, 'date_deadline':deadline_dt}) else: self.pool.get('project.task').write(cr, uid, task.id, {'date_start':start_dt}) return super(project_project,self).write(cr, uid, ids, vals, *args, **kwargs)
self.pool.get('project.task').write(cr, uid, task.id, {'date_start':start_dt, 'date_deadline':deadline_dt})
self.pool.get('project.task').write(cr, uid, [task.id], {'date_start':start_dt, 'date_deadline':deadline_dt})
def write(self, cr, uid, ids,vals, *args, **kwargs): if 'date' in vals and vals['date']: data_project = self.browse(cr, uid, ids) for prj in data_project: new_end_date = date(*time.strptime(vals['date'],'%Y-%m-%d')[:3]) if prj.date: old_end_date = date(*time.strptime(prj.date,'%Y-%m-%d')[:3]) for task in prj.tasks: if task.date_start: start_dt = (date(*time.strptime(str(task.date_start),'%Y-%m-%d %H:%M:%S')[:3])+(new_end_date-old_end_date)).strftime('%Y-%m-%d %H:%M:%S') if task.date_deadline: deadline_dt = (datetime(*time.strptime(str(task.date_deadline),'%Y-%m-%d')[:3])+(new_end_date-old_end_date)).strftime('%Y-%m-%d') self.pool.get('project.task').write(cr, uid, task.id, {'date_start':start_dt, 'date_deadline':deadline_dt}) else: self.pool.get('project.task').write(cr, uid, task.id, {'date_start':start_dt}) return super(project_project,self).write(cr, uid, ids, vals, *args, **kwargs)
self.pool.get('project.task').write(cr, uid, task.id, {'date_start':start_dt})
self.pool.get('project.task').write(cr, uid, [task.id], {'date_start':start_dt})
def write(self, cr, uid, ids,vals, *args, **kwargs): if 'date' in vals and vals['date']: data_project = self.browse(cr, uid, ids) for prj in data_project: new_end_date = date(*time.strptime(vals['date'],'%Y-%m-%d')[:3]) if prj.date: old_end_date = date(*time.strptime(prj.date,'%Y-%m-%d')[:3]) for task in prj.tasks: if task.date_start: start_dt = (date(*time.strptime(str(task.date_start),'%Y-%m-%d %H:%M:%S')[:3])+(new_end_date-old_end_date)).strftime('%Y-%m-%d %H:%M:%S') if task.date_deadline: deadline_dt = (datetime(*time.strptime(str(task.date_deadline),'%Y-%m-%d')[:3])+(new_end_date-old_end_date)).strftime('%Y-%m-%d') self.pool.get('project.task').write(cr, uid, task.id, {'date_start':start_dt, 'date_deadline':deadline_dt}) else: self.pool.get('project.task').write(cr, uid, task.id, {'date_start':start_dt}) return super(project_project,self).write(cr, uid, ids, vals, *args, **kwargs)
ref_obj_ids = model_obj.search(cr, uid, [], 0, 20, 'id desc', context=context)
ref_obj_ids = model_obj.search(cr, uid, [], 0, 20, 'id', context=context)
def _get_model_recs(self, cr, uid, context=None): if context is None: context = {} #Fills up the selection box which allows records from the selected object to be displayed self.context = context if 'template_id' in context: ref_obj_id = self.pool.get('email.template').read(cr, uid, context['template_id'], ['object_name'], context) ref_obj_name = self.pool.get('ir.model').read(cr, uid, ref_obj_id['object_name'][0], ['model'], context)['model'] model_obj = self.pool.get(ref_obj_name) ref_obj_ids = model_obj.search(cr, uid, [], 0, 20, 'id desc', context=context) if not ref_obj_ids: ref_obj_ids = []
""" Calculates Sub total"
""" Calculates Sub total
def _sub_total(self, cr, uid, ids, name, arg, context=None): """ Calculates Sub total" @param name: Names of fields. @param arg: User defined arguments @return: Dictionary of values. """ res = {} for obj in self.browse(cr, uid, ids): res[obj.id] = obj.pieces * obj.number return res
'account_id': a.id,
'account_id': a,
def inv_line_create(self, cr, uid, a, ol): return (0, False, { 'name': ol.name, 'account_id': a.id, 'price_unit': ol.price_unit or 0.0, 'quantity': ol.product_qty, 'product_id': ol.product_id.id or False, 'uos_id': ol.product_uom.id or False, 'invoice_line_tax_id': [(6, 0, [x.id for x in ol.taxes_id])], 'account_analytic_id': ol.account_analytic_id.id or False, })
a = self.pool.get('ir.property').get(cr, uid, 'property_account_expense_categ', 'product.category')
a = self.pool.get('ir.property').get(cr, uid, 'property_account_expense_categ', 'product.category').id
def action_invoice_create(self, cr, uid, ids, *args): res = False
if not inv.line_ids: raise osv.except_osv(_('No Lines !'), _('Please create some lines'))
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
credit = currency_pool.compute(cr, uid, inv.currency_id.id, company_currency, inv.amount)
credit = currency_pool.compute(cr, uid, current_currency, company_currency, inv.amount)
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
debit = currency_pool.compute(cr, uid, inv.currency_id.id, company_currency, inv.amount)
debit = currency_pool.compute(cr, uid, current_currency, company_currency, inv.amount)
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
sign = debit - credit < 0 and -1 or 1
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
'currency_id': inv.currency_id.id, 'amount_currency': inv.amount,
'currency_id': company_currency <> current_currency and current_currency or False, 'amount_currency': company_currency <> current_currency and sign * inv.amount or 0.0,
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
amount = currency_pool.compute(cr, uid, inv.currency_id.id, company_currency, line.amount)
amount = currency_pool.compute(cr, uid, current_currency, company_currency, line.amount)
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
'currency_id': inv.currency_id.id, 'amount_currency': line.amount,
'currency_id': company_currency <> current_currency and current_currency or False,
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 (not account_id) and 'account_id' in fields_list: raise osv.except_osv(_('Invalid Error !'), _('Please change partner and try again !'))
def default_get(self, cr, user, fields_list, context=None): """ Returns default values for fields @param fields_list: list of fields, for which default values are required to be read @param context: context arguments, like lang, time zone
if journal: journal = journal[0] else: journal = None
journal = journal and journal[0] or False
def default_get(self, cr, uid, fields, context): """ 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. """ res = super(pos_make_payment, self).default_get(cr, uid, fields, context=context)
for user_id in datas.get('user_ids', []):
if not datas.get('user_ids'): raise osv.except_osv(_('Error!'), ("Please select any User")) for user_id in datas.get('user_ids'):
def do_invite(self, cr, uid, ids, context={}): datas = self.read(cr, uid, ids)[0] model = False model_field = False if not context or not context.get('model'): return {} else: model = context.get('model') model_field = context.get('attendee_field', False) obj = self.pool.get(model) res_obj = obj.browse(cr, uid, context['active_id']) type = datas.get('type') att_obj = self.pool.get('calendar.attendee') vals = {} mail_to = [] if not model == 'calendar.attendee': vals = {'ref': '%s,%s' % (model, base_calendar_id2real_id(context['active_id']))}
att_id = att_obj.create(cr, uid, vals) if model_field: obj.write(cr, uid, res_obj.id, {model_field: [(4, att_id)]})
def do_invite(self, cr, uid, ids, context={}): datas = self.read(cr, uid, ids)[0] model = False model_field = False if not context or not context.get('model'): return {} else: model = context.get('model') model_field = context.get('attendee_field', False) obj = self.pool.get(model) res_obj = obj.browse(cr, uid, context['active_id']) type = datas.get('type') att_obj = self.pool.get('calendar.attendee') vals = {} mail_to = [] if not model == 'calendar.attendee': vals = {'ref': '%s,%s' % (model, base_calendar_id2real_id(context['active_id']))}
att_id = att_obj.create(cr, uid, vals) if model_field: obj.write(cr, uid, res_obj.id, {model_field: [(4, att_id)]})
def do_invite(self, cr, uid, ids, context={}): datas = self.read(cr, uid, ids)[0] model = False model_field = False if not context or not context.get('model'): return {} else: model = context.get('model') model_field = context.get('attendee_field', False) obj = self.pool.get(model) res_obj = obj.browse(cr, uid, context['active_id']) type = datas.get('type') att_obj = self.pool.get('calendar.attendee') vals = {} mail_to = [] if not model == 'calendar.attendee': vals = {'ref': '%s,%s' % (model, base_calendar_id2real_id(context['active_id']))}
todata.append('MAILTO:' + parent.email)
if parent.email: todata.append('MAILTO:' + parent.email)
def _compute_data(self, cr, uid, ids, name, arg, context): name = name[0] result = {}
fromdata.append('MAILTO:' + child.email)
if child.email: fromdata.append('MAILTO:' + child.email)
def _compute_data(self, cr, uid, ids, name, arg, context): name = name[0] result = {}
if view_type == 'search': journal_list = journal_pool.name_search(cr, uid, '', [], context=context) result['fields']['journal_id']['selection'] = journal_list
if view_type == 'search' and result['fields'].get('journal_id', False): result['fields']['journal_id']['selection'] = journal_pool.name_search(cr, uid, '', [], context=context)
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')
(_check_uos, 'Error: UOS must be in a different category than the UOM', ['uos_id']),
def _check_uos(self, cursor, user, ids): for product in self.browse(cursor, user, ids): if product.uos_id \ and product.uos_id.category_id.id \ == product.uom_id.category_id.id: return False return True
result[id][name] = obj['date']
result[id][name] = obj.get('date')
def get_delegate_data(user): email = user.address_id and user.address_id.email or '' return self._get_address(user.name, email)
result[id][name] = obj['date_deadline']
result[id][name] = obj.get('date_deadline')
def get_delegate_data(user): email = user.address_id and user.address_id.email or '' return self._get_address(user.name, email)
result[id][name] = obj['user_id']
result[id][name] = obj.get('user_id')
def get_delegate_data(user): email = user.address_id and user.address_id.email or '' return self._get_address(user.name, email)
vals = model_obj.import_cal(cr, uid, base64.decodestring(data['file_path']), context['active_id'], context)
vals = None try: vals = model_obj.import_cal(cr, uid, base64.decodestring(data['file_path']), context['active_id'], context) except: raise osv.except_osv(_('Warning !'),_('Invalid format of the ics, file can not be imported'))
def process_imp_ics(self, cr, uid, ids, context=None): """ Process Import ics File. @param cr: the current row, from the database cursor, @param uid: the current user’s ID for security checks, @param ids: List of calendar event import’s IDs @return: dictionary of calendar evet import window with Import successful msg. """ if context is None: context = {} else: context = context.copy() context['uid'] = uid
end = datetime.strptime(meeting.date_deadline[:19], "%Y-%m-%d %H:%M:%S") diff = end - start duration = float(diff.days)* 24 + (float(diff.seconds) / 3600) res[meeting.id] = round(duration, 2)
if meeting.date_deadline: end = datetime.strptime(meeting.date_deadline[:19], "%Y-%m-%d %H:%M:%S") diff = end - start duration = float(diff.days)* 24 + (float(diff.seconds) / 3600) res[meeting.id] = round(duration, 2)
def _get_duration(self, cr, uid, ids, name, arg, context): res = {} for meeting in self.browse(cr, uid, ids, context=context): start = datetime.strptime(meeting.date, "%Y-%m-%d %H:%M:%S") end = datetime.strptime(meeting.date_deadline[:19], "%Y-%m-%d %H:%M:%S") diff = end - start duration = float(diff.days)* 24 + (float(diff.seconds) / 3600) res[meeting.id] = round(duration, 2) return res
fp = Popen(['file','-b','--mime',fname], shell=False, stdout=PIPE).stdout try: result = fp.read() finally: fp.close()
pop = Popen(['file','-b','--mime',fname], shell=False, stdout=PIPE) (result, _) = pop.communicate()
def doIndex(self, content, filename=None, content_type=None, realfname = None, debug=False): fobj = None fname = None mime = None if content_type and self.mimes.has_key(content_type): mime = content_type fobj = self.mimes[content_type] elif filename: bname,ext = os.path.splitext(filename) if self.exts.has_key(ext): fobj = self.exts[ext] mime = fobj._getDefMime(ext) if content_type and not fobj: mime,fobj = mime_match(content_type, self.mimes) if not fobj: try: if realfname : fname = realfname else: try: bname,ext = os.path.splitext(filename or 'test.tmp') except Exception: bname, ext = filename, 'tmp' fd, fname = tempfile.mkstemp(suffix=ext) os.write(fd, content) os.close(fd) fp = Popen(['file','-b','--mime',fname], shell=False, stdout=PIPE).stdout try: result = fp.read() finally: fp.close() mime2 = result.split(';')[0] self.__logger.debug('File gave us: %s', mime2) # Note that the temporary file still exists now. mime,fobj = mime_match(mime2, self.mimes) if not mime: mime = mime2 except Exception: self.__logger.exception('Cannot determine mime type') try: if fobj: res = (mime, fobj.indexContent(content,filename,fname or realfname) ) else: self.__logger.debug("Have no object, return (%s, None)", mime) res = (mime, None ) except Exception: self.__logger.exception("Could not index file %s (%s)", filename, fname or realfname) res = None # If we created a tmp file, unlink it now if not realfname and fname: try: os.unlink(fname) except Exception: self.__logger.exception("Could not unlink %s", fname) return res
return security.ExceptionNoTb('AccessDenied')
raise security.ExceptionNoTb('AccessDenied')
def check(db, uid, passwd): cached_pass = security._uid_cache.get(db, {}).get(uid) if (cached_pass is not None) and cached_pass == passwd: return True cr = pooler.get_db(db).cursor() if passwd not in _salt_cache: cr.execute( 'select login from res_users where id=%s', (uid,) ) stored_login = cr.fetchone() if stored_login: stored_login = stored_login[0] if not login(db,stored_login,passwd): return security.ExceptionNoTb('AccessDenied') salt = _salt_cache[passwd] cr.execute(' select count(*) from res_users where id=%s and password=%s', (int(uid), encrypt_md5( passwd, salt )) ) res = cr.fetchone()[0] cr.close() if not bool(res): raise security.ExceptionNoTb('AccessDenied') if res: security._uid_cache[uid] = passwd return bool(res)
parent_ids = tuple(self.search(cr, uid, [('parent_id', 'child_of', ids)], context=context)) if parent_ids: cr.execute("SELECT account_analytic_line.account_id, COALESCE(SUM(amount_currency), 0.0) \
res_final = {} child_ids = tuple(self.search(cr, uid, [('parent_id', 'child_of', ids)], context=context)) for i in child_ids: res[i] = {} for n in [name]: res[i][n] = 0.0 if not child_ids: return res if child_ids: cr.execute("SELECT account_analytic_line.account_id, COALESCE(SUM(amount), 0.0) \
def _ca_invoiced_calc(self, cr, uid, ids, name, arg, context=None): res = {} parent_ids = tuple(self.search(cr, uid, [('parent_id', 'child_of', ids)], context=context)) if parent_ids: cr.execute("SELECT account_analytic_line.account_id, COALESCE(SUM(amount_currency), 0.0) \ FROM account_analytic_line \ JOIN account_analytic_journal \ ON account_analytic_line.journal_id = account_analytic_journal.id \ WHERE account_analytic_line.account_id IN %s \ AND account_analytic_journal.type = 'sale' \ GROUP BY account_analytic_line.account_id", (parent_ids,)) for account_id, sum in cr.fetchall(): res[account_id] = round(sum,2) return self._compute_currency_for_level_tree(cr, uid, ids, parent_ids, res, context=context)
GROUP BY account_analytic_line.account_id", (parent_ids,))
GROUP BY account_analytic_line.account_id", (child_ids,))
def _ca_invoiced_calc(self, cr, uid, ids, name, arg, context=None): res = {} parent_ids = tuple(self.search(cr, uid, [('parent_id', 'child_of', ids)], context=context)) if parent_ids: cr.execute("SELECT account_analytic_line.account_id, COALESCE(SUM(amount_currency), 0.0) \ FROM account_analytic_line \ JOIN account_analytic_journal \ ON account_analytic_line.journal_id = account_analytic_journal.id \ WHERE account_analytic_line.account_id IN %s \ AND account_analytic_journal.type = 'sale' \ GROUP BY account_analytic_line.account_id", (parent_ids,)) for account_id, sum in cr.fetchall(): res[account_id] = round(sum,2) return self._compute_currency_for_level_tree(cr, uid, ids, parent_ids, res, context=context)
res[account_id] = round(sum,2) return self._compute_currency_for_level_tree(cr, uid, ids, parent_ids, res, context=context)
res[account_id][name] = round(sum,2) data = self._compute_level_tree(cr, uid, ids, child_ids, res, [name], context) for i in data: res_final[i] = data[i][name] return res_final
def _ca_invoiced_calc(self, cr, uid, ids, name, arg, context=None): res = {} parent_ids = tuple(self.search(cr, uid, [('parent_id', 'child_of', ids)], context=context)) if parent_ids: cr.execute("SELECT account_analytic_line.account_id, COALESCE(SUM(amount_currency), 0.0) \ FROM account_analytic_line \ JOIN account_analytic_journal \ ON account_analytic_line.journal_id = account_analytic_journal.id \ WHERE account_analytic_line.account_id IN %s \ AND account_analytic_journal.type = 'sale' \ GROUP BY account_analytic_line.account_id", (parent_ids,)) for account_id, sum in cr.fetchall(): res[account_id] = round(sum,2) return self._compute_currency_for_level_tree(cr, uid, ids, parent_ids, res, context=context)
parent_ids = tuple(self.search(cr, uid, [('parent_id', 'child_of', ids)], context=context)) if parent_ids: cr.execute("""SELECT account_analytic_line.account_id, COALESCE(SUM(amount_currency), 0.0) \
res_final = {} child_ids = tuple(self.search(cr, uid, [('parent_id', 'child_of', ids)], context=context)) for i in child_ids: res[i] = {} for n in [name]: res[i][n] = 0.0 if not child_ids: return res if child_ids: cr.execute("""SELECT account_analytic_line.account_id, COALESCE(SUM(amount), 0.0) \
def _total_cost_calc(self, cr, uid, ids, name, arg, context=None): res = {} parent_ids = tuple(self.search(cr, uid, [('parent_id', 'child_of', ids)], context=context)) if parent_ids: cr.execute("""SELECT account_analytic_line.account_id, COALESCE(SUM(amount_currency), 0.0) \ FROM account_analytic_line \ JOIN account_analytic_journal \ ON account_analytic_line.journal_id = account_analytic_journal.id \ WHERE account_analytic_line.account_id IN %s \ AND amount<0 \ GROUP BY account_analytic_line.account_id""",(parent_ids,)) for account_id, sum in cr.fetchall(): res[account_id] = round(sum,2) return self._compute_currency_for_level_tree(cr, uid, ids, parent_ids, res, context=context)
GROUP BY account_analytic_line.account_id""",(parent_ids,))
GROUP BY account_analytic_line.account_id""",(child_ids,))
def _total_cost_calc(self, cr, uid, ids, name, arg, context=None): res = {} parent_ids = tuple(self.search(cr, uid, [('parent_id', 'child_of', ids)], context=context)) if parent_ids: cr.execute("""SELECT account_analytic_line.account_id, COALESCE(SUM(amount_currency), 0.0) \ FROM account_analytic_line \ JOIN account_analytic_journal \ ON account_analytic_line.journal_id = account_analytic_journal.id \ WHERE account_analytic_line.account_id IN %s \ AND amount<0 \ GROUP BY account_analytic_line.account_id""",(parent_ids,)) for account_id, sum in cr.fetchall(): res[account_id] = round(sum,2) return self._compute_currency_for_level_tree(cr, uid, ids, parent_ids, res, context=context)
res[account_id] = round(sum,2) return self._compute_currency_for_level_tree(cr, uid, ids, parent_ids, res, context=context)
res[account_id][name] = round(sum,2) data = self._compute_level_tree(cr, uid, ids, child_ids, res, [name], context) for i in data: res_final[i] = data[i][name] return res_final
def _total_cost_calc(self, cr, uid, ids, name, arg, context=None): res = {} parent_ids = tuple(self.search(cr, uid, [('parent_id', 'child_of', ids)], context=context)) if parent_ids: cr.execute("""SELECT account_analytic_line.account_id, COALESCE(SUM(amount_currency), 0.0) \ FROM account_analytic_line \ JOIN account_analytic_journal \ ON account_analytic_line.journal_id = account_analytic_journal.id \ WHERE account_analytic_line.account_id IN %s \ AND amount<0 \ GROUP BY account_analytic_line.account_id""",(parent_ids,)) for account_id, sum in cr.fetchall(): res[account_id] = round(sum,2) return self._compute_currency_for_level_tree(cr, uid, ids, parent_ids, res, context=context)
return voucher.ref
return voucher.name
def _get_ref(self, voucher_id, move_ids): voucher_line = self.pool.get('account.voucher.line').search(self.cr, self.uid, [('partner_id','=',move_ids.partner_id.id), ('voucher_id','=',voucher_id)]) if voucher_line: voucher = self.pool.get('account.voucher.line').browse(self.cr, self.uid, voucher_line)[0] return voucher.ref else: return
do_create = (mode[1] in ('w','a')) )
do_create = (mode[0] in ('w','a')) )
def get_file(self, cr, uid, id, file_node, mode, context=None): """ Return a file-like object for the contents of some node """ if context is None: context = {} boo = self.browse(cr, uid, id, context) if not boo.online: raise IOError(errno.EREMOTE, 'medium offline') if boo.readonly and mode not in ('r', 'rb'): raise IOError(errno.EPERM, "Readonly medium") ira = self.pool.get('ir.attachment').browse(cr, uid, file_node.file_id, context=context) if boo.type == 'filestore': if not ira.store_fname: # On a migrated db, some files may have the wrong storage type # try to fix their directory. if mode in ('r','r+'): if ira.file_size: self._doclog.warning( "ir.attachment #%d does not have a filename, but is at filestore, fix it!" % ira.id) raise IOError(errno.ENOENT, 'No file can be located') else: store_fname = self.__get_random_fname(boo.path) cr.execute('UPDATE ir_attachment SET store_fname = %s WHERE id = %s', (store_fname, ira.id)) fpath = os.path.join(boo.path, store_fname) else: fpath = os.path.join(boo.path, ira.store_fname) return nodefd_file(file_node, path=fpath, mode=mode)
if (not os.path.exists(fpath)) and mode[1] == 'r':
if (not os.path.exists(fpath)) and mode[0] == 'r':
def get_file(self, cr, uid, id, file_node, mode, context=None): """ Return a file-like object for the contents of some node """ if context is None: context = {} boo = self.browse(cr, uid, id, context) if not boo.online: raise IOError(errno.EREMOTE, 'medium offline') if boo.readonly and mode not in ('r', 'rb'): raise IOError(errno.EPERM, "Readonly medium") ira = self.pool.get('ir.attachment').browse(cr, uid, file_node.file_id, context=context) if boo.type == 'filestore': if not ira.store_fname: # On a migrated db, some files may have the wrong storage type # try to fix their directory. if mode in ('r','r+'): if ira.file_size: self._doclog.warning( "ir.attachment #%d does not have a filename, but is at filestore, fix it!" % ira.id) raise IOError(errno.ENOENT, 'No file can be located') else: store_fname = self.__get_random_fname(boo.path) cr.execute('UPDATE ir_attachment SET store_fname = %s WHERE id = %s', (store_fname, ira.id)) fpath = os.path.join(boo.path, store_fname) else: fpath = os.path.join(boo.path, ira.store_fname) return nodefd_file(file_node, path=fpath, mode=mode)
elif mode[1] in ('w', 'a') and not ira.store_fname:
elif mode[0] in ('w', 'a') and not ira.store_fname:
def get_file(self, cr, uid, id, file_node, mode, context=None): """ Return a file-like object for the contents of some node """ if context is None: context = {} boo = self.browse(cr, uid, id, context) if not boo.online: raise IOError(errno.EREMOTE, 'medium offline') if boo.readonly and mode not in ('r', 'rb'): raise IOError(errno.EPERM, "Readonly medium") ira = self.pool.get('ir.attachment').browse(cr, uid, file_node.file_id, context=context) if boo.type == 'filestore': if not ira.store_fname: # On a migrated db, some files may have the wrong storage type # try to fix their directory. if mode in ('r','r+'): if ira.file_size: self._doclog.warning( "ir.attachment #%d does not have a filename, but is at filestore, fix it!" % ira.id) raise IOError(errno.ENOENT, 'No file can be located') else: store_fname = self.__get_random_fname(boo.path) cr.execute('UPDATE ir_attachment SET store_fname = %s WHERE id = %s', (store_fname, ira.id)) fpath = os.path.join(boo.path, store_fname) else: fpath = os.path.join(boo.path, ira.store_fname) return nodefd_file(file_node, path=fpath, mode=mode)
raise NotImplementedError("Cannot move in realstore, yet") fname = fil_bo.store_fname
ira = self.pool.get('ir.attachment').browse(cr, uid, file_node.file_id, context=context) path, opath = self.__prepare_realpath(cr, file_node, ira, sbro.path, do_create=False) fname = ira.store_fname
def simple_move(self, cr, uid, file_node, ndir_bro, context=None): """ A preparation for a file move. It will not affect the database, but merely check and perhaps move the realstore file. @param ndir_bro a browse object of document.directory, where this file should move to. @return the dict of values that can safely be be stored in the db. """ sbro = self.browse(cr, uid, file_node.storage_id, context=context) assert sbro, "The file #%d didn't provide storage" % file_node.file_id
return ValueError("Tried to rename a non-stored file") path = sbro.path oldpath = os.path.join(path, fname) for ch in ('*', '|', "\\", '/', ':', '"', '<', '>', '?', '..'): if ch in new_name: raise ValueError("Invalid char %s in name %s" %(ch, new_name)) file_node.fix_ppath(cr, ira) npath = file_node.full_path() or [] dpath = [path,] dpath.extend(npath[:-1]) dpath.append(new_name) newpath = os.path.join(*dpath) os.rename(oldpath, newpath) return { 'name': new_name, 'datas_fname': new_name, 'store_fname': new_name }
self._doclog.warning("Trying to rename a non-stored file") if fname != os.path.join(*opath): self._doclog.warning("inconsistency in realstore: %s != %s" , fname, repr(opath)) oldpath = os.path.join(path, opath[-1]) npath = [sbro.path,] + (ndir_bro.get_full_path() or []) npath = filter(lambda x: x is not None, npath) newdir = os.path.join(*npath) if not os.path.isdir(newdir): self._doclog.debug("Must create dir %s", newdir) os.makedirs(newdir) npath.append(opath[-1]) newpath = os.path.join(*npath) self._doclog.debug("Going to move %s from %s to %s", opath[-1], oldpath, newpath) shutil.move(oldpath, newpath) store_path = npath[1:] + [opath[-1],] store_fname = os.path.join(*store_path) return { 'store_fname': store_fname }
def simple_move(self, cr, uid, file_node, ndir_bro, context=None): """ A preparation for a file move. It will not affect the database, but merely check and perhaps move the realstore file. @param ndir_bro a browse object of document.directory, where this file should move to. @return the dict of values that can safely be be stored in the db. """ sbro = self.browse(cr, uid, file_node.storage_id, context=context) assert sbro, "The file #%d didn't provide storage" % file_node.file_id
ldt = dt
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
proj_exist_id = self.pool.get('project.project').search(cr, uid, [('name','=',proj_name)], context=context)
proj_exist_id = project_obj.search(cr, uid, [('name','=',proj_name)], context=context)
def action_produce_assign_service(self, cr, uid, ids, context={}): for procurement in self.browse(cr, uid, ids): sline = self.pool.get('sale.order.line') content = '' sale_order = self.pool.get('sale.order') so_ref = procurement.name.split(':')[0] order_ids = sale_order.search(cr, uid, [('name','=',so_ref)], context)
project_id = self.pool.get('project.project').create(cr, uid, {'name':proj_name,'category_id':analytic_account_id, 'partner_id':partner_id})
project_id = project_obj.create(cr, uid, {'name':proj_name, 'partner_id':partner_id})
def action_produce_assign_service(self, cr, uid, ids, context={}): for procurement in self.browse(cr, uid, ids): sline = self.pool.get('sale.order.line') content = '' sale_order = self.pool.get('sale.order') so_ref = procurement.name.split(':')[0] order_ids = sale_order.search(cr, uid, [('name','=',so_ref)], context)
'account_id': vals['analytic_account_id'],
'account_id': 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
'amount': vals['debit'] or vals['credit'],
'amount': vals.get('debit', False) or vals.get('credit', False) or 0.0,
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
raise osv.except_osv(_('Warning !'), _('There is no stage for won oppportunities defined for this Sale Team.'))
raise osv.except_osv(_('Warning !'), _('There is no stage for won opportunities defined for this Sale Team.'))
def case_close(self, cr, uid, ids, *args): """Overrides close for crm_case for setting probability and close date @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 case Ids @param *args: Tuple Value for additional Params """ res = super(crm_opportunity, self).case_close(cr, uid, ids, args) stage_id = super(crm_opportunity, self).stage_next(cr, uid, ids, context={'force_domain': [('probability', '=', 100)]}) if not stage_id: raise osv.except_osv(_('Warning !'), _('There is no stage for won oppportunities defined for this Sale Team.')) value = self.onchange_stage_id(cr, uid, ids, stage_id, context={})['value'] value.update({'date_closed': time.strftime('%Y-%m-%d %H:%M:%S'), 'stage_id': stage_id})
raise osv.except_osv(_('Warning !'), _('There is no stage for lost oppportunities defined for this Sale Team.'))
raise osv.except_osv(_('Warning !'), _('There is no stage for lost opportunities defined for this Sale Team.'))
def case_mark_lost(self, cr, uid, ids, *args): """Mark the case as lost: state = done and probability = 0% @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 case Ids @param *args: Tuple Value for additional Params """ res = super(crm_opportunity, self).case_close(cr, uid, ids, args) stage_id = super(crm_opportunity, self).stage_next(cr, uid, ids, context={'force_domain': [('probability', '=', 0)]}) if not stage_id: raise osv.except_osv(_('Warning !'), _('There is no stage for lost oppportunities defined for this Sale Team.')) value = self.onchange_stage_id(cr, uid, ids, stage_id, context={})['value'] value.update({'date_closed': time.strftime('%Y-%m-%d %H:%M:%S'), 'stage_id': stage_id})
vals['date_end'] = work_times[-1][1].strftime('%Y-%m-%d %H:%M:%S')
if work_times: vals['date_end'] = work_times[-1][1].strftime('%Y-%m-%d %H:%M:%S')
def write(self, cr, uid, ids, vals, context={}): resource_calendar_obj = self.pool.get('resource.calendar') resource_obj = self.pool.get('resource.resource') uom_obj = self.pool.get('product.uom') if not context: context = {} if context.get('scheduler',False): return super(project_phase, self).write(cr, uid, ids, vals, context=context) # Consider calendar and efficiency if the phase is performed by a resource # otherwise consider the project's working calendar phase = self.browse(cr, uid, ids[0], context=context) calendar_id = phase.project_id.resource_calendar_id and phase.project_id.resource_calendar_id.id or False resource_id = resource_obj.search(cr, uid, [('user_id', '=', phase.responsible_id.id)],context=context) if resource_id: cal_id = resource_obj.browse(cr, uid, resource_id[0], context=context).calendar_id.id if cal_id: calendar_id = cal_id default_uom_id = uom_obj.search(cr, uid, [('name', '=', 'Hour')])[0] avg_hours = uom_obj._compute_qty(cr, uid, phase.product_uom.id, phase.duration, default_uom_id)
vals['date_start'] = work_times[0][0].strftime('%Y-%m-%d %H:%M:%S')
if work_times: vals['date_start'] = work_times[0][0].strftime('%Y-%m-%d %H:%M:%S')
def write(self, cr, uid, ids, vals, context={}): resource_calendar_obj = self.pool.get('resource.calendar') resource_obj = self.pool.get('resource.resource') uom_obj = self.pool.get('product.uom') if not context: context = {} if context.get('scheduler',False): return super(project_phase, self).write(cr, uid, ids, vals, context=context) # Consider calendar and efficiency if the phase is performed by a resource # otherwise consider the project's working calendar phase = self.browse(cr, uid, ids[0], context=context) calendar_id = phase.project_id.resource_calendar_id and phase.project_id.resource_calendar_id.id or False resource_id = resource_obj.search(cr, uid, [('user_id', '=', phase.responsible_id.id)],context=context) if resource_id: cal_id = resource_obj.browse(cr, uid, resource_id[0], context=context).calendar_id.id if cal_id: calendar_id = cal_id default_uom_id = uom_obj.search(cr, uid, [('name', '=', 'Hour')])[0] avg_hours = uom_obj._compute_qty(cr, uid, phase.product_uom.id, phase.duration, default_uom_id)
result['date_end'] = work_times[-1][1].strftime('%Y-%m-%d %H:%M:%S')
if work_times: result['date_end'] = work_times[-1][1].strftime('%Y-%m-%d %H:%M:%S')
def onchange_planned(self, cr, uid, ids, project, user_id=False, planned=0.0, effective=0.0, date_start=None, occupation_rate=0.0): result = {} resource = False resource_obj = self.pool.get('resource.resource') project_pool = self.pool.get('project.project') resource_calendar = self.pool.get('resource.calendar') if not project: return {'value' : result} if date_start: hrs = float(planned / float(occupation_rate)) calendar_id = project_pool.browse(cr, uid, project).resource_calendar_id.id dt_start = mx.DateTime.strptime(date_start, '%Y-%m-%d %H:%M:%S') resource_id = resource_obj.search(cr, uid, [('user_id','=',user_id)]) if resource_id: resource_data = resource_obj.browse(cr, uid, resource_id)[0] resource = resource_data.id hrs = planned / (float(occupation_rate) * resource_data.time_efficiency) if resource_data.calendar_id.id: calendar_id = resource_data.calendar_id.id work_times = resource_calendar.interval_get(cr, uid, calendar_id, dt_start, hrs or 0.0, resource or False) result['date_end'] = work_times[-1][1].strftime('%Y-%m-%d %H:%M:%S') result['remaining_hours'] = planned - effective return {'value' : result}
vals['date_end'] = work_times[-1][1].strftime('%Y-%m-%d %H:%M:%S') super(task, self).write(cr, uid, ids, vals, context=context)
if work_times: vals['date_end'] = work_times[-1][1].strftime('%Y-%m-%d %H:%M:%S')
def write(self, cr, uid, ids, vals, context={}): resource_calendar_obj = self.pool.get('resource.calendar') resource_obj = self.pool.get('resource.resource') if not context: context = {} if context.get('scheduler',False): return super(task, self).write(cr, uid, ids, vals, context=context)
vals['date_start'] = work_times[0][0].strftime('%Y-%m-%d %H:%M:%S') super(task, self).write(cr, uid, ids, vals, context=context)
if work_times: vals['date_start'] = work_times[0][0].strftime('%Y-%m-%d %H:%M:%S')
def write(self, cr, uid, ids, vals, context={}): resource_calendar_obj = self.pool.get('resource.calendar') resource_obj = self.pool.get('resource.resource') if not context: context = {} if context.get('scheduler',False): return super(task, self).write(cr, uid, ids, vals, context=context)
'ref': fields.related('move_id', 'ref', type='char', size=64),
'ref': fields.related('move_id', 'ref', type='char', size=64, store=True),
def _get_move_lines(self, cr, uid, ids, context={}): 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
'charts':fields.selection(_get_charts, 'Chart of Accounts', readonly=True),
'charts':fields.selection(_get_charts, 'Chart of Accounts'),
def _if_account(self, cr, uid, ids, context=None): chart = self.read(cr, uid, ids, ['charts'], context=context)[0]['charts'] self.logger.notifyChannel( 'installer', netsvc.LOG_DEBUG, 'Addon "account" selected, installing chart of accounts %s'%chart) return [chart]
raise osv.except_osv(_('Invalid action !'), _('Cannot delete Purchase Order(s) which are in %s State!' % s['state']))
state_dict = {'wait':'Waiting','confirmed':'Confirmed','approved':'Approved','except_picking': 'Shipping Exception','except_invoice': 'Invoice Exception','done': 'Done'} raise osv.except_osv(_('Invalid action !'), _('Cannot delete Purchase Order(s) which are in %s State!') %_(eval(s['state'],state_dict)))
def unlink(self, cr, uid, ids, context=None): purchase_orders = self.read(cr, uid, ids, ['state']) unlink_ids = [] for s in purchase_orders: if s['state'] in ['draft','cancel']: unlink_ids.append(s['id']) else: raise osv.except_osv(_('Invalid action !'), _('Cannot delete Purchase Order(s) which are in %s State!' % s['state']))
self.rpc(self.model, 'history', [id], 'Send', True, self._decode_header(msg['From']), body['body'])
self.rpc(self.model, 'history', [id], 'Send', True, self._decode_header(msg['To']), body['body'], self._decode_header(msg['From']), False, {'model' : self.model})
def msg_user(self, msg, id): body = self.msg_body_get(msg)
self.rpc(self.model, 'history', [id], 'Send', True, self._decode_header(msg['From']), message['body'])
self.rpc(self.model, 'history', [id], 'Send', True, self._decode_header(msg['To']), message['body'], self._decode_header(msg['From']), False, {'model' : self.model})
def msg_partner(self, msg, id): message = self.msg_body_get(msg) body = message['body'] act = 'case_open' self.rpc(self.model, act, [id]) #body2 = '\n'.join(map(lambda l: '> '+l, (body or '').split('\n'))) #data = { # 'description':body, #} #self.rpc(self.model, 'write', [id], data) attachments = message['attachment'] for attach in attachments or []: data_attach = { 'name': str(attach), 'datas': binascii.b2a_base64(str(attachments[attach])), 'datas_fname': str(attach), 'description': 'Mail attachment', 'res_model': self.model, 'res_id': id } self.rpc('ir.attachment', 'create', data_attach) self.rpc(self.model, 'history', [id], 'Send', True, self._decode_header(msg['From']), message['body']) return id
if not line.location_src_id: self.write(cr, uid, procurement.id, {'message': _('No source location defined to generate the picking !')})
def check_move(self, cr, uid, ids, context=None): for procurement in self.browse(cr, uid, ids): for line in procurement.product_id.flow_pull_ids: if line.location_id==procurement.location_id: if not line.location_src_id: self.write(cr, uid, procurement.id, {'message': _('No source location defined to generate the picking !')}) return (line.type_proc=='move') and (line.location_src_id) return False
def onchange_product_id(self, cr, uid, ids, prod_id=False, loc_id=False, loc_dest_id=False):
def onchange_product_id(self, cr, uid, ids, prod_id=False, loc_id=False, loc_dest_id=False, address_id=False):
def onchange_product_id(self, cr, uid, ids, prod_id=False, loc_id=False, loc_dest_id=False): if not prod_id: return {} product = self.pool.get('product.product').browse(cr, uid, [prod_id])[0] uos_id = product.uos_id and product.uos_id.id or False result = { 'name': product.partner_ref, 'product_uom': product.uom_id.id, 'product_uos': uos_id, 'product_qty': 1.00, 'product_uos_qty' : self.pool.get('stock.move').onchange_quantity(cr, uid, ids, prod_id, 1.00, product.uom_id.id, uos_id)['value']['product_uos_qty'] }
product = self.pool.get('product.product').browse(cr, uid, [prod_id])[0]
lang = False if address_id: addr_rec = self.pool.get('res.partner.address').browse(cr, uid, address_id) if addr_rec: lang = addr_rec.partner_id and addr_rec.partner_id.lang or False ctx = {'lang': lang} product = self.pool.get('product.product').browse(cr, uid, [prod_id], context=ctx)[0]
def onchange_product_id(self, cr, uid, ids, prod_id=False, loc_id=False, loc_dest_id=False): if not prod_id: return {} product = self.pool.get('product.product').browse(cr, uid, [prod_id])[0] uos_id = product.uos_id and product.uos_id.id or False result = { 'name': product.partner_ref, 'product_uom': product.uom_id.id, 'product_uos': uos_id, 'product_qty': 1.00, 'product_uos_qty' : self.pool.get('stock.move').onchange_quantity(cr, uid, ids, prod_id, 1.00, product.uom_id.id, uos_id)['value']['product_uos_qty'] }
message = email.message_from_string(str(msg)) subject = "[%s] %s" %(res_id, self._decode_header(message['Subject']))
message = email.message_from_string(tools.ustr(msg).encode('utf-8')) subject = "[%s] %s" %(res_id, message['Subject'])
def email_send(self, cr, uid, model, res_id, msg, from_email=False, email_default=False): """This function Sends return email on submission of Fetched email in OpenERP database @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 model: OpenObject Model @param res_id: Id of the record of OpenObject model created from the Email details @param msg: Email details @param email_default: Default Email address in case of any Problem """ history_pool = self.pool.get('mailgate.message') model_pool = self.pool.get(model) from_email = from_email or tools.config.get('email_from', None) message = email.message_from_string(str(msg)) subject = "[%s] %s" %(res_id, self._decode_header(message['Subject'])) #msg_mails = [] #mails = [self._decode_header(message['From']), self._decode_header(message['To'])] #mails += self._decode_header(message.get('Cc', '')).split(',')
""") %(self._decode_header(message['From']), res_id, message['body'])
""") %(message['From'], res_id, message['body'])
def email_send(self, cr, uid, model, res_id, msg, from_email=False, email_default=False): """This function Sends return email on submission of Fetched email in OpenERP database @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 model: OpenObject Model @param res_id: Id of the record of OpenObject model created from the Email details @param msg: Email details @param email_default: Default Email address in case of any Problem """ history_pool = self.pool.get('mailgate.message') model_pool = self.pool.get(model) from_email = from_email or tools.config.get('email_from', None) message = email.message_from_string(str(msg)) subject = "[%s] %s" %(res_id, self._decode_header(message['Subject'])) #msg_mails = [] #mails = [self._decode_header(message['From']), self._decode_header(message['To'])] #mails += self._decode_header(message.get('Cc', '')).split(',')
temp_msg = '[%s] %s'%(res_id, self._decode_header(message['Subject']))
temp_msg = '[%s] %s'%(res_id, message['Subject'])
def email_send(self, cr, uid, model, res_id, msg, from_email=False, email_default=False): """This function Sends return email on submission of Fetched email in OpenERP database @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 model: OpenObject Model @param res_id: Id of the record of OpenObject model created from the Email details @param msg: Email details @param email_default: Default Email address in case of any Problem """ history_pool = self.pool.get('mailgate.message') model_pool = self.pool.get(model) from_email = from_email or tools.config.get('email_from', None) message = email.message_from_string(str(msg)) subject = "[%s] %s" %(res_id, self._decode_header(message['Subject'])) #msg_mails = [] #mails = [self._decode_header(message['From']), self._decode_header(message['To'])] #mails += self._decode_header(message.get('Cc', '')).split(',')
'file_type': fields.char('Content Type', size=32),
'file_type': fields.char('Content Type', size=64),
def _data_set(self, cr, uid, id, name, value, arg, context): if not value: return True fbro = self.browse(cr, uid, id, context=context) nctx = nodes.get_node_context(cr, uid, context) fnode = nodes.node_file(None, None, nctx, fbro) res = fnode.set_data(cr, base64.decodestring(value), fbro) return res
from tools import yaml_tag
def doc_createXElement(xdoc, tagName): e = xElement(tagName) e.ownerDocument = xdoc return e
fname = model_pool._columns[key]._fields_id
model_pool._columns[key]._fields_id
def _create_record(self, cr, uid, doc, model, data, record_id, noupdate=False): data_pool = self.pool.get('ir.model.data') model_pool = self.pool.get(model) record = doc.createElement('record') record.setAttribute("id", record_id) record.setAttribute("model", model) record_list = [record] lids = data_pool.search(cr, uid, [('model','=',model)]) res = data_pool.read(cr, uid, lids[:1], ['module']) if res: self.depends[res[0]['module']]=True fields = model_pool.fields_get(cr, uid) for key,val in data.items(): if not (val or (fields[key]['type']=='boolean')): continue if fields[key]['type'] in ('integer','float'): field = doc.createElement('field') field.setAttribute("name", key) field.setAttribute("eval", val and str(val) or 'False' ) record.appendChild(field) elif fields[key]['type'] in ('boolean',): field = doc.createElement('field') field.setAttribute("name", key) field.setAttribute("eval", val and '1' or '0' ) record.appendChild(field) elif fields[key]['type'] in ('many2one',): field = doc.createElement('field') field.setAttribute("name", key) if type(val) in (type(''),type(u'')): id = val else: id,update = self._get_id(cr, uid, fields[key]['relation'], val) noupdate = noupdate or update if not id: relation_pool = self.pool.get(fields[key]['relation']) field.setAttribute("model", fields[key]['relation']) fld_nm = relation_pool._rec_name name = relation_pool.read(cr, uid, val,[fld_nm])[fld_nm] or False field.setAttribute("search", str([(str(fld_nm) ,'=', name)])) else: field.setAttribute("ref", id) record.appendChild(field) elif fields[key]['type'] in ('one2many',): for valitem in (val or []): if valitem[0] in (0,1): if key in model_pool._columns: fname = model_pool._columns[key]._fields_id else: fname = model_pool._inherit_fields[key][2]._fields_id if valitem[0] == 0: newid = self._create_id(cr, uid, fields[key]['relation'], valitem[2]) valitem[1]=newid else: newid,update = self._get_id(cr, uid, fields[key]['relation'], valitem[1]) if not newid: newid = self._create_id(cr, uid, fields[key]['relation'], valitem[2]) valitem[1]=newid self.ids[(fields[key]['relation'], valitem[1])] = newid childrecord, update = self._create_record(cr, uid, doc, fields[key]['relation'],valitem[2], newid) noupdate = noupdate or update record_list += childrecord else: pass elif fields[key]['type'] in ('many2many',): res = [] for valitem in (val or []): if valitem[0]==6: for id2 in valitem[2]: id,update = self._get_id(cr, uid, fields[key]['relation'], id2) self.ids[(fields[key]['relation'],id2)] = id noupdate = noupdate or update res.append(id) field = doc.createElement('field') field.setAttribute("name", key) field.setAttribute("eval", "[(6,0,["+','.join(map(lambda x: "ref('%s')" % (x,), res))+'])]') record.appendChild(field) else: field = doc_createXElement(doc, 'field') field.setAttribute("name", key) field.appendChild(doc.createTextNode(val)) record.appendChild(field)
fname = model_pool._inherit_fields[key][2]._fields_id
model_pool._inherit_fields[key][2]._fields_id
def _create_record(self, cr, uid, doc, model, data, record_id, noupdate=False): data_pool = self.pool.get('ir.model.data') model_pool = self.pool.get(model) record = doc.createElement('record') record.setAttribute("id", record_id) record.setAttribute("model", model) record_list = [record] lids = data_pool.search(cr, uid, [('model','=',model)]) res = data_pool.read(cr, uid, lids[:1], ['module']) if res: self.depends[res[0]['module']]=True fields = model_pool.fields_get(cr, uid) for key,val in data.items(): if not (val or (fields[key]['type']=='boolean')): continue if fields[key]['type'] in ('integer','float'): field = doc.createElement('field') field.setAttribute("name", key) field.setAttribute("eval", val and str(val) or 'False' ) record.appendChild(field) elif fields[key]['type'] in ('boolean',): field = doc.createElement('field') field.setAttribute("name", key) field.setAttribute("eval", val and '1' or '0' ) record.appendChild(field) elif fields[key]['type'] in ('many2one',): field = doc.createElement('field') field.setAttribute("name", key) if type(val) in (type(''),type(u'')): id = val else: id,update = self._get_id(cr, uid, fields[key]['relation'], val) noupdate = noupdate or update if not id: relation_pool = self.pool.get(fields[key]['relation']) field.setAttribute("model", fields[key]['relation']) fld_nm = relation_pool._rec_name name = relation_pool.read(cr, uid, val,[fld_nm])[fld_nm] or False field.setAttribute("search", str([(str(fld_nm) ,'=', name)])) else: field.setAttribute("ref", id) record.appendChild(field) elif fields[key]['type'] in ('one2many',): for valitem in (val or []): if valitem[0] in (0,1): if key in model_pool._columns: fname = model_pool._columns[key]._fields_id else: fname = model_pool._inherit_fields[key][2]._fields_id if valitem[0] == 0: newid = self._create_id(cr, uid, fields[key]['relation'], valitem[2]) valitem[1]=newid else: newid,update = self._get_id(cr, uid, fields[key]['relation'], valitem[1]) if not newid: newid = self._create_id(cr, uid, fields[key]['relation'], valitem[2]) valitem[1]=newid self.ids[(fields[key]['relation'], valitem[1])] = newid childrecord, update = self._create_record(cr, uid, doc, fields[key]['relation'],valitem[2], newid) noupdate = noupdate or update record_list += childrecord else: pass elif fields[key]['type'] in ('many2many',): res = [] for valitem in (val or []): if valitem[0]==6: for id2 in valitem[2]: id,update = self._get_id(cr, uid, fields[key]['relation'], id2) self.ids[(fields[key]['relation'],id2)] = id noupdate = noupdate or update res.append(id) field = doc.createElement('field') field.setAttribute("name", key) field.setAttribute("eval", "[(6,0,["+','.join(map(lambda x: "ref('%s')" % (x,), res))+'])]') record.appendChild(field) else: field = doc_createXElement(doc, 'field') field.setAttribute("name", key) field.appendChild(doc.createTextNode(val)) record.appendChild(field)
'product_id': fields.many2one('product.product', 'Product', required=True, select=True),
'product_id': fields.many2one('product.product', 'Product', required=True, select=True, domain=[('type','<>','service')]),
def _check_product_lot(self, cr, uid, ids): """ Checks whether move is done or not and production lot is assigned to that move. @return: True or False """ for move in self.browse(cr, uid, ids): if move.prodlot_id and move.state == 'done' and (move.prodlot_id.product_id.id != move.product_id.id): return False return True
tax_obj.compute(cr, uid, line.product_id.taxes_id,
tax_obj.compute_all(cr, uid, line.product_id.taxes_id,
def _amount_all(self, cr, uid, ids, name, args, context=None): tax_obj = self.pool.get('account.tax') res={} for order in self.browse(cr, uid, ids): res[order.id] = { 'amount_paid': 0.0, 'amount_return':0.0, 'amount_tax':0.0, } for payment in order.statement_ids: res[order.id]['amount_paid'] += payment.amount for payment in order.payments: res[order.id]['amount_return'] += (payment.amount < 0 and payment.amount or 0) for line in order.lines: if order.price_type!='tax_excluded': res[order.id]['amount_tax'] = reduce(lambda x, y: x+round(y['amount'], 2), tax_obj.compute_inv(cr, uid, line.product_id.taxes_id, line.price_unit * \ (1-(line.discount or 0.0)/100.0), line.qty), res[order.id]['amount_tax']) else: res[order.id]['amount_tax'] = reduce(lambda x, y: x+round(y['amount'], 2), tax_obj.compute(cr, uid, line.product_id.taxes_id, line.price_unit * \ (1-(line.discount or 0.0)/100.0), line.qty), res[order.id]['amount_tax']) return res
(1-(line.discount or 0.0)/100.0), line.qty), res[order.id]['amount_tax'])
(1-(line.discount or 0.0)/100.0), line.qty)['taxes'], res[order.id]['amount_tax'])
def _amount_all(self, cr, uid, ids, name, args, context=None): tax_obj = self.pool.get('account.tax') res={} for order in self.browse(cr, uid, ids): res[order.id] = { 'amount_paid': 0.0, 'amount_return':0.0, 'amount_tax':0.0, } for payment in order.statement_ids: res[order.id]['amount_paid'] += payment.amount for payment in order.payments: res[order.id]['amount_return'] += (payment.amount < 0 and payment.amount or 0) for line in order.lines: if order.price_type!='tax_excluded': res[order.id]['amount_tax'] = reduce(lambda x, y: x+round(y['amount'], 2), tax_obj.compute_inv(cr, uid, line.product_id.taxes_id, line.price_unit * \ (1-(line.discount or 0.0)/100.0), line.qty), res[order.id]['amount_tax']) else: res[order.id]['amount_tax'] = reduce(lambda x, y: x+round(y['amount'], 2), tax_obj.compute(cr, uid, line.product_id.taxes_id, line.price_unit * \ (1-(line.discount or 0.0)/100.0), line.qty), res[order.id]['amount_tax']) return res
computed_taxes = account_tax_obj.compute( cr, uid, taxes, line.price_unit, line.qty)
computed_taxes = account_tax_obj.compute_all( cr, uid, taxes, line.price_unit, line.qty)['taxes']
order_account = order.partner_id and order.partner_id.property_account_receivable and order.partner_id.property_account_receivable.id or account_def or curr_c.account_receivable.id
computed_taxes = account_tax_obj.compute(cr, uid, taxes, line.price_unit, line.qty)
computed_taxes = account_tax_obj.compute_all(cr, uid, taxes, line.price_unit, line.qty)['taxes']
def _amount_line_ttc(self, cr, uid, ids, field_name, arg, context): res = {} account_tax_obj = self.pool.get('account.tax') for line in self.browse(cr, uid, ids): tax_amount = 0.0 taxes = [t for t in line.product_id.taxes_id] computed_taxes = account_tax_obj.compute(cr, uid, taxes, line.price_unit, line.qty) for tax in computed_taxes: tax_amount += tax['amount'] price = self.price_by_product(cr, uid, ids, line.order_id.pricelist_id.id, line.product_id.id, line.qty, line.order_id.partner_id.id) if line.discount!=0.0: res[line.id] = line.price_unit * line.qty * (1 - (line.discount or 0.0) / 100.0) else: res[line.id]=line.price_unit*line.qty res[line.id] = res[line.id] + tax_amount return res
_order = "name"
_order = "project_id, date_start, sequence, name"
def _get_default_uom_id(self, cr, uid): model_data_obj = self.pool.get('ir.model.data') model_data_id = model_data_obj._get_id(cr, uid, 'product', 'uom_hour') return model_data_obj.read(cr, uid, [model_data_id], ['res_id'])[0]['res_id']
partner = (picking.purchase_id and picking.purchase_id.partner_id) or (picking.sale_id and picking.sale_id.partner_id) or (picking.address_id and picking.address_id.partner_id)
partner = picking.address_id and picking.address_id.partner_id
def action_invoice_create(self, cr, uid, ids, journal_id=False, group=False, type='out_invoice', context=None): """ Creates invoice based on the invoice state selected for picking. @param journal_id: Id of journal @param group: Whether to create a group invoice or not @param type: Type invoice to be created @return: Ids of created invoices for the pickings """ if context is None: context = {}