Ejemplo n.º 1
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.º 2
0
class WebsiteRedirect(models.Model):
    _name = "website.redirect"
    _description = "Website Redirect"
    _order = "sequence, id"
    _rec_name = 'url_from'

    type = fields.Selection([('301', 'Moved permanently'),
                             ('302', 'Moved temporarily')],
                            string='Redirection Type')
    url_from = fields.Char('Redirect From')
    url_to = fields.Char('Redirect To')
    website_id = fields.Many2one('website', 'Website')
    active = fields.Boolean(default=True)
    sequence = fields.Integer(default=0)
Ejemplo n.º 3
0
class ProductTemplate(models.Model):
    _inherit = "product.template"

    can_be_expensed = fields.Boolean(
        help="Specify whether the product can be selected in an HR expense.",
        string="Can be Expensed")

    @api.model
    def create(self, vals):
        # When creating an expense product on the fly, you don't expect to
        # have taxes on it
        if vals.get('can_be_expensed', False):
            vals.update({'supplier_taxes_id': False})
        return super(ProductTemplate, self).create(vals)
Ejemplo n.º 4
0
class AccountingAssertTest(models.Model):
    _name = "accounting.assert.test"
    _order = "sequence"

    name = fields.Char(string='Test Name',
                       required=True,
                       index=True,
                       translate=True)
    desc = fields.Text(string='Test Description', index=True, translate=True)
    code_exec = fields.Text(string='Python code',
                            required=True,
                            default=CODE_EXEC_DEFAULT)
    active = fields.Boolean(default=True)
    sequence = fields.Integer(default=10)
Ejemplo n.º 5
0
class BaseLanguageInstall(models.TransientModel):
    _name = "base.language.install"
    _description = "Install Language"

    @api.model
    def _default_language(self):
        """ Display the selected language when using the 'Update Terms' action
            from the language list view
        """
        if self._context.get('active_model') == 'res.lang':
            lang = self.env['res.lang'].browse(self._context.get('active_id'))
            return lang.code
        return False

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

    lang = fields.Selection(_get_languages, string='Language', required=True,
                            default=_default_language)
    overwrite = fields.Boolean('Overwrite Existing Terms',
                               help="If you check this box, your customized translations will be overwritten and replaced by the official ones.")
    state = fields.Selection([('init', 'init'), ('done', 'done')],
                             string='Status', readonly=True, default='init')

    @api.multi
    def lang_install(self):
        self.ensure_one()
        mods = self.env['ir.module.module'].search([('state', '=', 'installed')])
        mods.with_context(overwrite=self.overwrite)._update_translations(self.lang)
        self.state = 'done'
        return {
            'name': _('Language Pack'),
            'view_type': 'form',
            'view_mode': 'form',
            'view_id': False,
            'res_model': 'base.language.install',
            'domain': [],
            'context': dict(self._context, active_ids=self.ids),
            'type': 'ir.actions.act_window',
            'target': 'new',
            'res_id': self.id,
        }

    def reload(self):
        return {
            'type': 'ir.actions.client',
            'tag': 'reload',
        }
Ejemplo n.º 6
0
class HrPayslipRun(models.Model):
    _name = 'hr.payslip.run'
    _description = 'Payslip Batches'

    name = fields.Char(required=True,
                       readonly=True,
                       states={'draft': [('readonly', False)]})
    slip_ids = fields.One2many('hr.payslip',
                               'payslip_run_id',
                               string='Payslips',
                               readonly=True,
                               states={'draft': [('readonly', False)]})
    state = fields.Selection([
        ('draft', 'Draft'),
        ('close', 'Close'),
    ],
                             string='Status',
                             index=True,
                             readonly=True,
                             copy=False,
                             default='draft')
    date_start = fields.Date(string='Date From',
                             required=True,
                             readonly=True,
                             states={'draft': [('readonly', False)]},
                             default=time.strftime('%Y-%m-01'))
    date_end = fields.Date(
        string='Date To',
        required=True,
        readonly=True,
        states={'draft': [('readonly', False)]},
        default=str(datetime.now() +
                    relativedelta.relativedelta(months=+1, day=1, days=-1))
        [:10])
    credit_note = fields.Boolean(
        string='Credit Note',
        readonly=True,
        states={'draft': [('readonly', False)]},
        help=
        "If its checked, indicates that all payslips generated from here are refund payslips."
    )

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

    @api.multi
    def close_payslip_run(self):
        return self.write({'state': 'close'})
