Ejemplo n.º 1
0
class EventEvent(models.Model):
    """ Override Event model to add optional questions when buying tickets. """
    _inherit = 'event.event'

    question_ids = fields.One2many('event.question',
                                   'event_id',
                                   'Questions',
                                   copy=True)
    general_question_ids = fields.One2many('event.question',
                                           'event_id',
                                           'General Questions',
                                           domain=[('is_individual', '=',
                                                    False)])
    specific_question_ids = fields.One2many('event.question',
                                            'event_id',
                                            'Specific Questions',
                                            domain=[('is_individual', '=',
                                                     True)])

    @api.onchange('event_type_id')
    def _onchange_type(self):
        super(EventEvent, self)._onchange_type()
        if self.event_type_id.use_questions and self.event_type_id.question_ids:
            self.question_ids = [(5, 0, 0)] + [
                (0, 0, {
                    'title': question.title,
                    'sequence': question.sequence,
                    'is_individual': question.is_individual,
                }) for question in self.event_type_id.question_ids
            ]
Ejemplo n.º 2
0
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)
Ejemplo n.º 3
0
class SaleQuoteTemplate(models.Model):
    _name = "sale.quote.template"
    _description = "Sale Quotation Template"

    name = fields.Char('Quotation Template', required=True)
    website_description = fields.Html('Description',
                                      translate=html_translate,
                                      sanitize_attributes=False)
    quote_line = fields.One2many('sale.quote.line',
                                 'quote_id',
                                 'Quotation Template Lines',
                                 copy=True)
    note = fields.Text('Terms and conditions')
    options = fields.One2many('sale.quote.option',
                              'template_id',
                              'Optional Products Lines',
                              copy=True)
    number_of_days = fields.Integer(
        'Quotation Duration',
        help='Number of days for the validity date computation of the quotation'
    )
    require_payment = fields.Selection(
        [(0, 'Online Signature'), (1, 'Online Payment')],
        default=0,
        string='Confirmation Mode',
        help=
        "Choose how you want to confirm an order to launch the delivery process. You can either "
        "request a digital signature or an upfront payment. With a digital signature, you can "
        "request the payment when issuing the invoice.")
    mail_template_id = fields.Many2one(
        'mail.template',
        'Confirmation Mail',
        domain=[('model', '=', 'sale.order')],
        help=
        "This e-mail template will be sent on confirmation. Leave empty to send nothing."
    )
    active = fields.Boolean(
        default=True,
        help=
        "If unchecked, it will allow you to hide the quotation template without removing it."
    )

    @api.multi
    def open_template(self):
        self.ensure_one()
        return {
            'type': 'ir.actions.act_url',
            'target': 'self',
            'url': '/quote/template/%d' % self.id
        }
Ejemplo n.º 4
0
class Employee(models.Model):

    _inherit = "hr.employee"

    manager = fields.Boolean(string='Is a Manager')
    medic_exam = fields.Date(string='Medical Examination Date', groups="hr.group_hr_user")
    place_of_birth = fields.Char('Place of Birth', groups="hr.group_hr_user")
    children = fields.Integer(string='Number of Children', groups="hr.group_hr_user")
    vehicle = fields.Char(string='Company Vehicle', groups="hr.group_hr_user")
    vehicle_distance = fields.Integer(
        string='Home-Work Dist.', help="In kilometers", groups="hr.group_hr_user")
    contract_ids = fields.One2many('hr.contract', 'employee_id', string='Contracts')
    contract_id = fields.Many2one('hr.contract', compute='_compute_contract_id', string='Current Contract', help='Latest contract of the employee')
    contracts_count = fields.Integer(compute='_compute_contracts_count', string='Contracts')

    def _compute_contract_id(self):
        """ get the lastest contract """
        Contract = self.env['hr.contract']
        for employee in self:
            employee.contract_id = Contract.search([('employee_id', '=', employee.id)], order='date_start desc', limit=1)

    def _compute_contracts_count(self):
        # read_group as sudo, since contract count is displayed on form view
        contract_data = self.env['hr.contract'].sudo().read_group([('employee_id', 'in', self.ids)], ['employee_id'], ['employee_id'])
        result = dict((data['employee_id'][0], data['employee_id_count']) for data in contract_data)
        for employee in self:
            employee.contracts_count = result.get(employee.id, 0)
