Example #1
0
class test_inherit_property(models.Model):
    _name = 'test.inherit.property'
    _description = 'Test Inherit Property'

    name = fields.Char('Name', required=True)
    property_foo = fields.Integer(string='Foo', company_dependent=True)
    property_bar = fields.Integer(string='Bar', company_dependent=True)
Example #2
0
class PreviewModel(models.Model):
    _name = model('preview')
    _description = 'Tests : Base Import Model Preview'

    name = fields.Char('Name')
    somevalue = fields.Integer(string='Some Value', required=True)
    othervalue = fields.Integer(string='Other Variable')
Example #3
0
class report_paperformat(models.Model):
    _name = "report.paperformat"
    _description = "Paper Format Config"

    name = fields.Char('Name', required=True)
    default = fields.Boolean('Default paper format ?')
    format = fields.Selection([(ps['key'], ps['description'])
                               for ps in PAPER_SIZES],
                              'Paper size',
                              default='A4',
                              help="Select Proper Paper size")
    margin_top = fields.Float('Top Margin (mm)', default=40)
    margin_bottom = fields.Float('Bottom Margin (mm)', default=20)
    margin_left = fields.Float('Left Margin (mm)', default=7)
    margin_right = fields.Float('Right Margin (mm)', default=7)
    page_height = fields.Integer('Page height (mm)', default=False)
    page_width = fields.Integer('Page width (mm)', default=False)
    orientation = fields.Selection([('Landscape', 'Landscape'),
                                    ('Portrait', 'Portrait')],
                                   'Orientation',
                                   default='Landscape')
    header_line = fields.Boolean('Display a header line', default=False)
    header_spacing = fields.Integer('Header spacing', default=35)
    dpi = fields.Integer('Output DPI', required=True, default=90)
    report_ids = fields.One2many('ir.actions.report',
                                 'paperformat_id',
                                 'Associated reports',
                                 help="Explicitly associated reports")
    print_page_width = fields.Float('Print page width (mm)',
                                    compute='_compute_print_page_size')
    print_page_height = fields.Float('Print page height (mm)',
                                     compute='_compute_print_page_size')

    @api.constrains('format')
    def _check_format_or_page(self):
        if self.filtered(lambda x: x.format != 'custom' and
                         (x.page_width or x.page_height)):
            raise ValidationError(
                _('You can select either a format or a specific page width/height, but not both.'
                  ))

    def _compute_print_page_size(self):
        for record in self:
            width = height = 0.0
            if record.format:
                if record.format == 'custom':
                    width = record.page_width
                    height = record.page_height
                else:
                    paper_size = next(ps for ps in PAPER_SIZES
                                      if ps['key'] == record.format)
                    width = paper_size['width']
                    height = paper_size['height']

            if record.orientation == 'Landscape':
                # swap sizes
                width, height = height, width

            record.print_page_width = width
            record.print_page_height = height
Example #4
0
class BaseModuleUpdate(models.TransientModel):
    _name = "base.module.update"
    _description = "Update Module"

    updated = fields.Integer('Number of modules updated', readonly=True)
    added = fields.Integer('Number of modules added', readonly=True)
    state = fields.Selection([('init', 'init'), ('done', 'done')],
                             'Status',
                             readonly=True,
                             default='init')

    def update_module(self):
        for this in self:
            updated, added = self.env['ir.module.module'].update_list()
            this.write({'updated': updated, 'added': added, 'state': 'done'})
        return False

    def action_module_open(self):
        res = {
            'domain': str([]),
            'name': 'Modules',
            'view_mode': 'tree,form',
            'res_model': 'ir.module.module',
            'view_id': False,
            'type': 'ir.actions.act_window',
        }
        return res
Example #5
0
class Foo(models.Model):
    _name = 'test_new_api.foo'
    _description = 'Test New API Foo'

    name = fields.Char()
    value1 = fields.Integer(change_default=True)
    value2 = fields.Integer()
