Exemple #1
0
class BaseModuleUninstall(models.TransientModel):
    _name = "base.module.uninstall"
    _description = "Module Uninstallation"

    show_all = fields.Boolean()
    module_id = fields.Many2one('ir.module.module',
                                string="Module",
                                required=True,
                                domain=[
                                    ('state', 'in',
                                     ['installed', 'to upgrade', 'to install'])
                                ])
    module_ids = fields.Many2many('ir.module.module',
                                  string="Impacted modules",
                                  compute='_compute_module_ids')
    model_ids = fields.Many2many('ir.model',
                                 string="Impacted data models",
                                 compute='_compute_model_ids')

    def _get_modules(self):
        """ Return all the modules impacted by self. """
        return self.module_id.downstream_dependencies(self.module_id)

    @api.depends('module_id', 'show_all')
    def _compute_module_ids(self):
        for wizard in self:
            modules = wizard._get_modules()
            wizard.module_ids = modules if wizard.show_all else modules.filtered(
                'application')

    def _get_models(self):
        """ Return the models (ir.model) to consider for the impact. """
        return self.env['ir.model'].search([('transient', '=', False)])

    @api.depends('module_ids')
    def _compute_model_ids(self):
        ir_models = self._get_models()
        ir_models_xids = ir_models._get_external_ids()
        for wizard in self:
            if wizard.module_id:
                module_names = set(wizard._get_modules().mapped('name'))

                def lost(model):
                    xids = ir_models_xids.get(model.id, ())
                    return xids and all(
                        xid.split('.')[0] in module_names for xid in xids)

                # find the models that have all their XIDs in the given modules
                self.model_ids = ir_models.filtered(lost).sorted('name')

    @api.onchange('module_id')
    def _onchange_module_id(self):
        # if we select a technical module, show technical modules by default
        if not self.module_id.application:
            self.show_all = True

    @api.multi
    def action_uninstall(self):
        modules = self.mapped('module_id')
        return modules.button_immediate_uninstall()
Exemple #2
0
class GroupsImplied(models.Model):
    _inherit = 'res.groups'

    implied_ids = fields.Many2many('res.groups', 'res_groups_implied_rel', 'gid', 'hid',
        string='Inherits', help='Users of this group automatically inherit those groups')
    trans_implied_ids = fields.Many2many('res.groups', string='Transitively inherits',
        compute='_compute_trans_implied')

    @api.depends('implied_ids.trans_implied_ids')
    def _compute_trans_implied(self):
        # Compute the transitive closure recursively. Note that the performance
        # is good, because the record cache behaves as a memo (the field is
        # never computed twice on a given group.)
        for g in self:
            g.trans_implied_ids = g.implied_ids | g.mapped('implied_ids.trans_implied_ids')

    @api.model
    def create(self, values):
        user_ids = values.pop('users', None)
        group = super(GroupsImplied, self).create(values)
        if user_ids:
            # delegate addition of users to add implied groups
            group.write({'users': user_ids})
        return group

    @api.multi
    def write(self, values):
        res = super(GroupsImplied, self).write(values)
        if values.get('users') or values.get('implied_ids'):
            # add all implied groups (to all users of each group)
            for group in self:
                vals = {'users': list(pycompat.izip(repeat(4), group.with_context(active_test=False).users.ids))}
                super(GroupsImplied, group.trans_implied_ids).write(vals)
        return res
Exemple #3
0
class ProductTemplate(models.Model):
    _inherit = "product.template"

    taxes_id = fields.Many2many('account.tax',
                                'product_taxes_rel',
                                'prod_id',
                                'tax_id',
                                string='Customer Taxes',
                                domain=[('type_tax_use', '=', 'sale')])
    supplier_taxes_id = fields.Many2many('account.tax',
                                         'product_supplier_taxes_rel',
                                         'prod_id',
                                         'tax_id',
                                         string='Vendor Taxes',
                                         domain=[('type_tax_use', '=',
                                                  'purchase')])
    property_account_income_id = fields.Many2one(
        'account.account',
        company_dependent=True,
        string="Income Account",
        oldname="property_account_income",
        domain=[('deprecated', '=', False)],
        help=
        "Keep this field empty to use the default value from the product category."
    )
    property_account_expense_id = fields.Many2one(
        'account.account',
        company_dependent=True,
        string="Expense Account",
        oldname="property_account_expense",
        domain=[('deprecated', '=', False)],
        help=
        "The expense is accounted for when a vendor bill is validated, except in anglo-saxon accounting with perpetual inventory valuation in which case the expense (Cost of Goods Sold account) is recognized at the customer invoice validation. If the field is empty, it uses the one defined in the product category."
    )

    @api.multi
    def _get_product_accounts(self):
        return {
            'income':
            self.property_account_income_id
            or self.categ_id.property_account_income_categ_id,
            'expense':
            self.property_account_expense_id
            or self.categ_id.property_account_expense_categ_id
        }

    @api.multi
    def _get_asset_accounts(self):
        res = {}
        res['stock_input'] = False
        res['stock_output'] = False
        return res

    @api.multi
    def get_product_accounts(self, fiscal_pos=None):
        accounts = self._get_product_accounts()
        if not fiscal_pos:
            fiscal_pos = self.env['account.fiscal.position']
        return fiscal_pos.map_accounts(accounts)