Ejemplo n.º 5
0
class EventType(models.Model):
    _inherit = 'event.type'

    @api.model
    def _get_default_event_ticket_ids(self):
        product = self.env.ref('event_sale.product_product_event',
                               raise_if_not_found=False)
        if not product:
            return False
        return [(0, 0, {
            'name': _('Registration'),
            'product_id': product.id,
            'price': 0,
        })]

    use_ticketing = fields.Boolean('Ticketing')
    event_ticket_ids = fields.One2many('event.event.ticket',
                                       'event_type_id',
                                       string='Tickets',
                                       default=_get_default_event_ticket_ids)

    @api.onchange('name')
    def _onchange_name(self):
        if self.name:
            self.event_ticket_ids.filtered(
                lambda ticket: ticket.name == _('Registration')).update(
                    {'name': _('Registration for %s') % self.name})
Ejemplo n.º 6
0
class HrSalaryRuleCategory(models.Model):
    _name = 'hr.salary.rule.category'
    _description = 'Salary Rule Category'

    name = fields.Char(required=True, translate=True)
    code = fields.Char(required=True)
    parent_id = fields.Many2one(
        'hr.salary.rule.category',
        string='Parent',
        help=
        "Linking a salary category to its parent is used only for the reporting purpose."
    )
    children_ids = fields.One2many('hr.salary.rule.category',
                                   'parent_id',
                                   string='Children')
    note = fields.Text(string='Description')
    company_id = fields.Many2one(
        'res.company',
        string='Company',
        default=lambda self: self.env['res.company']._company_default_get())

    @api.constrains('parent_id')
    def _check_parent_id(self):
        if not self._check_recursion():
            raise ValidationError(
                _('Error! You cannot create recursive hierarchy of Salary Rule Category.'
                  ))
Ejemplo n.º 7
0
class ResPartner(models.Model):
    _inherit = 'res.partner'

    wishlist_ids = fields.One2many('product.wishlist',
                                   'partner_id',
                                   string='Wishlist',
                                   domain=[('active', '=', True)])
Ejemplo n.º 8
0
class Holidays(models.Model):
    _inherit = "hr.holidays"

    timesheet_ids = fields.One2many('account.analytic.line',
                                    'holiday_id',
                                    string="Analytic Lines")

    def _validate_leave_request(self):
        """ Timesheet will be generated on leave validation only if a timesheet_project_id and a
            timesheet_task_id are set on the corresponding leave type. The generated timesheet will
            be attached to this project/task.
        """
        # create the timesheet on the vacation project
        for holiday in self.filtered(
                lambda request: request.type == 'remove' and request.
                holiday_type == 'employee' and request.holiday_status_id.
                timesheet_project_id and request.holiday_status_id.
                timesheet_task_id):
            holiday_project = holiday.holiday_status_id.timesheet_project_id
            holiday_task = holiday.holiday_status_id.timesheet_task_id

            work_hours_data = [
                item for item in holiday.employee_id.iter_work_hours_count(
                    fields.Datetime.from_string(holiday.date_from),
                    fields.Datetime.from_string(holiday.date_to))
            ]
            for index, (day_date,
                        work_hours_count) in enumerate(work_hours_data):
                self.env['account.analytic.line'].create({
                    'name':
                    "%s (%s/%s)" %
                    (holiday.name or '', index + 1, len(work_hours_data)),
                    'project_id':
                    holiday_project.id,
                    'task_id':
                    holiday_task.id,
                    'account_id':
                    holiday_project.analytic_account_id.id,
                    'unit_amount':
                    work_hours_count,
                    'user_id':
                    holiday.employee_id.user_id.id,
                    'date':
                    fields.Date.to_string(day_date),
                    'holiday_id':
                    holiday.id,
                    'employee_id':
                    holiday.employee_id.id,
                })

        return super(Holidays, self)._validate_leave_request()

    @api.multi
    def action_refuse(self):
        """ Remove the timesheets linked to the refused holidays """
        result = super(Holidays, self).action_refuse()
        timesheets = self.sudo().mapped('timesheet_ids')
        timesheets.write({'holiday_id': False})
        timesheets.unlink()
        return result