Ejemplo n.º 7
0
class ProductTemplate(models.Model):
    _inherit = 'product.template'

    available_in_pos = fields.Boolean(
        string='Available in Point of Sale',
        help='Check if you want this product to appear in the Point of Sale',
        default=True)
    to_weight = fields.Boolean(
        string='To Weigh With Scale',
        help=
        "Check if the product should be weighted using the hardware scale integration"
    )
    pos_categ_id = fields.Many2one(
        'pos.category',
        string='Point of Sale Category',
        help=
        "Those categories are used to group similar products for point of sale."
    )

    @api.multi
    def unlink(self):
        product_ctx = dict(self.env.context or {}, active_test=False)
        if self.with_context(product_ctx).search_count([('id', 'in', self.ids),
                                                        ('available_in_pos',
                                                         '=', True)]):
            if self.env['pos.session'].search_count([('state', '!=', 'closed')
                                                     ]):
                raise UserError(
                    _('You cannot delete a product saleable in point of sale while a session is still opened.'
                      ))
        return super(ProductTemplate, self).unlink()

    @api.onchange('sale_ok')
    def _onchange_sale_ok(self):
        if not self.sale_ok:
            self.available_in_pos = False
Ejemplo n.º 8
0
class MrpWorkcenterProductivityLoss(models.Model):
    _name = "mrp.workcenter.productivity.loss"
    _description = "TPM Big Losses"
    _order = "sequence, id"

    name = fields.Char('Reason', required=True)
    sequence = fields.Integer('Sequence', default=1)
    manual = fields.Boolean('Is a Blocking Reason', default=True)
    loss_type = fields.Selection([('availability', 'Availability'),
                                  ('performance', 'Performance'),
                                  ('quality', 'Quality'),
                                  ('productive', 'Productive')],
                                 "Effectiveness Category",
                                 default='availability',
                                 required=True)
Ejemplo n.º 9
0
class Tags(models.Model):

    _name = 'res.partner.tag'
    _description = 'Partner Tags - These tags can be used on website to find customers by sector, or ... '
    _inherit = 'website.published.mixin'

    @api.model
    def get_selection_class(self):
        classname = ['default', 'primary', 'success', 'warning', 'danger']
        return [(x, str.title(x)) for x in classname]

    name = fields.Char('Category Name', required=True, translate=True)
    partner_ids = fields.Many2many('res.partner',
                                   'res_partner_res_partner_tag_rel',
                                   'tag_id',
                                   'partner_id',
                                   string='Partners')
    classname = fields.Selection(get_selection_class,
                                 'Class',
                                 default='default',
                                 help="Bootstrap class to customize the color",
                                 required=True)
    active = fields.Boolean('Active', default=True)
    website_published = fields.Boolean(default=True)
Ejemplo n.º 10
0
class AccountCommonJournalReport(models.TransientModel):
    _name = 'account.common.journal.report'
    _description = 'Account Common Journal Report'
    _inherit = "account.common.report"

    amount_currency = fields.Boolean(
        'With Currency',
        help=
        "Print Report with the currency column if the currency differs from the company currency."
    )

    @api.multi
    def pre_print_report(self, data):
        data['form'].update({'amount_currency': self.amount_currency})
        return data
Ejemplo n.º 11
0
class Stage(models.Model):

    _name = "note.stage"
    _description = "Note Stage"
    _order = 'sequence'

    name = fields.Char('Stage Name', translate=True, required=True)
    sequence = fields.Integer(help="Used to order the note stages", default=1)
    user_id = fields.Many2one('res.users',
                              string='Owner',
                              required=True,
                              ondelete='cascade',
                              default=lambda self: self.env.uid,
                              help="Owner of the note stage")
    fold = fields.Boolean('Folded by Default')