Exemple #4
0
class Discussion(models.Model):
    _name = 'test_new_api.discussion'

    name = fields.Char(
        string='Title',
        required=True,
        help="General description of what this discussion is about.")
    moderator = fields.Many2one('res.users')
    categories = fields.Many2many('test_new_api.category',
                                  'test_new_api_discussion_category',
                                  'discussion', 'category')
    participants = fields.Many2many('res.users')
    messages = fields.One2many('test_new_api.message', 'discussion')
    message_concat = fields.Text(string='Message concatenate')
    important_messages = fields.One2many('test_new_api.message',
                                         'discussion',
                                         domain=[('important', '=', True)])
    very_important_messages = fields.One2many(
        'test_new_api.message',
        'discussion',
        domain=lambda self: self._domain_very_important())
    emails = fields.One2many('test_new_api.emailmessage', 'discussion')
    important_emails = fields.One2many('test_new_api.emailmessage',
                                       'discussion',
                                       domain=[('important', '=', True)])

    def _domain_very_important(self):
        """Ensure computed O2M domains work as expected."""
        return [("important", "=", True)]

    @api.onchange('name')
    def _onchange_name(self):
        # test onchange modifying one2many field values
        if self.env.context.get('generate_dummy_message'
                                ) and self.name == '{generate_dummy_message}':
            # update body of existings messages and emails
            for message in self.messages:
                message.body = 'not last dummy message'
            for message in self.important_messages:
                message.body = 'not last dummy message'
            # add new dummy message
            message_vals = self.messages._add_missing_default_values({
                'body':
                'dummy message',
                'important':
                True
            })
            self.messages |= self.messages.new(message_vals)
            self.important_messages |= self.messages.new(message_vals)

    @api.onchange('moderator')
    def _onchange_moderator(self):
        self.participants |= self.moderator

    @api.onchange('messages')
    def _onchange_messages(self):
        self.message_concat = "\n".join(
            ["%s:%s" % (m.name, m.body) for m in self.messages])
class BaseLanguageExport(models.TransientModel):
    _name = "base.language.export"

    @api.model
    def _get_languages(self):
        langs = self.env['res.lang'].search([('translatable', '=', True)])
        return [(NEW_LANG_KEY, _('New Language (Empty translation template)'))] + \
               [(lang.code, lang.name) for lang in langs]

    name = fields.Char('File Name', readonly=True)
    lang = fields.Selection(_get_languages,
                            string='Language',
                            required=True,
                            default=NEW_LANG_KEY)
    format = fields.Selection([('csv', 'CSV File'), ('po', 'PO File'),
                               ('tgz', 'TGZ Archive')],
                              string='File Format',
                              required=True,
                              default='csv')
    modules = fields.Many2many('ir.module.module',
                               'rel_modules_langexport',
                               'wiz_id',
                               'module_id',
                               string='Apps To Export',
                               domain=[('state', '=', 'installed')])
    data = fields.Binary('File', readonly=True)
    state = fields.Selection(
        [('choose', 'choose'),
         ('get', 'get')],  # choose language or get the file
        default='choose')

    @api.multi
    def act_getfile(self):
        this = self[0]
        lang = this.lang if this.lang != NEW_LANG_KEY else False
        mods = sorted(this.mapped('modules.name')) or ['all']

        with contextlib.closing(io.BytesIO()) as buf:
            tools.trans_export(lang, mods, buf, this.format, self._cr)
            out = base64.encodestring(buf.getvalue())

        filename = 'new'
        if lang:
            filename = tools.get_iso_codes(lang)
        elif len(mods) == 1:
            filename = mods[0]
        extension = this.format
        if not lang and extension == 'po':
            extension = 'pot'
        name = "%s.%s" % (filename, extension)
        this.write({'state': 'get', 'data': out, 'name': name})
        return {
            'type': 'ir.actions.act_window',
            'res_model': 'base.language.export',
            'view_mode': 'form',
            'view_type': 'form',
            'res_id': this.id,
            'views': [(False, 'form')],
            'target': 'new',
        }