Ejemplo n.º 9
0
class Event(models.Model):
    _inherit = 'event.event'

    event_ticket_ids = fields.One2many('event.event.ticket',
                                       'event_id',
                                       string='Event Ticket',
                                       copy=True)

    @api.onchange('event_type_id')
    def _onchange_type(self):
        super(Event, self)._onchange_type()
        if self.event_type_id.use_ticketing:
            self.event_ticket_ids = [(5, 0, 0)] + [(0, 0, {
                'name':
                self.name and _('Registration for %s') % self.name
                or ticket.name,
                'product_id':
                ticket.product_id.id,
                'price':
                ticket.price,
            }) for ticket in self.event_type_id.event_ticket_ids]

    @api.multi
    def _is_event_registrable(self):
        self.ensure_one()
        if not self.event_ticket_ids:
            return True
        return all(
            self.event_ticket_ids.with_context(
                active_test=False).mapped(lambda t: t.product_id.active))
Ejemplo n.º 10
0
class ResCompany(models.Model):
    _inherit = 'res.company'

    resource_calendar_ids = fields.One2many('resource.calendar', 'company_id',
                                            'Working Hours')
    resource_calendar_id = fields.Many2one('resource.calendar',
                                           'Default Working Hours',
                                           ondelete='restrict')

    @api.model
    def _init_data_resource_calendar(self):
        for company in self.search([('resource_calendar_id', '=', False)]):
            company.resource_calendar_id = self.env[
                'resource.calendar'].create({
                    'name': _('Standard 40 hours/week')
                }).id

    @api.model
    def create(self, values):
        if not values.get('resource_calendar_id'):
            values['resource_calendar_id'] = self.env[
                'resource.calendar'].create({
                    'name': _('Standard 40 hours/week')
                }).id
        company = super(ResCompany, self).create(values)
        # calendar created from form view: no company_id set because record was still not created
        if not company.resource_calendar_id.company_id:
            company.resource_calendar_id.company_id = company.id
        return company
Ejemplo n.º 11
0
class ProductCategory(models.Model):
    _name = "product.category"
    _description = "Product Category"
    _parent_name = "parent_id"
    _parent_store = True
    _parent_order = 'name'
    _rec_name = 'complete_name'
    _order = 'parent_left'

    name = fields.Char('Name', index=True, required=True, translate=True)
    complete_name = fields.Char('Complete Name',
                                compute='_compute_complete_name',
                                store=True)
    parent_id = fields.Many2one('product.category',
                                'Parent Category',
                                index=True,
                                ondelete='cascade')
    child_id = fields.One2many('product.category', 'parent_id',
                               'Child Categories')
    parent_left = fields.Integer('Left Parent', index=1)
    parent_right = fields.Integer('Right Parent', index=1)
    product_count = fields.Integer(
        '# Products',
        compute='_compute_product_count',
        help=
        "The number of products under this category (Does not consider the children categories)"
    )

    @api.depends('name', 'parent_id.complete_name')
    def _compute_complete_name(self):
        for category in self:
            if category.parent_id:
                category.complete_name = '%s / %s' % (
                    category.parent_id.complete_name, category.name)
            else:
                category.complete_name = category.name

    def _compute_product_count(self):
        read_group_res = self.env['product.template'].read_group(
            [('categ_id', 'child_of', self.ids)], ['categ_id'], ['categ_id'])
        group_data = dict((data['categ_id'][0], data['categ_id_count'])
                          for data in read_group_res)
        for categ in self:
            product_count = 0
            for sub_categ_id in categ.search([('id', 'child_of', categ.id)
                                              ]).ids:
                product_count += group_data.get(sub_categ_id, 0)
            categ.product_count = product_count

    @api.constrains('parent_id')
    def _check_category_recursion(self):
        if not self._check_recursion():
            raise ValidationError(
                _('Error ! You cannot create recursive categories.'))
        return True

    @api.model
    def name_create(self, name):
        return self.create({'name': name}).name_get()[0]
Ejemplo n.º 12
0
class MailThread(models.AbstractModel):
    _inherit = 'mail.thread'

    _mail_post_token_field = 'access_token' # token field for external posts, to be overridden

    website_message_ids = fields.One2many('mail.message', 'res_id', string='Website Messages',
        domain=lambda self: [('model', '=', self._name), ('message_type', '=', 'comment')], auto_join=True,
        help="Website communication history")
