Example #1
0
class StockWarnInsufficientQtyScrap(models.TransientModel):
    _name = 'stock.warn.insufficient.qty.scrap'
    _inherit = 'stock.warn.insufficient.qty'
    _description = 'Warn Insufficient Scrap Quantity'

    scrap_id = fields.Many2one('stock.scrap', 'Scrap')

    def _get_reference_document_company_id(self):
        return self.scrap_id.company_id

    def action_done(self):
        return self.scrap_id.do_scrap()

    def action_cancel(self):
        # FIXME in master: we should not have created the scrap in a first place
        if self.env.context.get('not_unlink_on_discard'):
            return True
        else:
            return self.scrap_id.sudo().unlink()
Example #2
0
class StockMove(models.Model):
    _inherit = "stock.move"
    sale_line_id = fields.Many2one('sale.order.line', 'Sale Line', index=True)

    @api.model
    def _prepare_merge_moves_distinct_fields(self):
        distinct_fields = super(StockMove,
                                self)._prepare_merge_moves_distinct_fields()
        distinct_fields.append('sale_line_id')
        return distinct_fields

    @api.model
    def _prepare_merge_move_sort_method(self, move):
        move.ensure_one()
        keys_sorted = super(StockMove,
                            self)._prepare_merge_move_sort_method(move)
        keys_sorted.append(move.sale_line_id.id)
        return keys_sorted

    def _get_related_invoices(self):
        """ Overridden from stock_account to return the customer invoices
        related to this stock move.
        """
        rslt = super(StockMove, self)._get_related_invoices()
        invoices = self.mapped('picking_id.sale_id.invoice_ids').filtered(
            lambda x: x.state == 'posted')
        rslt += invoices
        #rslt += invoices.mapped('reverse_entry_ids')
        return rslt

    def _assign_picking_post_process(self, new=False):
        super(StockMove, self)._assign_picking_post_process(new=new)
        if new:
            picking_id = self.mapped('picking_id')
            sale_order_ids = self.mapped('sale_line_id.order_id')
            for sale_order_id in sale_order_ids:
                picking_id.message_post_with_view(
                    'mail.message_origin_link',
                    values={
                        'self': picking_id,
                        'origin': sale_order_id
                    },
                    subtype_id=self.env.ref('mail.mt_note').id)
Example #3
0
class Company(models.Model):
    _inherit = "res.company"

    def _default_confirmation_sms_picking_template(self):
        try:
            return self.env.ref(
                'stock_sms.sms_template_data_stock_delivery').id
        except ValueError:
            return False

    stock_move_sms_validation = fields.Boolean("SMS Confirmation",
                                               default=True)
    stock_sms_confirmation_template_id = fields.Many2one(
        'sms.template',
        string="SMS Template",
        domain="[('model', '=', 'stock.picking')]",
        default=_default_confirmation_sms_picking_template,
        help="SMS sent to the customer once the order is done.")
    has_received_warning_stock_sms = fields.Boolean()
Example #4
0
class mother(models.Model):
    _inherit = 'test.inherit.mother'

    field_in_mother = fields.Char()
    partner_id = fields.Many2one('res.partner')

    # extend the name field: make it required and change its default value
    name = fields.Char(required=True, default='Bar')

    # extend the selection of the state field, and discard its default value
    state = fields.Selection(selection_add=[('c', 'C')], default=None)

    # override the computed field, and extend its dependencies
    @api.depends('field_in_mother')
    def _compute_surname(self):
        for rec in self:
            if rec.field_in_mother:
                rec.surname = rec.field_in_mother
            else:
                super(mother, rec)._compute_surname()
Example #5
0
class Tour(models.Model):

    _name = "web_tour.tour"
    _description = "Tours"
    _log_access = False

    name = fields.Char(string="Tour name", required=True)
    user_id = fields.Many2one('res.users', string='Consumed by')

    @api.model
    def consume(self, tour_names):
        """ Sets given tours as consumed, meaning that
            these tours won't be active anymore for that user """
        for name in tour_names:
            self.create({'name': name, 'user_id': self.env.uid})

    @api.model
    def get_consumed_tours(self):
        """ Returns the list of consumed tours for the current user """
        return [t.name for t in self.search([('user_id', '=', self.env.uid)])]
