bugged
stringlengths
4
228k
fixed
stringlengths
0
96.3M
__index_level_0__
int64
0
481k
def attendance_action_change(self, cr, uid, ids, type='action', context={}, dt=False, *args): id = False warning_sign = 'sign' if type == 'sign_in': warning_sign = "Sign In" elif type == 'sign_out': warning_sign = "Sign Out" for emp in self.read(cr, uid, ids, ['id'], context=context): if not self._action_check(cr, uid, emp['id'], dt, context): raise osv.except_osv(_('Warning'), _('You tried to %s with a date anterior to another event !\nTry to contact the administrator to correct attendances.')%(warning_sign,)) res = {'action' : type, 'employee_id' : emp['id']} if dt: res['name'] = dt id = self.pool.get('hr.attendance').create(cr, uid, res, context=context) if type != 'action': return id return True
def attendance_action_change(self, cr, uid, ids, type='action', context={}, dt=False, *args): id = False warning_sign = 'sign' if type == 'sign_in': warning_sign = "Sign In" elif type == 'sign_out': warning_sign = "Sign Out" for emp in self.read(cr, uid, ids, ['id'], context=context): if not self._action_check(cr, uid, emp['id'], dt, context): raise osv.except_osv(_('Warning'), _('You tried to %s with a date anterior to another event !\nTry to contact the administrator to correct attendances.')%(warning_sign,)) res = {'action' : type, 'employee_id' : emp['id']} if dt: res['name'] = dt id = self.pool.get('hr.attendance').create(cr, uid, res, context=context) if type != 'action': return id return True
470,400
def copy(self, cr, uid, id, default=None, context={}): group_name = self.read(cr, uid, [id], ['name'])[0]['name'] default.update({'name': group_name +' (copy)'}) return super(groups, self).copy(cr, uid, id, default, context)
def copy(self, cr, uid, id, default=None, context={}): group_name = self.read(cr, uid, [id], ['name'])[0]['name'] default.update({'name': _('%s (copy)')%group_name}) return super(groups, self).copy(cr, uid, id, default, context)
470,401
def create(self, cr, uid, vals, context=None): if 'name' in vals: if vals['name'].startswith('-'): raise osv.except_osv(_('Error'), _('The name of the group can not start with "-"')) gid = super(groups, self).create(cr, uid, vals, context=context) if context and context.get('noadmin', False): pass else: # assign this new group to user_root user_obj = self.pool.get('res.users') aid = user_obj.browse(cr, 1, user_obj._get_admin_id(cr)) if aid: aid.write({'groups_id': [(4, gid)]}) return gid
def create(self, cr, uid, vals, context=None): if 'name' in vals: if vals['name'].startswith('-'): raise osv.except_osv(_('Error'), _('The name of the group can not start with "-"')) gid = super(groups, self).create(cr, uid, vals, context=context) if context and context.get('noadmin', False): pass else: # assign this new group to user_root user_obj = self.pool.get('res.users') aid = user_obj.browse(cr, 1, user_obj._get_admin_id(cr)) if aid: aid.write({'groups_id': [(4, gid)]}) return gid
470,402
def __init__(self): warnings.warn("The netsvc.Logger API shouldn't be used anymore, please " "use the standard `logging.getLogger` API instead") super(Logger, self).__init__()
def __init__(self): warnings.warn("The netsvc.Logger API shouldn't be used anymore, please " "use the standard `logging.getLogger` API instead", PendingDeprecationWarning, stacklevel=2) super(Logger, self).__init__()
470,403
def notifyChannel(self, name, level, msg): warnings.warn("notifyChannel API shouldn't be used anymore, please use " "the standard `logging` module instead") from service.web_services import common
def notifyChannel(self, name, level, msg): warnings.warn("notifyChannel API shouldn't be used anymore, please use " "the standard `logging` module instead", PendingDeprecationWarning, stacklevel=2) from service.web_services import common
470,404
def onchange_uos_quantity(self, cr, uid, ids, product_id, product_uos_qty, product_uos, product_uom): """ On change of product quantity finds UoM and UoS quantities @param product_id: Product id @param product_uos_qty: Changed UoS Quantity of product @param product_uom: Unit of measure of product @param product_uos: Unit of sale of product @return: Dictionary of values """ result = { 'product_qty': 0.00 }
def onchange_uos_quantity(self, cr, uid, ids, product_id, product_uos_qty, product_uos, product_uom): """ On change of product quantity finds UoM and UoS quantities @param product_id: Product id @param product_uos_qty: Changed UoS Quantity of product @param product_uom: Unit of measure of product @param product_uos: Unit of sale of product @return: Dictionary of values """ result = { 'product_qty': 0.00 }
470,405
def action_done(self, cr, uid, ids, context=None): """ Finished the inventory @return: True """
defaction_done(self,cr,uid,ids,context=None):"""Finishedtheinventory@return:True"""
470,406
def action_confirm(self, cr, uid, ids, context=None): """ Confirm the inventory and writes its finished date @return: True """ if context is None: context = {} # to perform the correct inventory corrections we need analyze stock location by # location, never recursively, so we use a special context product_context = dict(context, compute_child=False)
def action_confirm(self, cr, uid, ids, context=None): """ Confirm the inventory and writes its finished date @return: True """ if context is None: context = {} # to perform the correct inventory corrections we need analyze stock location by # location, never recursively, so we use a special context product_context = dict(context, compute_child=False)
470,407
def action_confirm(self, cr, uid, ids, context=None): """ Confirm the inventory and writes its finished date @return: True """ if context is None: context = {} # to perform the correct inventory corrections we need analyze stock location by # location, never recursively, so we use a special context product_context = dict(context, compute_child=False)
def action_confirm(self, cr, uid, ids, context=None): """ Confirm the inventory and writes its finished date @return: True """ if context is None: context = {} # to perform the correct inventory corrections we need analyze stock location by # location, never recursively, so we use a special context product_context = dict(context, compute_child=False)
470,408
def on_change_product_id(self, cr, uid, ids, location_id, product, uom=False): """ Changes UoM and name if product_id changes. @param location_id: Location id @param product: Changed product_id @param uom: UoM product @return: Dictionary of changed values """ if not product: return {} if not uom: prod = self.pool.get('product.product').browse(cr, uid, [product], {'uom': uom})[0] uom = prod.uom_id.id amount = self.pool.get('stock.location')._product_get(cr, uid, location_id, [product], {'uom': uom})[product] result = {'product_qty': amount, 'product_uom': uom} return {'value': result}
def on_change_product_id(self, cr, uid, ids, location_id, product, uom=False, to_date=False): """ Changes UoM and name if product_id changes. @param location_id: Location id @param product: Changed product_id @param uom: UoM product @return: Dictionary of changed values """ if not product: return {} if not uom: prod = self.pool.get('product.product').browse(cr, uid, [product], {'uom': uom})[0] uom = prod.uom_id.id amount = self.pool.get('stock.location')._product_get(cr, uid, location_id, [product], {'uom': uom})[product] result = {'product_qty': amount, 'product_uom': uom} return {'value': result}
470,409
def on_change_product_id(self, cr, uid, ids, location_id, product, uom=False): """ Changes UoM and name if product_id changes. @param location_id: Location id @param product: Changed product_id @param uom: UoM product @return: Dictionary of changed values """ if not product: return {} if not uom: prod = self.pool.get('product.product').browse(cr, uid, [product], {'uom': uom})[0] uom = prod.uom_id.id amount = self.pool.get('stock.location')._product_get(cr, uid, location_id, [product], {'uom': uom})[product] result = {'product_qty': amount, 'product_uom': uom} return {'value': result}
def on_change_product_id(self, cr, uid, ids, location_id, product, uom=False): """ Changes UoM and name if product_id changes. @param location_id: Location id @param product: Changed product_id @param uom: UoM product @return: Dictionary of changed values """ if not product: return {} if not uom: prod = self.pool.get('product.product').browse(cr, uid, [product], {'uom': uom})[0] uom = prod.uom_id.id amount = self.pool.get('stock.location')._product_get(cr, uid, location_id, [product], {'uom': uom, 'to_date': to_date})[product] result = {'product_qty': amount, 'product_uom': uom} return {'value': result}
470,410
def __leaf_to_sql(self, leaf, table): if leaf == self.__DUMMY_LEAF: return ('(1=1)', []) left, operator, right = leaf
def __leaf_to_sql(self, leaf, table): if leaf == self.__DUMMY_LEAF: return ('(1=1)', []) left, operator, right = leaf
470,411
def __leaf_to_sql(self, leaf, table): if leaf == self.__DUMMY_LEAF: return ('(1=1)', []) left, operator, right = leaf
def __leaf_to_sql(self, leaf, table): if leaf == self.__DUMMY_LEAF: return ('(1=1)', []) left, operator, right = leaf
470,412
def __leaf_to_sql(self, leaf, table): if leaf == self.__DUMMY_LEAF: return ('(1=1)', []) left, operator, right = leaf
defelse: if operator == 'in': query = '(%s.%s IS NULL)' % (table._table, left) else: query = '(%s.%s IS NOT NULL)' % (table._table, left) __leaf_to_sql(self,else: if operator == 'in': query = '(%s.%s IS NULL)' % (table._table, left) else: query = '(%s.%s IS NOT NULL)' % (table._table, left) leaf,else: if operator == 'in': query = '(%s.%s IS NULL)' % (table._table, left) else: query = '(%s.%s IS NOT NULL)' % (table._table, left) table):else: if operator == 'in': query = '(%s.%s IS NULL)' % (table._table, left) else: query = '(%s.%s IS NOT NULL)' % (table._table, left) ifelse: if operator == 'in': query = '(%s.%s IS NULL)' % (table._table, left) else: query = '(%s.%s IS NOT NULL)' % (table._table, left) leafelse: if operator == 'in': query = '(%s.%s IS NULL)' % (table._table, left) else: query = '(%s.%s IS NOT NULL)' % (table._table, left) ==else: if operator == 'in': query = '(%s.%s IS NULL)' % (table._table, left) else: query = '(%s.%s IS NOT NULL)' % (table._table, left) self.__DUMMY_LEAF:else: if operator == 'in': query = '(%s.%s IS NULL)' % (table._table, left) else: query = '(%s.%s IS NOT NULL)' % (table._table, left) returnelse: if operator == 'in': query = '(%s.%s IS NULL)' % (table._table, left) else: query = '(%s.%s IS NOT NULL)' % (table._table, left) ('(1=1)',else: if operator == 'in': query = '(%s.%s IS NULL)' % (table._table, left) else: query = '(%s.%s IS NOT NULL)' % (table._table, left) [])else: if operator == 'in': query = '(%s.%s IS NULL)' % (table._table, left) else: query = '(%s.%s IS NOT NULL)' % (table._table, left) left,else: if operator == 'in': query = '(%s.%s IS NULL)' % (table._table, left) else: query = '(%s.%s IS NOT NULL)' % (table._table, left) operator,else: if operator == 'in': query = '(%s.%s IS NULL)' % (table._table, left) else: query = '(%s.%s IS NOT NULL)' % (table._table, left) rightelse: if operator == 'in': query = '(%s.%s IS NULL)' % (table._table, left) else: query = '(%s.%s IS NOT NULL)' % (table._table, left) =else: if operator == 'in': query = '(%s.%s IS NULL)' % (table._table, left) else: query = '(%s.%s IS NOT NULL)' % (table._table, left) leaf
470,413
def _query_get(self, cr, uid, obj='l', context=None): fiscalyear_obj = self.pool.get('account.fiscalyear') fiscalperiod_obj = self.pool.get('account.period') account_obj = self.pool.get('account.account') fiscalyear_ids = [] if context is None: context = {} initial_bal = context.get('initial_bal', False) company_clause = " " if context.get('company_id', False): company_clause = " AND " +obj+".company_id = %s" % context.get('company_id', False) if not context.get('fiscalyear', False): fiscalyear_ids = fiscalyear_obj.search(cr, uid, [('state', '=', 'draft')]) else: #for initial balance as well as for normal query, we check only the selected FY because the best practice is to generate the FY opening entries fiscalyear_ids = [context['fiscalyear']]
def _query_get(self, cr, uid, obj='l', context=None): fiscalyear_obj = self.pool.get('account.fiscalyear') fiscalperiod_obj = self.pool.get('account.period') account_obj = self.pool.get('account.account') fiscalyear_ids = [] if context is None: context = {} initial_bal = context.get('initial_bal', False) company_clause = " " if context.get('company_id', False): company_clause = " AND " +obj+".company_id = %s" % context.get('company_id', False) if not context.get('fiscalyear', False): fiscalyear_ids = fiscalyear_obj.search(cr, uid, [('state', '=', 'draft')]) else: #for initial balance as well as for normal query, we check only the selected FY because the best practice is to generate the FY opening entries fiscalyear_ids = [context['fiscalyear']]
470,414
def _process_text(self, txt): if not self.localcontext: return str2xml(txt) if not txt: return '' result = '' sps = _regex.split(txt) while sps: # This is a simple text to translate to_translate = tools.ustr(sps.pop(0)) result += tools.ustr(self.localcontext.get('translate', lambda x:x)(to_translate)) if sps: try: txt = None expr = sps.pop(0) txt = eval(expr, self.localcontext) if txt and isinstance(txt, basestring): txt = tools.ustr(txt) except Exception: pass if isinstance(txt, basestring): result += str2xml(txt) elif (txt is not None) and (txt is not False): result += ustr(txt) return result
def _process_text(self, txt): if not self.localcontext: return str2xml(txt) if not txt: return '' result = '' sps = _regex.split(txt) while sps: # This is a simple text to translate to_translate = tools.ustr(sps.pop(0)) result += tools.ustr(self.localcontext.get('translate', lambda x:x)(to_translate)) if sps: try: txt = None expr = sps.pop(0) txt = eval(expr, self.localcontext) if txt and isinstance(txt, basestring): txt = tools.ustr(txt) except Exception: pass if isinstance(txt, basestring): result += str2xml(txt) elif txt and (txt is not None) and (txt is not False): result += ustr(txt) return result
470,415
def unlink(self, cr, uid, ids, context=None): for move in self.browse(cr, uid, ids, context=context): if move.state != 'draft': raise osv.except_osv(_('UserError'), _('You can only delete draft moves.')) return super(stock_move, self).unlink( cr, uid, ids, context=context)
def unlink(self, cr, uid, ids, context=None): for move in self.browse(cr, uid, ids, context=context): if move.state != 'draft': raise osv.except_osv(_('UserError'), _('You can only delete draft moves.')) return super(stock_move, self).unlink( cr, uid, ids, context=context)
470,416
def normalizeStyleProperties(self): """Transfer all style:style-properties attributes from the self.style_properties_hierarchical dict to the automatic-styles from content.xml. Use this function to preprocess content.xml for XSLT transformations etc.Do not try to implement this function with XSlT - believe me, it's a terrible task...""" styles_styles = self.styles_dom.getElementsByTagName("style:style") automatic_styles = self.content_dom.getElementsByTagName("office:automatic-styles")[0] for s in styles_styles: automatic_styles.appendChild(s.cloneNode(deep=1)) content_styles = self.content_dom.getElementsByTagName("style:style") # these are the content_styles with styles_styles added!!! for s in content_styles: c = self.findChildrenByName(s,"style:properties") if c == []: # some derived automatic styles do not have "style:properties": temp = self.content_dom.createElement("style:properties") s.appendChild(temp) c = self.findChildrenByName(s,"style:properties") c = c[0] dict = self.style_properties_dict[(s.getAttribute("style:name")).encode("latin-1")] or {} for attribute in dict.keys(): c.setAttribute(self.openOfficeStringUtf8(attribute),self.openOfficeStringUtf8(dict[attribute]))
def normalizeStyleProperties(self): """Transfer all style:style-properties attributes from the self.style_properties_hierarchical dict to the automatic-styles from content.xml. Use this function to preprocess content.xml for XSLT transformations etc.Do not try to implement this function with XSlT - believe me, it's a terrible task...""" styles_styles = self.styles_dom.getElementsByTagName("style:style") automatic_styles = self.content_dom.getElementsByTagName("office:automatic-styles")[0] for s in styles_styles: automatic_styles.appendChild(s.cloneNode(deep=1)) content_styles = self.content_dom.getElementsByTagName("style:style") # these are the content_styles with styles_styles added!!! for s in content_styles: c = self.findChildrenByName(s,"style:properties") if c == []: # some derived automatic styles do not have "style:properties": temp = self.content_dom.createElement("style:properties") s.appendChild(temp) c = self.findChildrenByName(s,"style:properties") c = c[0] dict = self.style_properties_dict[(s.getAttribute("style:name")).encode("utf-8")] or {} for attribute in dict.keys(): c.setAttribute(self.openOfficeStringUtf8(attribute),self.openOfficeStringUtf8(dict[attribute]))
470,417
def buildStyleDict(self): """Store all style:style-nodes from content.xml and styles.xml in self.style_dict. Caution: in this dict the nodes from two dom apis are merged!""" for st in (self.styles_dom,self.content_dom): for s in st.getElementsByTagName("style:style"): name = s.getAttribute("style:name").encode("latin-1") self.style_dict[name] = s return True
def buildStyleDict(self): """Store all style:style-nodes from content.xml and styles.xml in self.style_dict. Caution: in this dict the nodes from two dom apis are merged!""" for st in (self.styles_dom,self.content_dom): for s in st.getElementsByTagName("style:style"): name = s.getAttribute("style:name").encode("utf-8") self.style_dict[name] = s return True
470,418
def getStylePropertiesDict(self,style_name): res = {}
def getStylePropertiesDict(self,style_name): res = {}
470,419
def getStylePropertiesDict(self,style_name): res = {}
def getStylePropertiesDict(self,style_name): res = {}
470,420
def _get_currency(self, cr, uid, context): user = self.pool.get('res.users').browse(cr, uid, uid) if user.company_id: return user.company_id.currency_id.id return False
def _get_currency(self, cr, uid, context): user = self.pool.get('res.users').browse(cr, uid, uid) if user.company_id: return user.company_id.currency_id.id return False
470,421
def _get_currency(self, cr, uid, context): user = self.pool.get('res.users').browse(cr, uid, uid) if user.company_id: return user.company_id.currency_id.id return False
def _get_currency(self, cr, uid, context): user = self.pool.get('res.users').browse(cr, uid, uid) if user.company_id: return user.company_id.currency_id.id return False
470,422
def makeOrder(self, cr, uid, ids, context=None): """ This function create Quotation on given case. @param self: The object pointer @param cr: the current row, from the database cursor, @param uid: the current user’s ID for security checks, @param ids: List of crm make sale' ids @param context: A standard dictionary for contextual values @return : Dictionary value of created sale order. """ if not context: context = {}
def makeOrder(self, cr, uid, ids, context=None): """ This function create Quotation on given case. @param self: The object pointer @param cr: the current row, from the database cursor, @param uid: the current user’s ID for security checks, @param ids: List of crm make sale' ids @param context: A standard dictionary for contextual values @return : Dictionary value of created sale order. """ if not context: context = {}
470,423
def _get_shop_id(self, cr, uid, ids, context=None): if context is None: context = {} cmpny_id = self.pool.get('res.users')._get_company(cr, uid, context=context) shop = self.pool.get('sale.shop').search(cr, uid, [('company_id', '=', cmpny_id)]) return shop and shop[0] or False
def _get_shop_id(self, cr, uid, ids, context=None): if context is None: context = {} cmpny_id = self.pool.get('res.users')._get_company(cr, uid, context=context) shop = self.pool.get('sale.shop').search(cr, uid, [('company_id', '=', cmpny_id)]) return shop and shop[0] or False
470,424
def process_all(self, cr, uid, camp_ids=None, context={}): camp_obj = self.pool.get('marketing.campaign') if not camp_ids: camp_ids = camp_obj.search(cr, uid, [('state','=','running')], context=context) for camp in camp_obj.browse(cr, uid, camp_ids, context=context): if camp.mode in ('test_realtime','active'): workitem_ids = self.search(cr, uid, [('state', '=', 'todo'), ('date','<=', time.strftime('%Y-%m-%d %H:%M:%S'))]) elif camp.mode == 'test': workitem_ids = self.search(cr, uid, [('state', '=', 'todo')]) else: # manual states are not processed automatically workitem_ids = [] if workitem_ids: self.process(cr, uid, workitem_ids, context)
def process_all(self, cr, uid, camp_ids=None, context={}): camp_obj = self.pool.get('marketing.campaign') if not camp_ids: camp_ids = camp_obj.search(cr, uid, [('state','=','running')], context=context) for camp in camp_obj.browse(cr, uid, camp_ids, context=context): if camp.mode in ('test_realtime','active'): workitem_ids = self.search(cr, uid, [('state', '=', 'todo'), ('date','<=', time.strftime('%Y-%m-%d %H:%M:%S'))]) elif camp.mode == 'test': workitem_ids = self.search(cr, uid, [('state', '=', 'todo')]) else: # manual states are not processed automatically workitem_ids = [] if workitem_ids: self.process(cr, uid, workitem_ids, context)
470,425
def search(self, cr, user, args, offset=0, limit=None, order=None, context=None, count=False): """ Search for record/s with or without domain
def search(self, cr, user, args, offset=0, limit=None, order=None, context=None, count=False): """ Search for record/s with or without domain
470,426
def _check_date(self, cr, uid, ids): if ids: cr.execute('select number_of_days_temp from hr_holidays where id in ('+','.join(map(str, ids))+')') res = cr.fetchall() if res and res[0][0] < 0: return False return True
def _check_date(self, cr, uid, ids): for rec in self.read(cr, uid, ids, ['number_of_days','date_from','date_to']): if rec['number_of_days'] < 0: return False return True
470,427
def _check_date(self, cr, uid, ids): if ids: cr.execute('select number_of_days_temp from hr_holidays where id in ('+','.join(map(str, ids))+')') res = cr.fetchall() if res and res[0][0] < 0: return False return True
def _check_date(self, cr, uid, ids): if ids: cr.execute('select number_of_days_temp from hr_holidays where id in ('+','.join(map(str, ids))+')') res = cr.fetchall() if res and res[0][0] < 0: return False return True
470,428
def action_move_line_create(self, cr, uid, ids, *args): journal_pool = self.pool.get('account.journal') sequence_pool = self.pool.get('ir.sequence') move_pool = self.pool.get('account.move') move_line_pool = self.pool.get('account.move.line') analytic_pool = self.pool.get('account.analytic.line') currency_pool = self.pool.get('res.currency') invoice_pool = self.pool.get('account.invoice') for inv in self.browse(cr, uid, ids): if inv.move_id: continue
def action_move_line_create(self, cr, uid, ids, *args): journal_pool = self.pool.get('account.journal') sequence_pool = self.pool.get('ir.sequence') move_pool = self.pool.get('account.move') move_line_pool = self.pool.get('account.move.line') analytic_pool = self.pool.get('account.analytic.line') currency_pool = self.pool.get('res.currency') invoice_pool = self.pool.get('account.invoice') for inv in self.browse(cr, uid, ids): if inv.move_id: continue
470,429
def get(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None): if not context: context = {} if not values: values = {} res = {} if not ids: return res for id in ids: res[id] = [] if offset: warnings.warn("Specifying offset at a many2many.get() may produce unpredictable results.", DeprecationWarning, stacklevel=2) obj = obj.pool.get(self._obj)
def get(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None): if not context: context = {} if not values: values = {} res = {} if not ids: return res for id in ids: res[id] = [] if offset: warnings.warn("Specifying offset at a many2many.get() may produce unpredictable results.", DeprecationWarning, stacklevel=2) obj = obj.pool.get(self._obj)
470,430
fields_def = self.__view_look_dom(cr, user, node, view_id, context=context)
fields_def = self.__view_look_dom(cr, user, node, view_id, context=context)
470,431
fields_def = self.__view_look_dom(cr, user, node, view_id, context=context)
fields_def = self.__view_look_dom(cr, user, node, view_id, context=context)
470,432
def _process_text(self, txt): if not self.localcontext: return str2xml(txt) if not txt: return '' result = '' sps = _regex.split(txt) while sps: # This is a simple text to translate result += self.localcontext.get('translate', lambda x:x)(sps.pop(0)) if sps: try: expr = sps.pop(0) txt = eval(expr,self.localcontext) if txt and (isinstance(txt, unicode) or isinstance(txt, str)): txt = self.localcontext.get('translate', lambda x:x)(txt) except Exception,e: tb_s = reduce(lambda x, y: x+y, traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback)) netsvc.Logger().notifyChannel('report', netsvc.LOG_ERROR, 'report :\n%s\n%s\nexpr: %s' % (tb_s, str(e), expr.encode('utf-8'))) if type(txt)==type('') or type(txt)==type(u''): txt2 = str2xml(txt) result1 = tools.ustr(txt2) result = result + str(result1) # To avoid concatenation of unicode and str elif (txt is not None) and (txt is not False): result += str(txt) return result
def _process_text(self, txt): if not self.localcontext: return str2xml(txt) if not txt: return '' result = '' sps = _regex.split(txt) while sps: # This is a simple text to translate result += tools.ustr(self.localcontext.get('translate', lambda x:x)(sps.pop(0))) if sps: try: expr = sps.pop(0) txt = eval(expr,self.localcontext) if txt and (isinstance(txt, unicode) or isinstance(txt, str)): txt = self.localcontext.get('translate', lambda x:x)(txt) except Exception,e: tb_s = reduce(lambda x, y: x+y, traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback)) netsvc.Logger().notifyChannel('report', netsvc.LOG_ERROR, 'report :\n%s\n%s\nexpr: %s' % (tb_s, str(e), expr.encode('utf-8'))) if type(txt)==type('') or type(txt)==type(u''): txt2 = str2xml(txt) result1 = tools.ustr(txt2) result = result + str(result1) # To avoid concatenation of unicode and str elif (txt is not None) and (txt is not False): result += str(txt) return result
470,433
def _process_text(self, txt): if not self.localcontext: return str2xml(txt) if not txt: return '' result = '' sps = _regex.split(txt) while sps: # This is a simple text to translate result += self.localcontext.get('translate', lambda x:x)(sps.pop(0)) if sps: try: expr = sps.pop(0) txt = eval(expr,self.localcontext) if txt and (isinstance(txt, unicode) or isinstance(txt, str)): txt = self.localcontext.get('translate', lambda x:x)(txt) except Exception,e: tb_s = reduce(lambda x, y: x+y, traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback)) netsvc.Logger().notifyChannel('report', netsvc.LOG_ERROR, 'report :\n%s\n%s\nexpr: %s' % (tb_s, str(e), expr.encode('utf-8'))) if type(txt)==type('') or type(txt)==type(u''): txt2 = str2xml(txt) result1 = tools.ustr(txt2) result = result + str(result1) # To avoid concatenation of unicode and str elif (txt is not None) and (txt is not False): result += str(txt) return result
def _process_text(self, txt): if not self.localcontext: return str2xml(txt) if not txt: return '' result = '' sps = _regex.split(txt) while sps: # This is a simple text to translate result += self.localcontext.get('translate', lambda x:x)(sps.pop(0)) if sps: try: expr = sps.pop(0) txt = eval(expr,self.localcontext) if txt and (isinstance(txt, unicode) or isinstance(txt, str)): txt = tools.ustr(self.localcontext.get('translate', lambda x:x)(txt)) except Exception,e: tb_s = reduce(lambda x, y: x+y, traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback)) netsvc.Logger().notifyChannel('report', netsvc.LOG_ERROR, 'report :\n%s\n%s\nexpr: %s' % (tb_s, str(e), expr.encode('utf-8'))) if type(txt)==type('') or type(txt)==type(u''): txt2 = str2xml(txt) result1 = tools.ustr(txt2) result = result + str(result1) # To avoid concatenation of unicode and str elif (txt is not None) and (txt is not False): result += str(txt) return result
470,434
def _process_text(self, txt): if not self.localcontext: return str2xml(txt) if not txt: return '' result = '' sps = _regex.split(txt) while sps: # This is a simple text to translate result += self.localcontext.get('translate', lambda x:x)(sps.pop(0)) if sps: try: expr = sps.pop(0) txt = eval(expr,self.localcontext) if txt and (isinstance(txt, unicode) or isinstance(txt, str)): txt = self.localcontext.get('translate', lambda x:x)(txt) except Exception,e: tb_s = reduce(lambda x, y: x+y, traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback)) netsvc.Logger().notifyChannel('report', netsvc.LOG_ERROR, 'report :\n%s\n%s\nexpr: %s' % (tb_s, str(e), expr.encode('utf-8'))) if type(txt)==type('') or type(txt)==type(u''): txt2 = str2xml(txt) result1 = tools.ustr(txt2) result = result + str(result1) # To avoid concatenation of unicode and str elif (txt is not None) and (txt is not False): result += str(txt) return result
def _process_text(self, txt): if not self.localcontext: return str2xml(txt) if not txt: return '' result = '' sps = _regex.split(txt) while sps: # This is a simple text to translate result += self.localcontext.get('translate', lambda x:x)(sps.pop(0)) if sps: try: expr = sps.pop(0) txt = eval(expr,self.localcontext) if txt and (isinstance(txt, unicode) or isinstance(txt, str)): txt = self.localcontext.get('translate', lambda x:x)(txt) except Exception,e: tb_s = reduce(lambda x, y: x+y, traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback)) netsvc.Logger().notifyChannel('report', netsvc.LOG_ERROR, 'report :\n%s\n%s\nexpr: %s' % (tb_s, str(e), expr.encode('utf-8'))) if type(txt)==type('') or type(txt)==type(u''): txt2 = str2xml(txt) result += tools.ustr(txt2) # To avoid concatenation of unicode and str elif (txt is not None) and (txt is not False): result += str(txt) return result
470,435
def _process_text(self, txt): if not self.localcontext: return str2xml(txt) if not txt: return '' result = '' sps = _regex.split(txt) while sps: # This is a simple text to translate result += self.localcontext.get('translate', lambda x:x)(sps.pop(0)) if sps: try: expr = sps.pop(0) txt = eval(expr,self.localcontext) if txt and (isinstance(txt, unicode) or isinstance(txt, str)): txt = self.localcontext.get('translate', lambda x:x)(txt) except Exception,e: tb_s = reduce(lambda x, y: x+y, traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback)) netsvc.Logger().notifyChannel('report', netsvc.LOG_ERROR, 'report :\n%s\n%s\nexpr: %s' % (tb_s, str(e), expr.encode('utf-8'))) if type(txt)==type('') or type(txt)==type(u''): txt2 = str2xml(txt) result1 = tools.ustr(txt2) result = result + str(result1) # To avoid concatenation of unicode and str elif (txt is not None) and (txt is not False): result += str(txt) return result
def _process_text(self, txt): if not self.localcontext: return str2xml(txt) if not txt: return '' result = '' sps = _regex.split(txt) while sps: # This is a simple text to translate result += self.localcontext.get('translate', lambda x:x)(sps.pop(0)) if sps: try: expr = sps.pop(0) txt = eval(expr,self.localcontext) if txt and (isinstance(txt, unicode) or isinstance(txt, str)): txt = self.localcontext.get('translate', lambda x:x)(txt) except Exception,e: tb_s = reduce(lambda x, y: x+y, traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback)) netsvc.Logger().notifyChannel('report', netsvc.LOG_ERROR, 'report :\n%s\n%s\nexpr: %s' % (tb_s, str(e), expr.encode('utf-8'))) if type(txt)==type('') or type(txt)==type(u''): txt2 = str2xml(txt) result1 = tools.ustr(txt2) result = result + str(result1) # To avoid concatenation of unicode and str elif (txt is not None) and (txt is not False): result += tools.ustr(txt) return result
470,436
def __init__(self, cr, uid, name, context=None): super(third_party_ledger, self).__init__(cr, uid, name, context=context) self.localcontext.update({ 'time': time, 'lines': self.lines, 'sum_debit_partner': self._sum_debit_partner, 'sum_credit_partner': self._sum_credit_partner, 'sum_debit': self._sum_debit, 'sum_credit': self._sum_credit, 'get_currency': self._get_currency, 'comma_me' : self.comma_me, 'get_start_period': self.get_start_period, 'get_end_period': self.get_end_period, 'get_account': self._get_account, 'get_filter': self._get_filter, 'get_start_date': self._get_start_date, 'get_end_date': self._get_end_date, 'get_fiscalyear': self._get_fiscalyear, 'get_start_date':self._get_start_date, 'get_end_date': self._get_end_date, 'get_journal': self._get_journal, 'get_partners':self._get_partners, 'get_intial_balance':self._get_intial_balance, 'display_initial_balance':self._display_initial_balance, 'display_currency':self._display_currency, 'get_target_move': self._get_target_move, })
def __init__(self, cr, uid, name, context=None): super(third_party_ledger, self).__init__(cr, uid, name, context=context) self.localcontext.update({ 'time': time, 'lines': self.lines, 'sum_debit_partner': self._sum_debit_partner, 'sum_credit_partner': self._sum_credit_partner, 'get_currency': self._get_currency, 'comma_me' : self.comma_me, 'get_start_period': self.get_start_period, 'get_end_period': self.get_end_period, 'get_account': self._get_account, 'get_filter': self._get_filter, 'get_start_date': self._get_start_date, 'get_end_date': self._get_end_date, 'get_fiscalyear': self._get_fiscalyear, 'get_start_date':self._get_start_date, 'get_end_date': self._get_end_date, 'get_journal': self._get_journal, 'get_partners':self._get_partners, 'get_intial_balance':self._get_intial_balance, 'display_initial_balance':self._display_initial_balance, 'display_currency':self._display_currency, 'get_target_move': self._get_target_move, })
470,437
def _sum_debit_partner(self, partner): move_state = ['draft','posted'] if self.target_move == 'posted': move_state = ['posted']
def _sum_debit_partner(self, partner): move_state = ['draft','posted'] if self.target_move == 'posted': move_state = ['posted']
470,438
def _sum_credit_partner(self, partner): move_state = ['draft','posted'] if self.target_move == 'posted': move_state = ['posted']
def _sum_credit_partner(self, partner): move_state = ['draft','posted'] if self.target_move == 'posted': move_state = ['posted']
470,439
def _sum_credit(self): move_state = ['draft','posted'] if self.target_move == 'posted': move_state = ['posted']
def _sum_credit(self): move_state = ['draft','posted'] if self.target_move == 'posted': move_state = ['posted']
470,440
def action_number(self, cr, uid, ids, *args): #TODO: not correct fix but required a frech values before reading it. self.write(cr, uid, ids, {})
def action_number(self, cr, uid, ids, *args): #TODO: not correct fix but required a frech values before reading it. self.write(cr, uid, ids, {})
470,441
def onchange_lot_id(self, cr, uid, ids, prodlot_id=False, product_qty=False, loc_id=False, product_id=False, context=None): """ On change of production lot gives a warning message. @param prodlot_id: Changed production lot id @param product_qty: Quantity of product @param loc_id: Location id @param product_id: Product id @return: Warning message """ if not prodlot_id or not loc_id: return {} ctx = context and context.copy() or {} ctx['location_id'] = loc_id prodlot = self.pool.get('stock.production.lot').browse(cr, uid, prodlot_id, ctx) location = self.pool.get('stock.location').browse(cr, uid, loc_id) warning = {} if (location.usage == 'internal') and (product_qty > (prodlot.stock_available or 0.0)): warning = { 'title': _('Bad Lot Assignation !'), 'message': _('You are moving %.2f products but only %.2f available in this lot.') % (product_qty, prodlot.stock_available or 0.0) } return {'warning': warning}
def onchange_lot_id(self, cr, uid, ids, prodlot_id=False, product_qty=False, loc_id=False, product_id=False, context=None): """ On change of production lot gives a warning message. @param prodlot_id: Changed production lot id @param product_qty: Quantity of product @param loc_id: Location id @param product_id: Product id @return: Warning message """ if not prodlot_id or not loc_id: return {} ctx = context and context.copy() or {} ctx['location_id'] = loc_id prodlot = self.pool.get('stock.production.lot').browse(cr, uid, prodlot_id, ctx) location = self.pool.get('stock.location').browse(cr, uid, loc_id) warning = {} if (location.usage == 'internal') and (product_qty > (prodlot.stock_available or 0.0)): warning = { 'title': _('Insufficient Stock in Lot !'), 'message': _('You are moving %.2f products but only %.2f available in this lot.') % (product_qty, prodlot.stock_available or 0.0) } return {'warning': warning}
470,442
def preprocess_rml(self, root_node,type='pdf'): _regex1 = re.compile("\[\[(.*?)(repeatIn\(.*?\s*,\s*[\'\"].*?[\'\"]\s*(?:,\s*(.*?)\s*)?\s*\))(.*?)\]\]") _regex11= re.compile("\[\[(.*?)(repeatIn\(.*?\s*\(.*?\s*[\'\"].*?[\'\"]\s*\),[\'\"].*?[\'\"](?:,\s*(.*?)\s*)?\s*\))(.*?)\]\]") _regex2 = re.compile("\[\[(.*?)(removeParentNode\(\s*(?:['\"](.*?)['\"])\s*\))(.*?)\]\]") _regex3 = re.compile("\[\[\s*(.*?setTag\(\s*['\"](.*?)['\"]\s*,\s*['\"].*?['\"]\s*(?:,.*?)?\).*?)\s*\]\]") for node in root_node: if node.tag == etree.Comment: continue if node.text: def _sub3(txt): n = node while n.tag != txt.group(2): n = n.getparent() n.set('rml_tag', txt.group(1)) return "[[ '' ]]" def _sub2(txt): if txt.group(3): n = node try: while n.tag != txt.group(3): n = n.getparent() except: n = node else: n = node.getparent() n.set('rml_except', txt.group(0)[2:-2]) return txt.group(0) def _sub1(txt): if len(txt.group(4)) > 1: return " " match = rml_parents if type == 'odt': match = odt_parents if type == 'sxw': match = sxw_parents if type =='html2html': match = html_parents if txt.group(3): match = [txt.group(3)] n = node while n.tag not in match: n = n.getparent() n.set('rml_loop', txt.group(2)) return '[['+txt.group(1)+"''"+txt.group(4)+']]' t = _regex1.sub(_sub1, node.text) if t == " ": t = _regex11.sub(_sub1, node.text) t = _regex3.sub(_sub3, t) node.text = _regex2.sub(_sub2, t) self.preprocess_rml(node,type) return root_node
def preprocess_rml(self, root_node,type='pdf'): _regex1 = re.compile("\[\[(.*?)(repeatIn\(.*?\s*,\s*[\'\"].*?[\'\"]\s*(?:,\s*(.*?)\s*)?\s*\))(.*?)\]\]") _regex11= re.compile("\[\[(.*?)(repeatIn\(.*?\s*\(.*?\s*[\'\"].*?[\'\"]\s*\),[\'\"].*?[\'\"](?:,\s*(.*?)\s*)?\s*\))(.*?)\]\]") _regex2 = re.compile("\[\[(.*?)(removeParentNode\(\s*(?:['\"](.*?)['\"])\s*\))(.*?)\]\]") _regex3 = re.compile("\[\[\s*(.*?setTag\(\s*['\"](.*?)['\"]\s*,\s*['\"].*?['\"]\s*(?:,.*?)?\).*?)\s*\]\]") for node in root_node: if node.tag == etree.Comment: continue if node.text or node.tail: def _sub3(txt): n = node while n.tag != txt.group(2): n = n.getparent() n.set('rml_tag', txt.group(1)) return "[[ '' ]]" def _sub2(txt): if txt.group(3): n = node try: while n.tag != txt.group(3): n = n.getparent() except: n = node else: n = node.getparent() n.set('rml_except', txt.group(0)[2:-2]) return txt.group(0) def _sub1(txt): if len(txt.group(4)) > 1: return " " match = rml_parents if type == 'odt': match = odt_parents if type == 'sxw': match = sxw_parents if type =='html2html': match = html_parents if txt.group(3): match = [txt.group(3)] n = node while n.tag not in match: n = n.getparent() n.set('rml_loop', txt.group(2)) return '[['+txt.group(1)+"''"+txt.group(4)+']]' t = _regex1.sub(_sub1, node.text) if t == " ": t = _regex11.sub(_sub1, node.text) t = _regex3.sub(_sub3, t) node.text = _regex2.sub(_sub2, t) self.preprocess_rml(node,type) return root_node
470,443
def _sub1(txt): if len(txt.group(4)) > 1: return " " match = rml_parents if type == 'odt': match = odt_parents if type == 'sxw': match = sxw_parents if type =='html2html': match = html_parents if txt.group(3): match = [txt.group(3)] n = node while n.tag not in match: n = n.getparent() n.set('rml_loop', txt.group(2)) return '[['+txt.group(1)+"''"+txt.group(4)+']]'
def _sub1(txt): if len(txt.group(4)) > 1: return " " match = rml_parents if type == 'odt': match = odt_parents if type == 'sxw': match = sxw_parents if type =='html2html': match = html_parents if txt.group(3): match = [txt.group(3)] n = node while n.tag not in match: n = n.getparent() n.set('rml_loop', txt.group(2)) return '[['+txt.group(1)+"''"+txt.group(4)+']]'
470,444
def _sub1(txt): if len(txt.group(4)) > 1: return " " match = rml_parents if type == 'odt': match = odt_parents if type == 'sxw': match = sxw_parents if type =='html2html': match = html_parents if txt.group(3): match = [txt.group(3)] n = node while n.tag not in match: n = n.getparent() n.set('rml_loop', txt.group(2)) return '[['+txt.group(1)+"''"+txt.group(4)+']]'
def _sub1(txt): if len(txt.group(4)) > 1: return " " match = rml_parents if type == 'odt': match = odt_parents if type == 'sxw': match = sxw_parents if type =='html2html': match = html_parents if txt.group(3): match = [txt.group(3)] n = node while n.tag not in match: n = n.getparent() n.set('rml_loop', txt.group(2)) return '[['+txt.group(1)+"''"+txt.group(4)+']]'
470,445
def default_get(self, cr, uid, fields, context=None): """ To get default values for the object. @param self: The object pointer. @param cr: A database cursor @param uid: ID of the user currently logged in @param fields: List of fields for which we want default values @param context: A standard dictionary @return: A dictionary which of fields with values. """
def default_get(self, cr, uid, fields, context=None): """ To get default values for the object. @param self: The object pointer. @param cr: A database cursor @param uid: ID of the user currently logged in @param fields: List of fields for which we want default values @param context: A standard dictionary @return: A dictionary which of fields with values. """
470,446
def default_get(self, cr, uid, fields, context=None): """ To get default values for the object. @param self: The object pointer. @param cr: A database cursor @param uid: ID of the user currently logged in @param fields: List of fields for which we want default values @param context: A standard dictionary @return: A dictionary which of fields with values. """
def default_get(self, cr, uid, fields, context=None): """ To get default values for the object. @param self: The object pointer. @param cr: A database cursor @param uid: ID of the user currently logged in @param fields: List of fields for which we want default values @param context: A standard dictionary @return: A dictionary which of fields with values. """
470,447
def name_search(self, cr, user, name, args=None, operator='ilike', context=None, limit=100): if not args: args = [] if not context: context = {} args = args[:] ids = [] try: if name and str(name).startswith('partner:'): part_id = int(name.split(':')[1]) part = self.pool.get('res.partner').browse(cr, user, part_id, context) args += [('id', 'in', (part.property_account_payable.id, part.property_account_receivable.id))] name = False if name and str(name).startswith('type:'): type = name.split(':')[1] args += [('type', '=', type)] name = False except: pass if name: ids = self.search(cr, user, [('code', '=like', name+"%")]+args, limit=limit) if not ids: ids = self.search(cr, user, [('shortcut', '=', name)]+ args, limit=limit) if not ids: ids = self.search(cr, user, [('name', operator, name)]+ args, limit=limit) if not ids and len(name.split()) >= 2: ids = self.search(cr, user, [('code', operator, name.split()[0]), ('name', operator, name.split()[1])]+ args, limit=limit) else: ids = self.search(cr, user, args, context=context, limit=limit) return self.name_get(cr, user, ids, context=context)
def name_search(self, cr, user, name, args=None, operator='ilike', context=None, limit=100): if not args: args = [] if not context: context = {} args = args[:] ids = [] try: if name and str(name).startswith('partner:'): part_id = int(name.split(':')[1]) part = self.pool.get('res.partner').browse(cr, user, part_id, context) args += [('id', 'in', (part.property_account_payable.id, part.property_account_receivable.id))] name = False if name and str(name).startswith('type:'): type = name.split(':')[1] args += [('type', '=', type)] name = False except: pass if name: ids = self.search(cr, user, [('code', '=like', name+"%")]+args, limit=limit) if not ids: ids = self.search(cr, user, [('shortcut', '=', name)]+ args, limit=limit) if not ids: ids = self.search(cr, user, [('name', operator, name)]+ args, limit=limit) if not ids and len(name.split()) >= 2: operand1,operand2 = name.split(' ',1) ids = self.search(cr, user, [('code', operator, operand1), ('name', operator, operand2)]+ args, limit=limit) else: ids = self.search(cr, user, args, context=context, limit=limit) return self.name_get(cr, user, ids, context=context)
470,448
def email_send(email_from, email_to, subject, body, email_cc=None, email_bcc=None, reply_to=False, attach=None, openobject_id=False, ssl=False, debug=False, subtype='plain', x_headers=None, priority='3'): """Send an email.""" import smtplib from email.MIMEText import MIMEText from email.MIMEBase import MIMEBase from email.MIMEMultipart import MIMEMultipart from email.Header import Header from email.Utils import formatdate, COMMASPACE from email.Utils import formatdate, COMMASPACE from email import Encoders import netsvc if x_headers is None: x_headers = {} if not ssl: ssl = config.get('smtp_ssl', False) if not (email_from or config['email_from']): raise ValueError("Sending an email requires either providing a sender " "address or having configured one") if not email_from: email_from = config.get('email_from', False) if not email_cc: email_cc = [] if not email_bcc: email_bcc = [] if not body: body = u'' try: email_body = body.encode('utf-8') except (UnicodeEncodeError, UnicodeDecodeError): email_body = body email_text = MIMEText(mail_body, _subtype=subtype, _charset='utf-8') if attach: msg = MIMEMultipart() else: msg = email_text msg['Subject'] = Header(ustr(subject), 'utf-8') msg['From'] = email_from del msg['Reply-To'] if reply_to: msg['Reply-To'] = reply_to else: msg['Reply-To'] = msg['From'] msg['To'] = COMMASPACE.join(email_to) if email_cc: msg['Cc'] = COMMASPACE.join(email_cc) if email_bcc: msg['Bcc'] = COMMASPACE.join(email_bcc) msg['Date'] = formatdate(localtime=True) # Add OpenERP Server information msg['X-Generated-By'] = 'OpenERP (http://www.openerp.com)' msg['X-OpenERP-Server-Host'] = socket.gethostname() msg['X-OpenERP-Server-Version'] = release.version msg['X-Priority'] = priorities.get(priority, '3 (Normal)') # Add dynamic X Header for key, value in x_headers.iteritems(): msg['X-OpenERP-%s' % key] = str(value) if openobject_id: msg['Message-Id'] = "<%s-openobject-%s@%s>" % (time.time(), openobject_id, socket.gethostname()) if attach: msg.attach(email_text) for (fname,fcontent) in attach: part = MIMEBase('application', "octet-stream") part.set_payload( fcontent ) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % (fname,)) msg.attach(part) class WriteToLogger(object): def __init__(self): self.logger = netsvc.Logger() def write(self, s): self.logger.notifyChannel('email_send', netsvc.LOG_DEBUG, s) smtp_server = config['smtp_server'] if smtp_server.startswith('maildir:/'): from mailbox import Maildir maildir_path = smtp_server[8:] try: mdir = Maildir(maildir_path,factory=None, create = True) mdir.add(msg.as_string(True)) return True except Exception,e: netsvc.Logger().notifyChannel('email_send (maildir)', netsvc.LOG_ERROR, e) return False try: oldstderr = smtplib.stderr s = smtplib.SMTP() try: # in case of debug, the messages are printed to stderr. if debug: smtplib.stderr = WriteToLogger() s.set_debuglevel(int(bool(debug))) # 0 or 1 s.connect(smtp_server, config['smtp_port']) if ssl: s.ehlo() s.starttls() s.ehlo() if config['smtp_user'] or config['smtp_password']: s.login(config['smtp_user'], config['smtp_password']) s.sendmail(email_from, flatten([email_to, email_cc, email_bcc]), msg.as_string() ) finally: s.quit() if debug: smtplib.stderr = oldstderr except Exception, e: netsvc.Logger().notifyChannel('email_send', netsvc.LOG_ERROR, e) return False return True
def email_send(email_from, email_to, subject, body, email_cc=None, email_bcc=None, reply_to=False, attach=None, openobject_id=False, ssl=False, debug=False, subtype='plain', x_headers=None, priority='3'): """Send an email.""" import smtplib from email.MIMEText import MIMEText from email.MIMEBase import MIMEBase from email.MIMEMultipart import MIMEMultipart from email.Header import Header from email.Utils import formatdate, COMMASPACE from email.Utils import formatdate, COMMASPACE from email import Encoders import netsvc if x_headers is None: x_headers = {} if not ssl: ssl = config.get('smtp_ssl', False) if not (email_from or config['email_from']): raise ValueError("Sending an email requires either providing a sender " "address or having configured one") if not email_from: email_from = config.get('email_from', False) if not email_cc: email_cc = [] if not email_bcc: email_bcc = [] if not body: body = u'' try: email_body = body.encode('utf-8') except (UnicodeEncodeError, UnicodeDecodeError): email_body = body email_text = MIMEText(email_body, _subtype=subtype, _charset='utf-8') if attach: msg = MIMEMultipart() else: msg = email_text msg['Subject'] = Header(ustr(subject), 'utf-8') msg['From'] = email_from del msg['Reply-To'] if reply_to: msg['Reply-To'] = reply_to else: msg['Reply-To'] = msg['From'] msg['To'] = COMMASPACE.join(email_to) if email_cc: msg['Cc'] = COMMASPACE.join(email_cc) if email_bcc: msg['Bcc'] = COMMASPACE.join(email_bcc) msg['Date'] = formatdate(localtime=True) # Add OpenERP Server information msg['X-Generated-By'] = 'OpenERP (http://www.openerp.com)' msg['X-OpenERP-Server-Host'] = socket.gethostname() msg['X-OpenERP-Server-Version'] = release.version msg['X-Priority'] = priorities.get(priority, '3 (Normal)') # Add dynamic X Header for key, value in x_headers.iteritems(): msg['X-OpenERP-%s' % key] = str(value) if openobject_id: msg['Message-Id'] = "<%s-openobject-%s@%s>" % (time.time(), openobject_id, socket.gethostname()) if attach: msg.attach(email_text) for (fname,fcontent) in attach: part = MIMEBase('application', "octet-stream") part.set_payload( fcontent ) Encoders.encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % (fname,)) msg.attach(part) class WriteToLogger(object): def __init__(self): self.logger = netsvc.Logger() def write(self, s): self.logger.notifyChannel('email_send', netsvc.LOG_DEBUG, s) smtp_server = config['smtp_server'] if smtp_server.startswith('maildir:/'): from mailbox import Maildir maildir_path = smtp_server[8:] try: mdir = Maildir(maildir_path,factory=None, create = True) mdir.add(msg.as_string(True)) return True except Exception,e: netsvc.Logger().notifyChannel('email_send (maildir)', netsvc.LOG_ERROR, e) return False try: oldstderr = smtplib.stderr s = smtplib.SMTP() try: # in case of debug, the messages are printed to stderr. if debug: smtplib.stderr = WriteToLogger() s.set_debuglevel(int(bool(debug))) # 0 or 1 s.connect(smtp_server, config['smtp_port']) if ssl: s.ehlo() s.starttls() s.ehlo() if config['smtp_user'] or config['smtp_password']: s.login(config['smtp_user'], config['smtp_password']) s.sendmail(email_from, flatten([email_to, email_cc, email_bcc]), msg.as_string() ) finally: s.quit() if debug: smtplib.stderr = oldstderr except Exception, e: netsvc.Logger().notifyChannel('email_send', netsvc.LOG_ERROR, e) return False return True
470,449
def _makeOrder(self, cr, uid, data, context): pool = pooler.get_pool(cr.dbname) case_obj = pool.get('crm.case') sale_obj = pool.get('sale.order') partner_obj = pool.get('res.partner') sale_line_obj = pool.get('sale.order.line')
def _makeOrder(self, cr, uid, data, context): pool = pooler.get_pool(cr.dbname) case_obj = pool.get('crm.case') sale_obj = pool.get('sale.order') partner_obj = pool.get('res.partner') sale_line_obj = pool.get('sale.order.line')
470,450
def _makeOrder(self, cr, uid, data, context): pool = pooler.get_pool(cr.dbname) case_obj = pool.get('crm.case') sale_obj = pool.get('sale.order') partner_obj = pool.get('res.partner') sale_line_obj = pool.get('sale.order.line')
def _makeOrder(self, cr, uid, data, context): pool = pooler.get_pool(cr.dbname) case_obj = pool.get('crm.case') sale_obj = pool.get('sale.order') partner_obj = pool.get('res.partner') sale_line_obj = pool.get('sale.order.line')
470,451
def onchange_journal_id(self, cr, uid, ids, journal_id): if journal_id: journal = self.pool.get('account.journal').browse(cr, uid, journal_id) if journal.currency: result = {'value': { 'currency_id': journal.currency.id } } return result user_company = self.pool.get('res.users').browse(cr, uid, [uid])[0].company_id result = {'value': { 'currency_id': user_company.currency_id.id } } return result
def onchange_journal_id(self, cr, uid, ids, journal_id): if journal_id: journal = self.pool.get('account.journal').browse(cr, uid, journal_id) currency_id = journal.currency and journal.currency.id or journal.company_id.currency_id.id result = {'value': { 'currency_id': currency_id, } } return result user_company = self.pool.get('res.users').browse(cr, uid, [uid])[0].company_id result = {'value': { 'currency_id': user_company.currency_id.id } } return result
470,452
def onchange_journal_id(self, cr, uid, ids, journal_id): if journal_id: journal = self.pool.get('account.journal').browse(cr, uid, journal_id) if journal.currency: result = {'value': { 'currency_id': journal.currency.id } } return result user_company = self.pool.get('res.users').browse(cr, uid, [uid])[0].company_id result = {'value': { 'currency_id': user_company.currency_id.id } } return result
def onchange_journal_id(self, cr, uid, ids, journal_id): if journal_id: journal = self.pool.get('account.journal').browse(cr, uid, journal_id) if journal.currency: result = {'value': { 'currency_id': journal.currency.id } } return result
470,453
def name_search(self, cr, user, name, args=None, operator='ilike', context={}, limit=100): if not args: args = [] ids = [] if context.get('journal_type', False): args += [('type','=',context.get('journal_type'))]
def name_search(self, cr, user, name, args=None, operator='ilike', context=None, limit=100): if not args: args = [] ids = [] if context.get('journal_type', False): args += [('type','=',context.get('journal_type'))]
470,454
def name_search(self, cr, user, name, args=None, operator='ilike', context={}, limit=100): if not args: args = [] ids = [] if context.get('journal_type', False): args += [('type','=',context.get('journal_type'))]
defname_search(self,cr,user,name,args=None,operator='ilike',context={},limit=100):ifnotargs:args=[]ids=[]ifcontext.get('journal_type',False):args+=[('type','=',context.get('journal_type'))]
470,455
def name_search(self, cr, user, name, args=None, operator='ilike', context={}, limit=100): if not args: args = [] ids = [] if context.get('journal_type', False): args += [('type','=',context.get('journal_type'))]
def name_search(self, cr, user, name, args=None, operator='ilike', context={}, limit=100): if not args: args = [] ids = [] if context.get('journal_type', False): args += [('type','=',context.get('journal_type'))]
470,456
def _get_views(self, cr, uid, ids, field_name=None, arg=None, context={}): res = {} model_data_obj = self.pool.get('ir.model.data') view_obj = self.pool.get('ir.ui.view') report_obj = self.pool.get('ir.actions.report.xml') menu_obj = self.pool.get('ir.ui.menu') mlist = self.browse(cr, uid, ids, context=context) mnames = {} for m in mlist: mnames[m.name] = m.id res[m.id] = { 'menus_by_module':'', 'reports_by_module':'', 'views_by_module': '' } view_id = model_data_obj.search(cr,uid,[('module','in', mnames.keys()), ('model','in',('ir.ui.view','ir.actions.report.xml','ir.ui.menu'))]) for data_id in model_data_obj.browse(cr,uid,view_id,context): # We use try except, because views or menus may not exist try: key = data_id['model'] if key=='ir.ui.view': try: v = view_obj.browse(cr,uid,data_id.res_id) aa = v.inherit_id and '* INHERIT ' or '' res[mnames[data_id.module]]['views_by_module'] += aa + v.name + ' ('+v.type+')\n' except: pass elif key=='ir.actions.report.xml': res[mnames[data_id.module]]['reports_by_module'] += report_obj.browse(cr,uid,data_id.res_id).name + '\n' elif key=='ir.ui.menu': try: m = menu_obj.browse(cr,uid,data_id.res_id) res[mnames[data_id.module]]['menus_by_module'] += m.complete_name + '\n' except: pass except KeyError, e: pass return res
def _get_views(self, cr, uid, ids, field_name=None, arg=None, context={}): res = {} model_data_obj = self.pool.get('ir.model.data') view_obj = self.pool.get('ir.ui.view') report_obj = self.pool.get('ir.actions.report.xml') menu_obj = self.pool.get('ir.ui.menu') mlist = self.browse(cr, uid, ids, context=context) mnames = {} for m in mlist: mnames[m.name] = m.id res[m.id] = { 'menus_by_module':'', 'reports_by_module':'', 'views_by_module': '' } view_id = model_data_obj.search(cr,uid,[('module','in', mnames.keys()), ('model','in',('ir.ui.view','ir.actions.report.xml','ir.ui.menu'))]) for data_id in model_data_obj.browse(cr,uid,view_id,context): # We use try except, because views or menus may not exist try: key = data_id['model'] if key=='ir.ui.view': try: v = view_obj.browse(cr,uid,data_id.res_id) aa = v.inherit_id and '* INHERIT ' or '' res[mnames[data_id.module]]['views_by_module'] += aa + v.name + ' ('+v.type+')\n' except: pass elif key=='ir.actions.report.xml': res[mnames[data_id.module]]['reports_by_module'] += report_obj.browse(cr,uid,data_id.res_id).name + '\n' elif key=='ir.ui.menu': try: m = menu_obj.browse(cr,uid,data_id.res_id) res[mnames[data_id.module]]['menus_by_module'] += m.complete_name + '\n' except: pass except KeyError: pass return res
470,457
def download(self, cr, uid, ids, download=True, context=None): res = [] for mod in self.browse(cr, uid, ids, context=context): if not mod.url: continue match = re.search('-([a-zA-Z0-9\._-]+)(\.zip)', mod.url, re.I) version = '0' if match: version = match.group(1) if parse_version(mod.installed_version or '0') >= parse_version(version): continue res.append(mod.url) if not download: continue zipfile = urllib.urlopen(mod.url).read() fname = addons.get_module_path(str(mod.name)+'.zip', downloaded=True) try: fp = file(fname, 'wb') fp.write(zipfile) fp.close() except Exception, e: raise orm.except_orm(_('Error'), _('Can not create the module file:\n %s') % (fname,)) terp = self.get_module_info(mod.name) self.write(cr, uid, mod.id, self.get_values_from_terp(terp)) cr.execute('DELETE FROM ir_module_module_dependency ' \ 'WHERE module_id = %s', (mod.id,)) self._update_dependencies(cr, uid, mod.id, terp.get('depends', [])) self._update_category(cr, uid, mod.id, terp.get('category', 'Uncategorized')) # Import module zimp = zipimport.zipimporter(fname) zimp.load_module(mod.name) return res
def download(self, cr, uid, ids, download=True, context=None): res = [] for mod in self.browse(cr, uid, ids, context=context): if not mod.url: continue match = re.search('-([a-zA-Z0-9\._-]+)(\.zip)', mod.url, re.I) version = '0' if match: version = match.group(1) if parse_version(mod.installed_version or '0') >= parse_version(version): continue res.append(mod.url) if not download: continue zipfile = urllib.urlopen(mod.url).read() fname = addons.get_module_path(str(mod.name)+'.zip', downloaded=True) try: fp = file(fname, 'wb') fp.write(zipfile) fp.close() except Exception: raise orm.except_orm(_('Error'), _('Can not create the module file:\n %s') % (fname,)) terp = self.get_module_info(mod.name) self.write(cr, uid, mod.id, self.get_values_from_terp(terp)) cr.execute('DELETE FROM ir_module_module_dependency ' \ 'WHERE module_id = %s', (mod.id,)) self._update_dependencies(cr, uid, mod.id, terp.get('depends', [])) self._update_category(cr, uid, mod.id, terp.get('category', 'Uncategorized')) # Import module zimp = zipimport.zipimporter(fname) zimp.load_module(mod.name) return res
470,458
def read_group(self, cr, uid, domain, fields, groupby, offset=0, limit=None, orderby=False, context=None): raise NotImplementedError(_('The read_group method is not implemented on this object !'))
def read_group(self, cr, uid, domain, fields, groupby, offset=0, limit=None, context=None, orderby=False): raise NotImplementedError(_('The read_group method is not implemented on this object !'))
470,459
def read_group(self, cr, uid, domain, fields, groupby, offset=0, limit=None, orderby=False, context=None): """ Get the list of records in list view grouped by the given ``groupby`` fields
def read_group(self, cr, uid, domain, fields, groupby, offset=0, limit=None, context=None, orderby=False): """ Get the list of records in list view grouped by the given ``groupby`` fields
470,460
def sxw2rml(sxw_file, xsl, output='.', save_pict=False): import libxslt import libxml2 tool = PyOpenOffice(output, save_pict = save_pict) res = tool.unpackNormalize(sxw_file) styledoc = libxml2.parseDoc(xsl) style = libxslt.parseStylesheetDoc(styledoc) doc = libxml2.parseMemory(res,len(res)) result = style.applyStylesheet(doc, None) root = result.xpathEval("/document/stylesheet") if root: root=root[0] images = libxml2.newNode("images") for img in tool.images: node = libxml2.newNode('image') node.setProp('name', img) node.setContent( base64.encodestring(tool.images[img])) images.addChild(node) root.addNextSibling(images) try: xml = style.saveResultToString(result) return xml except: return result
def sxw2rml(sxw_file, xsl, output='.', save_pict=False): from lxml import etree from StringIO import StringIO tool = PyOpenOffice(output, save_pict = save_pict) res = tool.unpackNormalize(sxw_file) styledoc = libxml2.parseDoc(xsl) style = libxslt.parseStylesheetDoc(styledoc) doc = libxml2.parseMemory(res,len(res)) result = style.applyStylesheet(doc, None) root = result.xpathEval("/document/stylesheet") if root: root=root[0] images = libxml2.newNode("images") for img in tool.images: node = libxml2.newNode('image') node.setProp('name', img) node.setContent( base64.encodestring(tool.images[img])) images.addChild(node) root.addNextSibling(images) try: xml = style.saveResultToString(result) return xml except: return result
470,461
def sxw2rml(sxw_file, xsl, output='.', save_pict=False): import libxslt import libxml2 tool = PyOpenOffice(output, save_pict = save_pict) res = tool.unpackNormalize(sxw_file) styledoc = libxml2.parseDoc(xsl) style = libxslt.parseStylesheetDoc(styledoc) doc = libxml2.parseMemory(res,len(res)) result = style.applyStylesheet(doc, None) root = result.xpathEval("/document/stylesheet") if root: root=root[0] images = libxml2.newNode("images") for img in tool.images: node = libxml2.newNode('image') node.setProp('name', img) node.setContent( base64.encodestring(tool.images[img])) images.addChild(node) root.addNextSibling(images) try: xml = style.saveResultToString(result) return xml except: return result
def sxw2rml(sxw_file, xsl, output='.', save_pict=False): import libxslt import libxml2 tool = PyOpenOffice(output, save_pict = save_pict) res = tool.unpackNormalize(sxw_file) f = StringIO(xsl) styledoc = etree.parse(f) style = etree.XSLT(styledoc) f = StringIO(res) doc = etree.parse(f) result = style(doc) root = etree.XPathEvaluator(result)("/document/stylesheet") if root: root=root[0] images = libxml2.newNode("images") for img in tool.images: node = libxml2.newNode('image') node.setProp('name', img) node.setContent( base64.encodestring(tool.images[img])) images.addChild(node) root.addNextSibling(images) try: xml = style.saveResultToString(result) return xml except: return result
470,462
def sxw2rml(sxw_file, xsl, output='.', save_pict=False): import libxslt import libxml2 tool = PyOpenOffice(output, save_pict = save_pict) res = tool.unpackNormalize(sxw_file) styledoc = libxml2.parseDoc(xsl) style = libxslt.parseStylesheetDoc(styledoc) doc = libxml2.parseMemory(res,len(res)) result = style.applyStylesheet(doc, None) root = result.xpathEval("/document/stylesheet") if root: root=root[0] images = libxml2.newNode("images") for img in tool.images: node = libxml2.newNode('image') node.setProp('name', img) node.setContent( base64.encodestring(tool.images[img])) images.addChild(node) root.addNextSibling(images) try: xml = style.saveResultToString(result) return xml except: return result
def sxw2rml(sxw_file, xsl, output='.', save_pict=False): import libxslt import libxml2 tool = PyOpenOffice(output, save_pict = save_pict) res = tool.unpackNormalize(sxw_file) styledoc = libxml2.parseDoc(xsl) style = libxslt.parseStylesheetDoc(styledoc) doc = libxml2.parseMemory(res,len(res)) result = style.applyStylesheet(doc, None) root = result.xpathEval("/document/stylesheet") if root: root=root[0] images = etree.Element("images") for img in tool.images: node = libxml2.newNode('image') node.setProp('name', img) node.setContent( base64.encodestring(tool.images[img])) images.addChild(node) root.addNextSibling(images) try: xml = style.saveResultToString(result) return xml except: return result
470,463
def sxw2rml(sxw_file, xsl, output='.', save_pict=False): import libxslt import libxml2 tool = PyOpenOffice(output, save_pict = save_pict) res = tool.unpackNormalize(sxw_file) styledoc = libxml2.parseDoc(xsl) style = libxslt.parseStylesheetDoc(styledoc) doc = libxml2.parseMemory(res,len(res)) result = style.applyStylesheet(doc, None) root = result.xpathEval("/document/stylesheet") if root: root=root[0] images = libxml2.newNode("images") for img in tool.images: node = libxml2.newNode('image') node.setProp('name', img) node.setContent( base64.encodestring(tool.images[img])) images.addChild(node) root.addNextSibling(images) try: xml = style.saveResultToString(result) return xml except: return result
def sxw2rml(sxw_file, xsl, output='.', save_pict=False): import libxslt import libxml2 tool = PyOpenOffice(output, save_pict = save_pict) res = tool.unpackNormalize(sxw_file) styledoc = libxml2.parseDoc(xsl) style = libxslt.parseStylesheetDoc(styledoc) doc = libxml2.parseMemory(res,len(res)) result = style.applyStylesheet(doc, None) root = result.xpathEval("/document/stylesheet") if root: root=root[0] images = libxml2.newNode("images") for img in tool.images: node = etree.Element('image', name=img) node.text = base64.encodestring(tool.images[img]) images.append(node) root.append(images) try: xml = style.saveResultToString(result) return xml except: return result
470,464
def sxw2rml(sxw_file, xsl, output='.', save_pict=False): import libxslt import libxml2 tool = PyOpenOffice(output, save_pict = save_pict) res = tool.unpackNormalize(sxw_file) styledoc = libxml2.parseDoc(xsl) style = libxslt.parseStylesheetDoc(styledoc) doc = libxml2.parseMemory(res,len(res)) result = style.applyStylesheet(doc, None) root = result.xpathEval("/document/stylesheet") if root: root=root[0] images = libxml2.newNode("images") for img in tool.images: node = libxml2.newNode('image') node.setProp('name', img) node.setContent( base64.encodestring(tool.images[img])) images.addChild(node) root.addNextSibling(images) try: xml = style.saveResultToString(result) return xml except: return result
def sxw2rml(sxw_file, xsl, output='.', save_pict=False): import libxslt import libxml2 tool = PyOpenOffice(output, save_pict = save_pict) res = tool.unpackNormalize(sxw_file) styledoc = libxml2.parseDoc(xsl) style = libxslt.parseStylesheetDoc(styledoc) doc = libxml2.parseMemory(res,len(res)) result = style.applyStylesheet(doc, None) root = result.xpathEval("/document/stylesheet") if root: root=root[0] images = libxml2.newNode("images") for img in tool.images: node = libxml2.newNode('image') node.setProp('name', img) node.setContent( base64.encodestring(tool.images[img])) images.addChild(node) root.addNextSibling(images) try: xml = str(result) return xml except: return result
470,465
def sxw2rml(sxw_file, xsl, output='.', save_pict=False): import libxslt import libxml2 tool = PyOpenOffice(output, save_pict = save_pict) res = tool.unpackNormalize(sxw_file) styledoc = libxml2.parseDoc(xsl) style = libxslt.parseStylesheetDoc(styledoc) doc = libxml2.parseMemory(res,len(res)) result = style.applyStylesheet(doc, None) root = result.xpathEval("/document/stylesheet") if root: root=root[0] images = libxml2.newNode("images") for img in tool.images: node = libxml2.newNode('image') node.setProp('name', img) node.setContent( base64.encodestring(tool.images[img])) images.addChild(node) root.addNextSibling(images) try: xml = style.saveResultToString(result) return xml except: return result
def sxw2rml(sxw_file, xsl, output='.', save_pict=False): import libxslt import libxml2 tool = PyOpenOffice(output, save_pict = save_pict) res = tool.unpackNormalize(sxw_file) styledoc = libxml2.parseDoc(xsl) style = libxslt.parseStylesheetDoc(styledoc) doc = libxml2.parseMemory(res,len(res)) result = style.applyStylesheet(doc, None) root = result.xpathEval("/document/stylesheet") if root: root=root[0] images = libxml2.newNode("images") for img in tool.images: node = libxml2.newNode('image') node.setProp('name', img) node.setContent( base64.encodestring(tool.images[img])) images.addChild(node) root.addNextSibling(images) try: xml = style.saveResultToString(result) return xml except: return result
470,466
def split(self, cr, uid, ids, move_ids, context=None): """ To split stock moves into production lot @param self: The object pointer. @param cr: A database cursor @param uid: ID of the user currently logged in @param ids: the ID or list of IDs if we want more than one @param move_ids: the ID or list of IDs of stock move we want to split @param context: A standard dictionary @return: """ prodlot_obj = self.pool.get('stock.production.lot') ir_sequence_obj = self.pool.get('ir.sequence') move_obj = self.pool.get('stock.move') new_move = [] for data in self.browse(cr, uid, ids): for move in move_obj.browse(cr, uid, move_ids): move_qty = move.product_qty quantity_rest = move.product_qty uos_qty_rest = move.product_uos_qty new_move = [] for line in data.line_ids: quantity = line.quantity
def split(self, cr, uid, ids, move_ids, context=None): """ To split stock moves into production lot @param self: The object pointer. @param cr: A database cursor @param uid: ID of the user currently logged in @param ids: the ID or list of IDs if we want more than one @param move_ids: the ID or list of IDs of stock move we want to split @param context: A standard dictionary @return: """ prodlot_obj = self.pool.get('stock.production.lot') ir_sequence_obj = self.pool.get('ir.sequence') move_obj = self.pool.get('stock.move') new_move = [] for data in self.browse(cr, uid, ids): for move in move_obj.browse(cr, uid, move_ids): move_qty = move.product_qty quantity_rest = move.product_qty uos_qty_rest = move.product_uos_qty new_move = [] for line in data.line_ids: quantity = line.quantity
470,467
def split(self, cr, uid, ids, move_ids, context=None): """ To split stock moves into production lot @param self: The object pointer. @param cr: A database cursor @param uid: ID of the user currently logged in @param ids: the ID or list of IDs if we want more than one @param move_ids: the ID or list of IDs of stock move we want to split @param context: A standard dictionary @return: """ prodlot_obj = self.pool.get('stock.production.lot') ir_sequence_obj = self.pool.get('ir.sequence') move_obj = self.pool.get('stock.move') new_move = [] for data in self.browse(cr, uid, ids): for move in move_obj.browse(cr, uid, move_ids): move_qty = move.product_qty quantity_rest = move.product_qty uos_qty_rest = move.product_uos_qty new_move = [] for line in data.line_ids: quantity = line.quantity
def split(self, cr, uid, ids, move_ids, context=None): """ To split stock moves into production lot @param self: The object pointer. @param cr: A database cursor @param uid: ID of the user currently logged in @param ids: the ID or list of IDs if we want more than one @param move_ids: the ID or list of IDs of stock move we want to split @param context: A standard dictionary @return: """ prodlot_obj = self.pool.get('stock.production.lot') ir_sequence_obj = self.pool.get('ir.sequence') move_obj = self.pool.get('stock.move') new_move = [] for data in self.browse(cr, uid, ids): for move in move_obj.browse(cr, uid, move_ids): move_qty = move.product_qty quantity_rest = move.product_qty uos_qty_rest = move.product_uos_qty new_move = [] for line in data.line_ids: quantity = line.quantity
470,468
def get_module_from_path(path,mod_paths=None): if not mod_paths: # First, construct a list of possible paths def_path = os.path.abspath(os.path.join(tools.config['root_path'], 'addons')) # default addons path (base) ad_paths= map(lambda m: os.path.abspath(m.strip()),tools.config['addons_path'].split(',')) mod_paths=[def_path] for adp in ad_paths: mod_paths.append(adp) if not adp.startswith('/'): mod_paths.append(os.path.join(def_path,adp)) elif adp.startswith(def_path): mod_paths.append(adp[len(def_path)+1:])
def get_module_from_path(path,mod_paths=None): if not mod_paths: # First, construct a list of possible paths def_path = os.path.abspath(os.path.join(tools.config['root_path'], 'addons')) # default addons path (base) ad_paths= map(lambda m: os.path.abspath(m.strip()),tools.config['addons_path'].split(',')) mod_paths=[def_path] for adp in ad_paths: mod_paths.append(adp) if not adp.startswith('/'): mod_paths.append(os.path.join(def_path,adp)) elif adp.startswith(def_path): mod_paths.append(adp[len(def_path)+1:])
470,469
def get_module_from_path(path,mod_paths=None): if not mod_paths: # First, construct a list of possible paths def_path = os.path.abspath(os.path.join(tools.config['root_path'], 'addons')) # default addons path (base) ad_paths= map(lambda m: os.path.abspath(m.strip()),tools.config['addons_path'].split(',')) mod_paths=[def_path] for adp in ad_paths: mod_paths.append(adp) if not adp.startswith('/'): mod_paths.append(os.path.join(def_path,adp)) elif adp.startswith(def_path): mod_paths.append(adp[len(def_path)+1:])
def get_module_from_path(path,mod_paths=None): if not mod_paths: # First, construct a list of possible paths def_path = os.path.abspath(os.path.join(tools.config['root_path'], 'addons')) # default addons path (base) ad_paths= map(lambda m: os.path.abspath(m.strip()),tools.config['addons_path'].split(',')) mod_paths=[def_path] for adp in ad_paths: mod_paths.append(adp) if not adp.startswith('/'): mod_paths.append(os.path.join(def_path,adp)) elif adp.startswith(def_path): mod_paths.append(adp[len(def_path)+1:])
470,470
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
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
470,471
def _get_move_lines(self, cr, uid, ids, context=None): result = [] for move in self.pool.get('account.move').browse(cr, uid, ids, context=context): for line in move.line_id: result.append(line.id) return result
def _get_move_lines(self, cr, uid, ids, context=None): result = [] for move in self.pool.get('account.move').browse(cr, uid, ids, context=context): for line in move.line_id: result.append(line.id) return result
470,472
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)
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)
470,473
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)
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)
470,474
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)
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)
470,475
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)
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)
470,476
def post(self, cr, uid, ids, context=None): obj_sequence = self.pool.get('ir.sequence') res = super(account_move, self).post(cr, uid, ids, context=context) seq_no = False for line in self.browse(cr, uid, ids): if line.journal_id.internal_sequence: seq_no = obj_sequence.get_id(cr, uid, line.journal_id.internal_sequence.id, context=context) if seq_no: self.write(cr, uid, [line.id], {'internal_sequence_number': seq_no}) return res
def post(self, cr, uid, ids, context=None): obj_sequence = self.pool.get('ir.sequence') res = super(account_move, self).post(cr, uid, ids, context=context) seq_no = False for move in self.browse(cr, uid, ids, context): if move.journal_id.internal_sequence_id: seq_no = obj_sequence.get_id(cr, uid, move.journal_id.internal_sequence_id.id, context=context) if seq_no: self.write(cr, uid, [line.id], {'internal_sequence_number': seq_no}) return res
470,477
def post(self, cr, uid, ids, context=None): obj_sequence = self.pool.get('ir.sequence') res = super(account_move, self).post(cr, uid, ids, context=context) seq_no = False for line in self.browse(cr, uid, ids): if line.journal_id.internal_sequence: seq_no = obj_sequence.get_id(cr, uid, line.journal_id.internal_sequence.id, context=context) if seq_no: self.write(cr, uid, [line.id], {'internal_sequence_number': seq_no}) return res
def post(self, cr, uid, ids, context=None): obj_sequence = self.pool.get('ir.sequence') res = super(account_move, self).post(cr, uid, ids, context=context) seq_no = False for line in self.browse(cr, uid, ids): if line.journal_id.internal_sequence: seq_no = obj_sequence.get_id(cr, uid, line.journal_id.internal_sequence.id, context=context) if seq_no: self.write(cr, uid, [move.id], {'internal_sequence_number': seq_no}) return res
470,478
def action_send(self, cr, uid, ids, context=None): """ This sends an email to ALL the addresses of the selected partners. """
def action_send(self, cr, uid, ids, context=None): """ This sends an email to ALL the addresses of the selected partners. """
470,479
def createInstance(cls, pool, module, cr): parent_names = getattr(cls, '_inherit', None) if parent_names: if isinstance(parent_names, (str, unicode)): name = cls._name or parent_name parent_names = [parent_names] else: name = cls._name if not name: raise TypeError('_name is mandatory in case of multiple inheritance')
def createInstance(cls, pool, module, cr): parent_names = getattr(cls, '_inherit', None) if parent_names: if isinstance(parent_names, (str, unicode)): name = cls._name or parent_names parent_names = [parent_names] else: name = cls._name if not name: raise TypeError('_name is mandatory in case of multiple inheritance')
470,480
def createInstance(cls, pool, module, cr): parent_names = getattr(cls, '_inherit', None) if parent_names: if isinstance(parent_names, (str, unicode)): name = cls._name or parent_name parent_names = [parent_names] else: name = cls._name if not name: raise TypeError('_name is mandatory in case of multiple inheritance')
def createInstance(cls, pool, module, cr): parent_names = getattr(cls, '_inherit', None) if parent_names: if isinstance(parent_names, (str, unicode)): name = cls._name or parent_names parent_names = [parent_names] else: name = cls._name if not name: raise TypeError('_name is mandatory in case of multiple inheritance')
470,481
def formatLang(self, value, digits=2, date=False,date_time=False, grouping=True, monetary=False): if isinstance(value, (str, unicode)) and not value: return '' if not self.lang_dict_called: self._get_lang_dict() self.lang_dict_called = True
def formatLang(self, value, digits=2, date=False,date_time=False, grouping=True, monetary=False): if isinstance(value, (str, unicode)) and not value: return '' if not self.lang_dict_called: self._get_lang_dict() self.lang_dict_called = True
470,482
def product_id_change(self, cr, uid, ids, pricelist, product, qty=0, uom=False, qty_uos=0, uos=False, name='', partner_id=False, lang=False, update_tax=True, date_order=False, packaging=False, fiscal_position=False, flag=False): res = super(sale_order_line, self).product_id_change(cr, uid, ids, pricelist, product, qty=qty, uom=uom, qty_uos=qty_uos, uos=uos, name=name, partner_id=partner_id, lang=lang, update_tax=update_tax, date_order=date_order, packaging=packaging, fiscal_position=fiscal_position, flag=flag) if product: purchase_price = self.pool.get('product.product').browse(cr, uid, product).standard_price res['value'].update({'purchase_price': purchase_price}) return res
def product_id_change(self, cr, uid, ids, pricelist, product, qty=0, uom=False, qty_uos=0, uos=False, name='', partner_id=False, lang=False, update_tax=True, date_order=False, packaging=False, fiscal_position=False, flag=False): res = super(sale_order_line, self).product_id_change(cr, uid, ids, pricelist, product, qty=qty, uom=uom, qty_uos=qty_uos, uos=uos, name=name, partner_id=partner_id, lang=lang, update_tax=update_tax, date_order=date_order, packaging=packaging, fiscal_position=fiscal_position, flag=flag) if product: purchase_price = self.pool.get('product.product').browse(cr, uid, product).standard_price price = self.pool.get('res.currency').compute(cr, uid, frm_cur, to_cur, purchase_price, round=False) res['value'].update({'purchase_price': price}) return res
470,483
fields_def = self.fields_get(cr, uid, context=context)
fields_def = self.fields_get(cr, uid, context=context)
470,484
def _get_writeoff_amount(self, cr, uid, ids, name, args, context=None): if not ids: return {} res = {} debit = credit = 0.0 for voucher in self.browse(cr, uid, ids, context=context): for l in voucher.line_dr_ids: debit += l.amount for l in voucher.line_cr_ids: credit += l.amount res[voucher.id] = abs(voucher.amount - abs(credit - debit)) return res
def _get_writeoff_amount(self, cr, uid, ids, name, args, context=None): if not ids: return {} res = {} debit = credit = 0.0 for voucher in self.browse(cr, uid, ids, context=context): for l in voucher.line_dr_ids: debit += l.amount for l in voucher.line_cr_ids: credit += l.amount res[voucher.id] = abs(voucher.amount - abs(credit - debit)) return res
470,485
def _compute_balance(self, cr, uid, ids, name, args, context=None): currency_pool = self.pool.get('res.currency') rs_data = {} for line in self.browse(cr, uid, ids): res = {} company_currency = line.voucher_id.journal_id.company_id.currency_id.id voucher_currency = line.voucher_id.currency_id.id move_line = line.move_line_id or False
def _compute_balance(self, cr, uid, ids, name, args, context=None): currency_pool = self.pool.get('res.currency') rs_data = {} for line in self.browse(cr, uid, ids): res = {} company_currency = line.voucher_id.journal_id.company_id.currency_id.id voucher_currency = line.voucher_id.currency_id.id move_line = line.move_line_id or False
470,486
def _store_set_values(self, cr, uid, ids, fields, context): field_flag = False field_dict = {} if self._log_access: cr.execute('select id,write_date from '+self._table+' where id in ('+','.join(map(str, ids))+')') res = cr.fetchall() for r in res: if r[1]: field_dict.setdefault(r[0], []) res_date = time.strptime((r[1])[:19], '%Y-%m-%d %H:%M:%S') write_date = datetime.datetime.fromtimestamp(time.mktime(res_date)) for i in self.pool._store_function.get(self._name, []): if i[5]: up_write_date = write_date + datetime.timedelta(hours=i[5]) if datetime.datetime.now() < up_write_date: if i[1] in fields: field_dict[r[0]].append(i[1]) if not field_flag: field_flag = True todo = {} keys = [] for f in fields: if self._columns[f]._multi not in keys: keys.append(self._columns[f]._multi) todo.setdefault(self._columns[f]._multi, []) todo[self._columns[f]._multi].append(f) for key in keys: val = todo[key] if key: # uid == 1 for accessing objects having rules defined on store fields result = self._columns[val[0]].get(cr, self, ids, val, 1, context=context) for id,value in result.items(): if field_flag: for f in value.keys(): if f in field_dict[id]: value.pop(f) upd0 = [] upd1 = [] for v in value: if v not in val: continue if self._columns[v]._type in ('many2one', 'one2one'): try: value[v] = value[v][0] except: pass upd0.append('"'+v+'"='+self._columns[v]._symbol_set[0]) upd1.append(self._columns[v]._symbol_set[1](value[v])) upd1.append(id) cr.execute('update "' + self._table + '" set ' + \ string.join(upd0, ',') + ' where id = %s', upd1)
def _store_set_values(self, cr, uid, ids, fields, context): field_flag = False field_dict = {} if self._log_access: cr.execute('select id,write_date from '+self._table+' where id in ('+','.join(map(str, ids))+')') res = cr.fetchall() for r in res: if r[1]: field_dict.setdefault(r[0], []) res_date = time.strptime((r[1])[:19], '%Y-%m-%d %H:%M:%S') write_date = datetime.datetime.fromtimestamp(time.mktime(res_date)) for i in self.pool._store_function.get(self._name, []): if i[5]: up_write_date = write_date + datetime.timedelta(hours=i[5]) if datetime.datetime.now() < up_write_date: if i[1] in fields: field_dict[r[0]].append(i[1]) if not field_flag: field_flag = True todo = {} keys = [] for f in fields: if self._columns[f]._multi not in keys: keys.append(self._columns[f]._multi) todo.setdefault(self._columns[f]._multi, []) todo[self._columns[f]._multi].append(f) for key in keys: val = todo[key] if key: # uid == 1 for accessing objects having rules defined on store fields result = self._columns[val[0]].get(cr, self, ids, val, 1, context=context) for id,value in result.items(): if field_flag: for f in value.keys(): if f in field_dict[id]: value.pop(f) upd0 = [] upd1 = [] for v in value: if v not in val: continue if self._columns[v]._type in ('many2one', 'one2one'): try: value[v] = value[v][0] except: pass upd0.append('"'+v+'"='+self._columns[v]._symbol_set[0]) upd1.append(self._columns[v]._symbol_set[1](value[v])) upd1.append(id) cr.execute('update "' + self._table + '" set ' + \ string.join(upd0, ',') + ' where id = %s', upd1)
470,487
def action_consume(self, cr, uid, ids, quantity, location_id=False, context=None): """ Consumed product with specific quatity from specific source location @param cr: the database cursor @param uid: the user id @param ids: ids of stock move object to be consumed @param quantity : specify consume quantity @param location_id : specify source location @param context: context arguments @return: Consumed lines """ if context is None: context = {} if quantity <= 0: raise osv.except_osv(_('Warning!'), _('Please provide Proper Quantity !'))
defaction_consume(self,cr,uid,ids,quantity,location_id=False,context=None):"""Consumedproductwithspecificquatityfromspecificsourcelocation@paramcr:thedatabasecursor@paramuid:theuserid@paramids:idsofstockmoveobjecttobeconsumed@paramquantity:specifyconsumequantity@paramlocation_id:specifysourcelocation@paramcontext:contextarguments@return:Consumedlines"""ifcontextisNone:context={}ifquantity<=0:raiseosv.except_osv(_('Warning!'),_('PleaseprovideProperQuantity!'))
470,488
def action_consume(self, cr, uid, ids, quantity, location_id=False, context=None): """ Consumed product with specific quatity from specific source location @param cr: the database cursor @param uid: the user id @param ids: ids of stock move object to be consumed @param quantity : specify consume quantity @param location_id : specify source location @param context: context arguments @return: Consumed lines """ if context is None: context = {} if quantity <= 0: raise osv.except_osv(_('Warning!'), _('Please provide Proper Quantity !'))
defaction_consume(self,cr,uid,ids,quantity,location_id=False,context=None):"""Consumedproductwithspecificquatityfromspecificsourcelocation@paramcr:thedatabasecursor@paramuid:theuserid@paramids:idsofstockmoveobjecttobeconsumed@paramquantity:specifyconsumequantity@paramlocation_id:specifysourcelocation@paramcontext:contextarguments@return:Consumedlines"""ifcontextisNone:context={}ifquantity<=0:raiseosv.except_osv(_('Warning!'),_('PleaseprovideProperQuantity!'))
470,489
def action_consume(self, cr, uid, ids, quantity, location_id=False, context=None): """ Consumed product with specific quatity from specific source location @param cr: the database cursor @param uid: the user id @param ids: ids of stock move object to be consumed @param quantity : specify consume quantity @param location_id : specify source location @param context: context arguments @return: Consumed lines """ if context is None: context = {} if quantity <= 0: raise osv.except_osv(_('Warning!'), _('Please provide Proper Quantity !'))
def action_consume(self, cr, uid, ids, quantity, location_id=False, context=None): """ Consumed product with specific quatity from specific source location @param cr: the database cursor @param uid: the user id @param ids: ids of stock move object to be consumed @param quantity : specify consume quantity @param location_id : specify source location @param context: context arguments @return: Consumed lines """ if context is None: context = {} if quantity <= 0: raise osv.except_osv(_('Warning!'), _('Please provide Proper Quantity !'))
470,490
def action_consume(self, cr, uid, ids, quantity, location_id=False, context=None): """ Consumed product with specific quatity from specific source location @param cr: the database cursor @param uid: the user id @param ids: ids of stock move object to be consumed @param quantity : specify consume quantity @param location_id : specify source location @param context: context arguments @return: Consumed lines """ if context is None: context = {} if quantity <= 0: raise osv.except_osv(_('Warning!'), _('Please provide Proper Quantity !'))
def action_consume(self, cr, uid, ids, quantity, location_id=False, context=None): """ Consumed product with specific quatity from specific source location @param cr: the database cursor @param uid: the user id @param ids: ids of stock move object to be consumed @param quantity : specify consume quantity @param location_id : specify source location @param context: context arguments @return: Consumed lines """ if context is None: context = {} if quantity <= 0: raise osv.except_osv(_('Warning!'), _('Please provide Proper Quantity !'))
470,491
def load_module_graph(cr, graph, status=None, perform_checks=True, **kwargs): # **kwargs is passed directly to convert_xml_import if not status: status = {} status = status.copy() package_todo = [] statusi = 0 pool = pooler.get_pool(cr.dbname) migrations = MigrationManager(cr, graph) has_updates = False modobj = None logger.notifyChannel('init', netsvc.LOG_DEBUG, 'loading %d packages..' % len(graph)) for package in graph: logger.notifyChannel('init', netsvc.LOG_INFO, 'module %s: loading objects' % package.name) migrations.migrate_module(package, 'pre') register_class(package.name) modules = pool.instanciate(package.name, cr) if hasattr(package, 'init') or hasattr(package, 'update') or package.state in ('to install', 'to upgrade'): init_module_objects(cr, package.name, modules) cr.commit() for package in graph: status['progress'] = (float(statusi)+0.1) / len(graph) m = package.name mid = package.id if modobj is None: modobj = pool.get('ir.module.module') if modobj and perform_checks: modobj.check(cr, 1, [mid]) idref = {} status['progress'] = (float(statusi)+0.4) / len(graph) mode = 'update' if hasattr(package, 'init') or package.state == 'to install': mode = 'init' if hasattr(package, 'init') or hasattr(package, 'update') or package.state in ('to install', 'to upgrade'): has_updates = True for kind in ('init', 'update'): if package.state=='to upgrade': # upgrading the module information modobj.write(cr, 1, [mid], { 'description': package.data.get('description', ''), 'shortdesc': package.data.get('name', ''), 'author': package.data.get('author', 'Unknown'), 'website': package.data.get('website', ''), 'license': package.data.get('license', 'GPL-2'), 'certificate': package.data.get('certificate') or None, }) for filename in package.data.get('%s_xml' % kind, []): logger.notifyChannel('init', netsvc.LOG_INFO, 'module %s: loading %s' % (m, filename)) name, ext = os.path.splitext(filename) fp = tools.file_open(opj(m, filename)) if ext == '.csv': noupdate=False if kind == 'init': noupdate=True tools.convert_csv_import(cr, m, os.path.basename(filename), fp.read(), idref, mode=mode, noupdate=noupdate) elif ext == '.sql': queries = fp.read().split(';') for query in queries: new_query = ' '.join(query.split()) if new_query: cr.execute(new_query) elif ext == '.yaml': tools.convert_yaml_import(cr, m, fp, idref, mode=mode, **kwargs) else: tools.convert_xml_import(cr, m, fp, idref, mode=mode, **kwargs) fp.close() if hasattr(package, 'demo') or (package.dbdemo and package.state != 'installed'): status['progress'] = (float(statusi)+0.75) / len(graph) for xml in package.data.get('demo_xml', []): name, ext = os.path.splitext(xml) logger.notifyChannel('init', netsvc.LOG_INFO, 'module %s: loading %s' % (m, xml)) fp = tools.file_open(opj(m, xml)) if ext == '.csv': tools.convert_csv_import(cr, m, os.path.basename(xml), fp.read(), idref, mode=mode, noupdate=True) else: tools.convert_xml_import(cr, m, fp, idref, mode=mode, noupdate=True, **kwargs) fp.close() cr.execute('update ir_module_module set demo=%s where id=%s', (True, mid)) package_todo.append(package.name) migrations.migrate_module(package, 'post') if modobj: ver = release.major_version + '.' + package.data.get('version', '1.0') # Set new modules and dependencies modobj.write(cr, 1, [mid], {'state': 'installed', 'latest_version': ver}) cr.commit() # Update translations for all installed languages modobj.update_translations(cr, 1, [mid], None) cr.commit() package.state = 'installed' for kind in ('init', 'demo', 'update'): if hasattr(package, kind): delattr(package, kind) statusi += 1 cr.execute('select model from ir_model where state=%s', ('manual',)) for model in cr.dictfetchall(): pool.get('ir.model').instanciate(cr, 1, model['model'], {}) pool.get('ir.model.data')._process_end(cr, 1, package_todo) cr.commit() return has_updates
def load_module_graph(cr, graph, status=None, perform_checks=True, **kwargs): # **kwargs is passed directly to convert_xml_import if not status: status = {} status = status.copy() package_todo = [] statusi = 0 pool = pooler.get_pool(cr.dbname) migrations = MigrationManager(cr, graph) has_updates = False modobj = None logger.notifyChannel('init', netsvc.LOG_DEBUG, 'loading %d packages..' % len(graph)) for package in graph: logger.notifyChannel('init', netsvc.LOG_INFO, 'module %s: loading objects' % package.name) migrations.migrate_module(package, 'pre') register_class(package.name) modules = pool.instanciate(package.name, cr) if hasattr(package, 'init') or hasattr(package, 'update') or package.state in ('to install', 'to upgrade'): init_module_objects(cr, package.name, modules) cr.commit() for package in graph: status['progress'] = (float(statusi)+0.1) / len(graph) m = package.name mid = package.id if modobj is None: modobj = pool.get('ir.module.module') if modobj and perform_checks: modobj.check(cr, 1, [mid]) idref = {} status['progress'] = (float(statusi)+0.4) / len(graph) mode = 'update' if hasattr(package, 'init') or package.state == 'to install': mode = 'init' if hasattr(package, 'init') or hasattr(package, 'update') or package.state in ('to install', 'to upgrade'): has_updates = True for kind in ('init', 'update'): if package.state=='to upgrade': # upgrading the module information modobj.write(cr, 1, [mid], { 'description': package.data.get('description', ''), 'shortdesc': package.data.get('name', ''), 'author': package.data.get('author', 'Unknown'), 'website': package.data.get('website', ''), 'license': package.data.get('license', 'GPL-2'), 'certificate': package.data.get('certificate') or None, }) for filename in package.data.get('%s_xml' % kind, []): logger.notifyChannel('init', netsvc.LOG_INFO, 'module %s: loading %s' % (m, filename)) name, ext = os.path.splitext(filename) fp = tools.file_open(opj(m, filename)) if ext == '.csv': noupdate=False if kind == 'init': noupdate=True tools.convert_csv_import(cr, m, os.path.basename(filename), fp.read(), idref, mode=mode, noupdate=noupdate) elif ext == '.sql': queries = fp.read().split(';') for query in queries: new_query = ' '.join(query.split()) if new_query: cr.execute(new_query) elif ext == '.yml': tools.convert_yaml_import(cr, m, fp, idref, mode=mode, **kwargs) else: tools.convert_xml_import(cr, m, fp, idref, mode=mode, **kwargs) fp.close() if hasattr(package, 'demo') or (package.dbdemo and package.state != 'installed'): status['progress'] = (float(statusi)+0.75) / len(graph) for xml in package.data.get('demo_xml', []): name, ext = os.path.splitext(xml) logger.notifyChannel('init', netsvc.LOG_INFO, 'module %s: loading %s' % (m, xml)) fp = tools.file_open(opj(m, xml)) if ext == '.csv': tools.convert_csv_import(cr, m, os.path.basename(xml), fp.read(), idref, mode=mode, noupdate=True) else: tools.convert_xml_import(cr, m, fp, idref, mode=mode, noupdate=True, **kwargs) fp.close() cr.execute('update ir_module_module set demo=%s where id=%s', (True, mid)) package_todo.append(package.name) migrations.migrate_module(package, 'post') if modobj: ver = release.major_version + '.' + package.data.get('version', '1.0') # Set new modules and dependencies modobj.write(cr, 1, [mid], {'state': 'installed', 'latest_version': ver}) cr.commit() # Update translations for all installed languages modobj.update_translations(cr, 1, [mid], None) cr.commit() package.state = 'installed' for kind in ('init', 'demo', 'update'): if hasattr(package, kind): delattr(package, kind) statusi += 1 cr.execute('select model from ir_model where state=%s', ('manual',)) for model in cr.dictfetchall(): pool.get('ir.model').instanciate(cr, 1, model['model'], {}) pool.get('ir.model.data')._process_end(cr, 1, package_todo) cr.commit() return has_updates
470,492
def default_get(self, cr, uid, fields, context=None): """ This function gets default values """ if not context: context = {}
def default_get(self, cr, uid, fields, context=None): """ This function gets default values """ if not context: context = {}
470,493
def _get_journal(self, cr, uid, context={}): journal_pool = self.pool.get('account.journal') if context.get('journal_id', False): return context.get('journal_id') if not context.get('journal_id', False) and context.get('search_default_journal_id', False): return context.get('search_default_journal_id') ttype = context.get('type', 'bank') res = journal_pool.search(cr, uid, [('type', '=', ttype)], limit=1) return res and res[0] or False
def _get_journal(self, cr, uid, context={}): journal_pool = self.pool.get('account.journal') if context.get('journal_id', False): return context.get('journal_id') if not context.get('journal_id', False) and context.get('search_default_journal_id', False): return context.get('search_default_journal_id') ttype = context.get('type', 'bank') res = journal_pool.search(cr, uid, [('type', '=', ttype)], limit=1) return res and res[0] or False
470,494
def _get_partner(self, cr, uid, context={}): return context.get('partner_id', False)
def _get_partner(self, cr, uid, context={}): return context.get('partner_id', False)
470,495
def onchange_price(self, cr, uid, ids, line_ids, tax_id, partner_id=False, context={}): tax_pool = self.pool.get('account.tax') partner_pool = self.pool.get('res.partner') position_pool = self.pool.get('account.fiscal.position') voucher_line_pool = self.pool.get('account.voucher.line') res = { 'tax_amount':False, 'amount':False, } voucher_total_tax = 0.0 voucher_total = 0.0 voucher_line_ids = [] total = 0.0 total_tax = 0.0 for line in line_ids: line_amount = 0.0 if line[1]: line_amount = voucher_line_pool.browse(cr, uid, line[1]).untax_amount else: line_amount = line[2].get('amount') voucher_line_ids += [line[1]] voucher_total += line_amount total = voucher_total total_tax = 0.0 if tax_id: tax = [tax_pool.browse(cr, uid, tax_id)] if partner_id: partner = partner_pool.browse(cr, uid, partner_id) or False taxes = position_pool.map_tax(cr, uid, partner and partner.property_account_position or False, tax) tax = tax_pool.browse(cr, uid, taxes) if not tax[0].price_include: for tax_line in tax_pool.compute_all(cr, uid, tax, voucher_total, 1).get('taxes'): total_tax += tax_line.get('amount') total += total_tax res.update({ 'amount':total, 'tax_amount':total_tax })
def onchange_price(self, cr, uid, ids, line_ids, tax_id, partner_id=False, context={}): tax_pool = self.pool.get('account.tax') partner_pool = self.pool.get('res.partner') position_pool = self.pool.get('account.fiscal.position') voucher_line_pool = self.pool.get('account.voucher.line') res = { 'tax_amount':False, 'amount':False, } voucher_total_tax = 0.0 voucher_total = 0.0 voucher_line_ids = [] total = 0.0 total_tax = 0.0 for line in line_ids: line_amount = 0.0 line_amount = line[2].get('amount') voucher_line_ids += [line[1]] voucher_total += line_amount total = voucher_total total_tax = 0.0 if tax_id: tax = [tax_pool.browse(cr, uid, tax_id)] if partner_id: partner = partner_pool.browse(cr, uid, partner_id) or False taxes = position_pool.map_tax(cr, uid, partner and partner.property_account_position or False, tax) tax = tax_pool.browse(cr, uid, taxes) if not tax[0].price_include: for tax_line in tax_pool.compute_all(cr, uid, tax, voucher_total, 1).get('taxes'): total_tax += tax_line.get('amount') total += total_tax res.update({ 'amount':total, 'tax_amount':total_tax })
470,496
def onchange_price(self, cr, uid, ids, line_ids, tax_id, partner_id=False, context={}): tax_pool = self.pool.get('account.tax') partner_pool = self.pool.get('res.partner') position_pool = self.pool.get('account.fiscal.position') voucher_line_pool = self.pool.get('account.voucher.line') res = { 'tax_amount':False, 'amount':False, } voucher_total_tax = 0.0 voucher_total = 0.0 voucher_line_ids = [] total = 0.0 total_tax = 0.0 for line in line_ids: line_amount = 0.0 if line[1]: line_amount = voucher_line_pool.browse(cr, uid, line[1]).untax_amount else: line_amount = line[2].get('amount') voucher_line_ids += [line[1]] voucher_total += line_amount total = voucher_total total_tax = 0.0 if tax_id: tax = [tax_pool.browse(cr, uid, tax_id)] if partner_id: partner = partner_pool.browse(cr, uid, partner_id) or False taxes = position_pool.map_tax(cr, uid, partner and partner.property_account_position or False, tax) tax = tax_pool.browse(cr, uid, taxes) if not tax[0].price_include: for tax_line in tax_pool.compute_all(cr, uid, tax, voucher_total, 1).get('taxes'): total_tax += tax_line.get('amount') total += total_tax res.update({ 'amount':total, 'tax_amount':total_tax })
def onchange_price(self, cr, uid, ids, line_ids, tax_id, partner_id=False, context={}): tax_pool = self.pool.get('account.tax') partner_pool = self.pool.get('res.partner') position_pool = self.pool.get('account.fiscal.position') voucher_line_pool = self.pool.get('account.voucher.line') res = { 'tax_amount':False, 'amount':False, } voucher_total_tax = 0.0 voucher_total = 0.0 voucher_line_ids = [] total = 0.0 total_tax = 0.0 for line in line_ids: line_amount = 0.0 if line[1]: line_amount = voucher_line_pool.browse(cr, uid, line[1]).untax_amount else: line_amount = line[2].get('amount') voucher_line_ids += [line[1]] voucher_total += line_amount total = voucher_total total_tax = 0.0 if tax_id: tax = [tax_pool.browse(cr, uid, tax_id)] if partner_id: partner = partner_pool.browse(cr, uid, partner_id) or False taxes = position_pool.map_tax(cr, uid, partner and partner.property_account_position or False, tax) tax = tax_pool.browse(cr, uid, taxes) if not tax[0].price_include: for tax_line in tax_pool.compute_all(cr, uid, tax, voucher_total, 1).get('taxes'): total_tax += tax_line.get('amount') total += total_tax res.update({ 'amount':total or voucher_total, 'tax_amount':total_tax })
470,497
def onchange_price(self, cr, uid, ids, line_ids, tax_id, partner_id=False, context={}): tax_pool = self.pool.get('account.tax') partner_pool = self.pool.get('res.partner') position_pool = self.pool.get('account.fiscal.position') voucher_line_pool = self.pool.get('account.voucher.line') res = { 'tax_amount':False, 'amount':False, } voucher_total_tax = 0.0 voucher_total = 0.0 voucher_line_ids = [] total = 0.0 total_tax = 0.0 for line in line_ids: line_amount = 0.0 if line[1]: line_amount = voucher_line_pool.browse(cr, uid, line[1]).untax_amount else: line_amount = line[2].get('amount') voucher_line_ids += [line[1]] voucher_total += line_amount total = voucher_total total_tax = 0.0 if tax_id: tax = [tax_pool.browse(cr, uid, tax_id)] if partner_id: partner = partner_pool.browse(cr, uid, partner_id) or False taxes = position_pool.map_tax(cr, uid, partner and partner.property_account_position or False, tax) tax = tax_pool.browse(cr, uid, taxes) if not tax[0].price_include: for tax_line in tax_pool.compute_all(cr, uid, tax, voucher_total, 1).get('taxes'): total_tax += tax_line.get('amount') total += total_tax res.update({ 'amount':total, 'tax_amount':total_tax })
defonchange_price(self,cr,uid,ids,line_ids,tax_id,partner_id=False,context={}):tax_pool=self.pool.get('account.tax')partner_pool=self.pool.get('res.partner')position_pool=self.pool.get('account.fiscal.position')voucher_line_pool=self.pool.get('account.voucher.line')res={'tax_amount':False,'amount':False,}voucher_total_tax=0.0voucher_total=0.0voucher_line_ids=[]total=0.0total_tax=0.0forlineinline_ids:line_amount=0.0ifline[1]:line_amount=voucher_line_pool.browse(cr,uid,line[1]).untax_amountelse:line_amount=line[2].get('amount')voucher_line_ids+=[line[1]]voucher_total+=line_amounttotal=voucher_totaltotal_tax=0.0iftax_id:tax=[tax_pool.browse(cr,uid,tax_id)]ifpartner_id:partner=partner_pool.browse(cr,uid,partner_id)orFalsetaxes=position_pool.map_tax(cr,uid,partnerandpartner.property_account_positionorFalse,tax)tax=tax_pool.browse(cr,uid,taxes)ifnottax[0].price_include:fortax_lineintax_pool.compute_all(cr,uid,tax,voucher_total,1).get('taxes'):total_tax+=tax_line.get('amount')total+=total_taxres.update({'amount':total,'tax_amount':total_tax})
470,498
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
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
470,499