Ejemplo n.º 13
0
class ResUsers(models.Model):
    _inherit = 'res.users'

    resource_ids = fields.One2many(
        'resource.resource', 'user_id', 'Resources')
    resource_calendar_id = fields.Many2one(
        'resource.calendar', 'Default Working Hours',
        related='resource_ids.calendar_id')
Ejemplo n.º 14
0
class ResCompany(models.Model):
    _inherit = "res.company"

    ldaps = fields.One2many('res.company.ldap',
                            'company',
                            string='LDAP Parameters',
                            copy=True,
                            groups="base.group_system")
Ejemplo n.º 15
0
class EventType(models.Model):
    _inherit = 'event.type'

    use_questions = fields.Boolean('Questions to Attendees')
    question_ids = fields.One2many('event.question',
                                   'event_type_id',
                                   string='Questions',
                                   copy=True)
Ejemplo n.º 16
0
class CrossoveredBudget(models.Model):
    _name = "crossovered.budget"
    _description = "Budget"
    _inherit = ['mail.thread']

    name = fields.Char('Budget Name',
                       required=True,
                       states={'done': [('readonly', True)]})
    creating_user_id = fields.Many2one('res.users',
                                       'Responsible',
                                       default=lambda self: self.env.user)
    date_from = fields.Date('Start Date',
                            required=True,
                            states={'done': [('readonly', True)]})
    date_to = fields.Date('End Date',
                          required=True,
                          states={'done': [('readonly', True)]})
    state = fields.Selection([('draft', 'Draft'), ('cancel', 'Cancelled'),
                              ('confirm', 'Confirmed'),
                              ('validate', 'Validated'), ('done', 'Done')],
                             'Status',
                             default='draft',
                             index=True,
                             required=True,
                             readonly=True,
                             copy=False,
                             track_visibility='always')
    crossovered_budget_line = fields.One2many(
        'crossovered.budget.lines',
        'crossovered_budget_id',
        'Budget Lines',
        states={'done': [('readonly', True)]},
        copy=True)
    company_id = fields.Many2one('res.company',
                                 'Company',
                                 required=True,
                                 default=lambda self: self.env['res.company'].
                                 _company_default_get('account.budget.post'))

    @api.multi
    def action_budget_confirm(self):
        self.write({'state': 'confirm'})

    @api.multi
    def action_budget_draft(self):
        self.write({'state': 'draft'})

    @api.multi
    def action_budget_validate(self):
        self.write({'state': 'validate'})

    @api.multi
    def action_budget_cancel(self):
        self.write({'state': 'cancel'})

    @api.multi
    def action_budget_done(self):
        self.write({'state': 'done'})
Ejemplo n.º 17
0
class MrpBom(models.Model):
    _name = 'mrp.bom'
    _description = 'Bill of Material'
    _inherit = 'mrp.bom'

    sub_products = fields.One2many('mrp.subproduct',
                                   'bom_id',
                                   'Byproducts',
                                   copy=True)
Ejemplo n.º 18
0
class ProductAttribute(models.Model):
    _name = "product.attribute"
    _description = "Product Attribute"
    _order = 'sequence, name'

    name = fields.Char('Name', required=True, translate=True)
    value_ids = fields.One2many('product.attribute.value',
                                'attribute_id',
                                'Values',
                                copy=True)
    sequence = fields.Integer('Sequence', help="Determine the display order")
    attribute_line_ids = fields.One2many('product.attribute.line',
                                         'attribute_id', 'Lines')
    create_variant = fields.Boolean(
        default=True,
        help=
        "Check this if you want to create multiple variants for this attribute."
    )