Example #6
0
class MailTestSMS(models.Model):
    """ A model inheriting from mail.thread with some fields used for SMS
    gateway, like a partner, a specific mobile phone, ... """
    _description = 'Chatter Model for SMS Gateway'
    _name = 'mail.test.sms'
    _inherit = ['mail.thread']
    _order = 'name asc, id asc'

    name = fields.Char()
    subject = fields.Char()
    email_from = fields.Char()
    phone_nbr = fields.Char()
    mobile_nbr = fields.Char()
    customer_id = fields.Many2one('res.partner', 'Customer')

    def _sms_get_partner_fields(self):
        return ['customer_id']

    def _sms_get_number_fields(self):
        return ['phone_nbr', 'mobile_nbr']
Example #7
0
class MassSMSTest(models.TransientModel):
    _name = 'mailing.sms.test'
    _description = 'Test SMS Mailing'

    def _default_numbers(self):
        return self.env.user.partner_id.phone_sanitized or ""

    numbers = fields.Char(string='Number(s)',
                          required=True,
                          default=_default_numbers,
                          help='Comma-separated list of phone numbers')
    mailing_id = fields.Many2one('mailing.mailing',
                                 string='Mailing',
                                 required=True,
                                 ondelete='cascade')

    def action_send_sms(self):
        self.ensure_one()
        numbers = [number.strip() for number in self.numbers.split(',')]
        sanitize_res = phone_validation.phone_sanitize_numbers_w_record(
            numbers, self.env.user)
        sanitized_numbers = [
            info['sanitized'] for info in sanitize_res.values()
            if info['sanitized']
        ]
        invalid_numbers = [
            number for number, info in sanitize_res.items() if info['code']
        ]
        if invalid_numbers:
            raise exceptions.UserError(
                _('Following numbers are not correctly encoded: %s, example : "+32 495 85 85 77, +33 545 55 55 55"'
                  ) % repr(invalid_numbers))
        self.env['sms.api']._send_sms_batch([{
            'res_id':
            0,
            'number':
            number,
            'content':
            self.mailing_id.body_plaintext,
        } for number in sanitized_numbers])
        return True
Example #8
0
class StockPickingResponsible(models.TransientModel):
    _name = 'stock.picking.responsible'
    _description = 'Assign Responsible'

    user_id = fields.Many2one(
        'res.users',
        'Responsible',
        domain=lambda self: [('groups_id', 'in',
                              self.env.ref('stock.group_stock_user').id)],
        default=lambda self: self.env.user)

    def assign_responsible(self):
        self.ensure_one()
        pickings = self.env['stock.picking'].browse(
            self.env.context.get('active_ids'))
        restricted_companies = pickings.company_id - self.user_id.company_ids
        if restricted_companies:
            raise UserError(
                _('%s has a restricted access to %s') %
                (self.user_id.name, restricted_companies.mapped('name')))
        pickings.write({'user_id': self.user_id.id})
Example #9
0
class L10nLatamIdentificationType(models.Model):
    _name = 'l10n_latam.identification.type'
    _description = "Identification Types"
    _order = 'sequence'

    sequence = fields.Integer(default=10)
    name = fields.Char(
        translate=True,
        required=True,
    )
    description = fields.Char()
    active = fields.Boolean(default=True)
    is_vat = fields.Boolean()
    country_id = fields.Many2one('res.country')

    def name_get(self):
        multi_localization = len(self.search([]).mapped('country_id')) > 1
        return [(rec.id,
                 '%s%s' % (rec.name, multi_localization and rec.country_id
                           and ' (%s)' % rec.country_id.code or ''))
                for rec in self]
Example #10
0
class MrpDocument(models.Model):
    """ Extension of ir.attachment only used in MRP to handle archivage
    and basic versioning.
    """
    _name = 'mrp.document'
    _description = "Production Document"
    _inherits = {
        'ir.attachment': 'ir_attachment_id',
    }
    _order = "priority desc, id desc"

    ir_attachment_id = fields.Many2one('ir.attachment',
                                       string='Related attachment',
                                       required=True,
                                       ondelete='cascade')
    active = fields.Boolean('Active', default=True)
    priority = fields.Selection(
        [('0', 'Normal'), ('1', 'Low'), ('2', 'High'), ('3', 'Very High')],
        string="Priority",
        help='Gives the sequence order when displaying a list of MRP documents.'
    )