Example #6
0
class HrDepartment(models.Model):
    _inherit = 'hr.department'

    new_applicant_count = fields.Integer(
        compute='_compute_new_applicant_count', string='New Applicant')
    new_hired_employee = fields.Integer(compute='_compute_recruitment_stats',
                                        string='New Hired Employee')
    expected_employee = fields.Integer(compute='_compute_recruitment_stats',
                                       string='Expected Employee')

    def _compute_new_applicant_count(self):
        applicant_data = self.env['hr.applicant'].read_group(
            [('department_id', 'in', self.ids),
             ('stage_id.sequence', '<=', '1')], ['department_id'],
            ['department_id'])
        result = dict((data['department_id'][0], data['department_id_count'])
                      for data in applicant_data)
        for department in self:
            department.new_applicant_count = result.get(department.id, 0)

    def _compute_recruitment_stats(self):
        job_data = self.env['hr.job'].read_group(
            [('department_id', 'in', self.ids)],
            ['no_of_hired_employee', 'no_of_recruitment', 'department_id'],
            ['department_id'])
        new_emp = dict((data['department_id'][0], data['no_of_hired_employee'])
                       for data in job_data)
        expected_emp = dict(
            (data['department_id'][0], data['no_of_recruitment'])
            for data in job_data)
        for department in self:
            department.new_hired_employee = new_emp.get(department.id, 0)
            department.expected_employee = expected_emp.get(department.id, 0)
Example #7
0
class ResPartner(models.Model):
    _inherit = 'res.partner'

    certifications_count = fields.Integer('Certifications Count', compute='_compute_certifications_count')
    certifications_company_count = fields.Integer('Company Certifications Count', compute='_compute_certifications_company_count')

    @api.depends('is_company')
    def _compute_certifications_count(self):
        read_group_res = self.env['survey.user_input'].sudo().read_group(
            [('partner_id', 'in', self.ids), ('quizz_passed', '=', True)],
            ['partner_id'], 'partner_id'
        )
        data = dict((res['partner_id'][0], res['partner_id_count']) for res in read_group_res)
        for partner in self:
            partner.certifications_count = data.get(partner.id, 0)

    @api.depends('is_company', 'child_ids.certifications_count')
    def _compute_certifications_company_count(self):
        self.certifications_company_count = sum(child.certifications_count for child in self.child_ids)

    def action_view_certifications(self):
        action = self.env.ref('survey.res_partner_action_certifications').read()[0]
        action['view_mode'] = 'tree'
        action['domain'] = ['|', ('partner_id', 'in', self.ids), ('partner_id', 'in', self.child_ids.ids)]

        return action
Example #8
0
class product_price_list(models.TransientModel):
    _name = 'product.price_list'
    _description = 'Product Price per Unit Based on Pricelist Version'

    price_list = fields.Many2one('product.pricelist',
                                 'PriceList',
                                 required=True)
    qty1 = fields.Integer('Quantity-1', default=1)
    qty2 = fields.Integer('Quantity-2', default=5)
    qty3 = fields.Integer('Quantity-3', default=10)
    qty4 = fields.Integer('Quantity-4', default=0)
    qty5 = fields.Integer('Quantity-5', default=0)

    def print_report(self):
        """
        To get the date and print the report
        @return : return report
        """
        if (not self.env.company.logo):
            raise UserError(
                _("You have to set a logo or a layout for your company."))
        elif (not self.env.company.external_report_layout_id):
            raise UserError(
                _("You have to set your reports's header and footer layout."))

        datas = {'ids': self.env.context.get('active_ids', [])}
        res = self.read(['price_list', 'qty1', 'qty2', 'qty3', 'qty4', 'qty5'])
        res = res and res[0] or {}
        res['price_list'] = res['price_list'][0]
        datas['form'] = res
        return self.env.ref('product.action_report_pricelist').report_action(
            [], data=datas)
Example #9
0
class Aggregate(models.Model):
    _name = 'test_read_group.aggregate'
    _order = 'id'
    _description = 'Group Test Aggregate'

    key = fields.Integer()
    value = fields.Integer("Value")
    partner_id = fields.Many2one('res.partner')
