Beispiel #1
0
class AccountAssetCategory(models.Model):
    _name = 'account.asset.category'
    _description = 'Asset category'

    active = fields.Boolean(default=True)
    name = fields.Char(required=True, index=True, string="Asset Type")
    account_analytic_id = fields.Many2one('account.analytic.account', string='Analytic Account')
    account_asset_id = fields.Many2one('account.account', string='Asset Account', required=True, domain=[('internal_type','=','other'), ('deprecated', '=', False)])
    account_income_recognition_id = fields.Many2one('account.account', string='Recognition Income Account', domain=[('internal_type','=','other'), ('deprecated', '=', False)], oldname='account_expense_depreciation_id')
    account_depreciation_id = fields.Many2one('account.account', string='Depreciation Account', required=True, domain=[('internal_type','=','other'), ('deprecated', '=', False)])
    journal_id = fields.Many2one('account.journal', string='Journal', required=True)
    company_id = fields.Many2one('res.company', string='Company', required=True, default=lambda self: self.env['res.company']._company_default_get('account.asset.category'))
    method = fields.Selection([('linear', 'Linear'), ('degressive', 'Degressive')], string='Computation Method', required=True, default='linear',
        help="Choose the method to use to compute the amount of depreciation lines.\n"
            "  * Linear: Calculated on basis of: Gross Value / Number of Depreciations\n"
            "  * Degressive: Calculated on basis of: Residual Value * Degressive Factor")
    method_number = fields.Integer(string='Number of Depreciations', default=5, help="The number of depreciations needed to depreciate your asset")
    method_period = fields.Integer(string='Period Length', default=1, help="State here the time between 2 depreciations, in months", required=True)
    method_progress_factor = fields.Float('Degressive Factor', default=0.3)
    method_time = fields.Selection([('number', 'Number of Depreciations'), ('end', 'Ending Date')], string='Time Method', required=True, default='number',
        help="Choose the method to use to compute the dates and number of depreciation lines.\n"
           "  * Number of Depreciations: Fix the number of depreciation lines and the time between 2 depreciations.\n"
           "  * Ending Date: Choose the time between 2 depreciations and the date the depreciations won't go beyond.")
    method_end = fields.Date('Ending date')
    prorata = fields.Boolean(string='Prorata Temporis', help='Indicates that the first depreciation entry for this asset have to be done from the purchase date instead of the first of January')
    open_asset = fields.Boolean(string='Post Journal Entries', help="Check this if you want to automatically confirm the assets of this category when created by invoices.")
    type = fields.Selection([('sale', 'Sale: Revenue Recognition'), ('purchase', 'Purchase: Asset')], required=True, index=True, default='purchase')

    @api.onchange('type')
    def onchange_type(self):
        if self.type == 'sale':
            self.prorata = True
            self.method_period = 1
        else:
            self.method_period = 12
Beispiel #2
0
class PriceRule(models.Model):
    _name = "delivery.price.rule"
    _description = "Delivery Price Rules"
    _order = 'sequence, list_price'

    @api.depends('variable', 'operator', 'max_value', 'list_base_price', 'list_price', 'variable_factor')
    def _get_name(self):
        for rule in self:
            name = 'if %s %s %s then' % (rule.variable, rule.operator, rule.max_value)
            if rule.list_base_price and not rule.list_price:
                name = '%s fixed price %s' % (name, rule.list_base_price)
            elif rule.list_price and not rule.list_base_price:
                name = '%s %s times %s' % (name, rule.list_price, rule.variable_factor)
            else:
                name = '%s fixed price %s and %s times %s Extra' % (name, rule.list_base_price, rule.list_price, rule.variable_factor)
            rule.name = name

    name = fields.Char(compute='_get_name')
    sequence = fields.Integer(required=True, help="Gives the sequence order when calculating delivery carrier.", default=10)
    carrier_id = fields.Many2one('delivery.carrier', 'Carrier', required=True, ondelete='cascade')
    variable = fields.Selection([('weight', 'Weight'), ('volume', 'Volume'), ('wv', 'Weight * Volume'), ('price', 'Price'), ('quantity', 'Quantity')], 'Variable', required=True, default='weight')
    operator = fields.Selection([('==', '='), ('<=', '<='), ('<', '<'), ('>=', '>='), ('>', '>')], 'Operator', required=True, default='<=')
    max_value = fields.Float('Maximum Value', required=True)
    variable_factor = fields.Selection([('weight', 'Weight'), ('volume', 'Volume'), ('wv', 'Weight * Volume'), ('price', 'Price'), ('quantity', 'Quantity')], 'Variable Factor', required=True, default='weight')
    list_base_price = fields.Float(string='Sale Base Price', digits=dp.get_precision('Product Price'), required=True, default=0.0)
    list_price = fields.Float('Sale Price', digits=dp.get_precision('Product Price'), required=True, default=0.0)
    standard_price = fields.Float('Cost Price', digits=dp.get_precision('Product Price'), required=True, default=0.0)