Example #11
0
class TrackStage(models.Model):
    _name = 'event.track.stage'
    _description = 'Event Track Stage'
    _order = 'sequence, id'

    name = fields.Char(string='Stage Name', required=True, translate=True)
    sequence = fields.Integer(string='Sequence', default=1)
    mail_template_id = fields.Many2one(
        'mail.template',
        string='Email Template',
        domain=[('model', '=', 'event.track')],
        help=
        "If set an email will be sent to the customer when the track reaches this step."
    )
    fold = fields.Boolean(
        string='Folded in Kanban',
        help=
        'This stage is folded in the kanban view when there are no records in that stage to display.'
    )
    is_done = fields.Boolean(string='Accepted Stage')
    is_cancel = fields.Boolean(string='Canceled Stage')
Example #12
0
class Multi(models.Model):
    """ Model for testing multiple onchange methods in cascade that modify a
        one2many field several times.
    """
    _name = 'test_new_api.multi'
    _description = 'Test New API Multi'

    name = fields.Char(related='partner.name', readonly=True)
    partner = fields.Many2one('res.partner')
    lines = fields.One2many('test_new_api.multi.line', 'multi')
    partners = fields.One2many(related='partner.child_ids')

    @api.onchange('name')
    def _onchange_name(self):
        for line in self.lines:
            line.name = self.name

    @api.onchange('partner')
    def _onchange_partner(self):
        for line in self.lines:
            line.partner = self.partner
Example #13
0
class Bar(models.Model):
    _name = 'test_new_api.bar'
    _description = 'Test New API Bar'

    name = fields.Char()
    foo = fields.Many2one('test_new_api.foo',
                          compute='_compute_foo',
                          search='_search_foo')
    value1 = fields.Integer(related='foo.value1', readonly=False)
    value2 = fields.Integer(related='foo.value2', readonly=False)

    @api.depends('name')
    def _compute_foo(self):
        for bar in self:
            bar.foo = self.env['test_new_api.foo'].search(
                [('name', '=', bar.name)], limit=1)

    def _search_foo(self, operator, value):
        assert operator == 'in'
        records = self.env['test_new_api.foo'].browse(value)
        return [('name', 'in', records.mapped('name'))]
Example #14
0
class goal_manual_wizard(models.TransientModel):
    """Wizard to update a manual goal"""
    _name = 'gamification.goal.wizard'
    _description = 'Gamification Goal Wizard'

    goal_id = fields.Many2one("gamification.goal",
                              string='Goal',
                              required=True)
    current = fields.Float('Current')

    def action_update_current(self):
        """Wizard action for updating the current value"""
        for wiz in self:
            wiz.goal_id.write({
                'current': wiz.current,
                'goal_id': wiz.goal_id.id,
                'to_update': False,
            })
            wiz.goal_id.update_goal()

        return False
Example #15
0
class Expense(models.Model):
    _inherit = "hr.expense"

    sale_order_id = fields.Many2one('sale.order', string='Reinvoice Customer', readonly=True,
        states={'draft': [('readonly', False)], 'reported': [('readonly', False)]},
        # NOTE: only confirmed SO can be selected, but this domain in activated throught the name search with the `sale_expense_all_order`
        # context key. So, this domain is not the one applied.
        domain="[('state', '=', 'sale'), ('company_id', '=', company_id)]",
        help="If the product has an expense policy, it will be reinvoiced on this sales order")
    can_be_reinvoiced = fields.Boolean("Can be reinvoiced", compute='_compute_can_be_reinvoiced')

    @api.depends('product_id')
    def _compute_can_be_reinvoiced(self):
        for expense in self:
            expense.can_be_reinvoiced = expense.product_id.expense_policy in ['sales_price', 'cost']

    @api.onchange('product_id')
    def _onchange_product_id(self):
        super(Expense, self)._onchange_product_id()
        if not self.can_be_reinvoiced:
            self.sale_order_id = False

    @api.onchange('sale_order_id')
    def _onchange_sale_order(self):
        if self.sale_order_id:
            self.analytic_account_id = self.sale_order_id.sudo().analytic_account_id  # `sudo` required for normal employee without sale access rights

    def action_move_create(self):
        """ When posting expense, if the AA is given, we will track cost in that
            If a SO is set, this means we want to reinvoice the expense. But to do so, we
            need the analytic entries to be generated, so a AA is required to reinvoice. So,
            we ensure the AA if a SO is given.
        """
        for expense in self.filtered(lambda expense: expense.sale_order_id and not expense.analytic_account_id):
            if not expense.sale_order_id.analytic_account_id:
                expense.sale_order_id._create_analytic_account()
            expense.write({
                'analytic_account_id': expense.sale_order_id.analytic_account_id.id
            })
        return super(Expense, self).action_move_create()