Exemple #6
0
class MultiLine(models.Model):
    _name = 'test_new_api.multi.line'

    multi = fields.Many2one('test_new_api.multi', ondelete='cascade')
    name = fields.Char()
    partner = fields.Many2one('res.partner')
    tags = fields.Many2many('test_new_api.multi.tag')
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)
Exemple #8
0
class HolidaysSummaryDept(models.TransientModel):

    _name = 'hr.holidays.summary.dept'
    _description = 'HR Leaves Summary Report By Department'

    date_from = fields.Date(string='From',
                            required=True,
                            default=lambda *a: time.strftime('%Y-%m-01'))
    depts = fields.Many2many('hr.department',
                             'summary_dept_rel',
                             'sum_id',
                             'dept_id',
                             string='Department(s)')
    holiday_type = fields.Selection([('Approved', 'Approved'),
                                     ('Confirmed', 'Confirmed'),
                                     ('both', 'Both Approved and Confirmed')],
                                    string='Leave Type',
                                    required=True,
                                    default='Approved')

    @api.multi
    def print_report(self):
        self.ensure_one()
        [data] = self.read()
        if not data.get('depts'):
            raise UserError(
                _('You have to select at least one Department. And try again.')
            )
        departments = self.env['hr.department'].browse(data['depts'])
        datas = {'ids': [], 'model': 'hr.department', 'form': data}
        return self.env.ref(
            'hr_holidays.action_report_holidayssummary').with_context(
                from_transient_model=True).report_action(departments,
                                                         data=datas)
Exemple #9
0
class BaseLanguageInstall(models.TransientModel):

    _inherit = "base.language.install"

    website_ids = fields.Many2many('website', string='Websites to translate')

    @api.model
    def default_get(self, fields):
        defaults = super(BaseLanguageInstall, self).default_get(fields)
        website_id = self._context.get('params', {}).get('website_id')
        if website_id:
            if 'website_ids' not in defaults:
                defaults['website_ids'] = []
            defaults['website_ids'].append(website_id)
        return defaults

    @api.multi
    def lang_install(self):
        action = super(BaseLanguageInstall, self).lang_install()
        lang = self.env['res.lang'].search([('code', '=', self.lang)], limit=1)
        if self.website_ids and lang:
            self.website_ids.write({'language_ids': [(4, lang.id)]})
        params = self._context.get('params', {})
        if 'url_return' in params:
            return {
                'url': params['url_return'].replace('[lang]', self.lang),
                'type': 'ir.actions.act_url',
                'target': 'self'
            }
        return action
Exemple #10
0
class RestaurantPrinter(models.Model):

    _name = 'restaurant.printer'

    name = fields.Char('Printer Name', required=True, default='Printer', help='An internal identification of the printer')
    proxy_ip = fields.Char('Proxy IP Address', help="The IP Address or hostname of the Printer's hardware proxy")
    product_categories_ids = fields.Many2many('pos.category', 'printer_category_rel', 'printer_id', 'category_id', string='Printed Product Categories')
class HolidaysSummaryEmployee(models.TransientModel):

    _name = 'hr.holidays.summary.employee'
    _description = 'HR Leaves Summary Report By Employee'

    date_from = fields.Date(string='From',
                            required=True,
                            default=lambda *a: time.strftime('%Y-%m-01'))
    emp = fields.Many2many('hr.employee',
                           'summary_emp_rel',
                           'sum_id',
                           'emp_id',
                           string='Employee(s)')
    holiday_type = fields.Selection([('Approved', 'Approved'),
                                     ('Confirmed', 'Confirmed'),
                                     ('both', 'Both Approved and Confirmed')],
                                    string='Select Leave Type',
                                    required=True,
                                    default='Approved')

    @api.multi
    def print_report(self):
        self.ensure_one()
        [data] = self.read()
        data['emp'] = self.env.context.get('active_ids', [])
        employees = self.env['hr.employee'].browse(data['emp'])
        datas = {'ids': [], 'model': 'hr.employee', 'form': data}
        return self.env.ref(
            'hr_holidays.action_report_holidayssummary').report_action(
                employees, data=datas)