Beispiel #3
0
class AccountTaxTemplatePython(models.Model):
    _inherit = 'account.tax.template'

    amount_type = fields.Selection(selection_add=[('code', 'Python Code')])

    python_compute = fields.Text(
        string='Python Code',
        default="result = price_unit * 0.10",
        help=
        "Compute the amount of the tax by setting the variable 'result'.\n\n"
        ":param base_amount: float, actual amount on which the tax is applied\n"
        ":param price_unit: float\n"
        ":param quantity: float\n"
        ":param product: product.product recordset singleton or None\n"
        ":param partner: res.partner recordset singleton or None")
    python_applicable = fields.Text(
        string='Applicable Code',
        default="result = True",
        help=
        "Determine if the tax will be applied by setting the variable 'result' to True or False.\n\n"
        ":param price_unit: float\n"
        ":param quantity: float\n"
        ":param product: product.product recordset singleton or None\n"
        ":param partner: res.partner recordset singleton or None")

    def _get_tax_vals(self, company):
        """ This method generates a dictionnary of all the values for the tax that will be created.
        """
        self.ensure_one()
        res = super(AccountTaxTemplatePython, self)._get_tax_vals(company)
        res['python_compute'] = self.python_compute
        res['python_applicable'] = self.python_applicable
        return res
Beispiel #4
0
class base_module_update(models.TransientModel):
    _name = "base.module.update"
    _description = "Update Module"

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

    @api.one
    def update_module(self):
        self.updated, self.added = self.env['ir.module.module'].update_list()
        self.state = 'done'
        return False

    @api.multi
    def action_module_open(self):
        res = {
            'domain': str([]),
            'name': 'Modules',
            'view_type': 'form',
            'view_mode': 'tree,form',
            'res_model': 'ir.module.module',
            'view_id': False,
            'type': 'ir.actions.act_window',
        }
        return res
Beispiel #5
0
class LunchCashMove(models.Model):
    """ Two types of cashmoves: payment (credit) or order (debit) """
    _name = 'lunch.cashmove'
    _description = 'lunch cashmove'

    user_id = fields.Many2one('res.users',
                              'User',
                              required=True,
                              default=lambda self: self.env.uid)
    date = fields.Date('Date',
                       required=True,
                       default=fields.Date.context_today)
    amount = fields.Float(
        'Amount',
        required=True,
        help=
        'Can be positive (payment) or negative (order or payment if user wants to get his money back)'
    )
    description = fields.Text('Description',
                              help='Can be an order or a payment')
    order_id = fields.Many2one('lunch.order.line', 'Order', ondelete='cascade')
    state = fields.Selection([('order', 'Order'), ('payment', 'Payment')],
                             'Is an order or a payment',
                             default='payment')

    @api.multi
    def name_get(self):
        return [(cashmove.id,
                 '%s %s' % (_('Lunch Cashmove'), '#%d' % cashmove.id))
                for cashmove in self]
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"))
        return self.env['report'].with_context(landscape=True).get_action(
            self, 'account.report_generalledger', data=data)
Beispiel #7
0
class product_template(models.Model):
    _inherit = "product.template"
    project_id = fields.Many2one('project.project',
                                 string='Project',
                                 ondelete='set null')
    track_service = fields.Selection(
        selection_add=[('task', 'Create a task and track hours')])