Example #16
0
class ProductTemplate(models.Model):
    _name = 'product.template'
    _inherit = 'product.template'

    property_account_creditor_price_difference = fields.Many2one(
        'account.account', string="Price Difference Account", company_dependent=True,
        help="This account is used in automated inventory valuation to "\
             "record the price difference between a purchase order and its related vendor bill when validating this vendor bill.")
    purchased_product_qty = fields.Float(compute='_compute_purchased_product_qty', string='Purchased')
    purchase_method = fields.Selection([
        ('purchase', 'On ordered quantities'),
        ('receive', 'On received quantities'),
    ], string="Control Policy", help="On ordered quantities: Control bills based on ordered quantities.\n"
        "On received quantities: Control bills based on received quantities.", default="receive")
    purchase_line_warn = fields.Selection(WARNING_MESSAGE, 'Purchase Order Line', help=WARNING_HELP, required=True, default="no-message")
    purchase_line_warn_msg = fields.Text('Message for Purchase Order Line')

    def _compute_purchased_product_qty(self):
        for template in self:
            template.purchased_product_qty = float_round(sum([p.purchased_product_qty for p in template.product_variant_ids]), precision_rounding=template.uom_id.rounding)

    @api.model
    def get_import_templates(self):
        res = super(ProductTemplate, self).get_import_templates()
        if self.env.context.get('purchase_product_template'):
            return [{
                'label': _('Import Template for Products'),
                'template': '/purchase/static/xls/product_purchase.xls'
            }]
        return res

    def action_view_po(self):
        action = self.env.ref('purchase.action_purchase_order_report_all').read()[0]
        action['domain'] = ['&', ('state', 'in', ['purchase', 'done']), ('product_tmpl_id', 'in', self.ids)]
        action['context'] = {
            'graph_measure': 'qty_ordered',
            'search_default_orders': 1,
            'time_ranges': {'field': 'date_approve', 'range': 'last_365_days'}
        }
        return action
Example #17
0
class BaseModel(models.Model):
    _name = 'test_performance.base'
    _description = 'Test Performance Base'

    name = fields.Char()
    value = fields.Integer(default=0)
    value_pc = fields.Float(compute="_value_pc", store=True)
    partner_id = fields.Many2one('res.partner', string='Customer')

    line_ids = fields.One2many('test_performance.line', 'base_id')
    total = fields.Integer(compute="_total", store=True)
    tag_ids = fields.Many2many('test_performance.tag')

    @api.depends('value')
    def _value_pc(self):
        for record in self:
            record.value_pc = float(record.value) / 100

    @api.depends('line_ids.value')
    def _total(self):
        for record in self:
            record.total = sum(line.value for line in record.line_ids)
Example #18
0
class AccountCashRounding(models.Model):
    """
    In some countries, we need to be able to make appear on an invoice a rounding line, appearing there only because the
    smallest coinage has been removed from the circulation. For example, in Switzerland invoices have to be rounded to
    0.05 CHF because coins of 0.01 CHF and 0.02 CHF aren't used anymore.
    see https://en.wikipedia.org/wiki/Cash_rounding for more details.
    """
    _name = 'account.cash.rounding'
    _description = 'Account Cash Rounding'

    name = fields.Char(string='Name', translate=True, required=True)
    rounding = fields.Float(string='Rounding Precision', required=True,
        help='Represent the non-zero value smallest coinage (for example, 0.05).')
    strategy = fields.Selection([('biggest_tax', 'Modify tax amount'), ('add_invoice_line', 'Add a rounding line')],
        string='Rounding Strategy', default='add_invoice_line', required=True,
        help='Specify which way will be used to round the invoice amount to the rounding precision')
    account_id = fields.Many2one('account.account', string='Account')
    rounding_method = fields.Selection(string='Rounding Method', required=True,
        selection=[('UP', 'UP'), ('DOWN', 'DOWN'), ('HALF-UP', 'HALF-UP')],
        default='HALF-UP', help='The tie-breaking rule used for float rounding operations')

    def round(self, amount):
        """Compute the rounding on the amount passed as parameter.

        :param amount: the amount to round
        :return: the rounded amount depending the rounding value and the rounding method
        """
        return float_round(amount, precision_rounding=self.rounding, rounding_method=self.rounding_method)

    def compute_difference(self, currency, amount):
        """Compute the difference between the base_amount and the amount after rounding.
        For example, base_amount=23.91, after rounding=24.00, the result will be 0.09.

        :param currency: The currency.
        :param amount: The amount
        :return: round(difference)
        """
        difference = self.round(amount) - amount
        return currency.round(difference)