Exemple #12
0
class ProjectTaskType(models.Model):
    _name = 'project.task.type'
    _description = 'Task Stage'
    _order = 'sequence, id'

    def _get_default_project_ids(self):
        default_project_id = self.env.context.get('default_project_id')
        return [default_project_id] if default_project_id else None

    name = fields.Char(string='Stage Name', required=True, translate=True)
    description = fields.Text(translate=True)
    sequence = fields.Integer(default=1)
    project_ids = fields.Many2many('project.project', 'project_task_type_rel', 'type_id', 'project_id', string='Projects',
        default=_get_default_project_ids)
    legend_priority = fields.Char(
        string='Starred Explanation', translate=True,
        help='Explanation text to help users using the star on tasks or issues in this stage.')
    legend_blocked = fields.Char(
        'Red Kanban Label', default=lambda s: _('Blocked'), translate=True, required=True,
        help='Override the default value displayed for the blocked state for kanban selection, when the task or issue is in that stage.')
    legend_done = fields.Char(
        'Green Kanban Label', default=lambda s: _('Ready for Next Stage'), translate=True, required=True,
        help='Override the default value displayed for the done state for kanban selection, when the task or issue is in that stage.')
    legend_normal = fields.Char(
        'Grey Kanban Label', default=lambda s: _('In Progress'), translate=True, required=True,
        help='Override the default value displayed for the normal state for kanban selection, when the task or issue is in that stage.')
    mail_template_id = fields.Many2one(
        'mail.template',
        string='Email Template',
        domain=[('model', '=', 'project.task')],
        help="If set an email will be sent to the customer when the task or issue 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.')
Exemple #13
0
class StockImmediateTransfer(models.TransientModel):
    _name = 'stock.immediate.transfer'
    _description = 'Immediate Transfer'

    pick_ids = fields.Many2many('stock.picking', 'stock_picking_transfer_rel')

    def process(self):
        pick_to_backorder = self.env['stock.picking']
        pick_to_do = self.env['stock.picking']
        for picking in self.pick_ids:
            # If still in draft => confirm and assign
            if picking.state == 'draft':
                picking.action_confirm()
                if picking.state != 'assigned':
                    picking.action_assign()
                    if picking.state != 'assigned':
                        raise UserError(
                            _("Could not reserve all requested products. Please use the \'Mark as Todo\' button to handle the reservation manually."
                              ))
            for move in picking.move_lines:
                for move_line in move.move_line_ids:
                    move_line.qty_done = move_line.product_uom_qty
            if picking._check_backorder():
                pick_to_backorder |= picking
                continue
            pick_to_do |= picking
        # Process every picking that do not require a backorder, then return a single backorder wizard for every other ones.
        if pick_to_do:
            pick_to_do.action_done()
        if pick_to_backorder:
            return pick_to_backorder.action_generate_backorder_wizard()
        return False
Exemple #14
0
class PosDetails(models.TransientModel):
    _name = 'pos.details.wizard'
    _description = 'Open Sales Details Report'

    def _default_start_date(self):
        """ Find the earliest start_date of the latests sessions """
        # restrict to configs available to the user
        config_ids = self.env['pos.config'].search([]).ids
        # exclude configs has not been opened for 2 days
        self.env.cr.execute(
            """
            SELECT
            max(start_at) as start,
            config_id
            FROM pos_session
            WHERE config_id = ANY(%s)
            AND start_at > (NOW() - INTERVAL '2 DAYS')
            GROUP BY config_id
        """, (config_ids, ))
        latest_start_dates = [
            res['start'] for res in self.env.cr.dictfetchall()
        ]
        # earliest of the latest sessions
        return latest_start_dates and min(
            latest_start_dates) or fields.Datetime.now()

    start_date = fields.Datetime(required=True, default=_default_start_date)
    end_date = fields.Datetime(required=True, default=fields.Datetime.now)
    pos_config_ids = fields.Many2many(
        'pos.config',
        'pos_detail_configs',
        default=lambda s: s.env['pos.config'].search([]))

    @api.onchange('start_date')
    def _onchange_start_date(self):
        if self.start_date and self.end_date and self.end_date < self.start_date:
            self.end_date = self.start_date

    @api.onchange('end_date')
    def _onchange_end_date(self):
        if self.end_date and self.end_date < self.start_date:
            self.start_date = self.end_date

    @api.multi
    def generate_report(self):
        if (not self.env.user.company_id.logo):
            raise UserError(
                _("You have to set a logo or a layout for your company."))
        elif (not self.env.user.company_id.external_report_layout):
            raise UserError(
                _("You have to set your reports's header and footer layout."))
        data = {
            'date_start': self.start_date,
            'date_stop': self.end_date,
            'config_ids': self.pos_config_ids.ids
        }
        return self.env.ref('point_of_sale.sale_details_report').report_action(
            [], data=data)
Exemple #15
0
class CountryGroup(models.Model):
    _description = "Country Group"
    _name = 'res.country.group'

    name = fields.Char(required=True, translate=True)
    country_ids = fields.Many2many('res.country',
                                   'res_country_res_country_group_rel',
                                   'res_country_group_id',
                                   'res_country_id',
                                   string='Countries')
Exemple #16
0
class MaintenanceTeam(models.Model):
    _name = 'maintenance.team'
    _description = 'Maintenance Teams'

    name = fields.Char(required=True, translate=True)
    member_ids = fields.Many2many('res.users',
                                  'maintenance_team_users_rel',
                                  string="Team Members")
    color = fields.Integer("Color Index", default=0)
    request_ids = fields.One2many('maintenance.request',
                                  'maintenance_team_id',
                                  copy=False)
    equipment_ids = fields.One2many('maintenance.equipment',
                                    'maintenance_team_id',
                                    copy=False)

    # For the dashboard only
    todo_request_ids = fields.One2many('maintenance.request',
                                       string="Requests",
                                       copy=False,
                                       compute='_compute_todo_requests')
    todo_request_count = fields.Integer(string="Number of Requests",
                                        compute='_compute_todo_requests')
    todo_request_count_date = fields.Integer(
        string="Number of Requests Scheduled",
        compute='_compute_todo_requests')
    todo_request_count_high_priority = fields.Integer(
        string="Number of Requests in High Priority",
        compute='_compute_todo_requests')
    todo_request_count_block = fields.Integer(
        string="Number of Requests Blocked", compute='_compute_todo_requests')
    todo_request_count_unscheduled = fields.Integer(
        string="Number of Requests Unscheduled",
        compute='_compute_todo_requests')

    @api.one
    @api.depends('request_ids.stage_id.done')
    def _compute_todo_requests(self):
        self.todo_request_ids = self.request_ids.filtered(
            lambda e: e.stage_id.done == False)
        self.todo_request_count = len(self.todo_request_ids)
        self.todo_request_count_date = len(
            self.todo_request_ids.filtered(lambda e: e.schedule_date != False))
        self.todo_request_count_high_priority = len(
            self.todo_request_ids.filtered(lambda e: e.priority == '3'))
        self.todo_request_count_block = len(
            self.todo_request_ids.filtered(
                lambda e: e.kanban_state == 'blocked'))
        self.todo_request_count_unscheduled = len(
            self.todo_request_ids.filtered(lambda e: not e.schedule_date))

    @api.one
    @api.depends('equipment_ids')
    def _compute_equipment(self):
        self.equipment_count = len(self.equipment_ids)
Exemple #17
0
class MailActivityType(models.Model):
    """ Activity Types are used to categorize activities. Each type is a different
    kind of activity e.g. call, mail, meeting. An activity can be generic i.e.
    available for all models using activities; or specific to a model in which
    case res_model_id field should be used. """
    _name = 'mail.activity.type'
    _description = 'Activity Type'
    _rec_name = 'name'
    _order = 'sequence, id'

    name = fields.Char('Name', required=True, translate=True)
    summary = fields.Char('Summary', translate=True)
    sequence = fields.Integer('Sequence', default=10)
    days = fields.Integer(
        '# Days',
        default=0,
        help=
        'Number of days before executing the action. It allows to plan the action deadline.'
    )
    icon = fields.Char('Icon', help="Font awesome icon e.g. fa-tasks")
    res_model_id = fields.Many2one(
        'ir.model',
        'Model',
        index=True,
        help='Specify a model if the activity should be specific to a model'
        ' and not available when managing activities for other models.')
    next_type_ids = fields.Many2many('mail.activity.type',
                                     'mail_activity_rel',
                                     'activity_id',
                                     'recommended_id',
                                     string='Recommended Next Activities')
    previous_type_ids = fields.Many2many('mail.activity.type',
                                         'mail_activity_rel',
                                         'recommended_id',
                                         'activity_id',
                                         string='Preceding Activities')
    category = fields.Selection(
        [('default', 'Other')],
        default='default',
        string='Category',
        help=
        'Categories may trigger specific behavior like opening calendar view')
class AccountBalanceReport(models.TransientModel):
    _inherit = "account.common.account.report"
    _name = 'account.balance.report'
    _description = 'Trial Balance Report'

    journal_ids = fields.Many2many('account.journal', 'account_balance_report_journal_rel', 'account_id', 'journal_id', string='Journals', required=True, default=[])

    def _print_report(self, data):
        data = self.pre_print_report(data)
        records = self.env[data['model']].browse(data.get('ids', []))
        return self.env.ref('account.action_report_trial_balance').report_action(records, data=data)
Exemple #19
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)]
Exemple #20
0
class BlogTag(models.Model):
    _name = 'blog.tag'
    _description = 'Blog Tag'
    _inherit = ['website.seo.metadata']
    _order = 'name'

    name = fields.Char('Name', required=True, translate=True)
    post_ids = fields.Many2many('blog.post', string='Posts')

    _sql_constraints = [
        ('name_uniq', 'unique (name)', "Tag name already exists !"),
    ]