Example #10
0
class StockPickingType(models.Model):
    _inherit = 'stock.picking.type'

    code = fields.Selection(selection_add=[('mrp_operation', 'Manufacturing')])
    count_mo_todo = fields.Integer(
        string="Number of Manufacturing Orders to Process",
        compute='_get_mo_count')
    count_mo_waiting = fields.Integer(
        string="Number of Manufacturing Orders Waiting",
        compute='_get_mo_count')
    count_mo_late = fields.Integer(
        string="Number of Manufacturing Orders Late", compute='_get_mo_count')
    use_create_components_lots = fields.Boolean(
        string="Create New Lots/Serial Numbers for Components",
        help="Allow to create new lot/serial numbers for the components",
        default=False,
    )

    def _get_mo_count(self):
        mrp_picking_types = self.filtered(
            lambda picking: picking.code == 'mrp_operation')
        if not mrp_picking_types:
            self.count_mo_waiting = False
            self.count_mo_todo = False
            self.count_mo_late = False
            return
        domains = {
            'count_mo_waiting': [('reservation_state', '=', 'waiting')],
            'count_mo_todo': [
                '|',
                ('state', 'in', ('confirmed', 'draft', 'planned', 'progress'))
            ],
            'count_mo_late': [('date_planned_start', '<', fields.Date.today()),
                              ('state', '=', 'confirmed')],
        }
        for field in domains:
            data = self.env['mrp.production'].read_group(
                domains[field] + [('state', 'not in', ('done', 'cancel')),
                                  ('picking_type_id', 'in', self.ids)],
                ['picking_type_id'], ['picking_type_id'])
            count = {
                x['picking_type_id'] and x['picking_type_id'][0]:
                x['picking_type_id_count']
                for x in data
            }
            for record in mrp_picking_types:
                record[field] = count.get(record.id, 0)
        remaining = (self - mrp_picking_types)
        if remaining:
            remaining.count_mo_waiting = False
            remaining.count_mo_todo = False
            remaining.count_mo_late = False

    def get_mrp_stock_picking_action_picking_type(self):
        return self._get_action('mrp.mrp_production_action_picking_deshboard')
Example #11
0
class B(models.Model):
    _name = 'test_testing_utilities.readonly'
    _description = 'Testing Utilities Readonly'

    f1 = fields.Integer(default=1, readonly=True)
    f2 = fields.Integer(compute='_compute_f2')

    @api.depends('f1')
    def _compute_f2(self):
        for r in self:
            r.f2 = 2 * r.f1
Example #12
0
class O2MChange(models.Model):
    _name = 'test_testing_utilities.parent'
    _description = 'Testing Utilities Parent'

    value = fields.Integer(default=1)
    v = fields.Integer()
    subs = fields.One2many('test_testing_utilities.sub', 'parent_id')

    @api.onchange('value', 'subs')
    def _onchange_values(self):
        self.v = self.value + sum(s.value for s in self.subs)
Example #13
0
class O2MDefault(models.Model):
    _name = 'test_testing_utilities.default'
    _description = 'Testing Utilities Default'

    def _default_subs(self):
        return [(0, 0, {'v': 5})]

    value = fields.Integer(default=1)
    v = fields.Integer()
    subs = fields.One2many('test_testing_utilities.sub3',
                           'parent_id',
                           default=_default_subs)