Beispiel #8
0
class UserBadge(models.Model):
    _inherit = 'gamification.badge.user'

    level = fields.Selection([('bronze', 'bronze'), ('silver', 'silver'),
                              ('gold', 'gold')],
                             string='Forum Badge Level',
                             related="badge_id.level",
                             store=True)
Beispiel #9
0
class SaleConfiguration(models.TransientModel):
    _inherit = 'sale.config.settings'

    module_delivery = fields.Selection(
        [(0, 'No shipping costs on sales orders'),
         (1, 'Allow adding shipping costs')], "Shipping")
    default_picking_policy = fields.Selection(
        [(0, 'Ship products when some are available, and allow back orders'),
         (1, 'Ship all products at once, without back orders')],
        "Default Shipping Policy")
    group_mrp_properties = fields.Selection(
        [(0, "Don't use manufacturing properties (recommended as its easier)"),
         (1,
          'Allow setting manufacturing order properties per order line (advanced)'
          )],
        "Properties on SO Lines",
        implied_group='sale.group_mrp_properties',
        help="Allows you to tag sales order lines with properties.")
    group_route_so_lines = fields.Selection(
        [(0, 'No order specific routes like MTO or drop shipping'),
         (1, 'Choose specific routes on sales order lines (advanced)')],
        "Order Routing",
        implied_group='sale_stock.group_route_so_lines')

    @api.multi
    def get_default_sale_config(self):
        default_picking_policy = self.env['ir.values'].get_default(
            'sale.order', 'picking_policy')
        return {
            'default_picking_policy':
            1 if default_picking_policy == 'one' else 0,
        }

    @api.multi
    def set_sale_defaults(self):
        self.ensure_one()
        if not self.env.user._is_admin():
            raise AccessError(_("Only administrators can change the settings"))

        default_picking_policy = 'one' if self.default_picking_policy else 'direct'
        self.env['ir.values'].sudo().set_default('sale.order',
                                                 'picking_policy',
                                                 default_picking_policy)
        res = super(SaleConfiguration, self).set_sale_defaults()
        return res
Beispiel #10
0
class account_payment_method(models.Model):
    _name = "account.payment.method"
    _description = "Payment Methods"

    name = fields.Char(required=True)
    code = fields.Char(required=True)  # For internal identification
    payment_type = fields.Selection([('inbound', 'Inbound'),
                                     ('outbound', 'Outbound')],
                                    required=True)
Beispiel #11
0
class BusPresence(models.Model):
    """ User Presence
        Its status is 'online', 'away' or 'offline'. This model should be a one2one, but is not
        attached to res_users to avoid database concurrence errors. Since the 'update' method is executed
        at each poll, if the user have multiple opened tabs, concurrence errors can happend, but are 'muted-logged'.
    """

    _name = 'bus.presence'
    _description = 'User Presence'
    _log_access = False

    _sql_constraints = [('bus_user_presence_unique', 'unique(user_id)',
                         'A user can only have one IM status.')]

    user_id = fields.Many2one('res.users',
                              'Users',
                              required=True,
                              index=True,
                              ondelete='cascade')
    last_poll = fields.Datetime('Last Poll',
                                default=lambda self: fields.Datetime.now())
    last_presence = fields.Datetime('Last Presence',
                                    default=lambda self: fields.Datetime.now())
    status = fields.Selection([('online', 'Online'), ('away', 'Away'),
                               ('offline', 'Offline')],
                              'IM Status',
                              default='offline')

    @api.model
    def update(self, inactivity_period):
        """ Updates the last_poll and last_presence of the current user
            :param inactivity_period: duration in milliseconds
        """
        presence = self.search([('user_id', '=', self._uid)], limit=1)
        # compute last_presence timestamp
        last_presence = datetime.datetime.now() - datetime.timedelta(
            milliseconds=inactivity_period)
        values = {
            'last_poll': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT),
        }
        # update the presence or a create a new one
        if not presence:  # create a new presence for the user
            values['user_id'] = self._uid
            values['last_presence'] = last_presence.strftime(
                DEFAULT_SERVER_DATETIME_FORMAT)
            self.create(values)
        else:  # update the last_presence if necessary, and write values
            if datetime.datetime.strptime(
                    presence.last_presence,
                    DEFAULT_SERVER_DATETIME_FORMAT) < last_presence:
                values['last_presence'] = last_presence.strftime(
                    DEFAULT_SERVER_DATETIME_FORMAT)
            # Hide transaction serialization errors, which can be ignored, the presence update is not essential
            with tools.mute_logger('ecore.sql_db'):
                presence.write(values)
        # avoid TransactionRollbackError
        self.env.cr.commit()  # TODO : check if still necessary