Ejemplo n.º 19
0
class ProductTemplate(models.Model):
    _inherit = "product.template"

    bom_ids = fields.One2many('mrp.bom', 'product_tmpl_id',
                              'Bill of Materials')
    bom_count = fields.Integer('# Bill of Material',
                               compute='_compute_bom_count')
    used_in_bom_count = fields.Integer('# of BoM Where is Used',
                                       compute='_compute_used_in_bom_count')
    mo_count = fields.Integer('# Manufacturing Orders',
                              compute='_compute_mo_count')
    produce_delay = fields.Float(
        'Manufacturing Lead Time',
        default=0.0,
        help=
        "Average delay in days to produce this product. In the case of multi-level BOM, the manufacturing lead times of the components will be added."
    )

    def _compute_bom_count(self):
        read_group_res = self.env['mrp.bom'].read_group(
            [('product_tmpl_id', 'in', self.ids)], ['product_tmpl_id'],
            ['product_tmpl_id'])
        mapped_data = dict([(data['product_tmpl_id'][0],
                             data['product_tmpl_id_count'])
                            for data in read_group_res])
        for product in self:
            product.bom_count = mapped_data.get(product.id, 0)

    @api.multi
    def _compute_used_in_bom_count(self):
        for template in self:
            template.used_in_bom_count = self.env['mrp.bom'].search_count([
                ('bom_line_ids.product_id', 'in',
                 template.product_variant_ids.ids)
            ])

    @api.multi
    def action_used_in_bom(self):
        self.ensure_one()
        action = self.env.ref('mrp.mrp_bom_form_action').read()[0]
        action['domain'] = [('bom_line_ids.product_id', 'in',
                             self.product_variant_ids.ids)]
        return action

    @api.one
    def _compute_mo_count(self):
        # TDE FIXME: directly use a read_group
        self.mo_count = sum(
            self.mapped('product_variant_ids').mapped('mo_count'))

    @api.multi
    def action_view_mos(self):
        product_ids = self.mapped('product_variant_ids').ids
        action = self.env.ref('mrp.act_product_mrp_production').read()[0]
        action['domain'] = [('product_id', 'in', product_ids)]
        action['context'] = {}
        return action
Ejemplo n.º 20
0
class SaleOrderLine(models.Model):
    _inherit = "sale.order.line"

    linked_line_id = fields.Many2one('sale.order.line',
                                     string='Linked Order Line',
                                     domain="[('order_id', '!=', order_id)]",
                                     ondelete='cascade')
    option_line_ids = fields.One2many('sale.order.line',
                                      'linked_line_id',
                                      string='Options Linked')
Ejemplo n.º 21
0
class RestaurantFloor(models.Model):

    _name = 'restaurant.floor'

    name = fields.Char('Floor Name', required=True, help='An internal identification of the restaurant floor')
    pos_config_id = fields.Many2one('pos.config', string='Point of Sale')
    background_image = fields.Binary('Background Image', attachment=True, help='A background image used to display a floor layout in the point of sale interface')
    background_color = fields.Char('Background Color', help='The background color of the floor layout, (must be specified in a html-compatible format)', default='rgb(210, 210, 210)')
    table_ids = fields.One2many('restaurant.table', 'floor_id', string='Tables', help='The list of tables in this floor')
    sequence = fields.Integer('Sequence', help='Used to sort Floors', default=1)
