rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
mid = objid._get_id(cr, uid, 'document', 'dir_calendars') if not mid: return False root_id = objid.read(cr, uid, mid, ['res_id'])['res_id'] root_cal_dir = self.browse(cr,uid, root_id, context=context) return root_cal_dir.name
calendar_dir_id = data_pool.get_object(cr, uid, 'caldav', 'document_directory_calendars0') return calendar_dir_id.name
def _get_root_calendar_directory(self, cr, uid, context=None): objid = self.pool.get('ir.model.data') try: mid = objid._get_id(cr, uid, 'document', 'dir_calendars') if not mid: return False root_id = objid.read(cr, uid, mid, ['res_id'])['res_id'] root_cal_dir = self.browse(cr,uid, root_id, context=context) return root_cal_dir.name except Exception: logger = logging.getLogger('document') logger.warning('Cannot set root directory for Calendars:', exc_info=True) return False return False
logger = logging.getLogger('document')
logger = logging.getLogger('caldav')
def _get_root_calendar_directory(self, cr, uid, context=None): objid = self.pool.get('ir.model.data') try: mid = objid._get_id(cr, uid, 'document', 'dir_calendars') if not mid: return False root_id = objid.read(cr, uid, mid, ['res_id'])['res_id'] root_cal_dir = self.browse(cr,uid, root_id, context=context) return root_cal_dir.name except Exception: logger = logging.getLogger('document') logger.warning('Cannot set root directory for Calendars:', exc_info=True) return False return False
min(date), max(date)
min(date_expected), max(date_expected)
def get_min_max_date(self, cr, uid, ids, field_name, arg, context=None): """ Finds minimum and maximum dates for picking. @return: Dictionary of values """ res = {} for id in ids: res[id] = {'min_date': False, 'max_date': False} if not ids: return res cr.execute("""select picking_id, min(date), max(date) from stock_move where picking_id IN %s group by picking_id""",(tuple(ids),)) for pick, dt1, dt2 in cr.fetchall(): res[pick]['min_date'] = dt1 res[pick]['max_date'] = dt2 return res
phase_resource_obj = resource_pool.generate_resources(cr, uid, [phase.responsible_id.id], calendar_id, context=context)
phase_resource_obj = self.generate_resources(cr, uid, [phase.id], context=context)[phase.id]
def generate_schedule(self, cr, uid, ids, start_date=False, calendar_id=False, context=None): """ Schedule phase with the start date till all the next phases are completed. @param: start_date (datetime.datetime) : start date for the phase. It would be either Start date of phase or start date of project or system current date @param: calendar_id : working calendar of the project """ if context is None: context = {} resource_pool = self.pool.get('resource.resource') data_pool = self.pool.get('ir.model.data') resource_allocation_pool = self.pool.get('project.resource.allocation') uom_pool = self.pool.get('product.uom') data_model, day_uom_id = data_pool.get_object_reference(cr, uid, 'product', 'uom_day') for phase in self.browse(cr, uid, ids, context=context): if not phase.responsible_id: raise osv.except_osv(_('No responsible person assigned !'),_("You must assign a responsible person for phase '%s' !") % (phase.name,))
for phase in phase.next_phase_ids: if phase.state in ['draft', 'open', 'pending']: id_cal = phase.project_id.resource_calendar_id and phase.project_id.resource_calendar_id.id or False self.generate_schedule(cr, uid, [phase.id], date_start, id_cal, context=context)
for next_phase in phase.next_phase_ids: if next_phase.state in ['draft', 'open', 'pending']: id_cal = next_phase.project_id.resource_calendar_id and next_phase.project_id.resource_calendar_id.id or False self.generate_schedule(cr, uid, [next_phase.id], date_start+timedelta(days=1), id_cal, context=context)
def phase(): effort = duration
'partner_id': address.partner_id and address.partner_id.id or '',
'partner_id': address.partner_id and str(address.partner_id.id) or '',
def search_contact(self, cr, user, email): address_pool = self.pool.get('res.partner.address') address_ids = address_pool.search(cr, user, [('email','=',email)]) res = {}
if abs(amount) < 0.0001:
if abs(amount) < 10 ** -(int(config['price_accuracy'])1):
def validate(self, cr, uid, ids, context={}): if context and ('__last_update' in context): del context['__last_update'] ok = True for move in self.browse(cr, uid, ids, context): #unlink analytic lines on move_lines for obj_line in move.line_id: for obj in obj_line.analytic_lines: self.pool.get('account.analytic.line').unlink(cr,uid,obj.id)
vals['name'] = self.pool.get('ir.sequence').get(cr, user, 'stock.picking')
seq_obj_name = 'stock.picking.' + vals['type'] vals['name'] = self.pool.get('ir.sequence').get(cr, user, seq_obj_name)
def create(self, cr, user, vals, context=None): if ('name' not in vals) or (vals.get('name')=='/'): vals['name'] = self.pool.get('ir.sequence').get(cr, user, 'stock.picking') type_list = { 'out':_('Packing List'), 'in':_('Reception'), 'internal': _('Internal picking'), 'delivery': _('Delivery order') } if not vals.get('auto_picking', False): message = type_list.get(vals.get('type',_('Picking'))) + " '" + vals['name'] + "' "+ _("created.") self.log(cr, user, id, message) return super(stock_picking, self).create(cr, user, vals, context)
vals_journal = {
vals_journal.update({
def generate_configurable_chart(self, cr, uid, ids, context=None): obj_acc = self.pool.get('account.account') obj_acc_tax = self.pool.get('account.tax') obj_journal = self.pool.get('account.journal') obj_acc_tax_code = self.pool.get('account.tax.code') obj_acc_template = self.pool.get('account.account.template') obj_acc_tax_template = self.pool.get('account.tax.code.template') obj_fiscal_position_template = self.pool.get('account.fiscal.position.template') obj_fiscal_position = self.pool.get('account.fiscal.position') analytic_journal_obj = self.pool.get('account.analytic.journal') obj_acc_chart_template = self.pool.get('account.chart.template') obj_acc_journal_view = self.pool.get('account.journal.view') mod_obj = self.pool.get('ir.model.data') obj_sequence = self.pool.get('ir.sequence') property_obj = self.pool.get('ir.property') fields_obj = self.pool.get('ir.model.fields') obj_tax_fp = self.pool.get('account.fiscal.position.tax') obj_ac_fp = self.pool.get('account.fiscal.position.account')
}
})
def generate_configurable_chart(self, cr, uid, ids, context=None): obj_acc = self.pool.get('account.account') obj_acc_tax = self.pool.get('account.tax') obj_journal = self.pool.get('account.journal') obj_acc_tax_code = self.pool.get('account.tax.code') obj_acc_template = self.pool.get('account.account.template') obj_acc_tax_template = self.pool.get('account.tax.code.template') obj_fiscal_position_template = self.pool.get('account.fiscal.position.template') obj_fiscal_position = self.pool.get('account.fiscal.position') analytic_journal_obj = self.pool.get('account.analytic.journal') obj_acc_chart_template = self.pool.get('account.chart.template') obj_acc_journal_view = self.pool.get('account.journal.view') mod_obj = self.pool.get('ir.model.data') obj_sequence = self.pool.get('ir.sequence') property_obj = self.pool.get('ir.property') fields_obj = self.pool.get('ir.model.fields') obj_tax_fp = self.pool.get('account.fiscal.position.tax') obj_ac_fp = self.pool.get('account.fiscal.position.account')
datas = self.read(cr, uid, event_id, context=context)
def modify_this(self, cr, uid, event_id, defaults, real_date, context=None, *args): """Modifies only one event record out of virtual recurrent events and creates new event as a specific instance of a Recurring Event", @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 event_id: Id of Recurring Event @param real_date: Date of event recurrence that is being modified @param context: A standard dictionary for contextual values @param *args: Get Tupple Value """
'recurrent_uid': base_calendar_id2real_id(datas['id']), 'recurrent_id': defaults.get('date') or real_date,
'recurrent_uid': base_calendar_id2real_id(event_id), 'recurrent_id': real_date,
def modify_this(self, cr, uid, event_id, defaults, real_date, context=None, *args): """Modifies only one event record out of virtual recurrent events and creates new event as a specific instance of a Recurring Event", @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 event_id: Id of Recurring Event @param real_date: Date of event recurrence that is being modified @param context: A standard dictionary for contextual values @param *args: Get Tupple Value """
exdate = datas['exdate'] and datas['exdate'].split(',') or [] if real_date and defaults.get('date'): exdate.append(real_date) self.write(cr, uid, event_id, {'exdate': ','.join(exdate)}, context=context)
def modify_this(self, cr, uid, event_id, defaults, real_date, context=None, *args): """Modifies only one event record out of virtual recurrent events and creates new event as a specific instance of a Recurring Event", @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 event_id: Id of Recurring Event @param real_date: Date of event recurrence that is being modified @param context: A standard dictionary for contextual values @param *args: Get Tupple Value """
params += max_amount
params += (max_amount,)
def reconcile(self, cr, uid, ids, context=None): move_line_obj = self.pool.get('account.move.line') obj_model = self.pool.get('ir.model.data') if context is None: context = {} form = self.read(cr, uid, ids, [])[0] max_amount = form.get('max_amount', False) and form.get('max_amount') or 0.0 power = form['power'] allow_write_off = form['allow_write_off'] reconciled = unreconciled = 0 if not form['account_ids']: raise osv.except_osv(_('UserError'), _('You must select accounts to reconcile')) for account_id in form['account_ids']: params = (account_id,) if not allow_write_off: query = """SELECT partner_id FROM account_move_line WHERE account_id=%s AND reconcile_id IS NULL AND state <> 'draft' GROUP BY partner_id HAVING ABS(SUM(debit-credit)) = 0.0 AND count(*)>0""" else: query = """SELECT partner_id FROM account_move_line WHERE account_id=%s AND reconcile_id IS NULL AND state <> 'draft' GROUP BY partner_id HAVING ABS(SUM(debit-credit)) < %s AND count(*)>0""" params += max_amount # reconcile automatically all transactions from partners whose balance is 0 cr.execute(query, params) partner_ids = [id for (id,) in cr.fetchall()] for partner_id in partner_ids: cr.execute( "SELECT id " \ "FROM account_move_line " \ "WHERE account_id=%s " \ "AND partner_id=%s " \ "AND state <> 'draft' " \ "AND reconcile_id IS NULL", (account_id, partner_id)) line_ids = [id for (id,) in cr.fetchall()] if len(line_ids): reconciled += len(line_ids) if allow_write_off: move_line_obj.reconcile(cr, uid, line_ids, 'auto', form['writeoff_acc_id'], form['period_id'], form['journal_id'], context) else: move_line_obj.reconcile_partial(cr, uid, line_ids, 'manual', context={})
exists, r_id = caldav.uid2openobjectid(cr, val['id'], context.get('model'), \
exists, r_id = calendar.uid2openobjectid(cr, val['id'], context.get('model'), \
def check_import(self, cr, uid, vals, context={}): """ @param self: The object pointer @param cr: the current row, from the database cursor, @param uid: the current user’s ID for security checks, @param vals: Get Values @param context: A standard dictionary for contextual values """ ids = [] model_obj = self.pool.get(context.get('model')) recur_pool = {} try: for val in vals: exists, r_id = caldav.uid2openobjectid(cr, val['id'], context.get('model'), \ val.get('recurrent_id')) if val.has_key('create_date'): val.pop('create_date') u_id = val.get('id', None) val.pop('id') if exists and r_id: val.update({'recurrent_uid': exists}) model_obj.write(cr, uid, [r_id], val) ids.append(r_id) elif exists: # Compute value of duration if 'date_deadline' in val and 'duration' not in val: start = datetime.strptime(val['date'], '%Y-%m-%d %H:%M:%S') end = datetime.strptime(val['date_deadline'], '%Y-%m-%d %H:%M:%S') diff = end - start val['duration'] = (diff.seconds/float(86400) + diff.days) * 24 model_obj.write(cr, uid, [exists], val) ids.append(exists) else: if u_id in recur_pool and val.get('recurrent_id'): val.update({'recurrent_uid': recur_pool[u_id]}) revent_id = model_obj.create(cr, uid, val) ids.append(revent_id) else: event_id = model_obj.create(cr, uid, val) recur_pool[u_id] = event_id ids.append(event_id) except Exception, e: raise osv.except_osv(('Error !'), (str(e))) return ids
def email_send(self, cr, uid, obj, emails, body, emailfrom=tools.config.get('email_from', False), context={}):
def email_send(self, cr, uid, obj, emails, body, emailfrom=None, context=None):
def email_send(self, cr, uid, obj, emails, body, emailfrom=tools.config.get('email_from', False), context={}): """ send email @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 email: pass the emails @param emailfrom: Pass name the email From else False @param context: A standard dictionary for contextual values """ body = self.format_mail(obj, body) if not emailfrom: if hasattr(obj, 'user_id') and obj.user_id and obj.user_id.address_id and\ obj.user_id.address_id.email: emailfrom = obj.user_id.address_id.email
self.email_send(cr, uid, obj, emails, action.act_mail_body)
email_from = eval(action.act_email_from, { 'user' : self.pool.get('res.users').browse(cr, uid, uid, context=context), 'obj' : obj, }) self.email_send(cr, uid, obj, emails, action.act_mail_body, emailfrom=email_from)
def do_action(self, cr, uid, action, model_obj, obj, context={}): """ Do Action @param self: The object pointer @param cr: the current row, from the database cursor, @param uid: the current user’s ID for security checks, @param action: pass action @param model_obj: pass Model object @param context: A standard dictionary for contextual values """
res = obj.create(cr, uid, data, context)
obj.create(cr, uid, data, context)
def _history(self, cr, uid, cases, keyword, history=False, subject=None, email=False, details=None, \ email_from=False, message_id=False, references=None, attach=None, context=None): """ @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 cases: a browse record list @param keyword: Case action keyword e.g.: If case is closed "Close" keyword is used @param history: Value True/False, If True it makes entry in case History otherwise in Case Log @param email: Email address if any @param details: Details of case history if any @param atach: Attachment sent in email @param context: A standard dictionary for contextual values""" if context is None: context = {} if attach is None: attach = []
'name':fields.char('Subject', size=128), 'model': fields.char('Object Name', size=128), 'res_id': fields.integer('Resource ID'),
'name':fields.char('Subject', size=128), 'model': fields.char('Object Name', size=128, select=1), 'res_id': fields.integer('Resource ID', select=1),
def _history(self, cr, uid, cases, keyword, history=False, subject=None, email=False, details=None, \ email_from=False, message_id=False, references=None, attach=None, context=None): """ @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 cases: a browse record list @param keyword: Case action keyword e.g.: If case is closed "Close" keyword is used @param history: Value True/False, If True it makes entry in case History otherwise in Case Log @param email: Email address if any @param details: Details of case history if any @param atach: Attachment sent in email @param context: A standard dictionary for contextual values""" if context is None: context = {} if attach is None: attach = []
msg_id = msg_pool.create(cr, uid, msg_data, context=context)
msg_pool.create(cr, uid, msg_data, context=context)
def history(self, cr, uid, model, res_ids, msg, attach, context=None): """This function creates history for mails fetched @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_ids: Ids of the record of OpenObject model created @param msg: Email details @param attach: Email attachments """ if isinstance(res_ids, (int, long)): res_ids = [res_ids]
return res_id
return res_id, 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)
counter = 1
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)
elif part.get_content_maintype()=='application' or part.get_content_maintype()=='image' or part.get_content_maintype()=='text':
elif part.get_content_maintype() in ('application', 'image', 'text'):
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)
new_res_id = create_record(msg)
new_res_id, attachment_ids = create_record(msg)
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)
attach = msg.get('attachments', {}).items(),
attach = attachments.items(),
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)
self.history(cr, uid, model, res_ids, msg, att_ids, context=context)
self.history(cr, uid, model, res_ids, msg, attachment_ids, context=context)
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)
bom_parent = bom_obj.browse(cr, uid, context['active_id'])
bom_id = context and context.get('active_id', False) or False cr.execute('select id from mrp_bom') if all(bom_id != r[0] for r in cr.fetchall()): ids.sort() bom_id = ids[0] bom_parent = bom_obj.browse(cr, uid, bom_id)
def _child_compute(self, cr, uid, ids, name, arg, context={}): """ Gets child bom. @param self: The object pointer @param cr: The current row, from the database cursor, @param uid: The current user ID for security checks @param ids: List of selected IDs @param name: Name of the field @param arg: User defined argument @param context: A standard dictionary for contextual values @return: Dictionary of values """ result = {} bom_obj = self.pool.get('mrp.bom') bom_parent = bom_obj.browse(cr, uid, context['active_id']) for bom in self.browse(cr, uid, ids, context=context): if bom_parent.multi_level_bom or bom.id == context['active_id']: result[bom.id] = map(lambda x: x.id, bom.bom_lines) else: result[bom.id] = [] if bom.bom_lines: continue ok = ((name=='child_complete_ids') and (bom.product_id.supply_method=='produce')) if (bom.type=='phantom' or ok) and bom_parent.multi_level_bom: sids = bom_obj.search(cr, uid, [('bom_id','=',False),('product_id','=',bom.product_id.id)]) if sids: bom2 = bom_obj.browse(cr, uid, sids[0], context=context) result[bom.id] += map(lambda x: x.id, bom2.bom_lines)
if bom_parent.multi_level_bom or bom.id == context['active_id']:
if (bom_parent and bom_parent.multi_level_bom) or bom.id == bom_id:
def _child_compute(self, cr, uid, ids, name, arg, context={}): """ Gets child bom. @param self: The object pointer @param cr: The current row, from the database cursor, @param uid: The current user ID for security checks @param ids: List of selected IDs @param name: Name of the field @param arg: User defined argument @param context: A standard dictionary for contextual values @return: Dictionary of values """ result = {} bom_obj = self.pool.get('mrp.bom') bom_parent = bom_obj.browse(cr, uid, context['active_id']) for bom in self.browse(cr, uid, ids, context=context): if bom_parent.multi_level_bom or bom.id == context['active_id']: result[bom.id] = map(lambda x: x.id, bom.bom_lines) else: result[bom.id] = [] if bom.bom_lines: continue ok = ((name=='child_complete_ids') and (bom.product_id.supply_method=='produce')) if (bom.type=='phantom' or ok) and bom_parent.multi_level_bom: sids = bom_obj.search(cr, uid, [('bom_id','=',False),('product_id','=',bom.product_id.id)]) if sids: bom2 = bom_obj.browse(cr, uid, sids[0], context=context) result[bom.id] += map(lambda x: x.id, bom2.bom_lines)
where active")
WHERE active")
def pre_action(self, cr, uid, ids, model, context=None): # Searching for action rules cr.execute("SELECT model.model, rule.id FROM base_action_rule rule \ LEFT JOIN ir_model model on (model.id = rule.model_id) \ where active") res = cr.fetchall() # Check if any rule matching with current object for obj_name, rule_id in res: if not (model == obj_name): continue else: obj = self.pool.get(obj_name) self._action(cr, uid, [rule_id], obj.browse(cr, uid, ids, context=context), context=context) return True
'company_id': fields.many2one('res.company', 'Company', select=True, required=True),
'company_id': fields.many2one('res.company', 'Company', select=True, required=False),
def _dept_name_get_fnc(self, cr, uid, ids, prop, unknow_none, context): res = self.name_get(cr, uid, ids, context) return dict(res)
avg(100.0 * (l.price_unit*l.product_qty*u.factor) / (t.standard_price*l.product_qty*u.factor))::decimal(16,2) as negociation,
avg(case when t.standard_price <= 0 then (100.0 * (l.price_unit*l.product_qty*u.factor)) else (100.0 * (l.price_unit*l.product_qty*u.factor) / (t.standard_price*l.product_qty*u.factor)) end) as negociation,
def init(self, cr): tools.sql.drop_view_if_exists(cr, 'purchase_report') cr.execute(""" create or replace view purchase_report as ( select min(l.id) as id, s.date_order as date, to_char(s.date_order, 'YYYY') as name, to_char(s.date_order, 'MM') as month, to_char(s.date_order, 'YYYY-MM-DD') as day, s.state, s.date_approve, date_trunc('day',s.minimum_planned_date) as expected_date, s.partner_address_id, s.dest_address_id, s.pricelist_id, s.validator, s.warehouse_id as warehouse_id, s.partner_id as partner_id, s.create_uid as user_id, s.company_id as company_id, l.product_id, t.categ_id as category_id, l.product_uom as product_uom, s.location_id as location_id, sum(l.product_qty*u.factor) as quantity, extract(epoch from age(s.date_approve,s.date_order))/(24*60*60)::decimal(16,2) as delay, extract(epoch from age(l.date_planned,s.date_order))/(24*60*60)::decimal(16,2) as delay_pass, count(*) as nbr, (l.price_unit*l.product_qty*u.factor)::decimal(16,2) as price_total, avg(100.0 * (l.price_unit*l.product_qty*u.factor) / (t.standard_price*l.product_qty*u.factor))::decimal(16,2) as negociation, sum(t.standard_price*l.product_qty*u.factor)::decimal(16,2) as price_standard, (sum(l.product_qty*l.price_unit)/sum(l.product_qty*u.factor))::decimal(16,2) as price_average from purchase_order s left join purchase_order_line l on (s.id=l.order_id) left join product_product p on (l.product_id=p.id) left join product_template t on (p.product_tmpl_id=t.id) left join product_uom u on (u.id=l.product_uom) where l.product_id is not null group by s.company_id, s.create_uid, s.partner_id, l.product_qty, u.factor, s.location_id, l.price_unit, s.date_approve, l.date_planned, l.product_uom, date_trunc('day',s.minimum_planned_date), s.partner_address_id, s.pricelist_id, s.validator, s.dest_address_id, l.product_id, t.categ_id, s.date_order, to_char(s.date_order, 'YYYY'), to_char(s.date_order, 'MM'), to_char(s.date_order, 'YYYY-MM-DD'), s.state, s.warehouse_id ) """)
'phase_ids': fields.one2many('project.phase', 'project_id', "Project Phases")
'phase_ids': fields.one2many('project.phase', 'project_id', "Project Phases"), 'resource_calendar_id': fields.many2one('resource.calendar', 'Working Time', help="Timetable working hours to adjust the gantt diagram report"),
def phase_done(self, cr, uid, ids,*args): self.write(cr, uid, ids, {'state': 'done'}) return True
if company_currency_id==st_line.account_id.currency_id.id: amount_cur = st_line.amount else: amount_cur = res_currency_obj.compute(cr, uid, company_currency_id, st_line.account_id.currency_id.id, amount, context=context, account=acc_cur) val['amount_currency'] = amount_cur
amount_cur = res_currency_obj.compute(cr, uid, company_currency_id, st_line.account_id.currency_id.id, amount, context=context, account=acc_cur) val['amount_currency'] = -amount_cur
def create_move_from_st_line(self, cr, uid, st_line_id, company_currency_id, st_line_number, context=None): res_currency_obj = self.pool.get('res.currency') 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') st_line = account_bank_statement_line_obj.browse(cr, uid, st_line_id, context) st = st_line.statement_id
data['amount'] = cur_price_unit - reduce(lambda x,y: y.get('amount',0.0)+x, res, 0.0) data['balance'] = cur_price_unit
amount = cur_price_unit - reduce(lambda x,y: y.get('amount',0.0)+x, res, 0.0)
def _unit_compute_inv(self, cr, uid, taxes, price_unit, address_id=None, product=None, partner=None): taxes = self._applicable(cr, uid, taxes, price_unit, address_id, product, partner)
print "RULE: %s" % (rule,) print " %s" % (rule.last_run,)
def _check(self, cr, uid, automatic=False, use_new_cursor=False, \ context=None): """ This Function is call by scheduler. """ rule_pool = self.pool.get('base.action.rule') rule_ids = rule_pool.search(cr, uid, [], context=context) self._register_hook(cr, uid, rule_ids, context=context)
print " OBJ: %s" % (obj_id,)
def _check(self, cr, uid, automatic=False, use_new_cursor=False, \ context=None): """ This Function is call by scheduler. """ rule_pool = self.pool.get('base.action.rule') rule_ids = rule_pool.search(cr, uid, [], context=context) self._register_hook(cr, uid, rule_ids, context=context)
print " D: %s" % (d,)
def _check(self, cr, uid, automatic=False, use_new_cursor=False, \ context=None): """ This Function is call by scheduler. """ rule_pool = self.pool.get('base.action.rule') rule_ids = rule_pool.search(cr, uid, [], context=context) self._register_hook(cr, uid, rule_ids, context=context)
print " RUNNING"
def _check(self, cr, uid, automatic=False, use_new_cursor=False, \ context=None): """ This Function is call by scheduler. """ rule_pool = self.pool.get('base.action.rule') rule_ids = rule_pool.search(cr, uid, [], context=context) self._register_hook(cr, uid, rule_ids, context=context)
date_formatted = strptime(date_to_format,'%Y-%m-%d').strftime('%d.%m.%Y')
date_formatted = time.strptime(date_to_format,'%Y-%m-%d').strftime('%d.%m.%Y')
def _get_and_change_date_format_for_swiss (self,date_to_format): date_formatted='' print date_to_format if date_to_format: date_formatted = strptime(date_to_format,'%Y-%m-%d').strftime('%d.%m.%Y') return date_formatted
if not partner.ean13: continue if len(partner.ean13) not in [13,14,8]: return False try: int(partner.ean13) except: return False oddsum=0 evensum=0 total=0 eanvalue=partner.ean13 reversevalue = eanvalue[::-1] finalean=reversevalue[1:] for i in range(len(finalean)): if is_pair(i): oddsum += int(finalean[i]) else: evensum += int(finalean[i]) total=(oddsum * 3) + evensum check = int(10 - math.ceil(total % 10.0)) if check != int(partner.ean13[-1]): return False return True
res = check_ean(partner.ean13) return res
def _check_ean_key(self, cr, uid, ids): for partner in self.browse(cr, uid, ids): if not partner.ean13: continue if len(partner.ean13) not in [13,14,8]: return False try: int(partner.ean13) except: return False oddsum=0 evensum=0 total=0 eanvalue=partner.ean13 reversevalue = eanvalue[::-1] finalean=reversevalue[1:]
emp_ids = obj_emp.search(cr, uid, [('category_id', '=', record.category_id.id)])
emp_ids = obj_emp.search(cr, uid, [('category_ids', '=', record.category_id.id)])
def holidays_validate(self, cr, uid, ids, *args): obj_emp = self.pool.get('hr.employee') data_holiday = self.browse(cr, uid, ids) self.check_holidays(cr, uid, ids) vals = {'state':'validate'} ids2 = obj_emp.search(cr, uid, [('user_id', '=', uid)]) if ids2: if data_holiday[0].state == 'validate1': vals['manager_id2'] = ids2[0] else: vals['manager_id'] = ids2[0] else: raise osv.except_osv(_('Warning !'), _('No user related to the selected employee.')) self.write(cr, uid, ids, vals) for record in data_holiday: if record.holiday_type == 'employee' and record.type == 'remove': vals = { 'name': record.name, 'date_from': record.date_from, 'date_to': record.date_to, 'calendar_id': record.employee_id.calendar_id.id, 'company_id': record.employee_id.company_id.id, 'resource_id': record.employee_id.resource_id.id, 'holiday_id': record.id } self._create_resource_leave(cr, uid, vals) elif record.holiday_type == 'category' and record.type == 'remove': emp_ids = obj_emp.search(cr, uid, [('category_id', '=', record.category_id.id)]) for emp in obj_emp.browse(cr, uid, emp_ids): vals = { 'name': record.name, 'date_from': record.date_from, 'date_to': record.date_to, 'calendar_id': emp.calendar_id.id, 'company_id': emp.company_id.id, 'resource_id': emp.resource_id.id, 'holiday_id':record.id } self._create_resource_leave(cr, uid, vals) return True
'resource_id': fields.many2one('resource.resource', 'Resource', required=True),
'resource_id': fields.many2one('resource.resource', 'Resource', ondelete='cascade', required=True),
def set_done(self, cr, uid, ids, *args): self.write(cr, uid, ids, {'state': 'done'}) return True
'target': 'new',
'target': 'current',
def invoice_pay_customer(self, cr, uid, ids, context={}): if not ids: return [] inv = self.browse(cr, uid, ids[0], context=context) return { 'name':_("Pay Invoice"), 'view_mode': 'form', 'view_id': False, 'view_type': 'form', 'res_model': 'account.voucher', 'type': 'ir.actions.act_window', 'nodestroy': True, 'target': 'new', 'domain': '[]', 'context': { 'default_partner_id': inv.partner_id.id, 'default_amount': inv.residual, 'default_name':inv.name, 'close_after_process': True, 'invoice_type':inv.type, 'invoice_id':inv.id, 'default_type': inv.type in ('out_invoice','out_refund') and 'receipt' or 'payment' } }
db = pooler.get_db_only(cr.dbname) interface.register_all(db)
pool.get('ir.actions.report.xml').register_all(cr)
def upload_report(self, cr, uid, report_id, file_sxw, file_type, context): ''' Untested function ''' pool = pooler.get_pool(cr.dbname) sxwval = StringIO(base64.decodestring(file_sxw)) if file_type=='sxw': fp = open(addons.get_module_resource('base_report_designer','openerp_sxw2rml', 'normalized_oo2rml.xsl'),'rb') if file_type=='odt': fp = open(addons.get_module_resource('base_report_designer','openerp_sxw2rml', 'normalized_odt2rml.xsl'),'rb') report = pool.get('ir.actions.report.xml').write(cr, uid, [report_id], { 'report_sxw_content': base64.decodestring(file_sxw), 'report_rml_content': str(sxw2rml(sxwval, xsl=fp.read())), }) db = pooler.get_db_only(cr.dbname) interface.register_all(db) return True
if not company_currency_id: company_currency_id = line.company_id.id
def _amount_reconciled(self, cursor, user, ids, name, args, context=None): if not ids: return {} res_currency_obj = self.pool.get('res.currency') res = {} company_currency_id = False
res[line.id] = res_currency_obj.compute(cursor, user, company_currency_id, line.statement_id.currency.id, line.voucher_id.amount, context=context)
res[line.id] = line.voucher_id.amount
def _amount_reconciled(self, cursor, user, ids, name, args, context=None): if not ids: return {} res_currency_obj = self.pool.get('res.currency') res = {} company_currency_id = False
domain = [('object_id.name', '=', model),
domain = [('object_id.model', '=', model),
def signal(self, cr, uid, model, res_id, signal, context=None): if not signal: raise ValueError('signal cannot be False')
result = Activities.process(activity.id, workitem.id,
result = Activities.process(cr, uid, activity.id, workitem.id,
def _process_one(self, cr, uid, workitem, context=None): if workitem.state != 'todo': return
except Exception, e: workitem.write({'state': 'exception', 'error_msg': str(e)},
except Exception: tb = "".join(format_exception(*exc_info())) workitem.write({'state': 'exception', 'error_msg': tb},
def _process_one(self, cr, uid, workitem, context=None): if workitem.state != 'todo': return
if ctx.get('action_id', False): return ctx['action_id']
if ctx.get('active_id', False): return ctx['active_id']
def _get_picking(self, cr, uid, ctx=None): if ctx is None: ctx = {} if ctx.get('action_id', False): return ctx['action_id'] return False
if context.get('action_id', False): picking = picking_obj.browse(cr, uid, [context['action_id']])[0]
if context.get('active_id', False): picking = picking_obj.browse(cr, uid, [context['active_id']])[0]
def _get_picking_address(self, cr, uid, context=None): picking_obj = self.pool.get('stock.picking') if context is None: context = {} if context.get('action_id', False): picking = picking_obj.browse(cr, uid, [context['action_id']])[0] return picking.address_id and picking.address_id.id or False return False
st_line = account_bank_statement_line_obj.browse(cr, uid, st_line_id, context)
st_line = account_bank_statement_line_obj.browse(cr, uid, st_line_id.id, context)
def create_move_from_st_line(self, cr, uid, st_line_id, company_currency_id, st_line_number, context=None): 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_analytic_line_obj = self.pool.get('account.analytic.line') account_bank_statement_line_obj = self.pool.get('account.bank.statement.line')
cr.execute("SELECT production_id, move_id from mrp_production_move_ids where production_id in %s and move_id in %s", [tuple(ids), tuple(valid_move_ids)]) related_move_map = cr.fetchall() related_move_dict = dict((k, list(set([v[1] for v in itr]))) for k, itr in groupby(related_move_map, itemgetter(0))) res.update(related_move_dict)
if valid_move_ids: cr.execute("SELECT production_id, move_id from mrp_production_move_ids where production_id in %s and move_id in %s", [tuple(ids), tuple(valid_move_ids)]) related_move_map = cr.fetchall() related_move_dict = dict((k, list(set([v[1] for v in itr]))) for k, itr in groupby(related_move_map, itemgetter(0))) res.update(related_move_dict)
def get(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None): if not context: context = {}
def get_recurrent_ids(self, cr, uid, ids, start_date, until_date, limit=100):
def get_recurrent_ids(self, cr, uid, ids, base_start_date, base_until_date, limit=100):
def get_recurrent_ids(self, cr, uid, ids, start_date, until_date, limit=100): if not limit: limit = 100 if ids and (start_date or until_date): cr.execute("select m.id, m.rrule, c.date, m.exdate from crm_meeting m\ join crm_case c on (c.id=m.inherit_case_id) \ where m.id in ("+ ','.join(map(lambda x: str(x), ids))+")") result = [] count = 0 start_date = start_date and datetime.datetime.strptime(start_date, "%Y-%m-%d") or False until_date = until_date and datetime.datetime.strptime(until_date, "%Y-%m-%d") or False for data in cr.dictfetchall(): if count > limit: break event_date = datetime.datetime.strptime(data['date'], "%Y-%m-%d %H:%M:%S") if start_date and start_date <= event_date: start_date = event_date if not data['rrule']: idval = common.real_id2caldav_id(data['id'], data['date']) result.append(idval) count += 1 else: exdate = data['exdate'] and data['exdate'].split(',') or [] event_obj = self.pool.get('basic.calendar.event') rrule_str = data['rrule'] new_rrule_str = [] rrule_until_date = False is_until = False for rule in rrule_str.split(';'): name, value = rule.split('=') if name == "UNTIL": is_until = True value = parser.parse(value) rrule_until_date = parser.parse(value.strftime("%Y-%m-%d")) if until_date and until_date >= rrule_until_date: until_date = rrule_until_date if until_date: value = until_date.strftime("%Y%m%d%H%M%S") new_rule = '%s=%s' % (name, value) new_rrule_str.append(new_rule) if not is_until and until_date: value = until_date.strftime("%Y%m%d%H%M%S") name = "UNTIL" new_rule = '%s=%s' % (name, value) new_rrule_str.append(new_rule) new_rrule_str = ';'.join(new_rrule_str) start_date = datetime.datetime.strptime(data['date'], "%Y-%m-%d %H:%M:%S") rdates = event_obj.get_recurrent_dates(str(new_rrule_str), exdate, start_date) for rdate in rdates: idval = common.real_id2caldav_id(data['id'], rdate) result.append(idval) count += 1 ids = result return ids
if ids and (start_date or until_date):
if ids and (base_start_date or base_until_date):
def get_recurrent_ids(self, cr, uid, ids, start_date, until_date, limit=100): if not limit: limit = 100 if ids and (start_date or until_date): cr.execute("select m.id, m.rrule, c.date, m.exdate from crm_meeting m\ join crm_case c on (c.id=m.inherit_case_id) \ where m.id in ("+ ','.join(map(lambda x: str(x), ids))+")") result = [] count = 0 start_date = start_date and datetime.datetime.strptime(start_date, "%Y-%m-%d") or False until_date = until_date and datetime.datetime.strptime(until_date, "%Y-%m-%d") or False for data in cr.dictfetchall(): if count > limit: break event_date = datetime.datetime.strptime(data['date'], "%Y-%m-%d %H:%M:%S") if start_date and start_date <= event_date: start_date = event_date if not data['rrule']: idval = common.real_id2caldav_id(data['id'], data['date']) result.append(idval) count += 1 else: exdate = data['exdate'] and data['exdate'].split(',') or [] event_obj = self.pool.get('basic.calendar.event') rrule_str = data['rrule'] new_rrule_str = [] rrule_until_date = False is_until = False for rule in rrule_str.split(';'): name, value = rule.split('=') if name == "UNTIL": is_until = True value = parser.parse(value) rrule_until_date = parser.parse(value.strftime("%Y-%m-%d")) if until_date and until_date >= rrule_until_date: until_date = rrule_until_date if until_date: value = until_date.strftime("%Y%m%d%H%M%S") new_rule = '%s=%s' % (name, value) new_rrule_str.append(new_rule) if not is_until and until_date: value = until_date.strftime("%Y%m%d%H%M%S") name = "UNTIL" new_rule = '%s=%s' % (name, value) new_rrule_str.append(new_rule) new_rrule_str = ';'.join(new_rrule_str) start_date = datetime.datetime.strptime(data['date'], "%Y-%m-%d %H:%M:%S") rdates = event_obj.get_recurrent_dates(str(new_rrule_str), exdate, start_date) for rdate in rdates: idval = common.real_id2caldav_id(data['id'], rdate) result.append(idval) count += 1 ids = result return ids
count = 0 start_date = start_date and datetime.datetime.strptime(start_date, "%Y-%m-%d") or False until_date = until_date and datetime.datetime.strptime(until_date, "%Y-%m-%d") or False for data in cr.dictfetchall():
count = 0 for data in cr.dictfetchall(): start_date = base_start_date and datetime.datetime.strptime(base_start_date, "%Y-%m-%d") or False until_date = base_until_date and datetime.datetime.strptime(base_until_date, "%Y-%m-%d") or False
def get_recurrent_ids(self, cr, uid, ids, start_date, until_date, limit=100): if not limit: limit = 100 if ids and (start_date or until_date): cr.execute("select m.id, m.rrule, c.date, m.exdate from crm_meeting m\ join crm_case c on (c.id=m.inherit_case_id) \ where m.id in ("+ ','.join(map(lambda x: str(x), ids))+")") result = [] count = 0 start_date = start_date and datetime.datetime.strptime(start_date, "%Y-%m-%d") or False until_date = until_date and datetime.datetime.strptime(until_date, "%Y-%m-%d") or False for data in cr.dictfetchall(): if count > limit: break event_date = datetime.datetime.strptime(data['date'], "%Y-%m-%d %H:%M:%S") if start_date and start_date <= event_date: start_date = event_date if not data['rrule']: idval = common.real_id2caldav_id(data['id'], data['date']) result.append(idval) count += 1 else: exdate = data['exdate'] and data['exdate'].split(',') or [] event_obj = self.pool.get('basic.calendar.event') rrule_str = data['rrule'] new_rrule_str = [] rrule_until_date = False is_until = False for rule in rrule_str.split(';'): name, value = rule.split('=') if name == "UNTIL": is_until = True value = parser.parse(value) rrule_until_date = parser.parse(value.strftime("%Y-%m-%d")) if until_date and until_date >= rrule_until_date: until_date = rrule_until_date if until_date: value = until_date.strftime("%Y%m%d%H%M%S") new_rule = '%s=%s' % (name, value) new_rrule_str.append(new_rule) if not is_until and until_date: value = until_date.strftime("%Y%m%d%H%M%S") name = "UNTIL" new_rule = '%s=%s' % (name, value) new_rrule_str.append(new_rule) new_rrule_str = ';'.join(new_rrule_str) start_date = datetime.datetime.strptime(data['date'], "%Y-%m-%d %H:%M:%S") rdates = event_obj.get_recurrent_dates(str(new_rrule_str), exdate, start_date) for rdate in rdates: idval = common.real_id2caldav_id(data['id'], rdate) result.append(idval) count += 1 ids = result return ids
sum(ail.quantity*ail.price_unit)/sum(ail.quantity*u.factor)*count(ail.product_id)::decimal(16,2) as price_average,
(case when ai.type in ('out_refund','in_invoice') then sum(ail.quantity*ail.price_unit*-1) else sum(ail.quantity*ail.price_unit) end)/(case when ai.type in ('out_refund','in_invoice') then sum(ail.quantity*u.factor*-1) else sum(ail.quantity*u.factor) end) as price_average,
def init(self, cr): tools.drop_view_if_exists(cr, 'account_invoice_report') cr.execute(""" create or replace view account_invoice_report as ( select min(ail.id) as id, ai.date_invoice as date, to_char(ai.date_invoice, 'YYYY') as year, to_char(ai.date_invoice, 'MM') as month, to_char(ai.date_invoice, 'YYYY-MM-DD') as day, ail.product_id, ai.partner_id as partner_id, ai.payment_term as payment_term, ai.period_id as period_id, u.name as uom_name, ai.currency_id as currency_id, ai.journal_id as journal_id, ai.fiscal_position as fiscal_position, ai.user_id as user_id, ai.company_id as company_id, count(ail.*) as nbr, ai.type as type, ai.state, pt.categ_id, ai.date_due as date_due, ai.address_contact_id as address_contact_id, ai.address_invoice_id as address_invoice_id, ai.account_id as account_id, ai.partner_bank_id as partner_bank_id, sum(case when ai.type in ('out_refund','in_invoice') then ail.quantity * u.factor * -1 else ail.quantity * u.factor end) as product_qty, sum(case when ai.type in ('out_refund','in_invoice') then ail.quantity*ail.price_unit * -1 else ail.quantity*ail.price_unit end) as price_total, sum(case when ai.type in ('out_refund','in_invoice') then ai.amount_total * -1 else ai.amount_total end) as price_total_tax, sum(ail.quantity*ail.price_unit)/sum(ail.quantity*u.factor)*count(ail.product_id)::decimal(16,2) as price_average, sum((select extract(epoch from avg(date_trunc('day',aml.date_created)-date_trunc('day',l.create_date)))/(24*60*60)::decimal(16,2) from account_move_line as aml left join account_invoice as a ON (a.move_id=aml.move_id) left join account_invoice_line as l ON (a.id=l.invoice_id) where a.id=ai.id)) as delay_to_pay, (case when ai.type in ('out_refund','in_invoice') then ai.residual * -1 else ai.residual end)/(select count(l.*) from account_invoice_line as l left join account_invoice as a ON (a.id=l.invoice_id) where a.id=ai.id) as residual from account_invoice_line as ail left join account_invoice as ai ON (ai.id=ail.invoice_id) left join product_template pt on (pt.id=ail.product_id) left join product_uom u on (u.id=ail.uos_id) group by ail.product_id, ai.date_invoice, ai.id, to_char(ai.date_invoice, 'YYYY'), to_char(ai.date_invoice, 'MM'), to_char(ai.date_invoice, 'YYYY-MM-DD'), ai.partner_id, ai.payment_term, ai.period_id, u.name, ai.currency_id, ai.journal_id, ai.fiscal_position, ai.user_id, ai.company_id, ai.type, ai.state, pt.categ_id, ai.date_due, ai.address_contact_id, ai.address_invoice_id, ai.account_id, ai.partner_bank_id, ai.residual, ai.amount_total ) """)
if int(vat[0:2]) == 0 and len(vat) == 10:
if int(vat[0:2]) in (0, 10, 20) and len(vat) == 10:
def check_vat_sk(self, vat): ''' Check Slovakia VAT number. ''' try: int(vat) except: return False if len(vat) not in(9, 10): return False
help="Number of operations this workcenter can do."), 'hour_nbr': fields.float('Number of Hours', required=True, help="Time in hours for doing one cycle."),
help="Number of iterations this workcenter has to do in the specified operation of the routing."), 'hour_nbr': fields.float('Number of Hours', required=True, help="Time in hours for this workcenter to achieve the operation of the specified routing."),
def on_change_product_cost(self, cr, uid, ids, product_id, context=None): if context is None: context = {} value = {}
'unit_amount': wc.costs_hour * wc.time_cycle,
'unit_amount': wc_line.hour,
def _costs_generate(self, cr, uid, production): """ Calculates total costs at the end of the production. @param production: Id of production order. @return: Calculated amount. """ amount = 0.0 analytic_line_obj = self.pool.get('account.analytic.line') for wc_line in production.workcenter_lines: wc = wc_line.workcenter_id if wc.costs_journal_id and wc.costs_general_account_id: value = wc_line.hour * wc.costs_hour account = wc.costs_hour_account_id.id if value and account: amount += value analytic_line_obj.create(cr, uid, { 'name': wc_line.name + ' (H)', 'amount': value, 'account_id': account, 'general_account_id': wc.costs_general_account_id.id, 'journal_id': wc.costs_journal_id.id, 'ref': wc.code, 'product_id': wc.product_id.id, 'unit_amount': wc.costs_hour * wc.time_cycle, 'product_uom_id': wc.product_id.uom_id.id } ) if wc.costs_journal_id and wc.costs_general_account_id: value = wc_line.cycle * wc.costs_cycle account = wc.costs_cycle_account_id.id if value and account: amount += value analytic_line_obj.create(cr, uid, { 'name': wc_line.name+' (C)', 'amount': value, 'account_id': account, 'general_account_id': wc.costs_general_account_id.id, 'journal_id': wc.costs_journal_id.id, 'ref': wc.code, 'product_id': wc.product_id.id, 'unit_amount': wc.costs_hour * wc.time_cycle, 'product_uom_id': wc.product_id.uom_id.id } ) return amount
'unit_amount': wc.costs_hour * wc.time_cycle,
'unit_amount': wc_line.cycle,
def _costs_generate(self, cr, uid, production): """ Calculates total costs at the end of the production. @param production: Id of production order. @return: Calculated amount. """ amount = 0.0 analytic_line_obj = self.pool.get('account.analytic.line') for wc_line in production.workcenter_lines: wc = wc_line.workcenter_id if wc.costs_journal_id and wc.costs_general_account_id: value = wc_line.hour * wc.costs_hour account = wc.costs_hour_account_id.id if value and account: amount += value analytic_line_obj.create(cr, uid, { 'name': wc_line.name + ' (H)', 'amount': value, 'account_id': account, 'general_account_id': wc.costs_general_account_id.id, 'journal_id': wc.costs_journal_id.id, 'ref': wc.code, 'product_id': wc.product_id.id, 'unit_amount': wc.costs_hour * wc.time_cycle, 'product_uom_id': wc.product_id.uom_id.id } ) if wc.costs_journal_id and wc.costs_general_account_id: value = wc_line.cycle * wc.costs_cycle account = wc.costs_cycle_account_id.id if value and account: amount += value analytic_line_obj.create(cr, uid, { 'name': wc_line.name+' (C)', 'amount': value, 'account_id': account, 'general_account_id': wc.costs_general_account_id.id, 'journal_id': wc.costs_journal_id.id, 'ref': wc.code, 'product_id': wc.product_id.id, 'unit_amount': wc.costs_hour * wc.time_cycle, 'product_uom_id': wc.product_id.uom_id.id } ) return amount
def _get_company(self, cr, uid, ids, context={}):
def _get_company(self, cr, uid, context={}):
def _get_company(self, cr, uid, ids, context={}): user_obj = self.pool.get('res.users') company_obj = self.pool.get('res.company') user = user_obj.browse(cr, uid, uid, context=context) if user.company_id: return user.company_id.id else: return company_obj.search(cr, uid, [('parent_id', '=', False)])[0]
return {'value': {'work_email':mail}}
return {'value': {'work_email':mail.user_email}}
def onchange_user(self, cr, uid, ids, user_id, context=None): mail = self.pool.get('res.users').browse(cr,uid,user_id) return {'value': {'work_email':mail}}
if inv.type == 'out_invoice': xml_id = 'action_invoice_tree1' elif inv.type == 'in_invoice': xml_id = 'action_invoice_tree2' elif inv.type == 'out_refund':
if inv.type in ('out_invoice', 'out_refund'):
def compute_refund(self, cr, uid, ids, mode='refund', context=None): """ @param cr: the current row, from the database cursor, @param uid: the current user’s ID for security checks, @param ids: the account invoice refund’s ID or list of IDs
'create_date': fields.datetime('Latest Date of Inventory'), }
'date': fields.datetime('Latest Inventory Date'), }
def unlink(self, cr, uid, ids, context={}): raise osv.except_osv(_('Error !'), _('You cannot delete any record!'))
l.id as id,
min(l.id) as id,
def init(self, cr): cr.execute(""" create or replace view report_stock_lines_date as ( select l.id as id, p.id as product_id, max(l.create_date) as create_date from product_product p left outer join stock_inventory_line l on (p.id=l.product_id) where l.create_date is not null group by p.id,l.id )""")
max(l.create_date) as create_date
max(s.date) as date
def init(self, cr): cr.execute(""" create or replace view report_stock_lines_date as ( select l.id as id, p.id as product_id, max(l.create_date) as create_date from product_product p left outer join stock_inventory_line l on (p.id=l.product_id) where l.create_date is not null group by p.id,l.id )""")
group by p.id,l.id
and s.state = 'done' group by p.id
def init(self, cr): cr.execute(""" create or replace view report_stock_lines_date as ( select l.id as id, p.id as product_id, max(l.create_date) as create_date from product_product p left outer join stock_inventory_line l on (p.id=l.product_id) where l.create_date is not null group by p.id,l.id )""")
amount = currency_obj.compute(cr, user, line.currency_id.id,
amount = currency_obj.compute(cr, uid, line.currency_id.id,
def populate_statement(self, cr, uid, ids, context=None):
amount = currency_obj.compute(cr, user, line.invoice.currency_id.id,
amount = currency_obj.compute(cr, uid, line.invoice.currency_id.id,
def populate_statement(self, cr, uid, ids, context=None):
group_id = model_data_obj._get_id(cr, uid, 'survey', 'base.group_tool_user')
group_id = model_data_obj._get_id(cr, uid, 'base', 'group_tool_user')
def action_send(self, cr, uid, ids, context=None): record = self.read(cr, uid, ids, []) survey_ids = context.get('active_ids', []) record = record and record[0] partner_ids = record['partner_ids'] user_ref= self.pool.get('res.users') survey_ref= self.pool.get('survey')
super(account_cash_statement, self).write(cr, uid, rs, res.get(rs))
super(account_cash_statement, self).write(cr, uid, [rs], res.get(rs))
def write(self, cr, uid, ids, vals, context=None): """ Update redord(s) comes in {ids}, with new value comes as {vals} return True on success, False otherwise
string="Return with Echange" type="object"/>
string="Return with Exchange" type="object"/>
def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False,submenu=False):
select stock.create_date, min(stock.id) as id, sum(stock.product_qty) as qty, 0 as planned_qty
select stock.create_date as date, min(stock.id) as id, sum(stock.product_qty) as qty, 0 as planned_qty
def init(self, cr): tools.drop_view_if_exists(cr, 'report_products_to_received_planned') cr.execute(""" create or replace view report_products_to_received_planned as ( select stock.create_date, min(stock.id) as id, sum(stock.product_qty) as qty, 0 as planned_qty from stock_picking picking inner join stock_move stock on picking.id = stock.picking_id and picking.type = 'in' where stock.create_date between (select cast(date_trunc('week', current_date) as date)) and (select cast(date_trunc('week', current_date) as date) + 7) group by stock.create_date
select stock.date, min(stock.id) as id, 0 as actual_qty, sum(stock.product_qty) as planned_qty
select stock.date as date , min(stock.id) as id, 0 as actual_qty, sum(stock.product_qty) as planned_qty
def init(self, cr): tools.drop_view_if_exists(cr, 'report_products_to_received_planned') cr.execute(""" create or replace view report_products_to_received_planned as ( select stock.create_date, min(stock.id) as id, sum(stock.product_qty) as qty, 0 as planned_qty from stock_picking picking inner join stock_move stock on picking.id = stock.picking_id and picking.type = 'in' where stock.create_date between (select cast(date_trunc('week', current_date) as date)) and (select cast(date_trunc('week', current_date) as date) + 7) group by stock.create_date
value = {}
value = {'product_uom_id': ''}
def onchange_product_id(self, cr, uid, ids, product_id,product_uom_id, context={}):
if product_uom_id != prod.uom_id.id: value = {'product_uom_id': prod.uom_id.id}
def onchange_product_id(self, cr, uid, ids, product_id,product_uom_id, context={}):
for employee_id in ids: emp = obj_emp.read(cr, uid, [employee_id], ['name'])[0] stop, days_xml = False, [] user_repr = ''' <user> <name>%s</name> %%s </user> ''' % (toxml(emp['name'])) today, tomor = month, month + one_day while today.month == month.month: sql = ''' select action, att.name from hr_employee as emp inner join hr_attendance as att on emp.id = att.employee_id where att.name between %s and %s and emp.id = %s order by att.name ''' cr.execute(sql, (today.strftime('%Y-%m-%d %H:%M:%S'), tomor.strftime('%Y-%m-%d %H:%M:%S'), employee_id)) attendences = cr.dictfetchall() wh = 0 if attendences and attendences[0]['action'] == 'sign_out': attendences.insert(0, {'name': today.strftime('%Y-%m-%d %H:%M:%S'), 'action':'sign_in'}) if attendences and attendences[-1]['action'] == 'sign_in': attendences.append({'name': tomor.strftime('%Y-%m-%d %H:%M:%S'), 'action':'sign_out'}) for att in attendences: dt = DateTime.strptime(att['name'], '%Y-%m-%d %H:%M:%S') if att['action'] == 'sign_out': wh += (dt - ldt).hours ldt = dt wh = hour2str(wh) today_xml = '<day num="%s"><wh>%s</wh></day>' % ((today - month).days+1, wh) days_xml.append(today_xml) today, tomor = tomor, tomor + one_day user_xml.append(user_repr % '\n'.join(days_xml))
if emp_ids: for emp in obj_emp.read(cr, uid, emp_ids, ['name']): stop, days_xml = False, [] user_repr = ''' <user> <name>%s</name> %%s </user> ''' % (toxml(emp['name'])) today, tomor = month, month + one_day while today.month == month.month: sql = ''' select action, att.name from hr_employee as emp inner join hr_attendance as att on emp.id = att.employee_id where att.name between %s and %s and emp.id = %s order by att.name ''' cr.execute(sql, (today.strftime('%Y-%m-%d %H:%M:%S'), tomor.strftime('%Y-%m-%d %H:%M:%S'), emp['id'])) attendences = cr.dictfetchall() wh = 0 if attendences and attendences[0]['action'] == 'sign_out': attendences.insert(0, {'name': today.strftime('%Y-%m-%d %H:%M:%S'), 'action':'sign_in'}) if attendences and attendences[-1]['action'] == 'sign_in': attendences.append({'name': tomor.strftime('%Y-%m-%d %H:%M:%S'), 'action':'sign_out'}) for att in attendences: dt = DateTime.strptime(att['name'], '%Y-%m-%d %H:%M:%S') if att['action'] == 'sign_out': wh += (dt - ldt).hours ldt = dt wh = hour2str(wh) today_xml = '<day num="%s"><wh>%s</wh></day>' % ((today - month).days+1, wh) days_xml.append(today_xml) today, tomor = tomor, tomor + one_day user_xml.append(user_repr % '\n'.join(days_xml))
def create_xml(self, cr, uid, ids, datas, context=None): obj_emp = pooler.get_pool(cr.dbname).get('hr.employee') if context is None: context = {} month = DateTime.DateTime(datas['form']['year'], datas['form']['month'], 1) user_xml = ['<month>%s</month>' % month2name[month.month], '<year>%s</year>' % month.year] for employee_id in ids: emp = obj_emp.read(cr, uid, [employee_id], ['name'])[0] stop, days_xml = False, [] user_repr = ''' <user> <name>%s</name> %%s </user> ''' % (toxml(emp['name'])) today, tomor = month, month + one_day while today.month == month.month: #### Work hour calculation sql = ''' select action, att.name from hr_employee as emp inner join hr_attendance as att on emp.id = att.employee_id where att.name between %s and %s and emp.id = %s order by att.name ''' cr.execute(sql, (today.strftime('%Y-%m-%d %H:%M:%S'), tomor.strftime('%Y-%m-%d %H:%M:%S'), employee_id)) attendences = cr.dictfetchall() wh = 0 # Fake sign ins/outs at week ends, to take attendances across week ends into account if attendences and attendences[0]['action'] == 'sign_out': attendences.insert(0, {'name': today.strftime('%Y-%m-%d %H:%M:%S'), 'action':'sign_in'}) if attendences and attendences[-1]['action'] == 'sign_in': attendences.append({'name': tomor.strftime('%Y-%m-%d %H:%M:%S'), 'action':'sign_out'}) # sum up the attendances' durations for att in attendences: dt = DateTime.strptime(att['name'], '%Y-%m-%d %H:%M:%S') if att['action'] == 'sign_out': wh += (dt - ldt).hours ldt = dt
res += char.lower()
res += char.upper()
def _format_iban(string): ''' This function removes all characters from given 'string' that isn't a alpha numeric and converts it to lower case. ''' res = "" for char in string: if char.isalnum(): res += char.lower() return res
iban = _format_iban(bank_acc.iban)
iban = _format_iban(bank_acc.iban).lower()
def check_iban(self, cr, uid, ids): ''' Check the IBAN number ''' for bank_acc in self.browse(cr, uid, ids): if not bank_acc.iban: continue iban = _format_iban(bank_acc.iban) if iban[:2] in _iban_len and len(iban) != _iban_len[iban[:2]]: return False #the four first digits have to be shifted to the end iban = iban[4:] + iban[:4] #letters have to be transformed into numbers (a = 10, b = 11, ...) iban2 = "" for char in iban: if char.isalpha(): iban2 += str(ord(char)-87) else: iban2 += char #iban is correct if modulo 97 == 1 if not int(iban2) % 97 == 1: return False return True
address_ids = address_pool.search(cr, uid, [('email', '=', from_email)])
address_ids = address_pool.search(cr, uid, [('email', 'like', from_email)])
def get_partner(self, cr, uid, from_email, context=None): """This function returns partner Id based on email passed @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 from_email: email address based on that function will search for the correct """ address_pool = self.pool.get('res.partner.address') res = { 'partner_address_id': False, 'partner_id': False } from_email = self.to_email(from_email)[0] address_ids = address_pool.search(cr, uid, [('email', '=', from_email)]) if address_ids: address = address_pool.browse(cr, uid, address_ids[0]) res['partner_address_id'] = address_ids[0] res['partner_id'] = address.partner_id.id
nmonth = str(int(next_date.strftime("%m"))% 12+2)
nmonth = str(int(next_date.strftime("%m"))% 12+1)
def compute(self, cr, uid, id, value, date_ref=False, context={}): if not date_ref: date_ref = datetime.now().strftime('%Y-%m-%d') pt = self.browse(cr, uid, id, context) amount = value result = [] for line in pt.line_ids: prec = self.pool.get('decimal.precision').precision_get(cr, uid, 'Account') if line.value == 'fixed': amt = round(line.value_amount, prec) elif line.value == 'procent': amt = round(value * line.value_amount, prec) elif line.value == 'balance': amt = round(amount, prec) if amt: next_date = (datetime.strptime(date_ref, '%Y-%m-%d') + relativedelta(days=line.days)) if line.days2 < 0: nyear = next_date.strftime("%Y") nmonth = str(int(next_date.strftime("%m"))% 12+2) nday = "1"
"Function: %s" % (pa.function and pa.function.name_get()[0][1] or ''),
"Function: %s" % (pa.function or ''),
def get_lead_details(self, cr, uid, lead_id, context=None): body = [] lead_proxy = self.pool.get('crm.lead') lead = lead_proxy.browse(cr, uid, lead_id, context=context) if not lead.type or lead.type == 'lead': field_names = [ 'partner_name', 'title', 'function', 'street', 'street2', 'zip', 'city', 'country_id', 'state_id', 'email_from', 'phone', 'fax', 'mobile' ]
clause += 'AND inv.state <> \'paid\''
clause += 'AND inv.state != \'cancel\' AND sale.state != \'cancel\' AND inv.state <> \'paid\' AND rel.order_id = sale.id ' sale_clause = ', sale_order AS sale '
def _invoiced_search(self, cursor, user, obj, name, args, context=None): if context is None: context = {} if not len(args): return [] clause = '' no_invoiced = False for arg in args: if arg[1] == '=': if arg[2]: clause += 'AND inv.state = \'paid\'' else: clause += 'AND inv.state <> \'paid\'' no_invoiced = True
'FROM sale_order_invoice_rel AS rel, account_invoice AS inv ' \
'FROM sale_order_invoice_rel AS rel, account_invoice AS inv '+ sale_clause + \
def _invoiced_search(self, cursor, user, obj, name, args, context=None): if context is None: context = {} if not len(args): return [] clause = '' no_invoiced = False for arg in args: if arg[1] == '=': if arg[2]: clause += 'AND inv.state = \'paid\'' else: clause += 'AND inv.state <> \'paid\'' no_invoiced = True
'FROM sale_order_invoice_rel AS rel) ')
'FROM sale_order_invoice_rel AS rel) and sale.state != \'cancel\'')
def _invoiced_search(self, cursor, user, obj, name, args, context=None): if context is None: context = {} if not len(args): return [] clause = '' no_invoiced = False for arg in args: if arg[1] == '=': if arg[2]: clause += 'AND inv.state = \'paid\'' else: clause += 'AND inv.state <> \'paid\'' no_invoiced = True
def _product_reserve(self, cr, uid, ids, product_id, product_qty, context=None): """ @param product_id: Id of product @param product_qty: Quantity of product @return: List of Values or False
def _product_reserve(self, cr, uid, ids, product_id, product_qty, context=None, lock=False): """ Attempt to find a quantity ``product_qty`` (in the product's default uom or the uom passed in ``context``) of product ``product_id`` in locations with id ``ids`` and their child locations. If ``lock`` is True, the stock.move lines of product with id ``product_id`` in the searched location will be write-locked using Postgres's "FOR UPDATE NOWAIT" option until the transaction is committed or rolled back, to prevent reservin twice the same products. If ``lock`` is True and the lock cannot be obtained (because another transaction has locked some of the same stock.move lines), a log line will be output and False will be returned, as if there was not enough stock. :param product_id: Id of product to reserve :param product_qty: Quantity of product to reserve (in the product's default uom or the uom passed in ``context``) :param lock: if True, the stock.move lines of product with id ``product_id`` in all locations (and children locations) with ``ids`` will be write-locked using postgres's "FOR UPDATE NOWAIT" option until the transaction is committed or rolled back. This is to prevent reserving twice the same products. :param context: optional context dictionary: it a 'uom' key is present it will be used instead of the default product uom to compute the ``product_qty`` and in the return value. :return: List of tuples in the form (qty, location_id) with the (partial) quantities that can be taken in each location to reach the requested product_qty (``qty`` is expressed in the default uom of the product), of False if enough products could not be found, or the lock could not be obtained (and ``lock`` was True).
def _product_reserve(self, cr, uid, ids, product_id, product_qty, context=None): """ @param product_id: Id of product @param product_qty: Quantity of product @return: List of Values or False """ result = [] amount = 0.0 if context is None: context = {} for id in self.search(cr, uid, [('location_id', 'child_of', ids)]): cr.execute("select product_uom,sum(product_qty) as product_qty from stock_move where location_dest_id=%s and location_id<>%s and product_id=%s and state='done' group by product_uom", (id, id, product_id)) results = cr.dictfetchall() cr.execute("select product_uom,-sum(product_qty) as product_qty from stock_move where location_id=%s and location_dest_id<>%s and product_id=%s and state in ('done', 'assigned') group by product_uom", (id, id, product_id)) results += cr.dictfetchall()
cr.execute("select product_uom,sum(product_qty) as product_qty from stock_move where location_dest_id=%s and location_id<>%s and product_id=%s and state='done' group by product_uom", (id, id, product_id))
if lock: try: cr.execute("SAVEPOINT stock_location_product_reserve") cr.execute("""SELECT id FROM stock_move WHERE product_id=%s AND ( (location_dest_id=%s AND location_id<>%s AND state='done') OR (location_id=%s AND location_dest_id<>%s AND state in ('done', 'assigned')) ) FOR UPDATE of stock_move NOWAIT""", (product_id, id, id, id, id), log_exceptions=False) except Exception: cr.execute("ROLLBACK TO stock_location_product_reserve") logger = logging.getLogger('stock.location') logger.warn("Failed attempt to reserve %s x product %s, likely due to another transaction already in progress. Next attempt is likely to work. Detailed error available at DEBUG level.", product_qty, product_id) logger.debug("Trace of the failed product reservation attempt: ", exc_info=True) return False cr.execute("""SELECT product_uom, sum(product_qty) AS product_qty FROM stock_move WHERE location_dest_id=%s AND location_id<>%s AND product_id=%s AND state='done' GROUP BY product_uom """, (id, id, product_id))
def _product_reserve(self, cr, uid, ids, product_id, product_qty, context=None): """ @param product_id: Id of product @param product_qty: Quantity of product @return: List of Values or False """ result = [] amount = 0.0 if context is None: context = {} for id in self.search(cr, uid, [('location_id', 'child_of', ids)]): cr.execute("select product_uom,sum(product_qty) as product_qty from stock_move where location_dest_id=%s and location_id<>%s and product_id=%s and state='done' group by product_uom", (id, id, product_id)) results = cr.dictfetchall() cr.execute("select product_uom,-sum(product_qty) as product_qty from stock_move where location_id=%s and location_dest_id<>%s and product_id=%s and state in ('done', 'assigned') group by product_uom", (id, id, product_id)) results += cr.dictfetchall()
cr.execute("select product_uom,-sum(product_qty) as product_qty from stock_move where location_id=%s and location_dest_id<>%s and product_id=%s and state in ('done', 'assigned') group by product_uom", (id, id, product_id))
cr.execute("""SELECT product_uom,-sum(product_qty) AS product_qty FROM stock_move WHERE location_id=%s AND location_dest_id<>%s AND product_id=%s AND state in ('done', 'assigned') GROUP BY product_uom """, (id, id, product_id))
def _product_reserve(self, cr, uid, ids, product_id, product_qty, context=None): """ @param product_id: Id of product @param product_qty: Quantity of product @return: List of Values or False """ result = [] amount = 0.0 if context is None: context = {} for id in self.search(cr, uid, [('location_id', 'child_of', ids)]): cr.execute("select product_uom,sum(product_qty) as product_qty from stock_move where location_dest_id=%s and location_id<>%s and product_id=%s and state='done' group by product_uom", (id, id, product_id)) results = cr.dictfetchall() cr.execute("select product_uom,-sum(product_qty) as product_qty from stock_move where location_id=%s and location_dest_id<>%s and product_id=%s and state in ('done', 'assigned') group by product_uom", (id, id, product_id)) results += cr.dictfetchall()
res = self.pool.get('stock.location')._product_reserve(cr, uid, [move.location_id.id], move.product_id.id, move.product_qty, {'uom': move.product_uom.id})
res = self.pool.get('stock.location')._product_reserve(cr, uid, [move.location_id.id], move.product_id.id, move.product_qty, {'uom': move.product_uom.id}, lock=True)
def check_assign(self, cr, uid, ids, context=None): """ Checks the product type and accordingly writes the state. @return: No. of moves done """ done = [] count = 0 pickings = {} if context is None: context = {} for move in self.browse(cr, uid, ids, context=context): if move.product_id.type == 'consu': if move.state in ('confirmed', 'waiting'): done.append(move.id) pickings[move.picking_id.id] = 1 continue if move.state in ('confirmed', 'waiting'): res = self.pool.get('stock.location')._product_reserve(cr, uid, [move.location_id.id], move.product_id.id, move.product_qty, {'uom': move.product_uom.id}) if res: #_product_available_test depends on the next status for correct functioning #the test does not work correctly if the same product occurs multiple times #in the same order. This is e.g. the case when using the button 'split in two' of #the stock outgoing form self.write(cr, uid, [move.id], {'state':'assigned'}) done.append(move.id) pickings[move.picking_id.id] = 1 r = res.pop(0) cr.execute('update stock_move set location_id=%s, product_qty=%s where id=%s', (r[1], r[0], move.id))
values['description']=this.notes values['partner_id']=this.partner_id
values['description']=this.notes or '' values['partner_id']=this.partner_id.id
def action_apply(self, cr, uid, ids, context=None): this = self.browse(cr, uid, ids)[0] record_id = context and context.get('record_id', False) or False values={} values['name']=this.name values['user_id']=this.user_id and this.user_id.id values['categ_id']=this.category_id and this.category_id.id values['section_id']=this.section_id and this.section_id.id or False, values['description']=this.notes values['partner_id']=this.partner_id values['partner_address_id']=this.address_id.id phonecall_proxy = self.pool.get('crm.phonecall') phonecall_id = phonecall_proxy.create(cr, uid, values, context=context) value = { 'name': _('Phone Call'), 'view_type': 'form', 'view_mode': 'form', 'res_model': 'crm.phonecall', 'view_id': False, 'type': 'ir.actions.act_window', 'res_id': phonecall_id } return value
class audittrail_objects_proxy(osv_pool):
class audittrail_objects_proxy(object_proxy):
def _name_get_resname(self, cr, uid, ids, *args): data = {} for resname in self.browse(cr, uid, ids,[]): model_object = resname.object_id res_id = resname.res_id if model_object and res_id: model_pool = self.pool.get(model_object.model) res = model_pool.read(cr, uid, res_id, ['name']) data[resname.id] = res['name'] else: data[resname.id] = False return data
'name': pool.get('ir.sequence').get(cr, uid, 'stock.picking'),
'name': pool.get('ir.sequence').get(cr, uid, 'stock.picking.in'),
def _do_split(self, cr, uid, data, context): move_obj = pooler.get_pool(cr.dbname).get('stock.move') pick_obj = pooler.get_pool(cr.dbname).get('stock.picking') delivery_obj = pooler.get_pool(cr.dbname).get('stock.delivery') pick = pick_obj.browse(cr, uid, [data['id']])[0] new_picking = None new_moves = [] complete, too_many, too_few = [], [], [] pool = pooler.get_pool(cr.dbname) for move in move_obj.browse(cr, uid, data['form'].get('moves',[])): if move.product_qty == data['form']['move%s' % move.id]: complete.append(move) elif move.product_qty > data['form']['move%s' % move.id]: too_few.append(move) else: too_many.append(move) # Average price computation if (pick.type == 'in') and (move.product_id.cost_method == 'average'): product_obj = pool.get('product.product') currency_obj = pool.get('res.currency') users_obj = pool.get('res.users') uom_obj = pool.get('product.uom') product = product_obj.browse(cr, uid, [move.product_id.id])[0] user = users_obj.browse(cr, uid, [uid])[0] qty = data['form']['move%s' % move.id] uom = data['form']['uom%s' % move.id] price = data['form']['price%s' % move.id] currency = data['form']['currency%s' % move.id] qty = uom_obj._compute_qty(cr, uid, uom, qty, product.uom_id.id) pricetype=pool.get('product.price.type').browse(cr,uid,user.company_id.property_valuation_price_type.id) if (qty > 0): new_price = currency_obj.compute(cr, uid, currency, user.company_id.currency_id.id, price) new_price = uom_obj._compute_price(cr, uid, uom, new_price, product.uom_id.id) if product.qty_available<=0: new_std_price = new_price else: # Get the standard price amount_unit=product.price_get(pricetype.field, context)[product.id] new_std_price = ((amount_unit * product.qty_available)\ + (new_price * qty))/(product.qty_available + qty) # Write the field according to price type field product_obj.write(cr, uid, [product.id], {pricetype.field: new_std_price}) move_obj.write(cr, uid, [move.id], {'price_unit': new_price}) for move in too_few: if not new_picking: new_picking = pick_obj.copy(cr, uid, pick.id, { 'name': pool.get('ir.sequence').get(cr, uid, 'stock.picking'), 'move_lines' : [], 'state':'draft', }) if data['form']['move%s' % move.id] != 0: new_obj = move_obj.copy(cr, uid, move.id, { 'product_qty' : data['form']['move%s' % move.id], 'product_uos_qty':data['form']['move%s' % move.id], 'picking_id' : new_picking, 'state': 'assigned', 'move_dest_id': False, 'partner_id': data['form']['partner_id%s' % pick.id], 'address_id': data['form']['address_id%s' % pick.id], 'price_unit': move.price_unit, }) delivery_id = delivery_obj.search(cr,uid, [('name','=',pick.name)]) if not delivery_id : delivery_id = delivery_obj.create(cr, uid, { 'name': pick.name, 'partner_id': data['form']['partner_id%s' % pick.id], 'date': move.date, 'product_delivered':[(6,0, [new_obj])], 'picking_id':move.picking_id.id }, context=context) if not isinstance(delivery_id, (int, long)): delivery_id=delivery_id[0] delivery_obj.write(cr, uid, [delivery_id], {'product_delivered': [(4, new_obj)]}) move_obj.write(cr, uid, [move.id], { 'product_qty' : move.product_qty - data['form']['move%s' % move.id], 'product_uos_qty':move.product_qty - data['form']['move%s' % move.id], # 'delivered_id':delivery_id }) if new_picking: move_obj.write(cr, uid, [c.id for c in complete], {'picking_id': new_picking}) for move in too_many: move_obj.write(cr, uid, [move.id], { 'product_qty' : data['form']['move%s' % move.id], 'product_uos_qty': data['form']['move%s' % move.id], 'picking_id': new_picking, }) else: for move in too_many: move_obj.write(cr, uid, [move.id], { 'product_qty': data['form']['move%s' % move.id], 'product_uos_qty': data['form']['move%s' % move.id] }) # At first we confirm the new picking (if necessary) wf_service = netsvc.LocalService("workflow") if new_picking: wf_service.trg_validate(uid, 'stock.picking', new_picking, 'button_confirm', cr) # Then we finish the good picking if new_picking: pick_obj.write(cr, uid, [pick.id], {'backorder_id': new_picking}) pick_obj.action_move(cr, uid, [new_picking]) wf_service.trg_validate(uid, 'stock.picking', new_picking, 'button_done', cr) wf_service.trg_write(uid, 'stock.picking', pick.id, cr) else: pick_obj.action_move(cr, uid, [pick.id]) wf_service.trg_validate(uid, 'stock.picking', pick.id, 'button_done', cr) bo_name = '' if new_picking: bo_name = pick_obj.read(cr, uid, [new_picking], ['name'])[0]['name'] return {'new_picking':new_picking or False, 'back_order':bo_name}
pur_tax_parent = mod_obj._get_id(cr, uid, 'account', 'vat_code_base_purchases')
pur_tax_parent = mod_obj._get_id(cr, uid, 'account', 'tax_code_base_purchases')
def execute(self, cr, uid, ids, context=None): if context is None: context = {} super(account_installer, self).execute(cr, uid, ids, context=context) record = self.browse(cr, uid, ids, context=context)[0] company_id = self.pool.get('res.users').browse(cr, uid, [uid], context)[0].company_id for res in self.read(cr, uid, ids): if record.charts == 'configurable': mod_obj = self.pool.get('ir.model.data') fp = tools.file_open(opj('account','configurable_account_chart.xml')) tools.convert_xml_import(cr, 'account', fp, {}, 'init',True, None) fp.close() self.generate_configurable_chart(cr, uid, ids, context=context) obj_tax = self.pool.get('account.tax') obj_product = self.pool.get('product.product') ir_values = self.pool.get('ir.values') s_tax = (res.get('sale_tax',0.0))/100 p_tax = (res.get('purchase_tax',0.0))/100 tax_val = {} default_tax = []
sal_tax_parent = mod_obj._get_id(cr, uid, 'account', 'vat_code_base_sales')
sal_tax_parent = mod_obj._get_id(cr, uid, 'account', 'tax_code_base_sales')
def execute(self, cr, uid, ids, context=None): if context is None: context = {} super(account_installer, self).execute(cr, uid, ids, context=context) record = self.browse(cr, uid, ids, context=context)[0] company_id = self.pool.get('res.users').browse(cr, uid, [uid], context)[0].company_id for res in self.read(cr, uid, ids): if record.charts == 'configurable': mod_obj = self.pool.get('ir.model.data') fp = tools.file_open(opj('account','configurable_account_chart.xml')) tools.convert_xml_import(cr, 'account', fp, {}, 'init',True, None) fp.close() self.generate_configurable_chart(cr, uid, ids, context=context) obj_tax = self.pool.get('account.tax') obj_product = self.pool.get('product.product') ir_values = self.pool.get('ir.values') s_tax = (res.get('sale_tax',0.0))/100 p_tax = (res.get('purchase_tax',0.0))/100 tax_val = {} default_tax = []
'name': 'VAT%s%%'%(s_tax*100), 'code': 'VAT%s%%'%(s_tax*100),
'name': 'TAX%s%%'%(s_tax*100), 'code': 'TAX%s%%'%(s_tax*100),
def execute(self, cr, uid, ids, context=None): if context is None: context = {} super(account_installer, self).execute(cr, uid, ids, context=context) record = self.browse(cr, uid, ids, context=context)[0] company_id = self.pool.get('res.users').browse(cr, uid, [uid], context)[0].company_id for res in self.read(cr, uid, ids): if record.charts == 'configurable': mod_obj = self.pool.get('ir.model.data') fp = tools.file_open(opj('account','configurable_account_chart.xml')) tools.convert_xml_import(cr, 'account', fp, {}, 'init',True, None) fp.close() self.generate_configurable_chart(cr, uid, ids, context=context) obj_tax = self.pool.get('account.tax') obj_product = self.pool.get('product.product') ir_values = self.pool.get('ir.values') s_tax = (res.get('sale_tax',0.0))/100 p_tax = (res.get('purchase_tax',0.0))/100 tax_val = {} default_tax = []
{'name':'VAT%s%%'%(s_tax*100), 'description':'VAT%s%%'%(s_tax*100),
{'name':'TAX%s%%'%(s_tax*100), 'description':'TAX%s%%'%(s_tax*100),
def execute(self, cr, uid, ids, context=None): if context is None: context = {} super(account_installer, self).execute(cr, uid, ids, context=context) record = self.browse(cr, uid, ids, context=context)[0] company_id = self.pool.get('res.users').browse(cr, uid, [uid], context)[0].company_id for res in self.read(cr, uid, ids): if record.charts == 'configurable': mod_obj = self.pool.get('ir.model.data') fp = tools.file_open(opj('account','configurable_account_chart.xml')) tools.convert_xml_import(cr, 'account', fp, {}, 'init',True, None) fp.close() self.generate_configurable_chart(cr, uid, ids, context=context) obj_tax = self.pool.get('account.tax') obj_product = self.pool.get('product.product') ir_values = self.pool.get('ir.values') s_tax = (res.get('sale_tax',0.0))/100 p_tax = (res.get('purchase_tax',0.0))/100 tax_val = {} default_tax = []
'name': 'VAT%s%%'%(p_tax*100), 'code': 'VAT%s%%'%(p_tax*100),
'name': 'TAX%s%%'%(p_tax*100), 'code': 'TAX%s%%'%(p_tax*100),
def execute(self, cr, uid, ids, context=None): if context is None: context = {} super(account_installer, self).execute(cr, uid, ids, context=context) record = self.browse(cr, uid, ids, context=context)[0] company_id = self.pool.get('res.users').browse(cr, uid, [uid], context)[0].company_id for res in self.read(cr, uid, ids): if record.charts == 'configurable': mod_obj = self.pool.get('ir.model.data') fp = tools.file_open(opj('account','configurable_account_chart.xml')) tools.convert_xml_import(cr, 'account', fp, {}, 'init',True, None) fp.close() self.generate_configurable_chart(cr, uid, ids, context=context) obj_tax = self.pool.get('account.tax') obj_product = self.pool.get('product.product') ir_values = self.pool.get('ir.values') s_tax = (res.get('sale_tax',0.0))/100 p_tax = (res.get('purchase_tax',0.0))/100 tax_val = {} default_tax = []
{'name':'VAT%s%%'%(p_tax*100), 'description':'VAT%s%%'%(p_tax*100),
{'name':'TAX%s%%'%(p_tax*100), 'description':'TAX%s%%'%(p_tax*100),
def execute(self, cr, uid, ids, context=None): if context is None: context = {} super(account_installer, self).execute(cr, uid, ids, context=context) record = self.browse(cr, uid, ids, context=context)[0] company_id = self.pool.get('res.users').browse(cr, uid, [uid], context)[0].company_id for res in self.read(cr, uid, ids): if record.charts == 'configurable': mod_obj = self.pool.get('ir.model.data') fp = tools.file_open(opj('account','configurable_account_chart.xml')) tools.convert_xml_import(cr, 'account', fp, {}, 'init',True, None) fp.close() self.generate_configurable_chart(cr, uid, ids, context=context) obj_tax = self.pool.get('account.tax') obj_product = self.pool.get('product.product') ir_values = self.pool.get('ir.values') s_tax = (res.get('sale_tax',0.0))/100 p_tax = (res.get('purchase_tax',0.0))/100 tax_val = {} default_tax = []
if move.prodlot_id and (move.prodlot_id.product_id.id != move.product_id.id):
if move.prodlot_id and move.state == 'done' and (move.prodlot_id.product_id.id != move.product_id.id):
def _check_product_lot(self, cr, uid, ids): for move in self.browse(cr, uid, ids): if move.prodlot_id and (move.prodlot_id.product_id.id != move.product_id.id): return False return True