Example #19
0
class User(models.Model):
    _inherit = ['res.users']

    medic_exam = fields.Date(related="employee_id.medic_exam")
    vehicle = fields.Char(related="employee_id.vehicle")
    bank_account_id = fields.Many2one(related="employee_id.bank_account_id")

    def __init__(self, pool, cr):
        """ Override of __init__ to add access rights.
            Access rights are disabled by default, but allowed
            on some specific fields defined in self.SELF_{READ/WRITE}ABLE_FIELDS.
        """
        contract_readable_fields = [
            'medic_exam',
            'vehicle',
            'bank_account_id',
        ]
        init_res = super(User, self).__init__(pool, cr)
        # duplicate list to avoid modifying the original reference
        type(self).SELF_READABLE_FIELDS = type(
            self).SELF_READABLE_FIELDS + contract_readable_fields
        return init_res
class MailingMailingScheduleDate(models.TransientModel):
    _name = 'mailing.mailing.schedule.date'
    _description = 'Mass Mailing Scheduling'

    schedule_date = fields.Datetime(string='Scheduled for')
    mass_mailing_id = fields.Many2one('mailing.mailing',
                                      required=True,
                                      ondelete='cascade')

    @api.constrains('schedule_date')
    def _check_schedule_date(self):
        for scheduler in self:
            if scheduler.schedule_date < fields.Datetime.now():
                raise ValidationError(
                    _('Please select a date equal/or greater than the current date.'
                      ))

    def set_schedule_date(self):
        self.mass_mailing_id.write({
            'schedule_date': self.schedule_date,
            'state': 'in_queue'
        })
Example #21
0
class HrExpenseRefuseWizard(models.TransientModel):
    """This wizard can be launched from an he.expense (an expense line)
    or from an hr.expense.sheet (En expense report)
    'hr_expense_refuse_model' must be passed in the context to differentiate
    the right model to use.
    """

    _name = "hr.expense.refuse.wizard"
    _description = "Expense Refuse Reason Wizard"

    reason = fields.Char(string='Reason', required=True)
    hr_expense_ids = fields.Many2many('hr.expense')
    hr_expense_sheet_id = fields.Many2one('hr.expense.sheet')

    @api.model
    def default_get(self, fields):
        res = super(HrExpenseRefuseWizard, self).default_get(fields)
        active_ids = self.env.context.get('active_ids', [])
        refuse_model = self.env.context.get('hr_expense_refuse_model')
        if refuse_model == 'hr.expense':
            res.update({
                'hr_expense_ids': active_ids,
                'hr_expense_sheet_id': False,
            })
        elif refuse_model == 'hr.expense.sheet':
            res.update({
                'hr_expense_sheet_id': active_ids[0] if active_ids else False,
                'hr_expense_ids': [],
            })
        return res

    def expense_refuse_reason(self):
        self.ensure_one()
        if self.hr_expense_ids:
            self.hr_expense_ids.refuse_expense(self.reason)
        if self.hr_expense_sheet_id:
            self.hr_expense_sheet_id.refuse_sheet(self.reason)

        return {'type': 'ir.actions.act_window_close'}