Ejemplo n.º 12
0
class Notification(models.Model):
    _name = 'mail.notification'
    _table = 'mail_message_res_partner_needaction_rel'
    _rec_name = 'res_partner_id'
    _log_access = False
    _description = 'Message Notifications'

    mail_message_id = fields.Many2one('mail.message',
                                      'Message',
                                      index=True,
                                      ondelete='cascade',
                                      required=True)
    res_partner_id = fields.Many2one('res.partner',
                                     'Needaction Recipient',
                                     index=True,
                                     ondelete='cascade',
                                     required=True)
    is_read = fields.Boolean('Is Read', index=True)
    is_email = fields.Boolean('Sent by Email', index=True)
    email_status = fields.Selection([('ready', 'Ready to Send'),
                                     ('sent', 'Sent'), ('bounce', 'Bounced'),
                                     ('exception', 'Exception')],
                                    'Email Status',
                                    default='ready',
                                    index=True)

    @api.model_cr
    def init(self):
        self._cr.execute(
            'SELECT indexname FROM pg_indexes WHERE indexname = %s',
            ('mail_notification_res_partner_id_is_read_email_status_mail_message_id',
             ))
        if not self._cr.fetchone():
            self._cr.execute(
                'CREATE INDEX mail_notification_res_partner_id_is_read_email_status_mail_message_id ON mail_message_res_partner_needaction_rel (res_partner_id, is_read, email_status, mail_message_id)'
            )
Ejemplo n.º 13
0
class StockChangeStandardPrice(models.TransientModel):
    _name = "stock.change.standard.price"
    _description = "Change Standard Price"

    new_price = fields.Float(
        'Price',
        digits=dp.get_precision('Product Price'),
        required=True,
        help=
        "If cost price is increased, stock variation account will be debited "
        "and stock output account will be credited with the value = (difference of amount * quantity available).\n"
        "If cost price is decreased, stock variation account will be creadited and stock input account will be debited."
    )
    counterpart_account_id = fields.Many2one('account.account',
                                             string="Counter-Part Account",
                                             domain=[('deprecated', '=', False)
                                                     ])
    counterpart_account_id_required = fields.Boolean(
        string="Counter-Part Account Required")

    @api.model
    def default_get(self, fields):
        res = super(StockChangeStandardPrice, self).default_get(fields)

        product_or_template = self.env[self._context['active_model']].browse(
            self._context['active_id'])
        if 'new_price' in fields and 'new_price' not in res:
            res['new_price'] = product_or_template.standard_price
        if 'counterpart_account_id' in fields and 'counterpart_account_id' not in res:
            res['counterpart_account_id'] = product_or_template.property_account_expense_id.id or product_or_template.categ_id.property_account_expense_categ_id.id
        res['counterpart_account_id_required'] = bool(
            product_or_template.valuation == 'real_time')
        return res

    @api.multi
    def change_price(self):
        """ Changes the Standard Price of Product and creates an account move accordingly. """
        self.ensure_one()
        if self._context['active_model'] == 'product.template':
            products = self.env['product.template'].browse(
                self._context['active_id']).product_variant_ids
        else:
            products = self.env['product.product'].browse(
                self._context['active_id'])

        products.do_change_standard_price(self.new_price,
                                          self.counterpart_account_id.id)
        return {'type': 'ir.actions.act_window_close'}
Ejemplo n.º 14
0
class HolidaysType(models.Model):
    _inherit = "hr.holidays.status"

    def _default_project_id(self):
        company = self.company_id if self.company_id else self.env.user.company_id
        return company.leave_timesheet_project_id.id

    def _default_task_id(self):
        company = self.company_id if self.company_id else self.env.user.company_id
        return company.leave_timesheet_task_id.id

    timesheet_generate = fields.Boolean(
        'Generate Timesheet',
        default=True,
        help=
        "If checked, when validating a leave, timesheet will be generated in the Vacation Project of the company."
    )
    timesheet_project_id = fields.Many2one(
        'project.project',
        string="Internal Project",
        default=_default_project_id,
        help=
        "The project will contain the timesheet generated when a leave is validated."
    )
    timesheet_task_id = fields.Many2one(
        'project.task',
        string="Internal Task for timesheet",
        default=_default_task_id,
        domain="[('project_id', '=', timesheet_project_id)]")

    @api.onchange('timesheet_generate')
    def _onchange_timesheet_generate(self):
        if self.timesheet_generate:
            company = self.company_id if self.company_id else self.env.user.company_id
            self.timesheet_project_id = company.leave_timesheet_project_id
            self.timesheet_task_id = company.leave_timesheet_task_id
        else:
            self.timesheet_project_id = False
            self.timesheet_task_id = False

    @api.constrains('timesheet_generate')
    def _check_timesheet_generate(self):
        for holiday_status in self:
            if holiday_status.timesheet_generate:
                if not holiday_status.timesheet_project_id or not holiday_status.timesheet_task_id:
                    raise ValidationError(
                        _('For the leaves to generate timesheet, the internal project and task are requried.'
                          ))