Example #14
0
class ModuleCategory(models.Model):
    _name = "ir.module.category"
    _description = "Application"
    _order = 'name'

    @api.depends('module_ids')
    def _compute_module_nr(self):
        cr = self._cr
        cr.execute(
            'SELECT category_id, COUNT(*) \
                      FROM ir_module_module \
                     WHERE category_id IN %(ids)s \
                        OR category_id IN (SELECT id \
                                             FROM ir_module_category \
                                            WHERE parent_id IN %(ids)s) \
                     GROUP BY category_id', {'ids': tuple(self.ids)})
        result = dict(cr.fetchall())
        for cat in self.filtered('id'):
            cr.execute('SELECT id FROM ir_module_category WHERE parent_id=%s',
                       (cat.id, ))
            cat.module_nr = sum([result.get(c, 0) for (c, ) in cr.fetchall()],
                                result.get(cat.id, 0))

    name = fields.Char(string='Name',
                       required=True,
                       translate=True,
                       index=True)
    parent_id = fields.Many2one('ir.module.category',
                                string='Parent Application',
                                index=True)
    child_ids = fields.One2many('ir.module.category',
                                'parent_id',
                                string='Child Applications')
    module_nr = fields.Integer(string='Number of Apps',
                               compute='_compute_module_nr')
    module_ids = fields.One2many('ir.module.module',
                                 'category_id',
                                 string='Modules')
    description = fields.Text(string='Description', translate=True)
    sequence = fields.Integer(string='Sequence')
    visible = fields.Boolean(string='Visible', default=True)
    exclusive = fields.Boolean(string='Exclusive')
    xml_id = fields.Char(string='External ID', compute='_compute_xml_id')

    def _compute_xml_id(self):
        xml_ids = defaultdict(list)
        domain = [('model', '=', self._name), ('res_id', 'in', self.ids)]
        for data in self.env['ir.model.data'].sudo().search_read(
                domain, ['module', 'name', 'res_id']):
            xml_ids[data['res_id']].append("%s.%s" %
                                           (data['module'], data['name']))
        for cat in self:
            cat.xml_id = xml_ids.get(cat.id, [''])[0]
Example #15
0
class SomeObj(models.Model):
    _name = 'test_access_right.some_obj'
    _description = 'Object For Test Access Right'

    val = fields.Integer()
    categ_id = fields.Many2one('test_access_right.obj_categ')
    company_id = fields.Many2one('res.company')
    forbidden = fields.Integer(
        groups=
        'test_access_rights.test_group,!base.group_no_one,base.group_user,!base.group_public',
        default=5)
    forbidden2 = fields.Integer(groups='test_access_rights.test_group')
Example #16
0
class test_inherit_property(models.Model):
    _inherit = 'test.inherit.property'

    # override property_foo with a plain normal field
    property_foo = fields.Integer(company_dependent=False)

    # override property_bar with a new-api computed field
    property_bar = fields.Integer(compute='_compute_bar',
                                  company_dependent=False)

    def _compute_bar(self):
        for record in self:
            record.property_bar = 42
Example #17
0
class OnlyOne(models.Model):
    _name = 'export.unique'
    _description = 'Export Unique'

    value = fields.Integer()
    value2 = fields.Integer()
    value3 = fields.Integer()

    _sql_constraints = [
        ('value_unique', 'unique (value)', "The value must be unique"),
        ('pair_unique', 'unique (value2, value3)',
         "The values must be unique"),
    ]
Example #18
0
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')
Example #19
0
class IrAttachment(models.Model):

    _inherit = "ir.attachment"

    local_url = fields.Char("Attachment URL", compute='_compute_local_url')
    image_src = fields.Char(compute='_compute_image_src')
    image_width = fields.Integer(compute='_compute_image_size')
    image_height = fields.Integer(compute='_compute_image_size')

    def _compute_local_url(self):
        for attachment in self:
            if attachment.url:
                attachment.local_url = attachment.url
            else:
                attachment.local_url = '/web/image/%s?unique=%s' % (
                    attachment.id, attachment.checksum)

    @api.depends('mimetype', 'url', 'name')
    def _compute_image_src(self):
        for attachment in self:
            if attachment.mimetype not in [
                    'image/gif', 'image/jpe', 'image/jpeg', 'image/jpg',
                    'image/gif', 'image/png', 'image/svg+xml'
            ]:
                attachment.image_src = False
            else:
                attachment.image_src = attachment.url or '/web/image/%s/%s' % (
                    attachment.id,
                    url_quote(attachment.name or ''),
                )

    @api.depends('datas')
    def _compute_image_size(self):
        for attachment in self:
            try:
                image = tools.base64_to_image(attachment.datas)
                attachment.image_width = image.width
                attachment.image_height = image.height
            except Exception:
                attachment.image_width = 0
                attachment.image_height = 0

    def _get_media_info(self):
        """Return a dict with the values that we need on the media dialog."""
        self.ensure_one()
        return self.read([
            'id', 'name', 'mimetype', 'checksum', 'url', 'type', 'res_id',
            'res_model', 'public', 'access_token', 'image_src', 'image_width',
            'image_height'
        ])[0]