Exemple #21
0
class ProductTemplate(models.Model):
    _inherit = "product.template"

    optional_product_ids = fields.Many2many(
        'product.template',
        'product_optional_rel',
        'src_id',
        'dest_id',
        string='Optional Products',
        help="Optional Products are suggested "
        "whenever the customer hits *Add to Cart* (cross-sell strategy, "
        "e.g. for computers: warranty, software, etc.).")
Exemple #22
0
class TrackTag(models.Model):
    _name = "event.track.tag"
    _description = 'Track Tag'
    _order = 'name'

    name = fields.Char('Tag')
    track_ids = fields.Many2many('event.track', string='Tracks')
    color = fields.Integer(string='Color Index', default=10)

    _sql_constraints = [
        ('name_uniq', 'unique (name)', "Tag name already exists !"),
    ]
Exemple #23
0
class Category(models.Model):
    _name = 'test_new_api.category'

    name = fields.Char(required=True)
    color = fields.Integer('Color Index')
    parent = fields.Many2one('test_new_api.category')
    root_categ = fields.Many2one(_name, compute='_compute_root_categ')
    display_name = fields.Char(compute='_compute_display_name',
                               inverse='_inverse_display_name')
    dummy = fields.Char(store=False)
    discussions = fields.Many2many('test_new_api.discussion',
                                   'test_new_api_discussion_category',
                                   'category', 'discussion')

    @api.one
    @api.depends('name', 'parent.display_name')  # this definition is recursive
    def _compute_display_name(self):
        if self.parent:
            self.display_name = self.parent.display_name + ' / ' + self.name
        else:
            self.display_name = self.name

    @api.depends('parent')
    def _compute_root_categ(self):
        for cat in self:
            current = cat
            while current.parent:
                current = current.parent
            cat.root_categ = current

    @api.one
    def _inverse_display_name(self):
        names = self.display_name.split('/')
        # determine sequence of categories
        categories = []
        for name in names[:-1]:
            category = self.search([('name', 'ilike', name.strip())])
            categories.append(category[0])
        categories.append(self)
        # assign parents following sequence
        for parent, child in pycompat.izip(categories, categories[1:]):
            if parent and child:
                child.parent = parent
        # assign name of last category, and reassign display_name (to normalize it)
        self.name = names[-1].strip()

    @api.multi
    def read(self, fields=None, load='_classic_read'):
        if self.search_count([('id', 'in', self._ids),
                              ('name', '=', 'NOACCESS')]):
            raise AccessError('Sorry')
        return super(Category, self).read(fields=fields, load=load)