Ejemplo n.º 15
0
class website_form_model(models.Model):
    _name = 'ir.model'
    _inherit = 'ir.model'

    website_form_access = fields.Boolean('Allowed to use in forms', help='Enable the form builder feature for this model.')
    website_form_default_field_id = fields.Many2one('ir.model.fields', 'Field for custom form data', domain="[('model', '=', model), ('ttype', '=', 'text')]", help="Specify the field which will contain meta and custom form fields datas.")
    website_form_label = fields.Char("Label for form action", help="Form action label. Ex: crm.lead could be 'Send an e-mail' and project.issue could be 'Create an Issue'.")

    def _get_form_writable_fields(self):
        """
        Restriction of "authorized fields" (fields which can be used in the
        form builders) to fields which have actually been opted into form
        builders and are writable. By default no field is writable by the
        form builder.
        """
        included = {
            field.name
            for field in self.env['ir.model.fields'].sudo().search([
                ('model_id', '=', self.id),
                ('website_form_blacklisted', '=', False)
            ])
        }
        return {
            k: v for k, v in self.get_authorized_fields(self.model).items()
            if k in included
        }

    @api.model
    def get_authorized_fields(self, model_name):
        """ Return the fields of the given model name as a mapping like method `fields_get`. """
        model = self.env[model_name]
        fields_get = model.fields_get()

        for key, val in model._inherits.items():
            fields_get.pop(val, None)

        # Unrequire fields with default values
        default_values = model.default_get(list(fields_get))
        for field in [f for f in fields_get if f in default_values]:
            fields_get[field]['required'] = False

        # Remove readonly and magic fields
        MAGIC_FIELDS = models.MAGIC_COLUMNS + [model.CONCURRENCY_CHECK_FIELD]
        for field in list(fields_get):
            if fields_get[field]['readonly'] or field in MAGIC_FIELDS:
                del fields_get[field]

        return fields_get
Ejemplo n.º 16
0
class SaleOrderLine(models.Model):
    _inherit = 'sale.order.line'

    is_delivery = fields.Boolean(string="Is a Delivery", default=False)
    product_qty = fields.Float(
        compute='_compute_product_qty',
        string='Quantity',
        digits=dp.get_precision('Product Unit of Measure'))

    @api.depends('product_id', 'product_uom', 'product_uom_qty')
    def _compute_product_qty(self):
        for line in self:
            if not line.product_id or not line.product_uom or not line.product_uom_qty:
                return 0.0
            line.product_qty = line.product_uom._compute_quantity(
                line.product_uom_qty, line.product_id.uom_id)
Ejemplo n.º 17
0
class AccountTaxTemplate(models.Model):
    """ Add fields used to define some brazilian taxes """
    _inherit = 'account.tax.template'

    tax_discount = fields.Boolean(string='Discount this Tax in Prince',
                                  help="Mark it for (ICMS, PIS e etc.).")
    base_reduction = fields.Float(string='Redution',
                                  digits=0,
                                  required=True,
                                  help="Um percentual decimal em % entre 0-1.",
                                  default=0)
    amount_mva = fields.Float(string='MVA Percent',
                              digits=0,
                              required=True,
                              help="Um percentual decimal em % entre 0-1.",
                              default=0)