class RecruitmentSettings(models.TransientModel):
    _name = 'hr.recruitment.config.settings'
    _inherit = ['res.config.settings', 'fetchmail.config.settings']

    module_document = fields.Selection(selection=[
            (0, "Do not manage CVs and motivation letter"),
            (1, 'Allow the automatic indexation of resumes')
            ], string='Resumes',
            help='Manage your CV\'s and motivation letter related to all applicants.\n'
                            '-This installs the module document_ftp. This will install the knowledge management  module in order to allow you to search using specific keywords through  the content of all documents (PDF, .DOCx...)')
Beispiel #13
0
class AccountAccountTag(models.Model):
    _name = 'account.account.tag'
    _description = 'Account Tag'

    name = fields.Char(required=True)
    applicability = fields.Selection([('accounts', 'Accounts'),
                                      ('taxes', 'Taxes')],
                                     required=True,
                                     default='accounts')
    color = fields.Integer('Color Index')
Beispiel #14
0
class ProductProduct(models.Model):
    _inherit = "product.template"

    expense_policy = fields.Selection(
        [('cost', 'At Cost'), ('sales_price', 'At Sales Price')],
        string='Expense Invoice Policy',
        help=
        "If you invoice at cost, the expense will be invoiced on the sale order at the cost of the analytic line;"
        "if you invoice at sales price, the price of the product will be used instead.",
        default='cost')
Beispiel #15
0
class ChannelPartner(models.Model):
    _name = 'mail.channel.partner'
    _description = 'Last Seen Many2many'
    _table = 'mail_channel_partner'
    _rec_name = 'partner_id'

    partner_id = fields.Many2one('res.partner', string='Recipient', ondelete='cascade')
    channel_id = fields.Many2one('mail.channel', string='Channel', ondelete='cascade')
    seen_message_id = fields.Many2one('mail.message', string='Last Seen')
    fold_state = fields.Selection([('open', 'Open'), ('folded', 'Folded'), ('closed', 'Closed')], string='Conversation Fold State', default='open')
    is_minimized = fields.Boolean("Conversation is minimied")
    is_pinned = fields.Boolean("Is pinned on the interface", default=True)
Beispiel #16
0
class DateRangeGenerator(models.TransientModel):
    _name = 'date.range.generator'

    @api.model
    def _default_company(self):
        return self.env['res.company']._company_default_get('date.range')

    name_prefix = fields.Char('Range name prefix', required=True)
    date_start = fields.Date(strint='Start date', required=True)
    type_id = fields.Many2one(comodel_name='date.range.type',
                              string='Type',
                              required=True,
                              ondelete='cascade')
    company_id = fields.Many2one(comodel_name='res.company',
                                 string='Company',
                                 default=_default_company)
    unit_of_time = fields.Selection([(YEARLY, 'years'), (MONTHLY, 'months'),
                                     (WEEKLY, 'weeks'), (DAILY, 'days')],
                                    required=True)
    duration_count = fields.Integer('Duration', required=True)
    count = fields.Integer(string="Number of ranges to generate",
                           required=True)

    @api.multi
    def _compute_date_ranges(self):
        self.ensure_one()
        vals = rrule(freq=self.unit_of_time,
                     interval=self.duration_count,
                     dtstart=fields.Date.from_string(self.date_start),
                     count=self.count + 1)
        vals = list(vals)
        date_ranges = []
        for idx, dt_start in enumerate(vals[:-1]):
            date_start = fields.Date.to_string(dt_start.date())
            dt_end = vals[idx + 1].date() - relativedelta(days=1)
            date_end = fields.Date.to_string(dt_end)
            date_ranges.append({
                'name': '%s-%d' % (self.name_prefix, idx + 1),
                'date_start': date_start,
                'date_end': date_end,
                'type_id': self.type_id.id,
                'company_id': self.company_id.id
            })
        return date_ranges

    @api.multi
    def action_apply(self):
        date_ranges = self._compute_date_ranges()
        if date_ranges:
            for dr in date_ranges:
                self.env['date.range'].create(dr)
        return self.env['ir.actions.act_window'].for_xml_id(
            module='date_range', xml_id='date_range_action')