Exemple #24
0
class IrModelFieldsAnonymizationHistory(models.Model):
    _name = 'ir.model.fields.anonymization.history'
    _order = "date desc"

    date = fields.Datetime(required=True, readonly=True)
    field_ids = fields.Many2many(
        'ir.model.fields.anonymization', 'anonymized_field_to_history_rel',
        'field_id', 'history_id', string='Fields', readonly=True
    )
    state = fields.Selection(selection=ANONYMIZATION_HISTORY_STATE, string='Status', required=True, readonly=True)
    direction = fields.Selection(selection=ANONYMIZATION_DIRECTION, required=True, readonly=True)
    msg = fields.Text('Message', readonly=True)
    filepath = fields.Char('File path', readonly=True)
class HrPayslipEmployees(models.TransientModel):
    _name = 'hr.payslip.employees'
    _description = 'Generate payslips for all selected employees'

    employee_ids = fields.Many2many('hr.employee', 'hr_employee_group_rel',
                                    'payslip_id', 'employee_id', 'Employees')

    @api.multi
    def compute_sheet(self):
        payslips = self.env['hr.payslip']
        [data] = self.read()
        active_id = self.env.context.get('active_id')
        if active_id:
            [run_data] = self.env['hr.payslip.run'].browse(active_id).read(
                ['date_start', 'date_end', 'credit_note'])
        from_date = run_data.get('date_start')
        to_date = run_data.get('date_end')
        if not data['employee_ids']:
            raise UserError(
                _("You must select employee(s) to generate payslip(s)."))
        for employee in self.env['hr.employee'].browse(data['employee_ids']):
            slip_data = self.env['hr.payslip'].onchange_employee_id(
                from_date, to_date, employee.id, contract_id=False)
            res = {
                'employee_id':
                employee.id,
                'name':
                slip_data['value'].get('name'),
                'struct_id':
                slip_data['value'].get('struct_id'),
                'contract_id':
                slip_data['value'].get('contract_id'),
                'payslip_run_id':
                active_id,
                'input_line_ids':
                [(0, 0, x) for x in slip_data['value'].get('input_line_ids')],
                'worked_days_line_ids':
                [(0, 0, x)
                 for x in slip_data['value'].get('worked_days_line_ids')],
                'date_from':
                from_date,
                'date_to':
                to_date,
                'credit_note':
                run_data.get('credit_note'),
                'company_id':
                employee.company_id.id,
            }
            payslips += self.env['hr.payslip'].create(res)
        payslips.compute_sheet()
        return {'type': 'ir.actions.act_window_close'}