Ejemplo n.º 18
0
class website_form_model_fields(models.Model):
    """ fields configuration for form builder """
    _name = 'ir.model.fields'
    _inherit = 'ir.model.fields'

    @api.model_cr
    def init(self):
        # set all existing unset website_form_blacklisted fields to ``true``
        #  (so that we can use it as a whitelist rather than a blacklist)
        self._cr.execute('UPDATE ir_model_fields'
                         ' SET website_form_blacklisted=true'
                         ' WHERE website_form_blacklisted IS NULL')
        # add an SQL-level default value on website_form_blacklisted to that
        # pure-SQL ir.model.field creations (e.g. in _reflect) generate
        # the right default value for a whitelist (aka fields should be
        # blacklisted by default)
        self._cr.execute('ALTER TABLE ir_model_fields '
                         ' ALTER COLUMN website_form_blacklisted SET DEFAULT true')

    @api.model
    def formbuilder_whitelist(self, model, fields):
        """
        :param str model: name of the model on which to whitelist fields
        :param list(str) fields: list of fields to whitelist on the model
        :return: nothing of import
        """
        # postgres does *not* like ``in [EMPTY TUPLE]`` queries
        if not fields: return False

        # only allow users who can change the website structure
        if not self.env['res.users'].has_group('website.group_website_designer'):
            return False

        # the ORM only allows writing on custom fields and will trigger a
        # registry reload once that's happened. We want to be able to
        # whitelist non-custom fields and the registry reload absolutely
        # isn't desirable, so go with a method and raw SQL
        self.env.cr.execute(
            "UPDATE ir_model_fields"
            " SET website_form_blacklisted=false"
            " WHERE model=%s AND name in %s", (model, tuple(fields)))
        return True

    website_form_blacklisted = fields.Boolean(
        'Blacklisted in web forms', default=True, index=True, # required=True,
        help='Blacklist this field for web forms'
    )
Ejemplo n.º 19
0
class LunchOrderLineLucky(models.TransientModel):
    _name = 'lunch.order.line.lucky'

    def _default_supplier(self):
        suppliers_obj = self.env['lunch.product'].search([]).mapped("supplier")
        return [(4, supplier.id) for supplier in suppliers_obj]

    product_id = fields.Many2one('lunch.product', 'Product', store=True)
    supplier_ids = fields.Many2many(
        comodel_name='res.partner',
        string='Vendor',
        domain=lambda self: [("id", "in", self.env['lunch.product'].search([]).
                              mapped("supplier").ids)])
    is_max_budget = fields.Boolean(
        "I'm not feeling rich",
        help="Enable this option to set a maximal budget for your lucky order.",
        store=True)
    max_budget = fields.Float('Max Budget', store=True)

    @api.multi
    def random_pick(self):
        """
        To pick a random product from the selected suppliers, and create an order with this one
        """
        self.ensure_one()
        if self.is_max_budget:
            products_obj = self.env['lunch.product'].search([
                ('supplier', "in", self.supplier_ids.ids),
                ('price', '<=', self.max_budget)
            ])
        else:
            products_obj = self.env['lunch.product'].search([
                ('supplier', "in", self.supplier_ids.ids)
            ])
        if len(products_obj) != 0:
            random_product_obj = self.env['lunch.product'].browse(
                [random.choice(products_obj.ids)])
            order_line = self.env['lunch.order.line'].create({
                'product_id':
                random_product_obj.id,
                'order_id':
                self._context['active_id']
            })
        else:
            raise UserError(
                _('No product is matching your request. Now you will starve to death.'
                  ))
Ejemplo n.º 20
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.º 21
0
class SaleOrderLine(models.Model):

    _inherit = 'sale.order.line'

    event_id = fields.Many2one('event.event', string='Event',
       help="Choose an event and it will automatically create a registration for this event.")
    event_ticket_id = fields.Many2one('event.event.ticket', string='Event Ticket', help="Choose "
        "an event ticket and it will automatically create a registration for this event ticket.")
    event_ok = fields.Boolean(related='product_id.event_ok', readonly=True)

    @api.multi
    def _prepare_invoice_line(self, qty):
        self.ensure_one()
        res = super(SaleOrderLine, self)._prepare_invoice_line(qty)
        if self.event_id:
            res['name'] = '%s: %s' % (res.get('name', ''), self.event_id.name)
        return res

    @api.multi
    def _update_registrations(self, confirm=True, cancel_to_draft=False, registration_data=None):
        """ Create or update registrations linked to a sales order line. A sale
        order line has a product_uom_qty attribute that will be the number of
        registrations linked to this line. This method update existing registrations
        and create new one for missing one. """
        Registration = self.env['event.registration'].sudo()
        registrations = Registration.search([('sale_order_line_id', 'in', self.ids), ('state', '!=', 'cancel')])
        for so_line in self.filtered('event_id'):
            existing_registrations = registrations.filtered(lambda self: self.sale_order_line_id.id == so_line.id)
            if confirm:
                existing_registrations.filtered(lambda self: self.state != 'open').confirm_registration()
            if cancel_to_draft:
                existing_registrations.filtered(lambda self: self.state == 'cancel').do_draft()

            for count in range(int(so_line.product_uom_qty) - len(existing_registrations)):
                registration = {}
                if registration_data:
                    registration = registration_data.pop()
                # TDE CHECK: auto confirmation
                registration['sale_order_line_id'] = so_line
                Registration.with_context(registration_force_draft=True).create(
                    Registration._prepare_attendee_values(registration))
        return True

    @api.onchange('event_ticket_id')
    def _onchange_event_ticket_id(self):
        self.price_unit = (self.event_id.company_id or self.env.user.company_id).currency_id.compute(self.event_ticket_id.price, self.order_id.currency_id)
