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 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 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 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 DecimalPrecisionTestModel(models.Model): _name = 'decimal.precision.test' _description = 'Decimal Precision Test' float = fields.Float() float_2 = fields.Float(digits=(16, 2)) float_4 = fields.Float(digits=(16, 4))
class User(models.Model): _inherit = "res.users" leave_manager_id = fields.Many2one(related='employee_id.leave_manager_id') show_leaves = fields.Boolean(related='employee_id.show_leaves') allocation_used_count = fields.Float( related='employee_id.allocation_used_count') allocation_count = fields.Float(related='employee_id.allocation_count') leave_date_to = fields.Date(related='employee_id.leave_date_to') is_absent = fields.Boolean(related='employee_id.is_absent') allocation_used_display = fields.Char( related='employee_id.allocation_used_display') allocation_display = fields.Char(related='employee_id.allocation_display') 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. """ readable_fields = [ 'leave_manager_id', 'show_leaves', 'allocation_used_count', 'allocation_count', 'leave_date_to', 'is_absent', 'allocation_used_display', 'allocation_display', ] init_res = super(User, self).__init__(pool, cr) # duplicate list to avoid modifying the original reference type(self).SELF_READABLE_FIELDS = type( self).SELF_READABLE_FIELDS + readable_fields return init_res def _compute_im_status(self): super(User, self)._compute_im_status() on_leave_user_ids = self._get_on_leave_ids() for user in self: if user.id in on_leave_user_ids: if user.im_status == 'online': user.im_status = 'leave_online' else: user.im_status = 'leave_offline' @api.model def _get_on_leave_ids(self, partner=False): now = fields.Datetime.now() field = 'partner_id' if partner else 'id' self.env.cr.execute( '''SELECT res_users.%s FROM res_users JOIN hr_leave ON hr_leave.user_id = res_users.id AND state not in ('cancel', 'refuse') AND res_users.active = 't' AND date_from <= %%s AND date_to >= %%s''' % field, (now, now)) return [r[0] for r in self.env.cr.fetchall()]
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 GroupOperator(models.Model): _name = 'export.group_operator' _description = 'Export Group Operator' int_sum = fields.Integer(group_operator='sum') int_max = fields.Integer(group_operator='max') float_min = fields.Float(group_operator='min') float_avg = fields.Float(group_operator='avg') date_max = fields.Date(group_operator='max') bool_and = fields.Boolean(group_operator='bool_and') bool_or = fields.Boolean(group_operator='bool_or') many2one = fields.Many2one('export.integer') one2many = fields.One2many('export.group_operator.one2many', 'parent_id')
class LeadScoringFrequency(models.Model): _name = 'crm.lead.scoring.frequency' _description = 'Lead Scoring Frequency' variable = fields.Char('Variable', index=True) value = fields.Char('Value') won_count = fields.Float( 'Won Count', digits=(16, 1)) # Float because we add 0.1 to avoid zero Frequency issue lost_count = fields.Float( 'Lost Count', digits=(16, 1)) # Float because we add 0.1 to avoid zero Frequency issue team_id = fields.Many2one('crm.team', 'Sales Team')
class ResConfigSettings(models.TransientModel): _inherit = 'res.config.settings' country_code = fields.Char(string="Company Country code", related='company_id.country_id.code', readonly=True) account_check_printing_layout = fields.Selection( related='company_id.account_check_printing_layout', string="Check Layout", readonly=False, 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'.") account_check_printing_date_label = fields.Boolean( related='company_id.account_check_printing_date_label', string="Print Date Label", readonly=False, 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( related='company_id.account_check_printing_multi_stub', string='Multi-Pages Check Stub', readonly=False, 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( related='company_id.account_check_printing_margin_top', string='Check Top Margin', readonly=False, help= "Adjust the margins of generated checks to make it fit your printer's settings." ) account_check_printing_margin_left = fields.Float( related='company_id.account_check_printing_margin_left', string='Check Left Margin', readonly=False, help= "Adjust the margins of generated checks to make it fit your printer's settings." ) account_check_printing_margin_right = fields.Float( related='company_id.account_check_printing_margin_right', string='Check Right Margin', readonly=False, help= "Adjust the margins of generated checks to make it fit your printer's settings." )
class ProductPackaging(models.Model): _name = "product.packaging" _description = "Product Packaging" _order = 'sequence' _check_company_auto = True name = fields.Char('Package Type', required=True) sequence = fields.Integer( 'Sequence', default=1, help="The first in the sequence is the default one.") product_id = fields.Many2one('product.product', string='Product', check_company=True) qty = fields.Float('Contained Quantity', help="Quantity of products contained in the packaging.") barcode = fields.Char( 'Barcode', copy=False, help= "Barcode used for packaging identification. Scan this packaging barcode from a transfer in the Barcode app to move all the contained units" ) product_uom_id = fields.Many2one('uom.uom', related='product_id.uom_id', readonly=True) company_id = fields.Many2one('res.company', 'Company', index=True)
class FloatModel(models.Model): _name = model('float') _description = 'Tests: Base Import Model Float' value = fields.Float() value2 = fields.Monetary() currency_id = fields.Many2one('res.currency')
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 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 LunchTopping(models.Model): """""" _name = 'lunch.topping' _description = 'Lunch Extras' name = fields.Char('Name', required=True) company_id = fields.Many2one('res.company', default=lambda self: self.env.company) currency_id = fields.Many2one('res.currency', related='company_id.currency_id') price = fields.Float('Price', digits='Account', required=True) category_id = fields.Many2one('lunch.product.category') topping_category = fields.Integer('Topping Category', help="This field is a technical field", required=True, default=1) def name_get(self): currency_id = self.env.company.currency_id res = dict(super(LunchTopping, self).name_get()) for topping in self: price = formatLang(self.env, topping.price, currency_obj=currency_id) res[topping.id] = '%s %s' % (topping.name, price) return list(res.items())
class AccountAnalyticLine(models.Model): _name = 'account.analytic.line' _description = 'Analytic Line' _order = 'date desc, id desc' @api.model def _default_user(self): return self.env.context.get('user_id', self.env.user.id) name = fields.Char('Description', required=True) date = fields.Date('Date', required=True, index=True, default=fields.Date.context_today) amount = fields.Monetary('Amount', required=True, default=0.0) unit_amount = fields.Float('Quantity', default=0.0) product_uom_id = fields.Many2one('uom.uom', string='Unit of Measure', domain="[('category_id', '=', product_uom_category_id)]") product_uom_category_id = fields.Many2one(related='product_uom_id.category_id', readonly=True) account_id = fields.Many2one('account.analytic.account', 'Analytic Account', required=True, ondelete='restrict', index=True, domain="['|', ('company_id', '=', False), ('company_id', '=', company_id)]") partner_id = fields.Many2one('res.partner', string='Partner', domain="['|', ('company_id', '=', False), ('company_id', '=', company_id)]") user_id = fields.Many2one('res.users', string='User', default=_default_user) tag_ids = fields.Many2many('account.analytic.tag', 'account_analytic_line_tag_rel', 'line_id', 'tag_id', string='Tags', copy=True, domain="['|', ('company_id', '=', False), ('company_id', '=', company_id)]") company_id = fields.Many2one('res.company', string='Company', required=True, readonly=True, default=lambda self: self.env.company) currency_id = fields.Many2one(related="company_id.currency_id", string="Currency", readonly=True, store=True, compute_sudo=True) group_id = fields.Many2one('account.analytic.group', related='account_id.group_id', store=True, readonly=True, compute_sudo=True) @api.constrains('company_id', 'account_id') def _check_company_id(self): for line in self: if line.account_id.company_id and line.company_id.id != line.account_id.company_id.id: raise ValidationError(_('The selected account belongs to another company that the one you\'re trying to create an analytic item for'))
class MrpByProduct(models.Model): _name = 'mrp.bom.byproduct' _description = 'Byproduct' _rec_name = "product_id" _check_company_auto = True product_id = fields.Many2one('product.product', 'By-product', required=True, check_company=True) company_id = fields.Many2one(related='bom_id.company_id', store=True, index=True, readonly=True) product_qty = fields.Float( 'Quantity', default=1.0, digits='Product Unit of Measure', required=True) product_uom_id = fields.Many2one('uom.uom', 'Unit of Measure', required=True) bom_id = fields.Many2one('mrp.bom', 'BoM', ondelete='cascade') routing_id = fields.Many2one( 'mrp.routing', 'Routing', store=True, related='bom_id.routing_id') operation_id = fields.Many2one( 'mrp.routing.workcenter', 'Produced in Operation', check_company=True, domain="[('routing_id', '=', routing_id), '|', ('company_id', '=', company_id), ('company_id', '=', False)]") @api.onchange('product_id') def onchange_product_id(self): """ Changes UoM if product_id changes. """ if self.product_id: self.product_uom_id = self.product_id.uom_id.id @api.onchange('product_uom_id') def onchange_uom(self): res = {} if self.product_uom_id and self.product_id and self.product_uom_id.category_id != self.product_id.uom_id.category_id: res['warning'] = { 'title': _('Warning'), 'message': _('The unit of measure you choose is in a different category than the product unit of measure.') } self.product_uom_id = self.product_id.uom_id.id return res
class ProjectProductEmployeeMap(models.Model): _name = 'project.sale.line.employee.map' _description = 'Project Sales line, employee mapping' @api.model def _default_project_id(self): if self._context.get('active_id'): return self._context['active_id'] return False project_id = fields.Many2one('project.project', "Project", domain=[('billable_type', '!=', 'no')], required=True, default=_default_project_id) employee_id = fields.Many2one('hr.employee', "Employee", required=True) sale_line_id = fields.Many2one('sale.order.line', "Sale Order Item", domain=[('is_service', '=', True)], required=True) price_unit = fields.Float(related='sale_line_id.price_unit', readonly=True) _sql_constraints = [ ('uniqueness_employee', 'UNIQUE(project_id,employee_id)', 'An employee cannot be selected more than once in the mapping. Please remove duplicate(s) and try again.' ), ]
class CashBox(models.TransientModel): _register = False name = fields.Char(string='Reason', required=True) # Attention, we don't set a domain, because there is a journal_type key # in the context of the action amount = fields.Float(string='Amount', digits=0, required=True) def run(self): context = dict(self._context or {}) active_model = context.get('active_model', False) active_ids = context.get('active_ids', []) records = self.env[active_model].browse(active_ids) return self._run(records) def _run(self, records): for box in self: for record in records: if not record.journal_id: raise UserError(_("Please check that the field 'Journal' is set on the Bank Statement")) if not record.journal_id.company_id.transfer_account_id: raise UserError(_("Please check that the field 'Transfer Account' is set on the company.")) box._create_bank_statement_line(record) return {} def _create_bank_statement_line(self, record): for box in self: if record.state == 'confirm': raise UserError(_("You cannot put/take money in/out for a bank statement which is closed.")) values = box._calculate_values_for_statement_line(record) record.write({'line_ids': [(0, False, values)]})
class ProductProduct(models.Model): _name = 'product.product' _inherit = 'product.product' purchased_product_qty = fields.Float(compute='_compute_purchased_product_qty', string='Purchased') def _compute_purchased_product_qty(self): date_from = fields.Datetime.to_string(fields.datetime.now() - timedelta(days=365)) domain = [ ('state', 'in', ['purchase', 'done']), ('product_id', 'in', self.ids), ('date_order', '>', date_from) ] PurchaseOrderLines = self.env['purchase.order.line'].search(domain) order_lines = self.env['purchase.order.line'].read_group(domain, ['product_id', 'product_uom_qty'], ['product_id']) purchased_data = dict([(data['product_id'][0], data['product_uom_qty']) for data in order_lines]) for product in self: if not product.id: product.purchased_product_qty = 0.0 continue product.purchased_product_qty = float_round(purchased_data.get(product.id, 0), precision_rounding=product.uom_id.rounding) def action_view_po(self): action = self.env.ref('purchase.action_purchase_order_report_all').read()[0] action['domain'] = ['&', ('state', 'in', ['purchase', 'done']), ('product_id', 'in', self.ids)] action['context'] = { 'search_default_last_year_purchase': 1, 'search_default_status': 1, 'search_default_order_month': 1, 'graph_measure': 'qty_ordered' } return action
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 LunchProduct(models.Model): """ Products available to order. A product is linked to a specific vendor. """ _name = 'lunch.product' _description = 'Lunch Product' _inherit = 'image.mixin' _order = 'name' name = fields.Char('Product Name', required=True) category_id = fields.Many2one('lunch.product.category', 'Product Category', required=True) description = fields.Text('Description') price = fields.Float('Price', digits='Account', required=True) supplier_id = fields.Many2one('lunch.supplier', 'Vendor', required=True) active = fields.Boolean(default=True) company_id = fields.Many2one('res.company', related='supplier_id.company_id', store=True) currency_id = fields.Many2one('res.currency', related='company_id.currency_id') new_until = fields.Date('New Until') favorite_user_ids = fields.Many2many('res.users', 'lunch_product_favorite_user_rel', 'product_id', 'user_id')
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 CrmPartnerReportAssign(models.Model): """ CRM Lead Report """ _name = "crm.partner.report.assign" _auto = False _description = "CRM Partnership Analysis" partner_id = fields.Many2one('res.partner', 'Partner', required=False, readonly=True) grade_id = fields.Many2one('res.partner.grade', 'Grade', readonly=True) activation = fields.Many2one('res.partner.activation', 'Activation', index=True) user_id = fields.Many2one('res.users', 'User', readonly=True) date_review = fields.Date('Latest Partner Review') date_partnership = fields.Date('Partnership Date') country_id = fields.Many2one('res.country', 'Country', readonly=True) team_id = fields.Many2one('crm.team', 'Sales Team', readonly=True) nbr_opportunities = fields.Integer('# of Opportunity', readonly=True) turnover = fields.Float('Turnover', readonly=True) date = fields.Date('Invoice Account Date', readonly=True) _depends = { 'account.invoice.report': ['invoice_date', 'partner_id', 'price_subtotal', 'state', 'type'], 'crm.lead': ['partner_assigned_id'], 'res.partner': [ 'activation', 'country_id', 'date_partnership', 'date_review', 'grade_id', 'parent_id', 'team_id', 'user_id' ], } def init(self): """ CRM Lead Report @param cr: the current row, from the database cursor """ tools.drop_view_if_exists(self._cr, 'crm_partner_report_assign') self._cr.execute(""" CREATE OR REPLACE VIEW crm_partner_report_assign AS ( SELECT coalesce(i.id, p.id - 1000000000) as id, p.id as partner_id, (SELECT country_id FROM res_partner a WHERE a.parent_id=p.id AND country_id is not null limit 1) as country_id, p.grade_id, p.activation, p.date_review, p.date_partnership, p.user_id, p.team_id, (SELECT count(id) FROM crm_lead WHERE partner_assigned_id=p.id) AS nbr_opportunities, i.price_subtotal as turnover, i.invoice_date FROM res_partner p left join account_invoice_report i on (i.partner_id=p.id and i.type in ('out_invoice','out_refund') and i.state in ('open','in_payment','paid')) )""")
class SaleReport(models.Model): _inherit = 'sale.report' margin = fields.Float('Margin') def _query(self, with_clause='', fields={}, groupby='', from_clause=''): fields['margin'] = ", SUM(l.margin / CASE COALESCE(s.currency_rate, 0) WHEN 0 THEN 1.0 ELSE s.currency_rate END) AS margin" return super(SaleReport, self)._query(with_clause, fields, groupby, from_clause)
class ReportProjectTaskUser(models.Model): _inherit = "report.project.task.user" hours_planned = fields.Float('Planned Hours', readonly=True) hours_effective = fields.Float('Effective Hours', readonly=True) remaining_hours = fields.Float('Remaining Hours', readonly=True) progress = fields.Float('Progress', group_operator='avg', readonly=True) def _select(self): return super(ReportProjectTaskUser, self)._select() + """, progress as progress, t.effective_hours as hours_effective, t.planned_hours - t.effective_hours - t.subtask_effective_hours as remaining_hours, planned_hours as hours_planned""" def _group_by(self): return super(ReportProjectTaskUser, self)._group_by() + """,
class CurrencyRate(models.Model): _name = "res.currency.rate" _description = "Currency Rate" _order = "name desc" name = fields.Date(string='Date', required=True, index=True, default=lambda self: fields.Date.today()) rate = fields.Float( digits=0, default=1.0, help='The rate of the currency to the currency of rate 1') currency_id = fields.Many2one('res.currency', string='Currency', readonly=True) company_id = fields.Many2one('res.company', string='Company', default=lambda self: self.env.company) _sql_constraints = [ ('unique_name_per_day', 'unique (name,currency_id,company_id)', 'Only one currency rate per day allowed!'), ('currency_rate_check', 'CHECK (rate>0)', 'The currency rate must be strictly positive.'), ] @api.model def _name_search(self, name, args=None, operator='ilike', limit=100, name_get_uid=None): if operator in ['=', '!=']: try: date_format = '%Y-%m-%d' if self._context.get('lang'): lang_id = self.env['res.lang']._search( [('code', '=', self._context['lang'])], access_rights_uid=name_get_uid) if lang_id: date_format = self.browse(lang_id).date_format name = time.strftime('%Y-%m-%d', time.strptime(name, date_format)) except ValueError: try: args.append(('rate', operator, float(name))) except ValueError: return [] name = '' operator = 'ilike' return super(CurrencyRate, self)._name_search(name, args=args, operator=operator, limit=limit, name_get_uid=name_get_uid)
class TimesheetAttendance(models.Model): _name = 'hr.timesheet.attendance.report' _auto = False _description = 'Timesheet Attendance Report' user_id = fields.Many2one('res.users') date = fields.Date() total_timesheet = fields.Float() total_attendance = fields.Float() total_difference = fields.Float() def init(self): tools.drop_view_if_exists(self.env.cr, self._table) self._cr.execute("""CREATE OR REPLACE VIEW %s AS ( SELECT max(id) AS id, t.user_id, t.date, coalesce(sum(t.attendance), 0) AS total_attendance, coalesce(sum(t.timesheet), 0) AS total_timesheet, coalesce(sum(t.attendance), 0) - coalesce(sum(t.timesheet), 0) as total_difference FROM ( SELECT -hr_attendance.id AS id, resource_resource.user_id AS user_id, hr_attendance.worked_hours AS attendance, NULL AS timesheet, hr_attendance.check_in::date AS date FROM hr_attendance LEFT JOIN hr_employee ON hr_employee.id = hr_attendance.employee_id LEFT JOIN resource_resource on resource_resource.id = hr_employee.resource_id UNION ALL SELECT ts.id AS id, ts.user_id AS user_id, NULL AS attendance, ts.unit_amount AS timesheet, ts.date AS date FROM account_analytic_line AS ts WHERE ts.project_id IS NOT NULL ) AS t GROUP BY t.user_id, t.date ORDER BY t.date ) """ % self._table)
class ResConfigSettings(models.TransientModel): _inherit = 'res.config.settings' currency_id = fields.Many2one('res.currency', related='company_id.currency_id') company_lunch_minimum_threshold = fields.Float( string="Maximum Allowed Overdraft", readonly=False, related='company_id.lunch_minimum_threshold')
class ComplexModel(models.Model): _name = model('complex') _description = 'Tests: Base Import Model Complex' f = fields.Float() m = fields.Monetary() c = fields.Char() currency_id = fields.Many2one('res.currency') d = fields.Date() dt = fields.Datetime()