Example #20
0
class Stage(models.Model):
    """ Model for case stages. This models the main stages of a document
        management flow. Main CRM objects (leads, opportunities, project
        issues, ...) will now use only stages, instead of state and stages.
        Stages are for example used to display the kanban view of records.
    """
    _name = "crm.stage"
    _description = "CRM Stages"
    _rec_name = 'name'
    _order = "sequence, name, id"

    @api.model
    def default_get(self, fields):
        """ Hack :  when going from the pipeline, creating a stage with a sales team in
            context should not create a stage for the current Sales Team only
        """
        ctx = dict(self.env.context)
        if ctx.get('default_team_id') and not ctx.get('crm_team_mono'):
            ctx.pop('default_team_id')
        return super(Stage, self.with_context(ctx)).default_get(fields)

    name = fields.Char('Stage Name', required=True, translate=True)
    sequence = fields.Integer('Sequence',
                              default=1,
                              help="Used to order stages. Lower is better.")
    is_won = fields.Boolean('Is Won Stage?')
    requirements = fields.Text(
        'Requirements',
        help=
        "Enter here the internal requirements for this stage (ex: Offer sent to customer). It will appear as a tooltip over the stage's name."
    )
    team_id = fields.Many2one(
        'crm.team',
        string='Sales Team',
        ondelete='set null',
        help=
        'Specific team that uses this stage. Other teams will not be able to see or use this stage.'
    )
    fold = fields.Boolean(
        'Folded in Pipeline',
        help=
        'This stage is folded in the kanban view when there are no records in that stage to display.'
    )

    # This field for interface only
    team_count = fields.Integer('team_count', compute='_compute_team_count')

    def _compute_team_count(self):
        for stage in self:
            stage.team_count = self.env['crm.team'].search_count([])
Example #21
0
class Partner(models.Model):
    _name = 'res.partner'
    _inherit = 'res.partner'

    team_id = fields.Many2one('crm.team', string='Sales Team')
    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.model
    def default_get(self, fields):
        rec = super(Partner, self).default_get(fields)
        active_model = self.env.context.get('active_model')
        if active_model == 'crm.lead':
            lead = self.env[active_model].browse(self.env.context.get('active_id')).exists()
            if lead:
                rec.update(
                    phone=lead.phone,
                    mobile=lead.mobile,
                    function=lead.function,
                    title=lead.title.id,
                    website=lead.website,
                    street=lead.street,
                    street2=lead.street2,
                    city=lead.city,
                    state_id=lead.state_id.id,
                    country_id=lead.country_id.id,
                    zip=lead.zip,
                )
        return rec

    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')])

    def _compute_meeting_count(self):
        for partner in self:
            partner.meeting_count = len(partner.meeting_ids)

    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'] = {
            'default_partner_ids': partner_ids,
        }
        return action