Ejemplo n.º 22
0
class HrExpenseRegisterPaymentWizard(models.TransientModel):
    _inherit = "hr.expense.sheet.register.payment.wizard"

    check_amount_in_words = fields.Char(string="Amount in Words")
    check_manual_sequencing = fields.Boolean(
        related='journal_id.check_manual_sequencing')
    # Note: a check_number == 0 means that it will be attributed when the check is printed
    check_number = fields.Integer(
        string="Check Number",
        readonly=True,
        copy=False,
        default=0,
        help=
        "Number of the check corresponding to this payment. If your pre-printed check are not already numbered, "
        "you can manage the numbering in the journal configuration page.")
    payment_method_code_2 = fields.Char(
        related='payment_method_id.code',
        help=
        "Technical field used to adapt the interface to the payment type selected.",
        readonly=True)

    @api.onchange('journal_id')
    def _onchange_journal_id(self):
        if hasattr(super(HrExpenseRegisterPaymentWizard, self),
                   '_onchange_journal_id'):
            super(HrExpenseRegisterPaymentWizard, self)._onchange_journal_id()
        if self.journal_id.check_manual_sequencing:
            self.check_number = self.journal_id.check_sequence_id.number_next_actual

    @api.onchange('amount')
    def _onchange_amount(self):
        if hasattr(super(HrExpenseRegisterPaymentWizard, self),
                   '_onchange_amount'):
            super(HrExpenseRegisterPaymentWizard, self)._onchange_amount()
        self.check_amount_in_words = self.currency_id.amount_to_text(
            self.amount)

    def _get_payment_vals(self):
        res = super(HrExpenseRegisterPaymentWizard, self)._get_payment_vals()
        if self.payment_method_id == self.env.ref(
                'account_check_printing.account_payment_method_check'):
            res.update({
                'check_amount_in_words': self.check_amount_in_words,
                'check_manual_sequencing': self.check_manual_sequencing,
            })
        return res
Ejemplo n.º 23
0
class AccountReportGeneralLedger(models.TransientModel):
    _inherit = "account.common.account.report"
    _name = "account.report.general.ledger"
    _description = "General Ledger Report"

    initial_balance = fields.Boolean(string='Include Initial Balances',
                                    help='If you selected date, this field allow you to add a row to display the amount of debit/credit/balance that precedes the filter you\'ve set.')
    sortby = fields.Selection([('sort_date', 'Date'), ('sort_journal_partner', 'Journal & Partner')], string='Sort by', required=True, default='sort_date')
    journal_ids = fields.Many2many('account.journal', 'account_report_general_ledger_journal_rel', 'account_id', 'journal_id', string='Journals', required=True)

    def _print_report(self, data):
        data = self.pre_print_report(data)
        data['form'].update(self.read(['initial_balance', 'sortby'])[0])
        if data['form'].get('initial_balance') and not data['form'].get('date_from'):
            raise UserError(_("You must define a Start Date"))
        records = self.env[data['model']].browse(data.get('ids', []))
        return self.env.ref('account.action_report_general_ledger').with_context(landscape=True).report_action(records, data=data)