Ejemplo n.º 22
0
class PortalWizard(models.TransientModel):
    """
        A wizard to manage the creation/removal of portal users.
    """

    _name = 'portal.wizard'
    _description = 'Portal Access Management'

    def _default_portal(self):
        return self.env['res.groups'].search([('is_portal', '=', True)],
                                             limit=1)

    portal_id = fields.Many2one(
        'res.groups',
        domain=[('is_portal', '=', True)],
        required=True,
        string='Portal',
        default=_default_portal,
        help="The portal that users can be added in or removed from.")
    user_ids = fields.One2many('portal.wizard.user',
                               'wizard_id',
                               string='Users')
    welcome_message = fields.Text(
        'Invitation Message',
        help=
        "This text is included in the email sent to new users of the portal.")

    @api.onchange('portal_id')
    def onchange_portal_id(self):
        # for each partner, determine corresponding portal.wizard.user records
        partner_ids = self.env.context.get('active_ids', [])
        contact_ids = set()
        user_changes = []
        for partner in self.env['res.partner'].sudo().browse(partner_ids):
            contact_partners = partner.child_ids or [partner]
            for contact in contact_partners:
                # make sure that each contact appears at most once in the list
                if contact.id not in contact_ids:
                    contact_ids.add(contact.id)
                    in_portal = False
                    if contact.user_ids:
                        in_portal = self.portal_id in contact.user_ids[
                            0].groups_id
                    user_changes.append((0, 0, {
                        'partner_id': contact.id,
                        'email': contact.email,
                        'in_portal': in_portal,
                    }))
        self.user_ids = user_changes

    @api.multi
    def action_apply(self):
        self.ensure_one()
        self.user_ids.action_apply()
        return {'type': 'ir.actions.act_window_close'}
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 RegistrationEditor(models.TransientModel):
    _name = "registration.editor"

    sale_order_id = fields.Many2one('sale.order', 'Sales Order', required=True)
    event_registration_ids = fields.One2many('registration.editor.line', 'editor_id', string='Registrations to Edit')

    @api.model
    def default_get(self, fields):
        res = super(RegistrationEditor, self).default_get(fields)
        if not res.get('sale_order_id'):
            sale_order_id = res.get('sale_order_id', self._context.get('active_id'))
            res['sale_order_id'] = sale_order_id
        sale_order = self.env['sale.order'].browse(res.get('sale_order_id'))
        registrations = self.env['event.registration'].search([
            ('sale_order_id', '=', sale_order.id),
            ('event_ticket_id', 'in', sale_order.mapped('order_line.event_ticket_id').ids),
            ('state', '!=', 'cancel')])

        attendee_list = []
        for so_line in [l for l in sale_order.order_line if l.event_ticket_id]:
            existing_registrations = [r for r in registrations if r.event_ticket_id == so_line.event_ticket_id]
            for reg in existing_registrations:
                attendee_list.append({
                    'event_id': reg.event_id.id,
                    'event_ticket_id': reg.event_ticket_id.id,
                    'registration_id': reg.id,
                    'name': reg.name,
                    'email': reg.email,
                    'phone': reg.phone,
                    'sale_order_line_id': so_line.id,
                })
            for count in range(int(so_line.product_uom_qty) - len(existing_registrations)):
                attendee_list.append([0, 0, {
                    'event_id': so_line.event_id.id,
                    'event_ticket_id': so_line.event_ticket_id.id,
                    'sale_order_line_id': so_line.id,
                }])
        res['event_registration_ids'] = attendee_list
        res = self._convert_to_write(res)
        return res

    @api.multi
    def action_make_registration(self):
        self.ensure_one()
        for registration_line in self.event_registration_ids:
            values = registration_line.get_registration_data()
            if registration_line.registration_id:
                registration_line.registration_id.write(values)
            else:
                self.env['event.registration'].create(values)
        if self.env.context.get('active_model') == 'sale.order':
            for order in self.env['sale.order'].browse(self.env.context.get('active_ids', [])):
                order.order_line._update_registrations(confirm=False)
        return {'type': 'ir.actions.act_window_close'}
Ejemplo n.º 25
0
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)]
Ejemplo n.º 26
0
class ResPartner(models.Model):
    """ Inherits partner and adds Tasks information in the partner form """
    _inherit = 'res.partner'

    task_ids = fields.One2many('project.task', 'partner_id', string='Tasks')
    task_count = fields.Integer(compute='_compute_task_count', string='# Tasks')

    def _compute_task_count(self):
        fetch_data = self.env['project.task'].read_group([('partner_id', 'in', self.ids)], ['partner_id'], ['partner_id'])
        result = dict((data['partner_id'][0], data['partner_id_count']) for data in fetch_data)
        for partner in self:
            partner.task_count = result.get(partner.id, 0)
Ejemplo n.º 27
0
class Product(models.Model):
    _inherit = 'product.product'

    event_ticket_ids = fields.One2many('event.event.ticket',
                                       'product_id',
                                       string='Event Tickets')

    @api.onchange('event_ok')
    def _onchange_event_ok(self):
        """ Redirection, inheritance mechanism hides the method on the model """
        if self.event_ok:
            self.type = 'service'