Example #22
0
class ResPartner(models.Model):
    _inherit = "res.partner"

    partner_weight = fields.Integer(
        'Level Weight',
        default=0,
        tracking=True,
        help=
        "This should be a numerical value greater than 0 which will decide the contention for this partner to take this lead/opportunity."
    )
    grade_id = fields.Many2one('res.partner.grade',
                               'Partner Level',
                               tracking=True)
    grade_sequence = fields.Integer(related='grade_id.sequence',
                                    readonly=True,
                                    store=True)
    activation = fields.Many2one('res.partner.activation',
                                 'Activation',
                                 index=True,
                                 tracking=True)
    date_partnership = fields.Date('Partnership Date')
    date_review = fields.Date('Latest Partner Review')
    date_review_next = fields.Date('Next Partner Review')
    # customer implementation
    assigned_partner_id = fields.Many2one(
        'res.partner',
        'Implemented by',
    )
    implemented_partner_ids = fields.One2many(
        'res.partner',
        'assigned_partner_id',
        string='Implementation References',
    )
    implemented_count = fields.Integer(
        compute='_compute_implemented_partner_count', store=True)

    @api.depends('implemented_partner_ids',
                 'implemented_partner_ids.website_published',
                 'implemented_partner_ids.active')
    def _compute_implemented_partner_count(self):
        for partner in self:
            partner.implemented_count = len(
                partner.implemented_partner_ids.filtered('website_published'))

    @api.onchange('grade_id')
    def _onchange_grade_id(self):
        grade = self.grade_id
        self.partner_weight = grade.partner_weight if grade else 0
Example #23
0
class UtmCampaign(models.Model):
    _inherit = 'utm.campaign'

    crm_lead_activated = fields.Boolean('Use Leads',
                                        compute='_compute_crm_lead_activated')
    lead_count = fields.Integer(
        'Lead Count',
        groups='sales_team.group_sale_salesman',
        compute="_compute_global_opportunity_and_lead_count")
    opportunity_count = fields.Integer(
        'Opportunity Count',
        groups='sales_team.group_sale_salesman',
        compute="_compute_global_opportunity_and_lead_count")

    def _compute_crm_lead_activated(self):
        for campaign in self:
            campaign.crm_lead_activated = self.env.user.has_group(
                'crm.group_use_lead')

    def _compute_global_opportunity_and_lead_count(self):
        lead_data = self.env['crm.lead'].with_context(
            active_test=False).read_group([('campaign_id', 'in', self.ids)],
                                          ['campaign_id'], ['campaign_id'])
        data_map = {
            datum['campaign_id'][0]: datum['campaign_id_count']
            for datum in lead_data
        }
        if self.env.user.has_group('crm.group_use_lead'):
            for campaign in self:
                campaign.lead_count = data_map.get(campaign.id, 0)
                campaign.opportunity_count = 0
        else:
            for campaign in self:
                campaign.lead_count = 0
                campaign.opportunity_count = data_map.get(campaign.id, 0)

    def action_redirect_to_leads(self):
        action = self.env.ref('crm.crm_lead_all_leads').read()[0]
        action['domain'] = [('campaign_id', '=', self.id)]
        action['context'] = {'default_type': 'lead', 'active_test': False}
        return action

    def action_redirect_to_opportunities(self):
        action = self.env.ref('crm.crm_lead_opportunities').read()[0]
        action['view_mode'] = 'tree,kanban,graph,pivot,form,calendar'
        action['domain'] = [('campaign_id', '=', self.id)]
        action['context'] = {'active_test': False}
        return action
Example #24
0
class ProductionLot(models.Model):
    _inherit = 'stock.production.lot'

    purchase_order_ids = fields.Many2many(
        'purchase.order',
        string="Purchase Orders",
        compute='_compute_purchase_order_ids',
        readonly=True,
        store=False)
    purchase_order_count = fields.Integer(
        'Purchase order count', compute='_compute_purchase_order_ids')

    @api.depends('name')
    def _compute_purchase_order_ids(self):
        for lot in self:
            stock_moves = self.env['stock.move.line'].search([
                ('lot_id', '=', lot.id), ('state', '=', 'done')
            ]).mapped('move_id')
            stock_moves = stock_moves.search([
                ('id', 'in', stock_moves.ids)
            ]).filtered(lambda move: move.picking_id.location_id.usage ==
                        'supplier' and move.state == 'done')
            lot.purchase_order_ids = stock_moves.mapped(
                'purchase_line_id.order_id')
            lot.purchase_order_count = len(lot.purchase_order_ids)

    def action_view_po(self):
        self.ensure_one()
        action = self.env.ref('purchase.purchase_form_action').read()[0]
        action['domain'] = [('id', 'in', self.mapped('purchase_order_ids.id'))]
        action['context'] = dict(self._context, create=False)
        return action