Ejemplo n.º 24
0
class EventQuestion(models.Model):
    _name = 'event.question'
    _rec_name = 'title'
    _order = 'sequence,id'

    title = fields.Char(required=True, translate=True)
    event_type_id = fields.Many2one('event.type',
                                    'Event Type',
                                    ondelete='cascade')
    event_id = fields.Many2one('event.event', 'Event', ondelete='cascade')
    answer_ids = fields.One2many('event.answer',
                                 'question_id',
                                 "Answers",
                                 required=True,
                                 copy=True)
    sequence = fields.Integer(default=10)
    is_individual = fields.Boolean(
        'Ask each attendee',
        help=
        "If True, this question will be asked for every attendee of a reservation. If "
        "not it will be asked only once and its value propagated to every attendees."
    )

    @api.constrains('event_type_id', 'event_id')
    def _constrains_event(self):
        if any(question.event_type_id and question.event_id
               for question in self):
            raise UserError(
                _('Question should belong to either event category or event but not both'
                  ))

    @api.model
    def create(self, vals):
        event_id = vals.get('event_id', False)
        if event_id:
            event = self.env['event.event'].browse([event_id])
            if event.event_type_id.use_questions and event.event_type_id.question_ids:
                vals['answer_ids'] = vals.get(
                    'answer_ids', []) + [(0, 0, {
                        'name': answer.name,
                        'sequence': answer.sequence,
                    }) for answer in event.event_type_id.question_ids.filtered(
                        lambda question: question.title == vals.get('title')).
                                         mapped('answer_ids')]
        return super(EventQuestion, self).create(vals)
Ejemplo n.º 25
0
class ProjectTask(models.Model):
    _name = "project.task"
    _inherit = ["project.task", 'pad.common']

    description_pad = fields.Char('Pad URL',
                                  pad_content_field='description',
                                  copy=False)
    use_pad = fields.Boolean(related="project_id.use_pads",
                             string="Use collaborative pad")

    @api.model
    def create(self, vals):
        # When using quick create, the project_id is in the context, not in the vals
        project_id = vals.get('project_id', False) or self.default_get(
            ['project_id'])['project_id']
        if not self.env['project.project'].browse(project_id).use_pads:
            self = self.with_context(pad_no_create=True)
        return super(ProjectTask, self).create(vals)
Ejemplo n.º 26
0
class FleetVehicleModel(models.Model):
    _inherit = 'fleet.vehicle.model'

    default_recurring_cost_amount_depreciated = fields.Float(
        string="Cost (Depreciated)",
        help=
        "Default recurring cost amount that should be applied to a new car from this model"
    )
    default_co2 = fields.Float(string="CO2 emissions")
    default_fuel_type = fields.Selection([('gasoline', 'Gasoline'),
                                          ('diesel', 'Diesel'),
                                          ('electric', 'Electric'),
                                          ('hybrid', 'Hybrid')],
                                         'Fuel Type',
                                         help='Fuel Used by the vehicle')
    default_car_value = fields.Float(string="Catalog Value (VAT Incl.)")
    can_be_requested = fields.Boolean(
        string="Can be requested",
        help="Can be requested on a contract as a new car")
    default_atn = fields.Float(compute='_compute_atn', string="ATN")
    default_total_depreciated_cost = fields.Float(
        compute='_compute_default_total_depreciated_cost',
        string="Total Cost (Depreciated)")
    co2_fee = fields.Float(compute='_compute_co2_fee', string="CO2 fee")

    @api.depends('default_car_value', 'default_co2', 'default_fuel_type')
    def _compute_atn(self):
        now = Datetime.now()
        for model in self:
            model.default_atn = self.env['fleet.vehicle']._get_car_atn(
                now, model.default_car_value, model.default_fuel_type,
                model.default_co2)

    @api.depends('co2_fee', 'default_recurring_cost_amount_depreciated')
    def _compute_default_total_depreciated_cost(self):
        for model in self:
            model.default_total_depreciated_cost = model.co2_fee + model.default_recurring_cost_amount_depreciated

    @api.depends('default_co2')
    def _compute_co2_fee(self):
        for model in self:
            model.co2_fee = self.env['fleet.vehicle']._get_co2_fee(
                model.default_co2)