Ejemplo n.º 28
0
class Documentation(models.Model):
    _name = 'forum.documentation.toc'
    _description = 'Documentation ToC'
    _inherit = ['website.seo.metadata']
    _order = "parent_left"
    _parent_order = "sequence, name"
    _parent_store = True

    sequence = fields.Integer('Sequence')
    name = fields.Char('Name', required=True, translate=True)
    introduction = fields.Html('Introduction', translate=True)
    parent_id = fields.Many2one('forum.documentation.toc',
                                string='Parent Table Of Content',
                                ondelete='cascade')
    child_ids = fields.One2many('forum.documentation.toc',
                                'parent_id',
                                string='Children Table Of Content')
    parent_left = fields.Integer(string='Left Parent', index=True)
    parent_right = fields.Integer(string='Right Parent', index=True)
    post_ids = fields.One2many('forum.post',
                               'documentation_toc_id',
                               string='Posts')
    forum_id = fields.Many2one('forum.forum', string='Forum', required=True)

    @api.multi
    def name_get(self):
        res = []
        for record in self:
            name = record.name
            if record.parent_id:
                name = record.parent_id.name + ' / ' + name
            res.append((record.id, name))
        return res

    @api.constrains('parent_id')
    def _check_parent_id(self):
        if not self._check_recursion():
            raise ValidationError(
                _('Error ! You cannot create recursive categories.'))
Ejemplo n.º 29
0
class ProductPublicCategory(models.Model):
    _name = "product.public.category"
    _inherit = ["website.seo.metadata"]
    _description = "Website Product Category"
    _order = "sequence, name"

    name = fields.Char(required=True, translate=True)
    parent_id = fields.Many2one('product.public.category', string='Parent Category', index=True)
    child_id = fields.One2many('product.public.category', 'parent_id', string='Children Categories')
    sequence = fields.Integer(help="Gives the sequence order when displaying a list of product categories.")
    # NOTE: there is no 'default image', because by default we don't show
    # thumbnails for categories. However if we have a thumbnail for at least one
    # category, then we display a default image on the other, so that the
    # buttons have consistent styling.
    # In this case, the default image is set by the js code.
    image = fields.Binary(attachment=True, help="This field holds the image used as image for the category, limited to 1024x1024px.")
    image_medium = fields.Binary(string='Medium-sized image', attachment=True,
                                 help="Medium-sized image of the category. It is automatically "
                                 "resized as a 128x128px image, with aspect ratio preserved. "
                                 "Use this field in form views or some kanban views.")
    image_small = fields.Binary(string='Small-sized image', attachment=True,
                                help="Small-sized image of the category. It is automatically "
                                "resized as a 64x64px image, with aspect ratio preserved. "
                                "Use this field anywhere a small image is required.")

    @api.model
    def create(self, vals):
        tools.image_resize_images(vals)
        return super(ProductPublicCategory, self).create(vals)

    @api.multi
    def write(self, vals):
        tools.image_resize_images(vals)
        return super(ProductPublicCategory, self).write(vals)

    @api.constrains('parent_id')
    def check_parent_id(self):
        if not self._check_recursion():
            raise ValueError(_('Error ! You cannot create recursive categories.'))

    @api.multi
    def name_get(self):
        res = []
        for category in self:
            names = [category.name]
            parent_category = category.parent_id
            while parent_category:
                names.append(parent_category.name)
                parent_category = parent_category.parent_id
            res.append((category.id, ' / '.join(reversed(names))))
        return res
Ejemplo n.º 30
0
class HrEmployee(models.Model):
    _inherit = "hr.employee"

    goal_ids = fields.One2many('gamification.goal',
                               string='Employee HR Goals',
                               compute='_compute_employee_goals')
    badge_ids = fields.One2many(
        'gamification.badge.user',
        string='Employee Badges',
        compute='_compute_employee_badges',
        help=
        "All employee badges, linked to the employee either directly or through the user"
    )
    has_badges = fields.Boolean(compute='_compute_employee_badges')
    # necessary for correct dependencies of badge_ids and has_badges
    direct_badge_ids = fields.One2many(
        'gamification.badge.user',
        'employee_id',
        help="Badges directly linked to the employee")

    @api.depends('user_id.goal_ids.challenge_id.category')
    def _compute_employee_goals(self):
        for employee in self:
            employee.goal_ids = self.env['gamification.goal'].search([
                ('user_id', '=', employee.user_id.id),
                ('challenge_id.category', '=', 'hr'),
            ])

    @api.depends('direct_badge_ids', 'user_id.badge_ids.employee_id')
    def _compute_employee_badges(self):
        for employee in self:
            badge_ids = self.env['gamification.badge.user'].search([
                '|', ('employee_id', '=', employee.id), '&',
                ('employee_id', '=', False),
                ('user_id', '=', employee.user_id.id)
            ])
            employee.has_badges = bool(badge_ids)
            employee.badge_ids = badge_ids