Example #25
0
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')
Example #26
0
class ResConfigSettings(models.TransientModel):
    """ Inherit the base settings to add a counter of failed email + configure
    the alias domain. """
    _inherit = 'res.config.settings'

    fail_counter = fields.Integer('Fail Mail', readonly=True)
    alias_domain = fields.Char(
        'Alias Domain',
        help="If you have setup a catch-all email domain redirected to "
        "the Coffice server, enter the domain name here.",
        config_parameter='mail.catchall.domain')

    @api.model
    def get_values(self):
        res = super(ResConfigSettings, self).get_values()

        previous_date = datetime.datetime.now() - datetime.timedelta(days=30)

        res.update(fail_counter=self.env['mail.mail'].sudo().search_count([
            ('date', '>=',
             previous_date.strftime(tools.DEFAULT_SERVER_DATETIME_FORMAT)),
            ('state', '=', 'exception')
        ]), )

        return res

    def set_values(self):
        super(ResConfigSettings, self).set_values()
        self.env['ir.config_parameter'].set_param("mail.catchall.domain",
                                                  self.alias_domain or '')
Example #27
0
class UtmCampaign(models.Model):
    # OLD crm.case.resource.type
    _name = 'utm.campaign'
    _description = 'UTM Campaign'

    name = fields.Char(string='Campaign Name', required=True, translate=True)

    user_id = fields.Many2one(
        'res.users', string='Responsible',
        required=True, default=lambda self: self.env.uid)
    stage_id = fields.Many2one('utm.stage', string='Stage', ondelete='restrict', required=True,
        default=lambda self: self.env['utm.stage'].search([], limit=1),
        group_expand='_group_expand_stage_ids')
    tag_ids = fields.Many2many(
        'utm.tag', 'utm_tag_rel',
        'tag_id', 'campaign_id', string='Tags')

    is_website = fields.Boolean(default=False, help="Allows us to filter relevant Campaign")
    color = fields.Integer(string='Color Index')

    @api.model
    def _group_expand_stage_ids(self, stages, domain, order):
        """ Read group customization in order to display all the stages in the
            kanban view, even if they are empty
        """
        stage_ids = stages._search([], order=order, access_rights_uid=SUPERUSER_ID)
        return stages.browse(stage_ids)
Example #28
0
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)
Example #29
0
class ResConfigSettings(models.TransientModel):
    _inherit = ['res.config.settings']

    delay_alert_contract = fields.Integer(
        string='Delay alert contract outdated',
        default=30,
        config_parameter='hr_fleet.delay_alert_contract')
Example #30
0
class HrEmployeeBase(models.AbstractModel):
    _inherit = "hr.employee.base"

    child_all_count = fields.Integer('Indirect Surbordinates Count',
                                     compute='_compute_subordinates',
                                     store=False,
                                     compute_sudo=True)

    def _get_subordinates(self, parents=None):
        """
        Helper function to compute subordinates_ids.
        Get all subordinates (direct and indirect) of an employee.
        An employee can be a manager of his own manager (recursive hierarchy; e.g. the CEO is manager of everyone but is also
        member of the RD department, managed by the CTO itself managed by the CEO).
        In that case, the manager in not counted as a subordinate if it's in the 'parents' set.
        """
        if not parents:
            parents = self.env[self._name]

        indirect_subordinates = self.env[self._name]
        parents |= self
        direct_subordinates = self.child_ids - parents
        for child in direct_subordinates:
            child_subordinate = child._get_subordinates(parents=parents)
            child.subordinate_ids = child_subordinate
            indirect_subordinates |= child_subordinate
        return indirect_subordinates | direct_subordinates

    @api.depends('child_ids', 'child_ids.child_all_count')
    def _compute_subordinates(self):
        for employee in self:
            employee.subordinate_ids = employee._get_subordinates()
            employee.child_all_count = len(employee.subordinate_ids)