class ProductCategory(models.Model): _inherit = 'product.category' route_ids = fields.Many2many('stock.location.route', 'stock_location_route_categ', 'categ_id', 'route_id', 'Routes', domain=[('product_categ_selectable', '=', True)]) removal_strategy_id = fields.Many2one( 'product.removal', 'Force Removal Strategy', help= "Set a specific removal strategy that will be used regardless of the source location for this product category" ) total_route_ids = fields.Many2many('stock.location.route', string='Total routes', compute='_compute_total_route_ids', readonly=True) @api.one def _compute_total_route_ids(self): category = self routes = self.route_ids while category.parent_id: category = category.parent_id routes |= category.route_ids self.total_route_ids = routes
class ProductTemplate(models.Model): _inherit = "product.template" taxes_id = fields.Many2many('account.tax', 'product_taxes_rel', 'prod_id', 'tax_id', string='Customer Taxes', domain=[('type_tax_use', '=', 'sale')]) supplier_taxes_id = fields.Many2many('account.tax', 'product_supplier_taxes_rel', 'prod_id', 'tax_id', string='Vendor Taxes', domain=[('type_tax_use', '=', 'purchase')]) property_account_income_id = fields.Many2one( 'account.account', company_dependent=True, string="Income Account", oldname="property_account_income", domain=[('deprecated', '=', False)], help= "Keep this field empty to use the default value from the product category." ) property_account_expense_id = fields.Many2one( 'account.account', company_dependent=True, string="Expense Account", oldname="property_account_expense", domain=[('deprecated', '=', False)], help= "The expense is accounted for when a vendor bill is validated, except in anglo-saxon accounting with perpetual inventory valuation in which case the expense (Cost of Goods Sold account) is recognized at the customer invoice validation. If the field is empty, it uses the one defined in the product category." ) @api.multi def _get_product_accounts(self): return { 'income': self.property_account_income_id or self.categ_id.property_account_income_categ_id, 'expense': self.property_account_expense_id or self.categ_id.property_account_expense_categ_id } @api.multi def _get_asset_accounts(self): res = {} res['stock_input'] = False res['stock_output'] = False return res @api.multi def get_product_accounts(self, fiscal_pos=None): accounts = self._get_product_accounts() if not fiscal_pos: fiscal_pos = self.env['account.fiscal.position'] return fiscal_pos.map_accounts(accounts)
class account_financial_report(models.Model): _name = "account.financial.report" _description = "Account Report" @api.multi @api.depends('parent_id', 'parent_id.level') def _get_level(self): '''Returns a dictionary with key=the ID of a record and value = the level of this record in the tree structure.''' for report in self: level = 0 if report.parent_id: level = report.parent_id.level + 1 report.level = level def _get_children_by_order(self): '''returns a recordset of all the children computed recursively, and sorted by sequence. Ready for the printing''' res = self children = self.search([('parent_id', 'in', self.ids)], order='sequence ASC') if children: for child in children: res += child._get_children_by_order() return res name = fields.Char('Report Name', required=True, translate=True) parent_id = fields.Many2one('account.financial.report', 'Parent') children_ids = fields.One2many('account.financial.report', 'parent_id', 'Account Report') sequence = fields.Integer('Sequence') level = fields.Integer(compute='_get_level', string='Level', store=True) type = fields.Selection([ ('sum', 'View'), ('accounts', 'Accounts'), ('account_type', 'Account Type'), ('account_report', 'Report Value'), ], 'Type', default='sum') account_ids = fields.Many2many('account.account', 'account_account_financial_report', 'report_line_id', 'account_id', 'Accounts') account_report_id = fields.Many2one('account.financial.report', 'Report Value') account_type_ids = fields.Many2many('account.account.type', 'account_account_financial_report_type', 'report_id', 'account_type_id', 'Account Types') sign = fields.Selection([(-1, 'Reverse balance sign'), (1, 'Preserve balance sign')], 'Sign on Reports', required=True, default=1, help='For accounts that are typically more debited than credited and that you would like to print as negative amounts in your reports, you should reverse the sign of the balance; e.g.: Expense account. The same applies for accounts that are typically more credited than debited and that you would like to print as positive amounts in your reports; e.g.: Income account.') display_detail = fields.Selection([ ('no_detail', 'No detail'), ('detail_flat', 'Display children flat'), ('detail_with_hierarchy', 'Display children with hierarchy') ], 'Display details', default='detail_flat') style_overwrite = fields.Selection([ (0, 'Automatic formatting'), (1, 'Main Title 1 (bold, underlined)'), (2, 'Title 2 (bold)'), (3, 'Title 3 (bold, smaller)'), (4, 'Normal Text'), (5, 'Italic Text (smaller)'), (6, 'Smallest Text'), ], 'Financial Report Style', default=0, help="You can set up here the format you want this record to be displayed. If you leave the automatic formatting, it will be computed based on the financial reports hierarchy (auto-computed field 'level').")
class StockImmediateTransfer(models.TransientModel): _name = 'stock.immediate.transfer' _description = 'Immediate Transfer' pick_ids = fields.Many2many('stock.picking', 'stock_picking_transfer_rel') def process(self): pick_to_backorder = self.env['stock.picking'] pick_to_do = self.env['stock.picking'] for picking in self.pick_ids: # If still in draft => confirm and assign if picking.state == 'draft': picking.action_confirm() if picking.state != 'assigned': picking.action_assign() if picking.state != 'assigned': raise UserError( _("Could not reserve all requested products. Please use the \'Mark as Todo\' button to handle the reservation manually." )) for move in picking.move_lines: for move_line in move.move_line_ids: move_line.qty_done = move_line.product_uom_qty if picking._check_backorder(): pick_to_backorder |= picking continue pick_to_do |= picking # Process every picking that do not require a backorder, then return a single backorder wizard for every other ones. if pick_to_do: pick_to_do.action_done() if pick_to_backorder: return pick_to_backorder.action_generate_backorder_wizard() return False
class BaseLanguageInstall(models.TransientModel): _inherit = "base.language.install" website_ids = fields.Many2many('website', string='Websites to translate') @api.model def default_get(self, fields): defaults = super(BaseLanguageInstall, self).default_get(fields) website_id = self._context.get('params', {}).get('website_id') if website_id: if 'website_ids' not in defaults: defaults['website_ids'] = [] defaults['website_ids'].append(website_id) return defaults @api.multi def lang_install(self): action = super(BaseLanguageInstall, self).lang_install() lang = self.env['res.lang'].search([('code', '=', self.lang)], limit=1) if self.website_ids and lang: self.website_ids.write({'language_ids': [(4, lang.id)]}) params = self._context.get('params', {}) if 'url_return' in params: return { 'url': params['url_return'].replace('[lang]', self.lang), 'type': 'ir.actions.act_url', 'target': 'self' } return action
class HolidaysSummaryDept(models.TransientModel): _name = 'hr.holidays.summary.dept' _description = 'HR Leaves Summary Report By Department' date_from = fields.Date(string='From', required=True, default=lambda *a: time.strftime('%Y-%m-01')) depts = fields.Many2many('hr.department', 'summary_dept_rel', 'sum_id', 'dept_id', string='Department(s)') holiday_type = fields.Selection([('Approved', 'Approved'), ('Confirmed', 'Confirmed'), ('both', 'Both Approved and Confirmed')], string='Leave Type', required=True, default='Approved') @api.multi def print_report(self): self.ensure_one() [data] = self.read() if not data.get('depts'): raise UserError( _('You have to select at least one Department. And try again.') ) departments = self.env['hr.department'].browse(data['depts']) datas = {'ids': [], 'model': 'hr.department', 'form': data} return self.env.ref( 'hr_holidays.action_report_holidayssummary').with_context( from_transient_model=True).report_action(departments, data=datas)
class RestaurantPrinter(models.Model): _name = 'restaurant.printer' name = fields.Char('Printer Name', required=True, default='Printer', help='An internal identification of the printer') proxy_ip = fields.Char('Proxy IP Address', help="The IP Address or hostname of the Printer's hardware proxy") product_categories_ids = fields.Many2many('pos.category', 'printer_category_rel', 'printer_id', 'category_id', string='Printed Product Categories')
class LunchOrderLineLucky(models.TransientModel): _name = 'lunch.order.line.lucky' def _default_supplier(self): suppliers_obj = self.env['lunch.product'].search([]).mapped("supplier") return [(4, supplier.id) for supplier in suppliers_obj] product_id = fields.Many2one('lunch.product', 'Product', store=True) supplier_ids = fields.Many2many(comodel_name='res.partner', string='Vendor', domain=lambda self: [("id", "in", self.env['lunch.product'].search([]).mapped("supplier").ids)]) is_max_budget = fields.Boolean("I'm not feeling rich", help="Enable this option to set a maximal budget for your lucky order.", store=True) max_budget = fields.Float('Max Budget', store=True) @api.multi def random_pick(self): """ To pick a random product from the selected suppliers, and create an order with this one """ self.ensure_one() if self.is_max_budget: products_obj = self.env['lunch.product'].search([('supplier', "in", self.supplier_ids.ids), ('price', '<=', self.max_budget)]) else: products_obj = self.env['lunch.product'].search([('supplier', "in", self.supplier_ids.ids)]) if len(products_obj) != 0: random_product_obj = self.env['lunch.product'].browse([random.choice(products_obj.ids)]) order_line = self.env['lunch.order.line'].create({ 'product_id': random_product_obj.id, 'order_id': self._context['active_id'] }) else: raise UserError(_('No product is matching your request. Now you will starve to death.'))
class EventRegistration(models.Model): """ Store answers on attendees. """ _inherit = 'event.registration' answer_ids = fields.Many2many('event.answer', 'event_registration_answer', string='Answers')
class PosDetails(models.TransientModel): _name = 'pos.details.wizard' _description = 'Open Sales Details Report' def _default_start_date(self): """ Find the earliest start_date of the latests sessions """ # restrict to configs available to the user config_ids = self.env['pos.config'].search([]).ids # exclude configs has not been opened for 2 days self.env.cr.execute( """ SELECT max(start_at) as start, config_id FROM pos_session WHERE config_id = ANY(%s) AND start_at > (NOW() - INTERVAL '2 DAYS') GROUP BY config_id """, (config_ids, )) latest_start_dates = [ res['start'] for res in self.env.cr.dictfetchall() ] # earliest of the latest sessions return latest_start_dates and min( latest_start_dates) or fields.Datetime.now() start_date = fields.Datetime(required=True, default=_default_start_date) end_date = fields.Datetime(required=True, default=fields.Datetime.now) pos_config_ids = fields.Many2many( 'pos.config', 'pos_detail_configs', default=lambda s: s.env['pos.config'].search([])) @api.onchange('start_date') def _onchange_start_date(self): if self.start_date and self.end_date and self.end_date < self.start_date: self.end_date = self.start_date @api.onchange('end_date') def _onchange_end_date(self): if self.end_date and self.end_date < self.start_date: self.start_date = self.end_date @api.multi def generate_report(self): if (not self.env.user.company_id.logo): raise UserError( _("You have to set a logo or a layout for your company.")) elif (not self.env.user.company_id.external_report_layout): raise UserError( _("You have to set your reports's header and footer layout.")) data = { 'date_start': self.start_date, 'date_stop': self.end_date, 'config_ids': self.pos_config_ids.ids } return self.env.ref('point_of_sale.sale_details_report').report_action( [], data=data)
class Partner(models.Model): _inherit = 'res.partner' website_tag_ids = fields.Many2many('res.partner.tag', 'res_partner_res_partner_tag_rel', 'partner_id', 'tag_id', string='Website tags')
class RepairFee(models.Model): _name = 'mrp.repair.fee' _description = 'Repair Fees Line' repair_id = fields.Many2one( 'mrp.repair', 'Repair Order Reference', index=True, ondelete='cascade', required=True) name = fields.Char('Description', index=True, required=True) product_id = fields.Many2one('product.product', 'Product') product_uom_qty = fields.Float('Quantity', digits=dp.get_precision('Product Unit of Measure'), required=True, default=1.0) price_unit = fields.Float('Unit Price', required=True) product_uom = fields.Many2one('product.uom', 'Product Unit of Measure', required=True) price_subtotal = fields.Float('Subtotal', compute='_compute_price_subtotal', digits=0) tax_id = fields.Many2many('account.tax', 'repair_fee_line_tax', 'repair_fee_line_id', 'tax_id', 'Taxes') invoice_line_id = fields.Many2one('account.invoice.line', 'Invoice Line', copy=False, readonly=True) invoiced = fields.Boolean('Invoiced', copy=False, readonly=True) @api.one @api.depends('price_unit', 'repair_id', 'product_uom_qty', 'product_id') def _compute_price_subtotal(self): taxes = self.tax_id.compute_all(self.price_unit, self.repair_id.pricelist_id.currency_id, self.product_uom_qty, self.product_id, self.repair_id.partner_id) self.price_subtotal = taxes['total_excluded'] @api.onchange('repair_id', 'product_id', 'product_uom_qty') def onchange_product_id(self): """ On change of product it sets product quantity, tax account, name, uom of product, unit price and price subtotal. """ if not self.product_id: return partner = self.repair_id.partner_id pricelist = self.repair_id.pricelist_id if partner and self.product_id: self.tax_id = partner.property_account_position_id.map_tax(self.product_id.taxes_id, self.product_id, partner).ids if self.product_id: self.name = self.product_id.display_name self.product_uom = self.product_id.uom_id.id warning = False if not pricelist: warning = { 'title': _('No Pricelist!'), 'message': _('You have to select a pricelist in the Repair form !\n Please set one before choosing a product.')} else: price = pricelist.get_product_price(self.product_id, self.product_uom_qty, partner) if price is False: warning = { 'title': _('No valid pricelist line found !'), 'message': _("Couldn't find a pricelist line matching this product and quantity.\nYou have to change either the product, the quantity or the pricelist.")} else: self.price_unit = price if warning: return {'warning': warning}
class MaintenanceTeam(models.Model): _name = 'maintenance.team' _description = 'Maintenance Teams' name = fields.Char(required=True, translate=True) member_ids = fields.Many2many('res.users', 'maintenance_team_users_rel', string="Team Members") color = fields.Integer("Color Index", default=0) request_ids = fields.One2many('maintenance.request', 'maintenance_team_id', copy=False) equipment_ids = fields.One2many('maintenance.equipment', 'maintenance_team_id', copy=False) # For the dashboard only todo_request_ids = fields.One2many('maintenance.request', string="Requests", copy=False, compute='_compute_todo_requests') todo_request_count = fields.Integer(string="Number of Requests", compute='_compute_todo_requests') todo_request_count_date = fields.Integer( string="Number of Requests Scheduled", compute='_compute_todo_requests') todo_request_count_high_priority = fields.Integer( string="Number of Requests in High Priority", compute='_compute_todo_requests') todo_request_count_block = fields.Integer( string="Number of Requests Blocked", compute='_compute_todo_requests') todo_request_count_unscheduled = fields.Integer( string="Number of Requests Unscheduled", compute='_compute_todo_requests') @api.one @api.depends('request_ids.stage_id.done') def _compute_todo_requests(self): self.todo_request_ids = self.request_ids.filtered( lambda e: e.stage_id.done == False) self.todo_request_count = len(self.todo_request_ids) self.todo_request_count_date = len( self.todo_request_ids.filtered(lambda e: e.schedule_date != False)) self.todo_request_count_high_priority = len( self.todo_request_ids.filtered(lambda e: e.priority == '3')) self.todo_request_count_block = len( self.todo_request_ids.filtered( lambda e: e.kanban_state == 'blocked')) self.todo_request_count_unscheduled = len( self.todo_request_ids.filtered(lambda e: not e.schedule_date)) @api.one @api.depends('equipment_ids') def _compute_equipment(self): self.equipment_count = len(self.equipment_ids)
class MailActivityType(models.Model): """ Activity Types are used to categorize activities. Each type is a different kind of activity e.g. call, mail, meeting. An activity can be generic i.e. available for all models using activities; or specific to a model in which case res_model_id field should be used. """ _name = 'mail.activity.type' _description = 'Activity Type' _rec_name = 'name' _order = 'sequence, id' name = fields.Char('Name', required=True, translate=True) summary = fields.Char('Summary', translate=True) sequence = fields.Integer('Sequence', default=10) days = fields.Integer( '# Days', default=0, help= 'Number of days before executing the action. It allows to plan the action deadline.' ) icon = fields.Char('Icon', help="Font awesome icon e.g. fa-tasks") res_model_id = fields.Many2one( 'ir.model', 'Model', index=True, help='Specify a model if the activity should be specific to a model' ' and not available when managing activities for other models.') next_type_ids = fields.Many2many('mail.activity.type', 'mail_activity_rel', 'activity_id', 'recommended_id', string='Recommended Next Activities') previous_type_ids = fields.Many2many('mail.activity.type', 'mail_activity_rel', 'recommended_id', 'activity_id', string='Preceding Activities') category = fields.Selection( [('default', 'Other')], default='default', string='Category', help= 'Categories may trigger specific behavior like opening calendar view')
class PosConfig(models.Model): _inherit = 'pos.config' iface_splitbill = fields.Boolean( string='Bill Splitting', help='Enables Bill Splitting in the Point of Sale.') iface_printbill = fields.Boolean( string='Bill Printing', help='Allows to print the Bill before payment.') iface_orderline_notes = fields.Boolean( string='Orderline Notes', help='Allow custom notes on Orderlines.') floor_ids = fields.One2many( 'restaurant.floor', 'pos_config_id', string='Restaurant Floors', help='The restaurant floors served by this point of sale.') printer_ids = fields.Many2many('restaurant.printer', 'pos_config_printer_rel', 'config_id', 'printer_id', string='Order Printers') is_table_management = fields.Boolean('Table Management') is_order_printer = fields.Boolean('Order Printers') module_pos_restaurant = fields.Boolean(default=True) @api.onchange('iface_tipproduct') def _onchange_tipproduct(self): if self.iface_tipproduct: self.tip_product_id = self.env.ref( 'point_of_sale.product_product_tip', False) else: self.tip_product_id = False @api.onchange('module_pos_restaurant') def _onchange_module_pos_restaurant(self): if not self.module_pos_restaurant: self.update({ 'iface_printbill': False, 'iface_splitbill': False, 'iface_tipproduct': False, 'is_order_printer': False, 'is_table_management': False, 'iface_orderline_notes': False }) @api.onchange('is_table_management') def _onchange_is_table_management(self): if not self.is_table_management: self.floor_ids = [(5, 0, 0)] @api.onchange('is_order_printer') def _onchange_is_order_printer(self): if not self.is_order_printer: self.printer_ids = [(5, 0, 0)]
class BlogTag(models.Model): _name = 'blog.tag' _description = 'Blog Tag' _inherit = ['website.seo.metadata'] _order = 'name' name = fields.Char('Name', required=True, translate=True) post_ids = fields.Many2many('blog.post', string='Posts') _sql_constraints = [ ('name_uniq', 'unique (name)', "Tag name already exists !"), ]
class TrackTag(models.Model): _name = "event.track.tag" _description = 'Track Tag' _order = 'name' name = fields.Char('Tag') track_ids = fields.Many2many('event.track', string='Tracks') color = fields.Integer(string='Color Index', default=10) _sql_constraints = [ ('name_uniq', 'unique (name)', "Tag name already exists !"), ]
class ProductTemplate(models.Model): _inherit = "product.template" optional_product_ids = fields.Many2many( 'product.template', 'product_optional_rel', 'src_id', 'dest_id', string='Optional Products', help="Optional Products are suggested " "whenever the customer hits *Add to Cart* (cross-sell strategy, " "e.g. for computers: warranty, software, etc.).")
class IrModelFieldsAnonymizationHistory(models.Model): _name = 'ir.model.fields.anonymization.history' _order = "date desc" date = fields.Datetime(required=True, readonly=True) field_ids = fields.Many2many( 'ir.model.fields.anonymization', 'anonymized_field_to_history_rel', 'field_id', 'history_id', string='Fields', readonly=True ) state = fields.Selection(selection=ANONYMIZATION_HISTORY_STATE, string='Status', required=True, readonly=True) direction = fields.Selection(selection=ANONYMIZATION_DIRECTION, required=True, readonly=True) msg = fields.Text('Message', readonly=True) filepath = fields.Char('File path', readonly=True)
class HrPayslipEmployees(models.TransientModel): _name = 'hr.payslip.employees' _description = 'Generate payslips for all selected employees' employee_ids = fields.Many2many('hr.employee', 'hr_employee_group_rel', 'payslip_id', 'employee_id', 'Employees') @api.multi def compute_sheet(self): payslips = self.env['hr.payslip'] [data] = self.read() active_id = self.env.context.get('active_id') if active_id: [run_data] = self.env['hr.payslip.run'].browse(active_id).read( ['date_start', 'date_end', 'credit_note']) from_date = run_data.get('date_start') to_date = run_data.get('date_end') if not data['employee_ids']: raise UserError( _("You must select employee(s) to generate payslip(s).")) for employee in self.env['hr.employee'].browse(data['employee_ids']): slip_data = self.env['hr.payslip'].onchange_employee_id( from_date, to_date, employee.id, contract_id=False) res = { 'employee_id': employee.id, 'name': slip_data['value'].get('name'), 'struct_id': slip_data['value'].get('struct_id'), 'contract_id': slip_data['value'].get('contract_id'), 'payslip_run_id': active_id, 'input_line_ids': [(0, 0, x) for x in slip_data['value'].get('input_line_ids')], 'worked_days_line_ids': [(0, 0, x) for x in slip_data['value'].get('worked_days_line_ids')], 'date_from': from_date, 'date_to': to_date, 'credit_note': run_data.get('credit_note'), 'company_id': employee.company_id.id, } payslips += self.env['hr.payslip'].create(res) payslips.compute_sheet() return {'type': 'ir.actions.act_window_close'}
class AccountInvoiceLine(models.Model): _inherit = 'account.invoice.line' _order = 'invoice_id, layout_category_id, sequence, id' sale_line_ids = fields.Many2many('sale.order.line', 'sale_order_line_invoice_rel', 'invoice_line_id', 'order_line_id', string='Sales Order Lines', readonly=True, copy=False) layout_category_id = fields.Many2one('sale.layout_category', string='Section') layout_category_sequence = fields.Integer(string='Layout Sequence')
class AccountCommonReport(models.TransientModel): _name = "account.common.report" _description = "Account Common Report" company_id = fields.Many2one('res.company', string='Company', readonly=True, default=lambda self: self.env.user.company_id) journal_ids = fields.Many2many( 'account.journal', string='Journals', required=True, default=lambda self: self.env['account.journal'].search([])) 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') 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 return result def _print_report(self, data): raise NotImplementedError() @api.multi 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'])[0] used_context = self._build_contexts(data) data['form']['used_context'] = dict(used_context, lang=self.env.context.get('lang') or 'en_US') return self.with_context(discard_logo_check=True)._print_report(data)
class HrSalaryEmployeeBymonth(models.TransientModel): _name = 'hr.salary.employee.month' _description = 'Hr Salary Employee By Month Report' def _get_default_category(self): return self.env['hr.salary.rule.category'].search( [('code', '=', 'NET')], limit=1) def _get_default_start_date(self): year = fields.Date.from_string(fields.Date.today()).strftime('%Y') return '{}-01-01'.format(year) def _get_default_end_date(self): date = fields.Date.from_string(fields.Date.today()) return date.strftime('%Y') + '-' + date.strftime( '%m') + '-' + date.strftime('%d') start_date = fields.Date(string='Start Date', required=True, default=_get_default_start_date) end_date = fields.Date(string='End Date', required=True, default=_get_default_end_date) employee_ids = fields.Many2many('hr.employee', 'payroll_year_rel', 'payroll_year_id', 'employee_id', string='Employees', required=True) category_id = fields.Many2one('hr.salary.rule.category', string='Category', required=True, default=_get_default_category) @api.multi def print_report(self): """ To get the date and print the report @return: return report """ self.ensure_one() data = {'ids': self.env.context.get('active_ids', [])} res = self.read() res = res and res[0] or {} data.update({'form': res}) return self.env.ref( 'l10n_in_hr_payroll.action_report_hrsalarybymonth').report_action( self, data=data)
class EmployeeCategory(models.Model): _name = "hr.employee.category" _description = "Employee Category" name = fields.Char(string="Employee Tag", required=True) color = fields.Integer(string='Color Index') employee_ids = fields.Many2many('hr.employee', 'employee_category_rel', 'category_id', 'emp_id', string='Employees') _sql_constraints = [ ('name_uniq', 'unique (name)', "Tag name already exists !"), ]
class AccountReportGeneralLedger(models.TransientModel): _inherit = "account.common.account.report" _name = "account.report.general.ledger" _description = "General Ledger Report" initial_balance = fields.Boolean(string='Include Initial Balances', help='If you selected date, this field allow you to add a row to display the amount of debit/credit/balance that precedes the filter you\'ve set.') sortby = fields.Selection([('sort_date', 'Date'), ('sort_journal_partner', 'Journal & Partner')], string='Sort by', required=True, default='sort_date') journal_ids = fields.Many2many('account.journal', 'account_report_general_ledger_journal_rel', 'account_id', 'journal_id', string='Journals', required=True) def _print_report(self, data): data = self.pre_print_report(data) data['form'].update(self.read(['initial_balance', 'sortby'])[0]) if data['form'].get('initial_balance') and not data['form'].get('date_from'): raise UserError(_("You must define a Start Date")) records = self.env[data['model']].browse(data.get('ids', [])) return self.env.ref('account.action_report_general_ledger').with_context(landscape=True).report_action(records, data=data)
class Partner(models.Model): _inherit = 'res.partner' team_id = fields.Many2one('crm.team', string='Sales Channel', oldname='section_id') opportunity_ids = fields.One2many('crm.lead', 'partner_id', string='Opportunities', domain=[('type', '=', 'opportunity')]) meeting_ids = fields.Many2many('calendar.event', 'calendar_event_res_partner_rel', 'res_partner_id', 'calendar_event_id', string='Meetings', copy=False) opportunity_count = fields.Integer("Opportunity", compute='_compute_opportunity_count') meeting_count = fields.Integer("# Meetings", compute='_compute_meeting_count') @api.multi def _compute_opportunity_count(self): for partner in self: operator = 'child_of' if partner.is_company else '=' # the opportunity count should counts the opportunities of this company and all its contacts partner.opportunity_count = self.env['crm.lead'].search_count([ ('partner_id', operator, partner.id), ('type', '=', 'opportunity') ]) @api.multi def _compute_meeting_count(self): for partner in self: partner.meeting_count = len(partner.meeting_ids) @api.multi def schedule_meeting(self): partner_ids = self.ids partner_ids.append(self.env.user.partner_id.id) action = self.env.ref('calendar.action_calendar_event').read()[0] action['context'] = { 'search_default_partner_ids': self._context['partner_name'], 'default_partner_ids': partner_ids, } return action
class AccountBalanceReport(models.TransientModel): _inherit = "account.common.account.report" _name = 'account.balance.report' _description = 'Trial Balance Report' journal_ids = fields.Many2many('account.journal', 'account_balance_report_journal_rel', 'account_id', 'journal_id', string='Journals', required=True, default=[]) def _print_report(self, data): data = self.pre_print_report(data) records = self.env[data['model']].browse(data.get('ids', [])) return self.env.ref( 'account.action_report_trial_balance').report_action(records, data=data)
class AccountAgedTrialBalance(models.TransientModel): _name = 'account.aged.trial.balance' _inherit = 'account.common.partner.report' _description = 'Account Aged Trial balance Report' period_length = fields.Integer(string='Period Length (days)', required=True, default=30) journal_ids = fields.Many2many('account.journal', string='Journals', required=True) date_from = fields.Date(default=lambda *a: time.strftime('%Y-%m-%d')) def _print_report(self, data): res = {} data = self.pre_print_report(data) data['form'].update(self.read(['period_length'])[0]) period_length = data['form']['period_length'] if period_length <= 0: raise UserError(_('You must set a period length greater than 0.')) if not data['form']['date_from']: raise UserError(_('You must set a start date.')) start = datetime.strptime(data['form']['date_from'], "%Y-%m-%d") for i in range(5)[::-1]: stop = start - relativedelta(days=period_length - 1) res[str(i)] = { 'name': (i != 0 and (str( (5 - (i + 1)) * period_length) + '-' + str( (5 - i) * period_length)) or ('+' + str(4 * period_length))), 'stop': start.strftime('%Y-%m-%d'), 'start': (i != 0 and stop.strftime('%Y-%m-%d') or False), } start = stop - relativedelta(days=1) data['form'].update(res) return self.env.ref( 'account.action_report_aged_partner_balance').with_context( landscape=True).report_action(self, data=data)
class AccountBudgetPost(models.Model): _name = "account.budget.post" _order = "name" _description = "Budgetary Position" name = fields.Char('Name', required=True) account_ids = fields.Many2many('account.account', 'account_budget_rel', 'budget_id', 'account_id', 'Accounts', domain=[('deprecated', '=', False)]) crossovered_budget_line = fields.One2many('crossovered.budget.lines', 'general_budget_id', 'Budget Lines') company_id = fields.Many2one('res.company', 'Company', required=True, default=lambda self: self.env['res.company']. _company_default_get('account.budget.post')) def _check_account_ids(self, vals): # Raise an error to prevent the account.budget.post to have not specified account_ids. # This check is done on create because require=True doesn't work on Many2many fields. if 'account_ids' in vals: account_ids = self.resolve_2many_commands('account_ids', vals['account_ids']) else: account_ids = self.account_ids if not account_ids: raise ValidationError( _('The budget must have at least one account.')) @api.model def create(self, vals): self._check_account_ids(vals) return super(AccountBudgetPost, self).create(vals) @api.multi def write(self, vals): self._check_account_ids(vals) return super(AccountBudgetPost, self).write(vals)
class StockWarnInsufficientQty(models.AbstractModel): _name = 'stock.warn.insufficient.qty' product_id = fields.Many2one('product.product', 'Product', required=True) location_id = fields.Many2one('stock.location', 'Location', domain="[('usage', '=', 'internal')]", required=True) quant_ids = fields.Many2many('stock.quant', compute='_compute_quant_ids') @api.one @api.depends('product_id') def _compute_quant_ids(self): self.quant_ids = self.env['stock.quant'].search([ ('product_id', '=', self.product_id.id), ('location_id.usage', '=', 'internal') ]) def action_done(self): raise NotImplementedError()