class AccountMoveLine(models.Model):
    _inherit = 'account.move.line'

    # Overload of fields defined in account
    analytic_account_id = fields.Many2one(compute="_compute_analytic_account", store=True, readonly=False)
    analytic_tag_ids = fields.Many2many(compute="_compute_analytic_account", store=True, readonly=False)

    @api.depends('product_id', 'account_id', 'partner_id', 'date_maturity')
    def _compute_analytic_account(self):
        for record in self:
            record.analytic_account_id = record.analytic_account_id or False
            record.analytic_tag_ids = record.analytic_tag_ids or False
            rec = self.env['account.analytic.default'].account_get(
                product_id=record.product_id.id,
                partner_id=record.partner_id.commercial_partner_id.id or record.move_id.partner_id.commercial_partner_id.id,
                account_id=record.account_id.id,
                user_id=record.env.uid,
                date=record.date_maturity,
                company_id=record.move_id.company_id.id
            )
            if rec:
                record.analytic_account_id = rec.analytic_id
                record.analytic_tag_ids = rec.analytic_tag_ids
Example #23
0
class O2MSub(models.Model):
    _name = 'test_testing_utilities.sub'
    _description = 'Testing Utilities Subtraction'

    name = fields.Char(compute='_compute_name')
    value = fields.Integer(default=2)
    v = fields.Integer()
    parent_id = fields.Many2one('test_testing_utilities.parent')
    has_parent = fields.Boolean()

    @api.onchange('value')
    def _onchange_value(self):
        self.v = self.value

    @api.depends('v')
    def _compute_name(self):
        for r in self:
            r.name = str(r.v)

    @api.onchange('has_parent')
    def _onchange_has_parent(self):
        if self.has_parent:
            self.value = self.parent_id.value
Example #24
0
class MailShortcode(models.Model):
    """ Shortcode
        Canned Responses, allowing the user to defined shortcuts in its message. Should be applied before storing message in database.
        Emoji allowing replacing text with image for visual effect. Should be applied when the message is displayed (only for final rendering).
        These shortcodes are global and are available for every user.
    """

    _name = 'mail.shortcode'
    _description = 'Canned Response / Shortcode'
    source = fields.Char(
        'Shortcut',
        required=True,
        index=True,
        help="The shortcut which must be replaced in the Chat Messages")
    substitution = fields.Text(
        'Substitution',
        required=True,
        index=True,
        help="The escaped html code replacing the shortcut")
    description = fields.Char('Description')
    message_ids = fields.Many2one('mail.message',
                                  string="Messages",
                                  store=False)
Example #25
0
class MassMailingListMerge(models.TransientModel):
    _name = 'mailing.list.merge'
    _description = 'Merge Mass Mailing List'

    src_list_ids = fields.Many2many('mailing.list', string='Mailing Lists')
    dest_list_id = fields.Many2one('mailing.list',
                                   string='Destination Mailing List')
    merge_options = fields.Selection([
        ('new', 'Merge into a new mailing list'),
        ('existing', 'Merge into an existing mailing list'),
    ],
                                     'Merge Option',
                                     required=True,
                                     default='new')
    new_list_name = fields.Char('New Mailing List Name')
    archive_src_lists = fields.Boolean('Archive source mailing lists',
                                       default=True)

    @api.model
    def default_get(self, fields):
        res = super(MassMailingListMerge, self).default_get(fields)
        src_list_ids = self.env.context.get('active_ids')
        res.update({
            'src_list_ids': src_list_ids,
            'dest_list_id': src_list_ids and src_list_ids[0] or False,
        })
        return res

    def action_mailing_lists_merge(self):
        if self.merge_options == 'new':
            self.dest_list_id = self.env['mailing.list'].create({
                'name':
                self.new_list_name,
            }).id
        self.dest_list_id.action_merge(self.src_list_ids,
                                       self.archive_src_lists)
        return self.dest_list_id
Example #26
0
class MixedModel(models.Model):
    _name = 'test_new_api.mixed'
    _description = 'Test New API Mixed'

    number = fields.Float(digits=(10, 2), default=3.14)
    number2 = fields.Float(digits='New API Precision')
    date = fields.Date()
    moment = fields.Datetime()
    now = fields.Datetime(compute='_compute_now')
    lang = fields.Selection(string='Language', selection='_get_lang')
    reference = fields.Reference(string='Related Document',
                                 selection='_reference_models')
    comment1 = fields.Html(sanitize=False)
    comment2 = fields.Html(sanitize_attributes=True, strip_classes=False)
    comment3 = fields.Html(sanitize_attributes=True, strip_classes=True)
    comment4 = fields.Html(sanitize_attributes=True, strip_style=True)

    currency_id = fields.Many2one(
        'res.currency', default=lambda self: self.env.ref('base.EUR'))
    amount = fields.Monetary()

    def _compute_now(self):
        # this is a non-stored computed field without dependencies
        for message in self:
            message.now = fields.Datetime.now()

    @api.model
    def _get_lang(self):
        return self.env['res.lang'].get_installed()

    @api.model
    def _reference_models(self):
        models = self.env['ir.model'].sudo().search([('state', '!=', 'manual')
                                                     ])
        return [(model.model, model.name) for model in models
                if not model.model.startswith('ir.')]