Exemple #26
0
class test_uninstall_model(models.Model):
    """
    This model uses different types of columns to make it possible to test
    the uninstall feature of UNO, GECOERP.
    """
    _name = 'test_uninstall.model'

    name = fields.Char('Name')
    ref = fields.Many2one('res.users', string='User')
    rel = fields.Many2many('res.users', string='Users')

    _sql_constraints = [
        ('name_uniq', 'unique (name)', 'Each name must be unique.'),
    ]
class AccountCommonReport(models.TransientModel):
    _name = "account.common.report"
    _description = "Account Common Report"

    company_id = fields.Many2one('res.company',
                                 string='Company',
                                 readonly=True,
                                 default=lambda self: self.env.user.company_id)
    journal_ids = fields.Many2many(
        'account.journal',
        string='Journals',
        required=True,
        default=lambda self: self.env['account.journal'].search([]))
    date_from = fields.Date(string='Start Date')
    date_to = fields.Date(string='End Date')
    target_move = fields.Selection([
        ('posted', 'All Posted Entries'),
        ('all', 'All Entries'),
    ],
                                   string='Target Moves',
                                   required=True,
                                   default='posted')

    def _build_contexts(self, data):
        result = {}
        result['journal_ids'] = 'journal_ids' in data['form'] and data['form'][
            'journal_ids'] or False
        result['state'] = 'target_move' in data['form'] and data['form'][
            'target_move'] or ''
        result['date_from'] = data['form']['date_from'] or False
        result['date_to'] = data['form']['date_to'] or False
        result['strict_range'] = True if result['date_from'] else False
        return result

    def _print_report(self, data):
        raise NotImplementedError()

    @api.multi
    def check_report(self):
        self.ensure_one()
        data = {}
        data['ids'] = self.env.context.get('active_ids', [])
        data['model'] = self.env.context.get('active_model', 'ir.ui.menu')
        data['form'] = self.read(
            ['date_from', 'date_to', 'journal_ids', 'target_move'])[0]
        used_context = self._build_contexts(data)
        data['form']['used_context'] = dict(used_context,
                                            lang=self.env.context.get('lang')
                                            or 'en_US')
        return self.with_context(discard_logo_check=True)._print_report(data)
Exemple #28
0
class AccountInvoiceLine(models.Model):
    _inherit = 'account.invoice.line'
    _order = 'invoice_id, layout_category_id, sequence, id'

    sale_line_ids = fields.Many2many('sale.order.line',
                                     'sale_order_line_invoice_rel',
                                     'invoice_line_id',
                                     'order_line_id',
                                     string='Sales Order Lines',
                                     readonly=True,
                                     copy=False)
    layout_category_id = fields.Many2one('sale.layout_category',
                                         string='Section')
    layout_category_sequence = fields.Integer(string='Layout Sequence')