Ejemplo n.º 27
0
class BaseLanguageImport(models.TransientModel):
    _name = "base.language.import"
    _description = "Language Import"

    name = fields.Char('Language Name', required=True)
    code = fields.Char('ISO Code',
                       size=5,
                       required=True,
                       help="ISO Language and Country code, e.g. en_US")
    data = fields.Binary('File', required=True)
    filename = fields.Char('File Name', required=True)
    overwrite = fields.Boolean(
        'Overwrite Existing Terms',
        help=
        "If you enable this option, existing translations (including custom ones) "
        "will be overwritten and replaced by those in this file")

    @api.multi
    def import_lang(self):
        this = self[0]
        this = this.with_context(overwrite=this.overwrite)
        with TemporaryFile('wb+') as buf:
            try:
                buf.write(base64.decodestring(this.data))

                # now we determine the file format
                buf.seek(0)
                fileformat = os.path.splitext(this.filename)[-1][1:].lower()

                tools.trans_load_data(this._cr,
                                      buf,
                                      fileformat,
                                      this.code,
                                      lang_name=this.name,
                                      context=this._context)
            except Exception as e:
                _logger.exception(
                    'File unsuccessfully imported, due to format mismatch.')
                raise UserError(
                    _('File not imported due to format mismatch or a malformed file. (Valid formats are .csv, .po, .pot)\n\nTechnical Details:\n%s'
                      ) % tools.ustr(e))
        return True
Ejemplo n.º 28
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.º 29
0
class AccountRegisterPayments(models.TransientModel):
    _inherit = "account.register.payments"

    check_amount_in_words = fields.Char(string="Amount in Words")
    check_manual_sequencing = fields.Boolean(
        related='journal_id.check_manual_sequencing', readonly=1)
    # Note: a check_number == 0 means that it will be attributed when the check is printed
    check_number = fields.Integer(
        string="Check Number",
        readonly=True,
        copy=False,
        default=0,
        help=
        "Number of the check corresponding to this payment. If your pre-printed check are not already numbered, "
        "you can manage the numbering in the journal configuration page.")

    @api.onchange('journal_id')
    def _onchange_journal_id(self):
        if hasattr(super(AccountRegisterPayments, self),
                   '_onchange_journal_id'):
            super(AccountRegisterPayments, self)._onchange_journal_id()
        if self.journal_id.check_manual_sequencing:
            self.check_number = self.journal_id.check_sequence_id.number_next_actual

    @api.onchange('amount')
    def _onchange_amount(self):
        if hasattr(super(AccountRegisterPayments, self), '_onchange_amount'):
            super(AccountRegisterPayments, self)._onchange_amount()
        self.check_amount_in_words = self.currency_id.amount_to_text(
            self.amount)

    def _prepare_payment_vals(self, invoices):
        res = super(AccountRegisterPayments,
                    self)._prepare_payment_vals(invoices)
        if self.payment_method_id == self.env.ref(
                'account_check_printing.account_payment_method_check'):
            res.update({
                'check_amount_in_words':
                self.currency_id.amount_to_text(res['amount'])
                if self.multi else self.check_amount_in_words,
            })
        return res
Ejemplo n.º 30
0
class Bank(models.Model):
    _description = 'Bank'
    _name = 'res.bank'
    _order = 'name'

    name = fields.Char(required=True)
    street = fields.Char()
    street2 = fields.Char()
    zip = fields.Char()
    city = fields.Char()
    state = fields.Many2one('res.country.state',
                            'Fed. State',
                            domain="[('country_id', '=', country)]")
    country = fields.Many2one('res.country')
    email = fields.Char()
    phone = fields.Char()
    active = fields.Boolean(default=True)
    bic = fields.Char('Bank Identifier Code',
                      index=True,
                      help="Sometimes called BIC or Swift.")

    @api.multi
    @api.depends('name', 'bic')
    def name_get(self):
        result = []
        for bank in self:
            name = bank.name + (bank.bic and (' - ' + bank.bic) or '')
            result.append((bank.id, name))
        return result

    @api.model
    def name_search(self, name, args=None, operator='ilike', limit=100):
        args = args or []
        domain = []
        if name:
            domain = [
                '|', ('bic', '=ilike', name + '%'), ('name', operator, name)
            ]
            if operator in expression.NEGATIVE_TERM_OPERATORS:
                domain = ['&'] + domain
        banks = self.search(domain + args, limit=limit)
        return banks.name_get()