Example #27
0
class LinkTrackerCode(models.Model):
    _name = "link.tracker.code"
    _description = "Link Tracker Code"

    code = fields.Char(string='Short URL Code', required=True, store=True)
    link_id = fields.Many2one('link.tracker',
                              'Link',
                              required=True,
                              ondelete='cascade')

    _sql_constraints = [('code', 'unique( code )', 'Code must be unique.')]

    @api.model
    def get_random_code_string(self):
        size = 3
        while True:
            code_proposition = ''.join(
                random.choice(string.ascii_letters + string.digits)
                for _ in range(size))

            if self.search([('code', '=', code_proposition)]):
                size += 1
            else:
                return code_proposition
Example #28
0
class CalendarEvent(models.Model):
    """ Model for Calendar Event """
    _inherit = 'calendar.event'

    @api.model
    def default_get(self, fields):
        if self.env.context.get('default_applicant_id'):
            self = self.with_context(
                default_res_model_id=self.env.ref(
                    'hr_recruitment.model_hr_applicant').id,
                default_res_id=self.env.context['default_applicant_id'])

        defaults = super(CalendarEvent, self).default_get(fields)

        # sync res_model / res_id to opportunity id (aka creating meeting from lead chatter)
        if 'applicant_id' not in defaults and defaults.get('res_id') and (
                defaults.get('res_model') or defaults.get('res_model_id')):
            if (defaults.get('res_model')
                    and defaults['res_model'] == 'hr.applicant') or (
                        defaults.get('res_model_id')
                        and self.env['ir.model'].sudo().browse(
                            defaults['res_model_id']).model == 'hr.applicant'):
                defaults['applicant_id'] = defaults['res_id']

        return defaults

    def _compute_is_highlighted(self):
        super(CalendarEvent, self)._compute_is_highlighted()
        applicant_id = self.env.context.get('active_id')
        if self.env.context.get(
                'active_model') == 'hr.applicant' and applicant_id:
            for event in self:
                if event.applicant_id.id == applicant_id:
                    event.is_highlighted = True

    applicant_id = fields.Many2one('hr.applicant', string="Applicant")
Example #29
0
class MembershipInvoice(models.TransientModel):
    _name = "membership.invoice"
    _description = "Membership Invoice"

    product_id = fields.Many2one('product.product',
                                 string='Membership',
                                 required=True)
    member_price = fields.Float(string='Member Price',
                                digits='Product Price',
                                required=True)

    @api.onchange('product_id')
    def onchange_product(self):
        """This function returns value of  product's member price based on product id.
        """
        price_dict = self.product_id.price_compute('list_price')
        self.member_price = price_dict.get(self.product_id.id) or False

    def membership_invoice(self):
        invoice_list = self.env['res.partner'].browse(
            self._context.get('active_ids')).create_membership_invoice(
                self.product_id, self.member_price)

        search_view_ref = self.env.ref('account.view_account_invoice_filter',
                                       False)
        form_view_ref = self.env.ref('account.view_move_form', False)
        tree_view_ref = self.env.ref('account.view_move_tree', False)

        return {
            'domain': [('id', 'in', invoice_list.ids)],
            'name': 'Membership Invoices',
            'res_model': 'account.move',
            'type': 'ir.actions.act_window',
            'views': [(tree_view_ref.id, 'tree'), (form_view_ref.id, 'form')],
            'search_view_id': search_view_ref and search_view_ref.id,
        }
Example #30
0
class O2MChangeSub(models.Model):
    _name = 'test_testing_utilities.onchange_count_sub'
    _description = _name

    parent = fields.Many2one('test_testing_utilities.onchange_count')
    name = fields.Char()