Exemple #29
0
class ImLivechatChannelRule(models.Model):
    """ Channel Rules
        Rules defining access to the channel (countries, and url matching). It also provide the 'auto pop'
        option to open automatically the conversation.
    """

    _name = 'im_livechat.channel.rule'
    _description = 'Channel Rules'
    _order = 'sequence asc'


    regex_url = fields.Char('URL Regex',
        help="Regular expression specifying the web pages this rule will be applied on.")
    action = fields.Selection([('display_button', 'Display the button'), ('auto_popup', 'Auto popup'), ('hide_button', 'Hide the button')],
        string='Action', required=True, default='display_button',
        help="* 'Display the button' displays the chat button on the pages.\n"\
             "* 'Auto popup' displays the button and automatically open the conversation pane.\n"\
             "* 'Hide the button' hides the chat button on the pages.")
    auto_popup_timer = fields.Integer('Auto popup timer', default=0,
        help="Delay (in seconds) to automatically open the conversation window. Note: the selected action must be 'Auto popup' otherwise this parameter will not be taken into account.")
    channel_id = fields.Many2one('im_livechat.channel', 'Channel',
        help="The channel of the rule")
    country_ids = fields.Many2many('res.country', 'im_livechat_channel_country_rel', 'channel_id', 'country_id', 'Country',
        help="The rule will only be applied for these countries. Example: if you select 'Belgium' and 'United States' and that you set the action to 'Hide Button', the chat button will be hidden on the specified URL from the visitors located in these 2 countries. This feature requires GeoIP installed on your server.")
    sequence = fields.Integer('Matching order', default=10,
        help="Given the order to find a matching rule. If 2 rules are matching for the given url/country, the one with the lowest sequence will be chosen.")

    def match_rule(self, channel_id, url, country_id=False):
        """ determine if a rule of the given channel matches with the given url
            :param channel_id : the identifier of the channel_id
            :param url : the url to match with a rule
            :param country_id : the identifier of the country
            :returns the rule that matches the given condition. False otherwise.
            :rtype : im_livechat.channel.rule
        """
        def _match(rules):
            for rule in rules:
                if re.search(rule.regex_url or '', url):
                    return rule
            return False
        # first, search the country specific rules (the first match is returned)
        if country_id: # don't include the country in the research if geoIP is not installed
            domain = [('country_ids', 'in', [country_id]), ('channel_id', '=', channel_id)]
            rule = _match(self.search(domain))
            if rule:
                return rule
        # second, fallback on the rules without country
        domain = [('country_ids', '=', False), ('channel_id', '=', channel_id)]
        return _match(self.search(domain))
Exemple #30
0
class HrSalaryEmployeeBymonth(models.TransientModel):

    _name = 'hr.salary.employee.month'
    _description = 'Hr Salary Employee By Month Report'

    def _get_default_category(self):
        return self.env['hr.salary.rule.category'].search(
            [('code', '=', 'NET')], limit=1)

    def _get_default_start_date(self):
        year = fields.Date.from_string(fields.Date.today()).strftime('%Y')
        return '{}-01-01'.format(year)

    def _get_default_end_date(self):
        date = fields.Date.from_string(fields.Date.today())
        return date.strftime('%Y') + '-' + date.strftime(
            '%m') + '-' + date.strftime('%d')

    start_date = fields.Date(string='Start Date',
                             required=True,
                             default=_get_default_start_date)
    end_date = fields.Date(string='End Date',
                           required=True,
                           default=_get_default_end_date)
    employee_ids = fields.Many2many('hr.employee',
                                    'payroll_year_rel',
                                    'payroll_year_id',
                                    'employee_id',
                                    string='Employees',
                                    required=True)
    category_id = fields.Many2one('hr.salary.rule.category',
                                  string='Category',
                                  required=True,
                                  default=_get_default_category)

    @api.multi
    def print_report(self):
        """
         To get the date and print the report
         @return: return report
        """
        self.ensure_one()
        data = {'ids': self.env.context.get('active_ids', [])}
        res = self.read()
        res = res and res[0] or {}
        data.update({'form': res})
        return self.env.ref(
            'l10n_in_hr_payroll.action_report_hrsalarybymonth').report_action(
                self, data=data)