Beispiel #17
0
class ProductTemplate(models.Model):
    _inherit = 'product.template'
    track_service = fields.Selection(
        selection_add=[('timesheet', 'Timesheets on contract')])

    @api.onchange('type', 'invoice_policy')
    def onchange_type_timesheet(self):
        if self.type == 'service' and self.invoice_policy == 'cost':
            self.track_service = 'timesheet'
        if self.type != 'service':
            self.track_service = 'manual'
        return {}
Beispiel #18
0
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 (_('Error!'), _('Not implemented.'))

    @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', 'en_US'))
        return self._print_report(data)
Beispiel #19
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 identifying the web page on which the rules will be applied.")
    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="* Select 'Display the button' to simply display the chat button on the pages.\n"\
             "* Select 'Auto popup' for to display the button, and automatically open the conversation window.\n"\
             "* Select 'Hide the button' to hide the chat button on the pages.")
    auto_popup_timer = fields.Integer('Auto popup timer', default=0,
        help="Delay (in seconds) to automatically open the converssation window. Note : the selected action must be 'Auto popup', otherwise this parameter will not be take 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 actual rule will match only for this country. So if you set select 'Belgium' and 'France' and you set the action to 'Hide Buttun', this 2 country will not be see the support button for the specified URL. 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 match 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 match the given condition. False otherwise.
            :rtype : im_livechat.channel.rule
        """
        def _match(rules):
            for rule in rules:
                if re.search(rule.regex_url, 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))
class AccountingCommonPartnerReport(models.TransientModel):
    _name = 'account.common.partner.report'
    _description = 'Account Common Partner Report'
    _inherit = "account.common.report"

    result_selection = fields.Selection(
        [('customer', 'Receivable Accounts'), ('supplier', 'Payable Accounts'),
         ('customer_supplier', 'Receivable and Payable Accounts')],
        string="Partner's",
        required=True,
        default='customer')

    def pre_print_report(self, data):
        data['form'].update(self.read(['result_selection'])[0])
        return data
Beispiel #21
0
class AccountJournal(models.Model):
    _inherit = "account.journal"

    bank_statements_source = fields.Selection(selection_add=[("file_import", "File Import")])

    @api.multi
    def import_statement(self):
        """return action to import bank/cash statements. This button should be called only on journals with type =='bank'"""
        model = 'account.bank.statement'
        action_name = 'action_account_bank_statement_import'
        ir_model_obj = self.pool['ir.model.data']
        model, action_id = ir_model_obj.get_object_reference(self._cr, self._uid, 'account_bank_statement_import', action_name)
        action = self.pool[model].read(self._cr, self._uid, action_id, context=self.env.context)
        # Note: this drops action['context'], which is a dict stored as a string, which is not easy to update
        action.update({'context': (u"{'journal_id': " + str(self.id) + u"}")})
        return action
Beispiel #22
0
class company(models.Model):
    _inherit = 'res.company'

    po_lead = fields.Float(string='Purchase Lead Time', required=True,\
        help="Margin of error for vendor lead times. When the system "
             "generates Purchase Orders for procuring products, "
             "they will be scheduled that many days earlier "
             "to cope with unexpected vendor delays.", default=1.0)

    po_double_validation = fields.Selection([
        ('one_step', 'Confirm purchase orders in one step'),
        ('two_step', 'Get 2 levels of approvals to confirm a purchase order')
        ], string="Levels of Approvals", default='one_step',\
        help="Provide a double validation mechanism for purchases")
    po_double_validation_amount = fields.Monetary(string='Double validation amount', default=5000,\
        help="Minimum amount for which a double validation is required")
Beispiel #23
0
class SaasConfigParam(models.TransientModel):
    _name = 'saas.config.param'

    def _get_keys(self):
        return [
            ('saas_client.max_users', 'Max Users'),
            ('saas_client.suspended', 'Suspended'),
            ('saas_client.total_storage_limit', 'Total storage limit'),
        ]

    key = fields.Selection(selection=_get_keys,
                           string='Key',
                           required=1,
                           size=64)
    value = fields.Char('Value', required=1, size=64)
    config_id = fields.Many2one('saas.config', 'Config')
    hidden = fields.Boolean('Hidden parameter', default=True)
Beispiel #24
0
class AccountCommonAccountReport(models.TransientModel):
    _name = 'account.common.account.report'
    _description = 'Account Common Account Report'
    _inherit = "account.common.report"

    display_account = fields.Selection([
        ('all', 'All'),
        ('movement', 'With movements'),
        ('not_zero', 'With balance is not equal to 0'),
    ],
                                       string='Display Accounts',
                                       required=True,
                                       default='movement')

    @api.multi
    def pre_print_report(self, data):
        data['form'].update(self.read(['display_account'])[0])
        return data
Beispiel #25
0
class HtmlFormField(models.Model):

    _name = "html.form.field"
    _description = "HTML Form Field"
    _order = "sequence asc"

    sequence = fields.Integer(string="Sequence")
    html_id = fields.Many2one('html.form',
                              ondelete='cascade',
                              string="HTML Form")
    model_id = fields.Many2one('ir.model', string="Model", readonly=True)
    model = fields.Char(related="model_id.model",
                        string="Model Name",
                        readonly=True)
    field_id = fields.Many2one(
        'ir.model.fields',
        domain=
        "[('name','!=','create_date'),('name','!=','create_uid'),('name','!=','id'),('name','!=','write_date'),('name','!=','write_uid')]",
        string="Form Field")
    field_type = fields.Many2one('html.form.field.type', string="Field Type")
    field_label = fields.Char(string="Field Label")
    html_name = fields.Char(string="HTML Name")
    validation_format = fields.Char(string="Validation Format")
    setting_general_required = fields.Boolean(string="Required")
    setting_binary_file_type_filter = fields.Selection(
        [('image', 'Image'), ('audio', 'Audio')], string="File Type Filter")
    character_limit = fields.Integer(string="Character Limit", default="100")

    @api.model
    def create(self, values):
        sequence = self.env['ir.sequence'].get('sequence')
        values['sequence'] = sequence
        return super(HtmlFormField, self).create(values)

    @api.onchange('field_id')
    def _onchange_field_id(self):
        """Set the default field type, html_name and field label"""
        if self.field_id:
            self.field_type = self.env['html.form.field.type'].search([
                ('data_type', '=', self.field_id.ttype), ('default', '=', True)
            ])[0].id
            self.html_name = self.field_id.name
            self.field_label = self.field_id.field_description
Beispiel #26
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
    state = fields.Selection(selection_add=[('c', 'C')])

    # override the computed field, and extend its dependencies
    @api.one
    @api.depends('field_in_mother')
    def _compute_surname(self):
        if self.field_in_mother:
            self.surname = self.field_in_mother
        else:
            super(mother, self)._compute_surname()
Beispiel #27
0
class AccountAccountType(models.Model):
    _name = "account.account.type"
    _description = "Account Type"

    name = fields.Char(string='Account Type', required=True, translate=True)
    include_initial_balance = fields.Boolean(
        string="Bring Accounts Balance Forward",
        help=
        "Used in reports to know if we should consider journal items from the beginning of time instead of from the fiscal year only. Account types that should be reset to zero at each new fiscal year (like expenses, revenue..) should not have this option set."
    )
    type = fields.Selection([
        ('other', 'Regular'),
        ('receivable', 'Receivable'),
        ('payable', 'Payable'),
        ('liquidity', 'Liquidity'),
    ], required=True, default='other',
        help="The 'Internal Type' is used for features available on "\
        "different types of accounts: liquidity type is for cash or bank accounts"\
        ", payable/receivable is for vendor/customer accounts.")
    note = fields.Text(string='Description')
Beispiel #28
0
class TemplatePreview(models.TransientModel):
    _inherit = "mail.template"
    _name = "email_template.preview"
    _description = "Email Template Preview"

    @api.model
    def _get_records(self):
        """ Return Records of particular Email Template's Model """
        template_id = self._context.get('template_id')
        default_res_id = self._context.get('default_res_id')
        if not template_id:
            return []
        template = self.env['mail.template'].browse(int(template_id))
        records = self.env[template.model_id.model].search([], limit=10)
        records |= records.browse(default_res_id)
        return records.name_get()

    @api.model
    def default_get(self, fields):
        result = super(TemplatePreview, self).default_get(fields)

        if 'res_id' in fields and not result.get('res_id'):
            records = self._get_records()
            result['res_id'] = records and records[0][0] or False  # select first record as a Default
        if self._context.get('template_id') and 'model_id' in fields and not result.get('model_id'):
            result['model_id'] = self.env['mail.template'].browse(self._context['template_id']).model_id.id
        return result

    res_id = fields.Selection(_get_records, 'Sample Document')
    partner_ids = fields.Many2many('res.partner', string='Recipients')

    @api.onchange('res_id')
    @api.multi
    def on_change_res_id(self):
        mail_values = {}
        if self.res_id and self._context.get('template_id'):
            template = self.env['mail.template'].browse(self._context['template_id'])
            self.name = template.name
            mail_values = template.generate_email(self.res_id)
        for field in ['email_from', 'email_to', 'email_cc', 'reply_to', 'subject', 'body_html', 'partner_to', 'partner_ids', 'attachment_ids']:
            setattr(self, field, mail_values.get(field, False))
Beispiel #29
0
class forecast_product(models.Model):

    _name = 'forecast.product'

    name = fields.Char('Name')
    forecast_id = fields.Many2one('sale.forecast', string='Forecast')
    product_id = fields.Many2one('product.product', string='Product')
    period_start_date = fields.Date('Start Date')
    period_end_date = fields.Date('End Date')
    sales_person = fields.Many2one('res.users', string='Salesperson')
    # sales_team = fields.Many2one('crm.team', string='Sales Team')
    forecast_qty = fields.Float('Forecast Qty')
    onhand_qty = fields.Float('Onhand Qty')
    rest_period_qty = fields.Float('Rest Period Qty')
    incoming_qty = fields.Float('Incoming Qty')
    outgoing_qty = fields.Float('Outgoing Qty')
    action_qty = fields.Float('Action Qty')
    document_number = fields.Char('Ref.Doc.No.')
    procurement_id = fields.Char('Procurement id')
    action_required = fields.Selection([('buy', 'Buy'),
                                        ('manufacture', 'Manufacture'),
                                        ('both', 'Both'),
                                        ('none', 'Not Required')],
                                       'Action Required',
                                       copy=False)
    last_period_qty = fields.Float('Last Period Qty')
    sec_last_period_qty = fields.Float('Second Last Period Qty')
    third_last_period_qty = fields.Float('Third Last Period Qty')
    avg_qty = fields.Float("Average Forecast Qty")
    avg_sale_qty = fields.Float("Average Sale Quantity")

    @api.multi
    def unlink(self):
        '''
        Here as per the selection of forecast_filter_id the records other than the filter value are not managable as filter is applying on One2many field.
        so, by default unlink method is called for the records other than the filter records.
        To resolve this here unlink method is marked as false, as delete functionality has been removed  for this perticular field once the record is created.
        '''
        return False
Beispiel #30
0
class module_dependency(osv.Model):
    _name = "ir.module.module.dependency"
    _description = "Module dependency"

    # the dependency name
    name = fields2.Char(index=True)

    # the module that depends on it
    module_id = fields2.Many2one('ir.module.module',
                                 'Module',
                                 ondelete='cascade')

    # the module corresponding to the dependency, and its status
    depend_id = fields2.Many2one('ir.module.module',
                                 'Dependency',
                                 compute='_compute_depend')
    state = fields2.Selection(DEP_STATES,
                              string='Status',
                              compute='_compute_state')

    @api.multi
    @api.depends('name')
    def _compute_depend(self):
        # retrieve all modules corresponding to the dependency names
        names = list(set(dep.name for dep in self))
        mods = self.env['ir.module.module'].search([('name', 'in', names)])

        # index modules by name, and assign dependencies
        name_mod = dict((mod.name, mod) for mod in mods)
        for dep in self:
            dep.depend_id = name_mod.get(dep.name)

    @api.one
    @api.depends('depend_id.state')
    def _compute_state(self):
        self.state = self.depend_id.state or 'unknown'