class mgmtsystem_kpi_threshold(orm.Model): """ KPI Threshold """ _name = "mgmtsystem.kpi.threshold" _description = "KPI Threshold" def _is_valid_threshold(self, cr, uid, ids, field_name, arg, context=None): if context is None: context = {} result = {} for obj in self.browse(cr, uid, ids, context): # check if ranges overlap # TODO: This code can be done better for range1 in obj.range_ids: for range2 in obj.range_ids: if (range1.valid and range2.valid and range1.min_value < range2.min_value): result[obj.id] = range1.max_value <= range2.min_value return result def _generate_invalid_message( self, cr, uid, ids, field_name, arg, context=None): if context is None: context = {} result = {} for obj in self.browse(cr, uid, ids, context): if obj.valid: result[obj.id] = "" else: result[obj.id] = ("2 of your ranges are overlapping! Please " "make sure your ranges do not overlap.") return result name = fields.Char('Name', size=50, required=True) 'range_ids': fields.Many2many( 'mgmtsystem.kpi.threshold.range', 'mgmtsystem_kpi_threshold_range_rel', 'threshold_id', 'range_id', 'Ranges' ), 'valid': fields.Function( _is_valid_threshold, string='Valid', type='boolean', required=True, ), 'invalid_message': fields.Function( _generate_invalid_message, string='Message', type='char', size=100, ),
class email_template(Model): _inherit = 'email.template' def _get_is_template_template(self, cr, uid, ids, fields_name, arg, context=None): cr.execute('''select id, (select count(*) > 0 from email_template e where email_template_id=email_template.id) from email_template where id in %s''', (tuple(ids),)) return dict(cr.fetchall()) email_template_id = fields.Many2one('email.template', 'Template') 'is_template_template': fields.Function( _get_is_template_template, type='boolean', string='Is a template template'),
class SaleOrderAmountTotal(models.Model): _inherit = 'sale.order' def _amount_all_wrapper(self, cr, uid, ids, field_name, arg, context=None): return super(SaleOrderAmountTotal, self)._amount_all_wrapper(cr, uid, ids, field_name, arg, context=None) def _get_order(self, cr, uid, ids, context=None): result = {} for line in self.pool.get('sale.order.line').browse(cr, uid, ids, context=context): result[line.order_id.id] = True return result.keys() amount_total = fields.Function(_amount_all_wrapper, digits_compute=dp.get_precision('Account'), string='Total' store={ 'sale.order': (lambda self, cr, uid, ids, c={}: ids, ['order_line'], 10), 'sale.order.line': (_get_order, ['price_unit', 'tax_id', 'discount', 'product_uom_qty', 'state'], 10)}, multi='sums', help="The total amount."),
class sale_order_line(models.Model): _inherit = "sale.order.line" discount_global = fields.Float(string="Global dicount") price_subtotal = fields.Function( _amount_line, string="Subtotal", digits_compute=dp.get_precision('Account')) def _amount_line(self, cr, uid, ids, field_name, arg, context=None): print "Computing amount" tax_obj = self.pool.get('account.tax') cur_obj = self.pool.get('res.currency') res = {} if context is None: context = {} for line in self.browse(cr, uid, ids, context=context): price = self._calc_line_base_price(cr, uid, line, context=context) qty = self._calc_line_quantity(cr, uid, line, context=context) taxes = tax_obj.compute_all(cr, uid, line.tax_id, price, qty, line.product_id, line.order_id.partner_id) cur = line.order_id.pricelist_id.currency_id res[line.id] = cur_obj.round(cr, uid, cur, taxes['total'])
class ResCompany(orm.Model): """override company to add currency update""" def _multi_curr_enable(self, cr, uid, ids, field_name, arg, context=None): "check if multi company currency is enabled" result = {} if self.pool.get('ir.model.fields').search(cr, uid, [('name', '=', 'company_id'), ('model', '=', 'res.currency')]) == []: enable = 0 else: enable = 1 for id in ids: result[id] = enable return result def button_refresh_currency(self, cr, uid, ids, context=None): """Refrech the currency !!for all the company now""" currency_updater_obj = self.pool.get('currency.rate.update') try: currency_updater_obj.run_currency_update(cr, uid) except Exception as e: raise e # print "ok" return True def write(self, cr, uid, ids, vals, context=None): """handle the activation of the currecny update on compagnies. There are two ways of implementing multi_company currency, the currency is shared or not. The module take care of the two ways. If the currency are shared, you will only be able to set auto update on one company, this will avoid to have unusefull cron object running. If yours currency are not share you will be able to activate the auto update on each separated company""" save_cron = {} for company in self.browse(cr, uid, ids, context=context): if 'auto_currency_up' in vals: enable = company.multi_company_currency_enable compagnies = self.search(cr, uid, []) activate_cron = 'f' value = vals.get('auto_currency_up') if not value: for comp in compagnies: if self.browse(cr, uid, comp).auto_currency_up: activate_cron = 't' break save_cron.update({'active': activate_cron}) else: for comp in compagnies: if comp != company.id and not enable: if self.browse(cr, uid, comp).multi_company_currency_enable: raise Exception('Yon can not activate auto currency ' + 'update on more thant one company with this ' + 'multi company configuration') for comp in compagnies: if self.browse(cr, uid, comp).auto_currency_up: activate_cron = 't' break save_cron.update({'active': activate_cron}) if 'interval_type' in vals: save_cron.update({'interval_type': vals.get('interval_type')}) if save_cron: self.pool.get('currency.rate.update').save_cron( cr, uid, save_cron ) return super(ResCompany, self).write(cr, uid, ids, vals, context=context) _inherit = "res.company" # activate the currency update auto_currency_up = fields.Boolean('Automatical update of the currency this company') services_to_use = fields.One2many( 'currency.rate.update.service', 'company_id', 'Currency update services' ) # predifine cron frequence interval_type = fields.Selection( [ ('days', 'Day(s)'), ('weeks', 'Week(s)'), ('months', 'Month(s)') ], 'Currency update frequence', help="""changing this value will also affect other compagnies""" ) # function field that allows to know the # mutli company currency implementation multi_company_currency_enable = fields.Function( _multi_curr_enable, method=True, type='boolean', string="Multi company currency", help='if this case is not check you can' + ' not set currency is active on two company' )
class Sessionpos(models.Model): def _fun_difference(self, cr, uid, ids, fields, args, context=None): res = {} for session in self.browse(cr, uid, ids, context=context): total = 0 totali = 0 totali = session.cash_register_balance_end totalf = session.cash_register_balance_end_real for order in session.order_ids: flag = False for producto in order.lines: if producto.product_id.expense_pdt: # print producto.product_id.name flag = True if flag: totali -= (order.amount_total * 2) total = (totali - totalf) res[session.id] = total if total < 0: total = -total else: total = -total if session.state != 'closed': self.write(cr, uid, session.id, {'difference2': total}, context=context) self.write(cr, uid, session.id, {'money_close': totali}, context=context) self.write(cr, uid, session.id, {'money_reported': totalf}, context=context) return res def _calc_vb(self, cr, uid, ids, fields, args, context=None): res = {} flag = False for session in self.browse(cr, uid, ids, context=context): total = 0 for order in session.order_ids: flag = False for producto in order.lines: if producto.product_id.expense_pdt or producto.product_id.income_pdt: flag = True if not flag: total += order.amount_total res[session.id] = total return res def _calc_statements_total(self, cr, uid, ids, fields, args, context=None): res = {} for session in self.browse(cr, uid, ids, context=context): total = 0 for st in session.statement_ids: total += st.total_entry_encoding res[session.id] = total return res def _calc_isv(self, cr, uid, ids, fields, args, context=None): res = {} for session in self.browse(cr, uid, ids, context=context): total = 0 for order in session.order_ids: total += order.amount_tax res[session.id] = total return res def _calc_subtotal(self, cr, uid, ids, fields, args, context=None): res = {} for session in self.browse(cr, uid, ids, context=context): total = session.venta_bruta - session.isv res[session.id] = total return res def _calc_no_facturas(self, cr, uid, ids, fields, args, context=None): res = {} array = [] count = 0 for session in self.browse(cr, uid, ids, context=context): for order in session.order_ids: count += 1 array.append(order.pos_reference) if array: res[session.id] = str(count) + " facturas " + str( array[len(array) - 1]) + " A " + str(array[0]) return res def _calc_discount(self, cr, uid, ids, fields, args, context=None): res = {} for session in self.browse(cr, uid, ids, context=context): des_total = 0 for order in session.order_ids: discount = 0 for desc in order.lines: discount += desc.price_unit * (desc.discount / 100) des_total += discount res[session.id] = des_total return res def _calc_money_incoming(self, cr, uid, ids, fields, args, context=None): res = {} for session in self.browse(cr, uid, ids, context=context): total = 0 counttotal = 0 for order in session.order_ids: total2 = 0 count = 0 for desc in order.lines: if desc.product_id.income_pdt: count += 1 total2 += desc.price_subtotal_incl total += total2 counttotal += count res[session.id] = str( counttotal) + " Entrada(s) " + " Total Entradas " + str(total) return res def _calc_money_outgoing(self, cr, uid, ids, fields, args, context=None): res = {} for session in self.browse(cr, uid, ids, context=context): total = 0 counttotal = 0 for order in session.order_ids: total2 = 0 count = 0 for desc in order.lines: if desc.product_id.expense_pdt: count += 1 total2 += desc.price_subtotal_incl total += total2 counttotal += count res[session.id] = str( counttotal) + " Salida(s) " + " Total Salidas " + str(total) return res def _calc_tickets(self, cr, uid, ids, name, args, context=None): res = {} for session in self.browse(cr, uid, ids, context=context): res[session.id] = { 'tickets_num': 0, 'ticket_first_id': None, 'ticket_last_id': None, } if session.order_ids: res[session.id]['tickets_num'] = len(session.order_ids) res[session.id]['ticket_first_id'] = session.order_ids[-1] res[session.id]['ticket_last_id'] = session.order_ids[0] return res def summary_by_product(self, cr, uid, ids, context=None): assert len( ids ) == 1, 'This option should only be used for a single id at a time.' products = {} # product_id -> data for session in self.browse(cr, uid, ids, context=context): for order in session.order_ids: for line in order.lines: id = line.product_id.id if id not in products: products[id] = { 'product': line.product_id.name, 'qty': 0, 'total': 0 } products[id]['qty'] += line.qty products[id]['total'] += line.price_subtotal_incl return products.values() def summary_by_tax(self, cr, uid, ids, context=None): assert len( ids ) == 1, 'This option should only be used for a single id at a time.' account_tax_obj = self.pool.get('account.tax') res = {} # tax_id -> data for session in self.browse(cr, uid, ids, context=context): for order in session.order_ids: for line in order.lines: taxes_ids = [ tax for tax in line.product_id.taxes_id if tax.company_id.id == line.order_id.company_id.id ] price = line.price_unit * (1 - (line.discount or 0.0) / 100.0) taxes = account_tax_obj.compute_all( cr, uid, taxes_ids, price, line.qty, product=line.product_id, partner=line.order_id.partner_id or False) for tax in taxes['taxes']: id = tax['tax_code_id'] if id not in res: t = account_tax_obj.browse(cr, uid, id, context=context) tax_rule = '' if t.type == 'percent': tax_rule = str(100 * t.amount) + '%' else: tax_rule = str(t.amount) res[id] = { 'name': tax['name'], 'base': 0, 'tax': tax_rule, 'total': 0, } res[id]['base'] += price * line.qty res[id]['total'] += tax['amount'] # cur_obj.round(cr, uid, cur, taxes['amount']) return res.values() def _calc_tax(self, cr, uid, ids, name, args, context=None): account_tax_obj = self.pool.get('account.tax') res = {} for session in self.browse(cr, uid, ids, context=context): res[session.id] = {'tax_base_total': 0} for order in session.order_ids: for line in order.lines: taxes_ids = [ tax for tax in line.product_id.taxes_id if tax.company_id.id == line.order_id.company_id.id ] price = line.price_unit * (1 - (line.discount or 0.0) / 100.0) taxes = account_tax_obj.compute_all( cr, uid, taxes_ids, price, line.qty, product=line.product_id, partner=line.order_id.partner_id or False) res[session.id]['tax_base_total'] += taxes['total'] return res def _calc_sales(self, cr, uid, ids, name, args, context=None): res = {} for session in self.browse(cr, uid, ids, context=context): res[session.id] = {'untaxed_sales': 0} for order in session.order_ids: for line in order.lines: if not line.product_id.taxes_id: res[session.id]['untaxed_sales'] += line.price_subtotal return res _inherit = 'pos.session' validate = fields.Boolean(string="Validation", help="validation") difference = fields.Function(_fun_difference, string="Difference") difference2 = fields.Float('difference2') venta_bruta = fields.Function(_calc_vb, string='Venta bruta', help='Gross sales') isv = fields.Function(_calc_isv, string='ISV') subtotal = fields.Function(_calc_subtotal, string='subtotal') nro_facturas = fields.Char( compute="_calc_no_facturas", string='nro facturas', ) discount = fields.Function(_calc_discount, string='discount') tax_base_total = fields.Function( _calc_tax, string='Total Sales without taxes', ) untaxed_sales = fields.Function( _calc_sales, string='Untaxed sales', ) money_incoming = fields.Char( compute="_calc_money_incoming", string='money incoming', ) money_outgoing = fields.Char( compute="_calc_money_outgoing", string='money outgoing', ) statements_total = fields.Function(_calc_statements_total, string='Total Payments Received') tickets_num = fields.Integer( compute="_calc_tickets", string='Number of Tickets', ) ticket_first_id = fields.Many2one( 'pos.order', compute="_calc_tickets", string='First Ticket', ) ticket_last_id = fields.Many2one( 'pos.order', compute="_calc_tickets", string='Last Ticket', ) money_close = fields.Float('money Close') money_reported = fields.Float('money Reported')
def _get_smtp_conf(self, cr, uid, ids, name, args, context=None): """ Return configuration """ res = {} for mail_server in self.browse(cr, uid, ids, context=context): global_section_name = 'outgoing_mail' # default vals config_vals = {'smtp_port': 587} if serv_config.has_section(global_section_name): config_vals.update((serv_config.items(global_section_name))) custom_section_name = '.'.join((global_section_name, mail_server.name)) if serv_config.has_section(custom_section_name): config_vals.update(serv_config.items(custom_section_name)) if config_vals.get('smtp_port'): config_vals['smtp_port'] = int(config_vals['smtp_port']) res[mail_server.id] = config_vals return res 'smtp_host': fields.Function( _get_smtp_conf, string='SMTP Server', type="char", multi='outgoing_mail_config', states={'draft': [('readonly', True)]}, help="Hostname or IP of SMTP server"), 'smtp_port': fields.Function( _get_smtp_conf, string='SMTP Port', type="integer", multi='outgoing_mail_config', states={'draft': [('readonly', True)]}, help="SMTP Port. Usually 465 for SSL, " "and 25 or 587 for other cases.", size=5), 'smtp_user': fields.Function( _get_smtp_conf, string='Username', type="char", multi='outgoing_mail_config', states={'draft': [('readonly', True)]}, help="Optional username for SMTP authentication", size=64), 'smtp_pass': fields.Function( _get_smtp_conf, string='Password', type="char", multi='outgoing_mail_config', states={'draft': [('readonly', True)]}, help="Optional password for SMTP authentication", size=64), 'smtp_encryption': fields.Function( _get_smtp_conf, string='smtp_encryption', type="selection", multi='outgoing_mail_config', selection=[('none', 'None'), ('starttls', 'TLS (STARTTLS)'), ('ssl', 'SSL/TLS')], states={'draft': [('readonly', True)]}, help="Choose the connection encryption scheme:\n" "- none: SMTP sessions are done in cleartext.\n" "- starttls: TLS encryption is requested at start " "of SMTP session (Recommended)\n" "- ssl: SMTP sessions are encrypted with SSL/TLS " "through a dedicated port (default: 465)")
def _type_search(self, cr, uid, obj, name, args, context=None): result_ids = [] # read all incoming servers values all_ids = self.search(cr, uid, [], context=context) results = self.read(cr, uid, all_ids, ['id', 'type'], context=context) args = args[:] i = 0 while i < len(args): operator = args[i][1] if operator == '=': for res in results: if (res['type'] == args[i][2] and res['id'] not in result_ids): result_ids.append(res['id']) elif operator == 'in': for search_vals in args[i][2]: for res in results: if (res['type'] == search_vals and res['id'] not in result_ids): result_ids.append(res['id']) else: continue i += 1 return [('id', 'in', result_ids)] 'server': fields.Function( _get_incom_conf, string='Server', type="char", multi='income_mail_config', states={'draft': [('readonly', True)]}, help="Hostname or IP of the mail server"), 'port': fields.Function( _get_incom_conf, string='Port', type="integer", states={'draft': [('readonly', True)]}, multi='income_mail_config'), 'type': fields.Function( _get_incom_conf, string='Type', type="selection", selection=[('pop', 'POP Server'), ('imap', 'IMAP Server'), ('local', 'Local Server'), ], multi='income_mail_config', fnct_search=_type_search, states={'draft': [('readonly', True)]}, help="pop, imap, local"), 'is_ssl': fields.Function( _get_incom_conf, string='Is SSL', type="boolean", multi='income_mail_config', states={'draft': [('readonly', True)]}, help='Connections are encrypted with SSL/TLS through' ' a dedicated port (default: IMAPS=993, POP3S=995)'), 'attach': fields.Function( _get_incom_conf, string='Keep Attachments', type="boolean", multi='income_mail_config', states={'draft': [('readonly', True)]}, help="Whether attachments should be downloaded. " "If not enabled, incoming emails will be stripped of any " "attachments before being processed"), 'original': fields.Function( _get_incom_conf, string='Keep Original', type="boolean", multi='income_mail_config', states={'draft': [('readonly', True)]}, help="Whether a full original copy of each email should be kept " "for reference and attached to each processed message. This " "will usually double the size of your message database."), 'user': fields.Function( _get_incom_conf, string='Username', type="char", states={'draft': [('readonly', True)]}, multi='income_mail_config'), 'password': fields.Function( _get_incom_conf, string='password', type="char", states={'draft': [('readonly', True)]}, multi='income_mail_config')
name = fields.Char('Number', required=True, copy=False) ref = fields.Char('Reference', copy=False) period_id = fields.Many2one('account.period', 'Period', required=True, states={'posted =[('readonly',True)]}) journal_id = fields.Many2one('account.journal', 'Journal', required=True, states={'posted =[('readonly',True)]}) state = fields.Selection( [('draft','Unposted'), ('posted','Posted')], 'Status', required=True, readonly=True, copy=False, help='All manually created new journal entries are usually in the status \'Unposted\', ' 'but you can set the option to skip that status on the related journal. ' 'In that case, they will behave as journal entries automatically created by the ' 'system on document validation (invoices, bank statements...) and will be created ' 'in \'Posted\' status.'), line_id = fields.One2many('account.move.line', 'move_id', 'Entries', states={'posted =[('readonly',True)]}, reversal_id = fields.Char('Reversal Entry') to_be_reversed = fields.Boolean('To Be Reversed') to_check = fields.Boolean('To Review', help='Check this box if you are unsure of that journal entry and if you want to note it as \'to be reviewed\' by an accounting expert.'), partner_id = fields.Related('line_id', 'partner_id', type="many2one", relation="res.partner", string="Partner", store={ _name: (lambda self, cr,uid,ids,c: ids, ['line_id'], 10) 'account.move.line = (_get_move_from_lines, ['partner_id'],10) }), amount = fields.Function(_amount_compute, string='Amount', digits_compute=dp.get_precision('Account'), type='float', fnct_search=_search_amount), date = fields.date('Date', required=True, states={'posted =[('readonly',True)]}, select=True), narration =fields.Text('Internal Note'), \ company_id = fields.related('journal_id','company_id',type='many2one',relation='res.company',string='Company', store=True, readonly=True), \ balance = fields.Float('balance', digits_compute=dp.get_precision('Account'), help="This is a field only used for internal purpose and shouldn't be displayed"),
class mgmtsystem_kpi_threshold_range(orm.Model): """ KPI Threshold Range """ _name = "mgmtsystem.kpi.threshold.range" _description = "KPI Threshold Range" def compute_min_value(self, cr, uid, ids, field_name, arg, context=None): if context is None: context = {} result = {} for obj in self.browse(cr, uid, ids): value = None if obj.min_type == 'local' and is_select_query(obj.min_code): cr.execute(obj.min_code) dic = cr.dictfetchall() if is_one_value(dic): value = dic[0]['value'] elif (obj.min_type == 'external' and obj.min_dbsource_id.id and is_select_query(obj.min_code)): dbsrc_obj = obj.min_dbsource_id res = dbsrc_obj.execute(obj.min_code) if is_one_value(res): value = res[0]['value'] elif obj.min_type == 'python': value = safe_eval(obj.min_code) else: value = obj.min_fixed_value result[obj.id] = value return result def compute_max_value(self, cr, uid, ids, field_name, arg, context=None): if context is None: context = {} result = {} for obj in self.browse(cr, uid, ids, context): value = None if obj.max_type == 'local' and is_select_query(obj.max_code): cr.execute(obj.max_code) dic = cr.dictfetchall() if is_one_value(dic): value = dic[0]['value'] elif obj.max_type == 'python': value = safe_eval(obj.max_code) elif (obj.max_type == 'external' and obj.max_dbsource_id.id and is_select_query(obj.max_code)): dbsrc_obj = obj.max_dbsource_id res = dbsrc_obj.execute(obj.max_code) if is_one_value(res): value = res[0]['value'] else: value = obj.max_fixed_value result[obj.id] = value return result def _is_valid_range(self, cr, uid, ids, field_name, arg, context=None): if context is None: context = {} result = {} for obj in self.browse(cr, uid, ids, context): if obj.max_value < obj.min_value: result[obj.id] = False else: result[obj.id] = True return result def _generate_invalid_message( self, cr, uid, ids, field_name, arg, context=None): if context is None: context = {} result = {} for obj in self.browse(cr, uid, ids, context): if obj.valid: result[obj.id] = "" else: result[obj.id] = ("Minimum value is greater than the maximum " "value! Please adjust them.") return result name = fields.Char('Name', size=50, required=True) 'valid': fields.Function( _is_valid_range, string='Valid', type='boolean', required=True, ), 'invalid_message': fields.Function( _generate_invalid_message, string='Message', type='char', size=100, ), 'min_type': fields.Selection(( ('static', 'Fixed value'), ('python', 'Python Code'), ('local', 'SQL - Local DB'), ('external', 'SQL - Externa DB'), ), 'Min Type', required=True), 'min_value': fields.Function( compute_min_value, string='Minimum', type='float', ),
), min_fixed_value = fields.Float('Minimum') min_code = fields.Text('Minimum Computation Code') 'min_dbsource_id': fields.Many2one( 'base.external.dbsource', 'External DB Source', ), 'max_type': fields.Selection(( ('static', 'Fixed value'), ('python', 'Python Code'), ('local', 'SQL - Local DB'), ('external', 'SQL - External DB'), ), 'Max Type', required=True), 'max_value': fields.Function( compute_max_value, string='Maximum', type='float', ), max_fixed_value = fields.Float('Maximum') max_code = fields.Text('Maximum Computation Code') 'max_dbsource_id': fields.Many2one( 'base.external.dbsource', 'External DB Source', ), 'color': fields.Char( 'Color', help='RGB code with #', size=7, required=True, ), 'threshold_ids': fields.Many2many(