class Company(models.Model): _inherit = 'res.company' po_lead = fields.Float( string='Purchase Lead Time', required=True, help="Margin of error for vendor lead times. When the system " "generates Purchase Orders for procuring products, " "they will be scheduled that many days earlier " "to cope with unexpected vendor delays.", default=0.0) po_lock = fields.Selection( [('edit', 'Allow to edit purchase orders'), ('lock', 'Confirmed purchase orders are not editable')], string="Purchase Order Modification", default="edit", help= 'Purchase Order Modification used when you want to purchase order editable after confirm' ) po_double_validation = fields.Selection( [('one_step', 'Confirm purchase orders in one step'), ('two_step', 'Get 2 levels of approvals to confirm a purchase order') ], string="Levels of Approvals", default='one_step', help="Provide a double validation mechanism for purchases") po_double_validation_amount = fields.Monetary( string='Double validation amount', default=5000, help="Minimum amount for which a double validation is required")
class BaseLanguageInstall(models.TransientModel): _name = "base.language.install" _description = "Install Language" @api.model def _default_language(self): """ Display the selected language when using the 'Update Terms' action from the language list view """ if self._context.get('active_model') == 'res.lang': lang = self.env['res.lang'].browse(self._context.get('active_id')) return lang.code return False @api.model def _get_languages(self): return [[code, name] for code, _, name in self.env['res.lang'].get_available()] lang = fields.Selection(_get_languages, string='Language', required=True, default=_default_language) overwrite = fields.Boolean( 'Overwrite Existing Terms', default=True, help= "If you check this box, your customized translations will be overwritten and replaced by the official ones." ) state = fields.Selection([('init', 'init'), ('done', 'done')], string='Status', readonly=True, default='init') def lang_install(self): self.ensure_one() mods = self.env['ir.module.module'].search([('state', '=', 'installed') ]) mods.with_context(overwrite=self.overwrite)._update_translations( self.lang) self.state = 'done' self.env.cr.execute('ANALYZE ir_translation') return { 'name': _('Language Pack'), 'view_mode': 'form', 'view_id': False, 'res_model': 'base.language.install', 'domain': [], 'context': dict(self._context, active_ids=self.ids), 'type': 'ir.actions.act_window', 'target': 'new', 'res_id': self.id, } def reload(self): return { 'type': 'ir.actions.client', 'tag': 'reload', }
class PriceRule(models.Model): _name = "delivery.price.rule" _description = "Delivery Price Rules" _order = 'sequence, list_price, id' @api.depends('variable', 'operator', 'max_value', 'list_base_price', 'list_price', 'variable_factor') def _compute_name(self): for rule in self: name = 'if %s %s %s then' % (rule.variable, rule.operator, rule.max_value) if rule.list_base_price and not rule.list_price: name = '%s fixed price %s' % (name, rule.list_base_price) elif rule.list_price and not rule.list_base_price: name = '%s %s times %s' % (name, rule.list_price, rule.variable_factor) else: name = '%s fixed price %s plus %s times %s' % (name, rule.list_base_price, rule.list_price, rule.variable_factor) rule.name = name name = fields.Char(compute='_compute_name') sequence = fields.Integer(required=True, default=10) carrier_id = fields.Many2one('delivery.carrier', 'Carrier', required=True, ondelete='cascade') variable = fields.Selection([('weight', 'Weight'), ('volume', 'Volume'), ('wv', 'Weight * Volume'), ('price', 'Price'), ('quantity', 'Quantity')], required=True, default='weight') operator = fields.Selection([('==', '='), ('<=', '<='), ('<', '<'), ('>=', '>='), ('>', '>')], required=True, default='<=') max_value = fields.Float('Maximum Value', required=True) list_base_price = fields.Float(string='Sale Base Price', digits='Product Price', required=True, default=0.0) list_price = fields.Float('Sale Price', digits='Product Price', required=True, default=0.0) variable_factor = fields.Selection([('weight', 'Weight'), ('volume', 'Volume'), ('wv', 'Weight * Volume'), ('price', 'Price'), ('quantity', 'Quantity')], 'Variable Factor', required=True, default='weight')
class PurchaseRequisitionType(models.Model): _name = "purchase.requisition.type" _description = "Purchase Requisition Type" _order = "sequence" name = fields.Char(string='Agreement Type', required=True, translate=True) sequence = fields.Integer(default=1) exclusive = fields.Selection( [('exclusive', 'Select only one RFQ (exclusive)'), ('multiple', 'Select multiple RFQ')], string='Agreement Selection Type', required=True, default='multiple', help= """Select only one RFQ (exclusive): when a purchase order is confirmed, cancel the remaining purchase order.\n Select multiple RFQ: allows multiple purchase orders. On confirmation of a purchase order it does not cancel the remaining orders""" ) quantity_copy = fields.Selection([('copy', 'Use quantities of agreement'), ('none', 'Set quantities manually')], string='Quantities', required=True, default='none') line_copy = fields.Selection( [('copy', 'Use lines of agreement'), ('none', 'Do not create RfQ lines automatically')], string='Lines', required=True, default='copy')
class report_paperformat(models.Model): _name = "report.paperformat" _description = "Paper Format Config" name = fields.Char('Name', required=True) default = fields.Boolean('Default paper format ?') format = fields.Selection([(ps['key'], ps['description']) for ps in PAPER_SIZES], 'Paper size', default='A4', help="Select Proper Paper size") margin_top = fields.Float('Top Margin (mm)', default=40) margin_bottom = fields.Float('Bottom Margin (mm)', default=20) margin_left = fields.Float('Left Margin (mm)', default=7) margin_right = fields.Float('Right Margin (mm)', default=7) page_height = fields.Integer('Page height (mm)', default=False) page_width = fields.Integer('Page width (mm)', default=False) orientation = fields.Selection([('Landscape', 'Landscape'), ('Portrait', 'Portrait')], 'Orientation', default='Landscape') header_line = fields.Boolean('Display a header line', default=False) header_spacing = fields.Integer('Header spacing', default=35) dpi = fields.Integer('Output DPI', required=True, default=90) report_ids = fields.One2many('ir.actions.report', 'paperformat_id', 'Associated reports', help="Explicitly associated reports") print_page_width = fields.Float('Print page width (mm)', compute='_compute_print_page_size') print_page_height = fields.Float('Print page height (mm)', compute='_compute_print_page_size') @api.constrains('format') def _check_format_or_page(self): if self.filtered(lambda x: x.format != 'custom' and (x.page_width or x.page_height)): raise ValidationError( _('You can select either a format or a specific page width/height, but not both.' )) def _compute_print_page_size(self): for record in self: width = height = 0.0 if record.format: if record.format == 'custom': width = record.page_width height = record.page_height else: paper_size = next(ps for ps in PAPER_SIZES if ps['key'] == record.format) width = paper_size['width'] height = paper_size['height'] if record.orientation == 'Landscape': # swap sizes width, height = height, width record.print_page_width = width record.print_page_height = height
class ResConfigSettings(models.TransientModel): _inherit = 'res.config.settings' lock_confirmed_po = fields.Boolean( "Lock Confirmed Orders", default=lambda self: self.env.company.po_lock == 'lock') po_lock = fields.Selection(related='company_id.po_lock', string="Purchase Order Modification *", readonly=False) po_order_approval = fields.Boolean("Purchase Order Approval", default=lambda self: self.env.company. po_double_validation == 'two_step') po_double_validation = fields.Selection( related='company_id.po_double_validation', string="Levels of Approvals *", readonly=False) po_double_validation_amount = fields.Monetary( related='company_id.po_double_validation_amount', string="Minimum Amount", currency_field='company_currency_id', readonly=False) company_currency_id = fields.Many2one( 'res.currency', related='company_id.currency_id', string="Company Currency", readonly=True, help='Utility field to express amount currency') default_purchase_method = fields.Selection( [ ('purchase', 'Ordered quantities'), ('receive', 'Received quantities'), ], string="Bill Control", default_model="product.template", help="This default value is applied to any new product created. " "This can be changed in the product detail form.", default="receive") group_warning_purchase = fields.Boolean( "Purchase Warnings", implied_group='purchase.group_warning_purchase') module_account_3way_match = fields.Boolean( "3-way matching: purchases, receptions and bills") module_purchase_requisition = fields.Boolean("Purchase Agreements") module_purchase_product_matrix = fields.Boolean("Purchase Grid Entry") po_lead = fields.Float(related='company_id.po_lead', readonly=False) use_po_lead = fields.Boolean( string="Security Lead Time for Purchase", config_parameter='purchase.use_po_lead', help= "Margin of error for vendor lead times. When the system generates Purchase Orders for reordering products,they will be scheduled that many days earlier to cope with unexpected vendor delays." ) @api.onchange('use_po_lead') def _onchange_use_po_lead(self): if not self.use_po_lead: self.po_lead = 0.0 def set_values(self): super(ResConfigSettings, self).set_values() self.po_lock = 'lock' if self.lock_confirmed_po else 'edit' self.po_double_validation = 'two_step' if self.po_order_approval else 'one_step'
class BaseLanguageExport(models.TransientModel): _name = "base.language.export" _description = 'Language Export' @api.model def _get_languages(self): langs = self.env['res.lang'].get_installed() return [(NEW_LANG_KEY, _('New Language (Empty translation template)'))] + \ langs name = fields.Char('File Name', readonly=True) lang = fields.Selection(_get_languages, string='Language', required=True, default=NEW_LANG_KEY) format = fields.Selection([('csv', 'CSV File'), ('po', 'PO File'), ('tgz', 'TGZ Archive')], string='File Format', required=True, default='csv') modules = fields.Many2many('ir.module.module', 'rel_modules_langexport', 'wiz_id', 'module_id', string='Apps To Export', domain=[('state', '=', 'installed')]) data = fields.Binary('File', readonly=True, attachment=False) state = fields.Selection( [('choose', 'choose'), ('get', 'get')], # choose language or get the file default='choose') def act_getfile(self): this = self[0] lang = this.lang if this.lang != NEW_LANG_KEY else False mods = sorted(this.mapped('modules.name')) or ['all'] with contextlib.closing(io.BytesIO()) as buf: tools.trans_export(lang, mods, buf, this.format, self._cr) out = base64.encodestring(buf.getvalue()) filename = 'new' if lang: filename = tools.get_iso_codes(lang) elif len(mods) == 1: filename = mods[0] extension = this.format if not lang and extension == 'po': extension = 'pot' name = "%s.%s" % (filename, extension) this.write({'state': 'get', 'data': out, 'name': name}) return { 'type': 'ir.actions.act_window', 'res_model': 'base.language.export', 'view_mode': 'form', 'res_id': this.id, 'views': [(False, 'form')], 'target': 'new', }
class ResourceCalendarAttendance(models.Model): _name = "resource.calendar.attendance" _description = "Work Detail" _order = 'week_type, dayofweek, hour_from' name = fields.Char(required=True) dayofweek = fields.Selection([('0', 'Monday'), ('1', 'Tuesday'), ('2', 'Wednesday'), ('3', 'Thursday'), ('4', 'Friday'), ('5', 'Saturday'), ('6', 'Sunday')], 'Day of Week', required=True, index=True, default='0') date_from = fields.Date(string='Starting Date') date_to = fields.Date(string='End Date') hour_from = fields.Float( string='Work from', required=True, index=True, help="Start and End time of working.\n" "A specific value of 24:00 is interpreted as 23:59:59.999999.") hour_to = fields.Float(string='Work to', required=True) calendar_id = fields.Many2one("resource.calendar", string="Resource's Calendar", required=True, ondelete='cascade') day_period = fields.Selection([('morning', 'Morning'), ('afternoon', 'Afternoon')], required=True, default='morning') resource_id = fields.Many2one('resource.resource', 'Resource') week_type = fields.Selection([('1', 'Odd week'), ('0', 'Even week')], 'Week Even/Odd', default=False) two_weeks_calendar = fields.Boolean( "Calendar in 2 weeks mode", related='calendar_id.two_weeks_calendar') display_type = fields.Selection([('line_section', "Section")], default=False, help="Technical field for UX purpose.") sequence = fields.Integer( default=10, help= "Gives the sequence of this line when displaying the resource calendar." ) @api.onchange('hour_from', 'hour_to') def _onchange_hours(self): # avoid negative or after midnight self.hour_from = min(self.hour_from, 23.99) self.hour_from = max(self.hour_from, 0.0) self.hour_to = min(self.hour_to, 23.99) self.hour_to = max(self.hour_to, 0.0) # avoid wrong order self.hour_to = max(self.hour_to, self.hour_from)
class MailingTraceReport(models.Model): _name = 'mailing.trace.report' _auto = False _description = 'Mass Mailing Statistics' # mailing name = fields.Char(string='Mass Mail', readonly=True) mailing_type = fields.Selection([('mail', 'Mail')], string='Type', default='mail', required=True) campaign = fields.Char(string='Mass Mail Campaign', readonly=True) scheduled_date = fields.Datetime(string='Scheduled Date', readonly=True) state = fields.Selection([('draft', 'Draft'), ('test', 'Tested'), ('done', 'Sent')], string='Status', readonly=True) email_from = fields.Char('From', readonly=True) # traces sent = fields.Integer(readonly=True) delivered = fields.Integer(readonly=True) opened = fields.Integer(readonly=True) replied = fields.Integer(readonly=True) clicked = fields.Integer(readonly=True) bounced = fields.Integer(readonly=True) def init(self): """Mass Mail Statistical Report: based on mailing.trace that models the various statistics collected for each mailing, and mailing.mailing model that models the various mailing performed. """ tools.drop_view_if_exists(self.env.cr, 'mailing_trace_report') self.env.cr.execute(""" CREATE OR REPLACE VIEW mailing_trace_report AS ( SELECT min(trace.id) as id, utm_source.name as name, mailing.mailing_type, utm_campaign.name as campaign, trace.scheduled as scheduled_date, mailing.state, mailing.email_from, count(trace.sent) as sent, (count(trace.sent) - count(trace.bounced)) as delivered, count(trace.opened) as opened, count(trace.replied) as replied, count(trace.clicked) as clicked, count(trace.bounced) as bounced FROM mailing_trace as trace left join mailing_mailing as mailing ON (trace.mass_mailing_id=mailing.id) left join utm_campaign as utm_campaign ON (mailing.campaign_id = utm_campaign.id) left join utm_source as utm_source ON (mailing.source_id = utm_source.id) GROUP BY trace.scheduled, utm_source.name, utm_campaign.name, mailing.mailing_type, mailing.state, mailing.email_from )""")
class AccountTaxTemplatePython(models.Model): _inherit = 'account.tax.template' amount_type = fields.Selection(selection_add=[('code', 'Python Code')]) python_compute = fields.Text( string='Python Code', default="result = price_unit * 0.10", help= "Compute the amount of the tax by setting the variable 'result'.\n\n" ":param base_amount: float, actual amount on which the tax is applied\n" ":param price_unit: float\n" ":param quantity: float\n" ":param product: product.product recordset singleton or None\n" ":param partner: res.partner recordset singleton or None") python_applicable = fields.Text( string='Applicable Code', default="result = True", help= "Determine if the tax will be applied by setting the variable 'result' to True or False.\n\n" ":param price_unit: float\n" ":param quantity: float\n" ":param product: product.product recordset singleton or None\n" ":param partner: res.partner recordset singleton or None") def _get_tax_vals(self, company, tax_template_to_tax): """ This method generates a dictionnary of all the values for the tax that will be created. """ self.ensure_one() res = super(AccountTaxTemplatePython, self)._get_tax_vals(company, tax_template_to_tax) res['python_compute'] = self.python_compute res['python_applicable'] = self.python_applicable return res
class res_company(models.Model): _inherit = "res.company" account_check_printing_layout = fields.Selection(string="Check Layout", required=True, help="Select the format corresponding to the check paper you will be printing your checks on.\n" "In order to disable the printing feature, select 'None'.", selection=[ ('disabled', 'None'), ('action_print_check_top', 'check on top'), ('action_print_check_middle', 'check in middle'), ('action_print_check_bottom', 'check on bottom') ], default="action_print_check_top") account_check_printing_date_label = fields.Boolean('Print Date Label', default=True, help="This option allows you to print the date label on the check as per CPA. Disable this if your pre-printed check includes the date label.") account_check_printing_multi_stub = fields.Boolean('Multi-Pages Check Stub', help="This option allows you to print check details (stub) on multiple pages if they don't fit on a single page.") account_check_printing_margin_top = fields.Float('Check Top Margin', default=0.25, help="Adjust the margins of generated checks to make it fit your printer's settings.") account_check_printing_margin_left = fields.Float('Check Left Margin', default=0.25, help="Adjust the margins of generated checks to make it fit your printer's settings.") account_check_printing_margin_right = fields.Float('Right Margin', default=0.25, help="Adjust the margins of generated checks to make it fit your printer's settings.")
class test_model(models.Model): _name = 'test_converter.test_model' _description = 'Test Converter Model' char = fields.Char() integer = fields.Integer() float = fields.Float() numeric = fields.Float(digits=(16, 2)) many2one = fields.Many2one('test_converter.test_model.sub', group_expand='_gbf_m2o') binary = fields.Binary(attachment=False) date = fields.Date() datetime = fields.Datetime() selection_str = fields.Selection( [ ('A', u"Qu'il n'est pas arrivé à Toronto"), ('B', u"Qu'il était supposé arriver à Toronto"), ('C', u"Qu'est-ce qu'il fout ce maudit pancake, tabernacle ?"), ('D', u"La réponse D"), ], string=u"Lorsqu'un pancake prend l'avion à destination de Toronto et " u"qu'il fait une escale technique à St Claude, on dit:") html = fields.Html() text = fields.Text() # `base` module does not contains any model that implement the functionality # `group_expand`; test this feature here... @api.model def _gbf_m2o(self, subs, domain, order): sub_ids = subs._search([], order=order, access_rights_uid=SUPERUSER_ID) return subs.browse(sub_ids)
class PaymentWizard(models.TransientModel): """ Override for the sale quotation onboarding panel. """ _inherit = 'payment.acquirer.onboarding.wizard' _name = 'sale.payment.acquirer.onboarding.wizard' _description = 'Sale Payment acquire onboarding wizard' def _get_default_payment_method(self): return self.env.company.sale_onboarding_payment_method or 'digital_signature' payment_method = fields.Selection(selection_add=[ ('digital_signature', 'Online signature'), ('paypal', "PayPal"), ('stripe', "Credit card (via Stripe)"), ('other', "Other payment acquirer"), ('manual', "Custom payment instructions"), ], default=_get_default_payment_method) # def _set_payment_acquirer_onboarding_step_done(self): """ Override. """ self.env.company.set_onboarding_step_done( 'sale_onboarding_order_confirmation_state') def add_payment_methods(self, *args, **kwargs): self.env.company.sale_onboarding_payment_method = self.payment_method if self.payment_method == 'digital_signature': self.env.company.portal_confirmation_sign = True if self.payment_method in ('paypal', 'stripe', 'other', 'manual'): self.env.company.portal_confirmation_pay = True return super(PaymentWizard, self).add_payment_methods(*args, **kwargs)
class EventMailScheduler(models.Model): _inherit = 'event.mail' notification_type = fields.Selection(selection_add=[('sms', 'SMS')]) sms_template_id = fields.Many2one( 'sms.template', string='SMS Template', domain=[('model', '=', 'event.registration')], ondelete='restrict', help= 'This field contains the template of the SMS that will be automatically sent' ) def execute(self): for mail in self: now = fields.Datetime.now() if mail.interval_type != 'after_sub': # Do not send SMS if the communication was scheduled before the event but the event is over if not mail.mail_sent and ( mail.interval_type != 'before_event' or mail.event_id.date_end > now ) and mail.notification_type == 'sms' and mail.sms_template_id: self.env['event.registration']._message_sms_schedule_mass( template=mail.sms_template_id, active_domain=[('event_id', '=', mail.event_id.id), ('state', '!=', 'cancel')], mass_keep_log=True) mail.write({'mail_sent': True}) return super(EventMailScheduler, self).execute()
class Notification(models.Model): _inherit = 'mail.notification' notification_type = fields.Selection(selection_add=[('sms', 'SMS')]) sms_id = fields.Many2one('sms.sms', string='SMS', index=True, ondelete='set null') sms_number = fields.Char('SMS Number') failure_type = fields.Selection(selection_add=[( 'sms_number_missing', 'Missing Number'), ( 'sms_number_format', 'Wrong Number Format'), ( 'sms_credit', 'Insufficient Credit'), ('sms_server', 'Server Error')])
class BaseModuleUpdate(models.TransientModel): _name = "base.module.update" _description = "Update Module" updated = fields.Integer('Number of modules updated', readonly=True) added = fields.Integer('Number of modules added', readonly=True) state = fields.Selection([('init', 'init'), ('done', 'done')], 'Status', readonly=True, default='init') def update_module(self): for this in self: updated, added = self.env['ir.module.module'].update_list() this.write({'updated': updated, 'added': added, 'state': 'done'}) return False def action_module_open(self): res = { 'domain': str([]), 'name': 'Modules', 'view_mode': 'tree,form', 'res_model': 'ir.module.module', 'view_id': False, 'type': 'ir.actions.act_window', } return res
class account_payment_method(models.Model): _name = "account.payment.method" _description = "Payment Methods" name = fields.Char(required=True, translate=True) code = fields.Char(required=True) # For internal identification payment_type = fields.Selection([('inbound', 'Inbound'), ('outbound', 'Outbound')], required=True)
class Tags(models.Model): _name = 'res.partner.tag' _description = 'Partner Tags - These tags can be used on website to find customers by sector, or ...' _inherit = 'website.published.mixin' @api.model def get_selection_class(self): classname = ['default', 'primary', 'success', 'warning', 'danger'] return [(x, str.title(x)) for x in classname] name = fields.Char('Category Name', required=True, translate=True) partner_ids = fields.Many2many('res.partner', 'res_partner_res_partner_tag_rel', 'tag_id', 'partner_id', string='Partners') classname = fields.Selection(get_selection_class, 'Class', default='default', help="Bootstrap class to customize the color", required=True) active = fields.Boolean('Active', default=True) def _default_is_published(self): return True
class Users(models.Model): _inherit = 'res.users' cofficebot_state = fields.Selection( [ ('not_initialized', 'Not initialized'), ('onboarding_emoji', 'Onboarding emoji'), ('onboarding_attachement', 'Onboarding attachement'), ('onboarding_command', 'Onboarding command'), ('onboarding_ping', 'Onboarding ping'), ('idle', 'Idle'), ('disabled', 'Disabled'), ], string="COfficeBot Status", readonly=True, required=True, default="not_initialized" ) # keep track of the state: correspond to the code of the last message sent def __init__(self, pool, cr): """ Override of __init__ to add access rights. Access rights are disabled by default, but allowed on some specific fields defined in self.SELF_{READ/WRITE}ABLE_FIELDS. """ init_res = super(Users, self).__init__(pool, cr) # duplicate list to avoid modifying the original reference type(self).SELF_READABLE_FIELDS = type(self).SELF_READABLE_FIELDS + [ 'cofficebot_state' ] return init_res
class User(models.Model): _inherit = ['res.users'] hours_last_month = fields.Float(related='employee_id.hours_last_month') hours_last_month_display = fields.Char( related='employee_id.hours_last_month_display') attendance_state = fields.Selection(related='employee_id.attendance_state') last_check_in = fields.Datetime( related='employee_id.last_attendance_id.check_in') last_check_out = fields.Datetime( related='employee_id.last_attendance_id.check_out') def __init__(self, pool, cr): """ Override of __init__ to add access rights. Access rights are disabled by default, but allowed on some specific fields defined in self.SELF_{READ/WRITE}ABLE_FIELDS. """ attendance_readable_fields = [ 'hours_last_month', 'hours_last_month_display', 'attendance_state', 'last_check_in', 'last_check_out' ] super(User, self).__init__(pool, cr) # duplicate list to avoid modifying the original reference type(self).SELF_READABLE_FIELDS = type( self).SELF_READABLE_FIELDS + attendance_readable_fields
class ConverterTest(models.Model): _name = 'web_editor.converter.test' _description = 'Web Editor Converter Test' # disable translation export for those brilliant field labels and values _translate = False char = fields.Char() integer = fields.Integer() float = fields.Float() numeric = fields.Float(digits=(16, 2)) many2one = fields.Many2one('web_editor.converter.test.sub') binary = fields.Binary(attachment=False) date = fields.Date() datetime = fields.Datetime() selection_str = fields.Selection( [ ('A', "Qu'il n'est pas arrivé à Toronto"), ('B', "Qu'il était supposé arriver à Toronto"), ('C', "Qu'est-ce qu'il fout ce maudit pancake, tabernacle ?"), ('D', "La réponse D"), ], string=u"Lorsqu'un pancake prend l'avion à destination de Toronto et " u"qu'il fait une escale technique à St Claude, on dit:") html = fields.Html() text = fields.Text()
class SMSTemplatePreview(models.TransientModel): _inherit = "sms.template" _name = "sms.template.preview" _description = "SMS Template Preview" @api.model def _selection_target_model(self): models = self.env['ir.model'].search([]) return [(model.model, model.name) for model in models] @api.model def _selection_languages(self): return self.env['res.lang'].get_installed() @api.model def default_get(self, fields): result = super(SMSTemplatePreview, self).default_get(fields) sms_template = self._context.get( 'default_sms_template_id') and self.env['sms.template'].browse( self._context['default_sms_template_id']) or False if sms_template and not result.get('res_id'): result['res_id'] = self.env[sms_template.model].search([], limit=1) return result sms_template_id = fields.Many2one( 'sms.template') # NOTE This should probably be required lang = fields.Selection(_selection_languages, string='Template Preview Language') model_id = fields.Many2one('ir.model', related="sms_template_id.model_id") res_id = fields.Integer(string='Record ID') resource_ref = fields.Reference(string='Record reference', selection='_selection_target_model', compute='_compute_resource_ref', inverse='_inverse_resource_ref') @api.depends('model_id', 'res_id') def _compute_resource_ref(self): for preview in self: if preview.model_id: preview.resource_ref = '%s,%s' % (preview.model_id.model, preview.res_id or 0) else: preview.resource_ref = False def _inverse_resource_ref(self): for preview in self: if preview.resource_ref: preview.res_id = preview.resource_ref.id @api.onchange('lang', 'resource_ref') def on_change_resource_ref(self): # Update res_id and body depending of the resource_ref if self.resource_ref: self.res_id = self.resource_ref.id if self.sms_template_id: template = self.sms_template_id.with_context(lang=self.lang) self.body = template._render_template(template.body, template.model, self.res_id or 0)
class AccountCommonReport(models.TransientModel): _name = "account.common.report" _description = "Account Common Report" company_id = fields.Many2one('res.company', string='Company', required=True, default=lambda self: self.env.company) journal_ids = fields.Many2many( 'account.journal', string='Journals', required=True, default=lambda self: self.env['account.journal'].search([( 'company_id', '=', self.company_id.id)])) date_from = fields.Date(string='Start Date') date_to = fields.Date(string='End Date') target_move = fields.Selection([ ('posted', 'All Posted Entries'), ('all', 'All Entries'), ], string='Target Moves', required=True, default='posted') @api.onchange('company_id') def _onchange_company_id(self): if self.company_id: self.journal_ids = self.env['account.journal'].search([ ('company_id', '=', self.company_id.id) ]) else: self.journal_ids = self.env['account.journal'].search([]) def _build_contexts(self, data): result = {} result['journal_ids'] = 'journal_ids' in data['form'] and data['form'][ 'journal_ids'] or False result['state'] = 'target_move' in data['form'] and data['form'][ 'target_move'] or '' result['date_from'] = data['form']['date_from'] or False result['date_to'] = data['form']['date_to'] or False result['strict_range'] = True if result['date_from'] else False result['company_id'] = data['form']['company_id'][0] or False return result def _print_report(self, data): raise NotImplementedError() def check_report(self): self.ensure_one() data = {} data['ids'] = self.env.context.get('active_ids', []) data['model'] = self.env.context.get('active_model', 'ir.ui.menu') data['form'] = self.read([ 'date_from', 'date_to', 'journal_ids', 'target_move', 'company_id' ])[0] used_context = self._build_contexts(data) data['form']['used_context'] = dict(used_context, lang=get_lang(self.env).code) return self.with_context(discard_logo_check=True)._print_report(data)
class FleetVehicleOdometer(models.Model): _name = 'fleet.vehicle.odometer' _description = 'Odometer log for a vehicle' _order = 'date desc' name = fields.Char(compute='_compute_vehicle_log_name', store=True) date = fields.Date(default=fields.Date.context_today) value = fields.Float('Odometer Value', group_operator="max") vehicle_id = fields.Many2one('fleet.vehicle', 'Vehicle', required=True) unit = fields.Selection(related='vehicle_id.odometer_unit', string="Unit", readonly=True) driver_id = fields.Many2one(related="vehicle_id.driver_id", string="Driver", readonly=False) @api.depends('vehicle_id', 'date') def _compute_vehicle_log_name(self): for record in self: name = record.vehicle_id.name if not name: name = str(record.date) elif record.date: name += ' / ' + str(record.date) record.name = name @api.onchange('vehicle_id') def _onchange_vehicle(self): if self.vehicle_id: self.unit = self.vehicle_id.odometer_unit
class BaseUpdateTranslations(models.TransientModel): _name = 'base.update.translations' _description = 'Update Translations' @api.model def _get_languages(self): return self.env['res.lang'].get_installed() lang = fields.Selection(_get_languages, 'Language', required=True) @api.model def _get_lang_name(self, lang_code): lang = self.env['res.lang']._lang_get(lang_code) if not lang: raise UserError(_('No language with code "%s" exists') % lang_code) return lang.name def act_update(self): this = self[0] lang_name = self._get_lang_name(this.lang) with tempfile.NamedTemporaryFile() as buf: tools.trans_export(this.lang, ['all'], buf, 'po', self._cr) context = {'create_empty_translation': True} tools.trans_load_data(self._cr, buf, 'po', this.lang, lang_name=lang_name, context=context) return {'type': 'ir.actions.act_window_close'}
class BarcodeRule(models.Model): _inherit = 'barcode.rule' type = fields.Selection(selection_add=[( 'weight', 'Weighted Product'), ('location', 'Location'), ('lot', 'Lot'), ('package', 'Package')])
class ProductAttribute(models.Model): _inherit = "product.attribute" display_type = fields.Selection( [('radio', 'Radio'), ('select', 'Select'), ('color', 'Color')], default='radio', required=True, help="The display type used in the Product Configurator.")
class StockTrackingLines(models.TransientModel): _name = 'stock.track.line' _description = 'Stock Track Line' product_id = fields.Many2one('product.product', 'Product', readonly=True) tracking = fields.Selection([('lot', 'Tracked by lot'), ('serial', 'Tracked by serial number')], readonly=True) wizard_id = fields.Many2one('stock.track.confirmation', readonly=True)
class ProductTemplateAttributeValue(models.Model): _inherit = "product.template.attribute.value" html_color = fields.Char('HTML Color Index', related="product_attribute_value_id.html_color") is_custom = fields.Boolean('Is custom value', related="product_attribute_value_id.is_custom") display_type = fields.Selection( related='product_attribute_value_id.display_type', readonly=True)
class PaymentAcquirer(models.Model): _inherit = 'payment.acquirer' so_reference_type = fields.Selection(string='Communication', selection=[ ('so_name', 'Based on Document Reference'), ('partner', 'Based on Customer ID')], default='so_name', help='You can set here the communication type that will appear on sales orders.' 'The communication will be given to the customer when they choose the payment method.')