示例#1
0
class HrEquipmentConfigSettings(models.TransientModel):
    _name = 'hr.equipment.config.settings'
    _inherit = 'res.config.settings'

    equipment_alias_prefix = fields.Char('Use the following alias to report internal equipment issue')
    alias_domain = fields.Char("Alias Domain")

    @api.multi
    def get_default_alias_equipment(self):
        alias_name = False
        alias_id = self.env.ref('hr_equipment.mail_alias_equipment')
        if alias_id:
            alias_name = alias_id.alias_name
        return {'equipment_alias_prefix': alias_name}

    @api.multi
    def set_default_alias_equipment(self):
        for record in self:
            default_equipment_alias_prefix = record.get_default_alias_equipment()['equipment_alias_prefix']
            if record.equipment_alias_prefix != default_equipment_alias_prefix:
                alias_id = self.env.ref('hr_equipment.mail_alias_equipment')
                if alias_id:
                    alias_id.write({'alias_name': record.equipment_alias_prefix})
        return True

    @api.multi
    def get_default_alias_domain(self):
        alias_domain = self.env['ir.config_parameter'].get_param("mail.catchall.domain")
        if not alias_domain:
            domain = self.env["ir.config_parameter"].get_param("web.base.url")
            try:
                alias_domain = urlsplit(domain).netloc.split(':')[0]
            except Exception:
                pass
        return {'alias_domain': alias_domain}
示例#2
0
文件: res_config.py 项目: ecoreos/hz
class SaasPortalConfigWizard(models.TransientModel):
    _inherit = 'saas_server.config.settings'

    saas_s3_aws_accessid = fields.Char('AWS Access ID')
    saas_s3_aws_accesskey = fields.Char('AWS Secret Key')
    saas_s3_aws_bucket = fields.Char('S3 Bucket')

    def get_default_saas_s3_aws_accessid(self, cr, uid, ids, context=None):
        saas_s3_aws_accessid = self.pool.get("ir.config_parameter").get_param(
            cr,
            uid,
            "saas_s3.saas_s3_aws_accessid",
            default=None,
            context=context)
        return {'saas_s3_aws_accessid': saas_s3_aws_accessid or False}

    def set_saas_s3_aws_accessid(self, cr, uid, ids, context=None):
        config_parameters = self.pool.get("ir.config_parameter")
        for record in self.browse(cr, uid, ids, context=context):
            config_parameters.set_param(cr,
                                        uid,
                                        "saas_s3.saas_s3_aws_accessid",
                                        record.saas_s3_aws_accessid or '',
                                        context=context)

    def get_default_saas_s3_aws_accesskey(self, cr, uid, ids, context=None):
        saas_s3_aws_accesskey = self.pool.get("ir.config_parameter").get_param(
            cr,
            uid,
            "saas_s3.saas_s3_aws_accesskey",
            default=None,
            context=context)
        return {'saas_s3_aws_accesskey': saas_s3_aws_accesskey or False}

    def set_saas_s3_aws_accesskey(self, cr, uid, ids, context=None):
        config_parameters = self.pool.get("ir.config_parameter")
        for record in self.browse(cr, uid, ids, context=context):
            config_parameters.set_param(cr,
                                        uid,
                                        "saas_s3.saas_s3_aws_accesskey",
                                        record.saas_s3_aws_accesskey or '',
                                        context=context)

    def get_default_saas_s3_aws_bucket(self, cr, uid, ids, context=None):
        saas_s3_aws_bucket = self.pool.get("ir.config_parameter").get_param(
            cr,
            uid,
            "saas_s3.saas_s3_aws_bucket",
            default=None,
            context=context)
        return {'saas_s3_aws_bucket': saas_s3_aws_bucket or False}

    def set_saas_s3_aws_bucket(self, cr, uid, ids, context=None):
        config_parameters = self.pool.get("ir.config_parameter")
        for record in self.browse(cr, uid, ids, context=context):
            config_parameters.set_param(cr,
                                        uid,
                                        "saas_s3.saas_s3_aws_bucket",
                                        record.saas_s3_aws_bucket or '',
                                        context=context)
示例#3
0
class RegistrationEditorLine(models.TransientModel):
    """Event Registration"""
    _name = "registration.editor.line"

    editor_id = fields.Many2one('registration.editor')
    sale_order_line_id = fields.Many2one('sale.order.line',
                                         string='Sale Order Line')
    event_id = fields.Many2one('event.event', string='Event', required=True)
    registration_id = fields.Many2one('event.registration',
                                      'Original Registration')
    event_ticket_id = fields.Many2one('event.event.ticket',
                                      string='Event Ticket')
    email = fields.Char(string='Email')
    phone = fields.Char(string='Phone')
    name = fields.Char(string='Name', select=True)

    @api.one
    def get_registration_data(self):
        return {
            'event_id': self.event_id.id,
            'event_ticket_id': self.event_ticket_id.id,
            'partner_id': self.editor_id.sale_order_id.partner_id.id,
            'name': self.name or self.editor_id.sale_order_id.partner_id.name,
            'phone': self.phone
            or self.editor_id.sale_order_id.partner_id.phone,
            'email': self.email
            or self.editor_id.sale_order_id.partner_id.email,
            'origin': self.editor_id.sale_order_id.name,
            'sale_order_id': self.editor_id.sale_order_id.id,
            'sale_order_line_id': self.sale_order_line_id.id,
        }
示例#4
0
class SaaSPortalModule(models.Model):
    _name = 'saas_portal.module'

    name = fields.Char('Name')
    technical_name = fields.Char('Technical Name')
    summary = fields.Text('Summary')
    author = fields.Char('Author')
    url = fields.Char('URL')
    module_id = fields.Many2one('ir.module.module', required=False)

    @api.onchange('module_id')
    def onchange_module_id(self):
        if self.module_id:
            self.name = self.module_id.shortdesc
            self.technical_name = self.module_id.name
            self.summary = self.module_id.summary
            self.author = self.module_id.author
            self.url = self.module_id.url
        else:
            self.name, self.technical_name, self.summary, self.author, self.url = [
                False
            ] * 5

    _sql_constraints = [
        ('technical_name_uniq', 'unique(technical_name)',
         'The module already exists!'),
    ]
示例#5
0
class HtmlFormCaptcha(models.Model):

    _name = "html.form.captcha"
    _description = "HTML Form Captcha"

    name = fields.Char(string="Captcha Name")
    internal_name = fields.Char(string="Internal Name")
示例#6
0
class PostReason(models.Model):
    _name = "forum.post.reason"
    _description = "Post Closing Reason"
    _order = 'name'

    name = fields.Char(string='Closing Reason', required=True, translate=True)
    reason_type = fields.Char(string='Reason Type')
示例#7
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)
示例#8
0
class SaasPricingPrice(models.Model):
    _name = 'saas_pricing.price'

    name = fields.Char('Price name')
    interval = fields.Char('Price interval')
    price = fields.Float('Price', digits=(16, 2))
    stripe_planid = fields.Char('Stripe Plan id')
    stripe_currency = fields.Many2one('res.currency')
    trial_period_days = fields.Char('Stripe trial period days')
示例#9
0
class HtmlFormActionType(models.Model):

    _name = "html.form.action.type"
    _description = "HTML Form Action Type"

    name = fields.Char(string="Name")
    internal_name = fields.Char(
        string="Internal Name",
        help="action is executed in controller '_html_action_<internal_name>'")
示例#10
0
class intrastat_transport_mode(models.Model):
    _name = 'l10n_be_intrastat.transport_mode'

    code = fields.Char('Code', required=True, readonly=True)
    name = fields.Char('Description', readonly=True)

    _sql_constraints = [
        ('l10n_be_intrastat_trmodecodeunique', 'UNIQUE (code)', 'Code must be unique.'),
    ]
示例#11
0
class SaasPortalPlan(models.Model):
    _name = 'saas_portal.plan'
    _inherit = 'saas_portal.plan'

    page_url = fields.Char('Plan URL', placeholder='some-name')
    ecore_version = fields.Char('eCore Version', placeholder='8.0')
    app_store_module_ids = fields.Many2many('saas_portal.module',
                                            'saas_portal_plan_module',
                                            'plan_id', 'module_id', 'Modules')
示例#12
0
class account_cost_center(models.Model):
    _name = 'account.cost.center'
    _description = 'Cuenta de centro de costos'

    name = fields.Char(string='Nombre', required=False, size=64)
    code = fields.Char(string='Codigo', required=True, size=16)
    company_id = fields.Many2one(comodel_name='res.company',
                                 string='Company',
                                 required=True,
                                 default=lambda self: self.env.user.company_id)
示例#13
0
class intrastat_region(models.Model):
    _name = 'l10n_be_intrastat.region'

    code = fields.Char('Code', required=True)
    country_id = fields.Many2one('res.country', 'Country')
    name = fields.Char('Name', translate=True)
    description = fields.Char('Description')

    _sql_constraints = [
        ('l10n_be_intrastat_regioncodeunique', 'UNIQUE (code)', 'Code must be unique.'),
    ]
示例#14
0
class MailMessageSubtype(models.Model):
    """ Class holding subtype definition for messages. Subtypes allow to tune
        the follower subscription, allowing only some subtypes to be pushed
        on the Wall. """
    _name = 'mail.message.subtype'
    _description = 'Message subtypes'
    _order = 'sequence, id'

    name = fields.Char(
        'Message Type',
        required=True,
        translate=True,
        help='Message subtype gives a more precise type on the message, '
        'especially for system notifications. For example, it can be '
        'a notification related to a new record (New), or to a stage '
        'change in a process (Stage change). Message subtypes allow to '
        'precisely tune the notifications the user want to receive on its wall.'
    )
    description = fields.Text(
        'Description',
        translate=True,
        help='Description that will be added in the message posted for this '
        'subtype. If void, the name will be added instead.')
    internal = fields.Boolean(
        'Internal Only',
        help=
        'Messages with internal subtypes will be visible only by employees, aka members of base_user group'
    )
    parent_id = fields.Many2one(
        'mail.message.subtype',
        string='Parent',
        ondelete='set null',
        help=
        'Parent subtype, used for automatic subscription. This field is not '
        'correctly named. For example on a project, the parent_id of project '
        'subtypes refers to task-related subtypes.')
    relation_field = fields.Char(
        'Relation field',
        help='Field used to link the related model to the subtype model when '
        'using automatic subscription on a related document. The field '
        'is used to compute getattr(related_document.relation_field).')
    res_model = fields.Char(
        'Model',
        help=
        "Model the subtype applies to. If False, this subtype applies to all models."
    )
    default = fields.Boolean('Default',
                             default=True,
                             help="Activated by default when subscribing.")
    sequence = fields.Integer('Sequence',
                              default=1,
                              help="Used to order subtypes.")
    hidden = fields.Boolean('Hidden',
                            help="Hide the subtype in the follower options")
示例#15
0
class HtmlFormAction(models.Model):

    _name = "html.form.action"
    _description = "HTML Form Action"

    hf_id = fields.Many2one('html.form', string="HTML Form")
    action_type_id = fields.Many2one('html.form.action.type',
                                     string="Submit Action")
    setting_name = fields.Char(string="Internal Name",
                               related="action_type_id.internal_name")
    settings_description = fields.Char(string="Settings Description")
示例#16
0
class SaasPortalCategory(models.Model):

    @api.multi
    def name_get(self):
        res = []
        for record in self:
            res.append((record.id, record.display_name))
        return res

    @api.one
    @api.depends('name')
    def _name_get_fnc(self):
        name = self.name
        if self.parent_id:
            name = self.parent_id.name + ' / ' + name
        self.display_name = name

    _name = "saas.portal.category"
    _description = "SaaS Client  Category"
    name = fields.Char(
        "Employee Tag",
        required=True
    )
    display_name = fields.Char(
        'Name',
        compute='_name_get_fnc',
        store=True,
        readonly=True
    )
    parent_id = fields.Many2one(
        'saas.portal.category',
        'Parent Employee Tag',
        index=True
    )
    child_ids = fields.One2many(
        'saas.portal.category',
        'parent_id',
        'Child Categories'
    )

    @api.constrains('parent_id')
    @api.multi
    def _check_recursion(self):
        level = 100
        cr = self.env.cr
        ids = self.ids
        while len(ids):
            cr.execute('select distinct parent_id from saas_portal_category where id IN %s', (tuple(ids), ))
            ids = filter(None, map(lambda x:x[0], cr.fetchall()))
            if not level:
                raise Warning('Error! You cannot create recursive Categories')
            level -= 1
        return True
示例#17
0
class HtmlFormFieldType(models.Model):

    _name = "html.form.field.type"
    _description = "HTML Form Field Type"

    name = fields.Char(string="Name")
    html_type = fields.Char(string="HTML Type",
                            help="Internal Reference to this HTML type")
    data_type = fields.Char(string="Data Type",
                            help="The eCore data type(ttype)")
    default = fields.Boolean(
        string="Default",
        help="Is this the default HTML type for this datatype?")
示例#18
0
class AccountAnalyticLine(models.Model):
    _inherit = 'account.analytic.line'
    _description = 'Analytic Line'
    _order = 'date desc'

    product_uom_id = fields.Many2one('product.uom', string='Unit of Measure')
    product_id = fields.Many2one('product.product', string='Product')
    general_account_id = fields.Many2one('account.account', string='Financial Account', ondelete='restrict',
                                         related='move_id.account_id', store=True, domain=[('deprecated', '=', False)])
    move_id = fields.Many2one('account.move.line', string='Move Line', ondelete='cascade', index=True)
    code = fields.Char(size=8)
    ref = fields.Char(string='Ref.')
    currency_id = fields.Many2one('res.currency', related='move_id.currency_id', string='Account Currency', store=True, help="The related account currency if not equal to the company one.", readonly=True)
    amount_currency = fields.Monetary(related='move_id.amount_currency', store=True, help="The amount expressed in the related account currency if not equal to the company one.", readonly=True)
    partner_id = fields.Many2one('res.partner', related='account_id.partner_id', string='Partner', store=True)

    @api.v8
    @api.onchange('product_id', 'product_uom_id', 'unit_amount', 'currency_id')
    def on_change_unit_amount(self):
        if not self.product_id:
            return {}

        result = 0.0
        prod_accounts = self.product_id.product_tmpl_id._get_product_accounts()
        unit = self.product_uom_id
        account = prod_accounts['expense']
        if not unit or self.product_id.uom_po_id.category_id.id != unit.category_id.id:
            unit = self.product_id.uom_po_id

        ctx = dict(self._context or {})
        if unit:
            # price_get() will respect a 'uom' in its context, in order
            # to return a default price for those units
            ctx['uom'] = unit.id

        # Compute based on pricetype
        amount_unit = self.product_id.with_context(ctx).price_get('standard_price')[self.product_id.id]
        amount = amount_unit * self.unit_amount or 0.0
        result = round(amount, self.currency_id.decimal_places) * -1
        self.amount = result
        self.general_account_id = account
        self.product_uom_id = unit

    @api.model
    def view_header_get(self, view_id, view_type):
        context = (self._context or {})
        header = False
        if context.get('account_id', False):
            analytic_account = self.env['account.analytic.account'].search([('id', '=', context['account_id'])], limit=1)
            header = _('Entries: ') + (analytic_account.name or '')
        return header
示例#19
0
class HtmlFormDefaults(models.Model):

    _name = "html.form.defaults"
    _description = "HTML Form Defaults"

    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', string="Form Fields")
    default_value = fields.Char(string="Default Value")
示例#20
0
class DocumentPageHistory(models.Model):
    """This model is necessary to manage a document history."""

    _name = "document.page.history"
    _description = "Document Page History"
    _order = 'id DESC'
    _rec_name = "create_date"

    page_id = fields.Many2one('document.page', 'Page')
    summary = fields.Char('Summary', select=True)
    content = fields.Text("Content")
    create_date = fields.Datetime("Date")
    create_uid = fields.Many2one('res.users', "Modified By")

    def getDiff(self, v1, v2):
        """Return the difference between two version of document version."""
        text1 = self.browse(v1).content
        text2 = self.browse(v2).content
        line1 = line2 = ''
        if text1:
            line1 = text1.splitlines(1)
        if text2:
            line2 = text2.splitlines(1)
        if (not line1 and not line2) or (line1 == line2):
            return _('There are no changes in revisions.')
        else:
            diff = difflib.HtmlDiff()
            return diff.make_table(
                line1, line2,
                "Revision-{}".format(v1),
                "Revision-{}".format(v2),
                context=True
            )
示例#21
0
文件: models.py 项目: ecoreos/hz
class Box(models.Model):
    _name = 'test.box'
    _inherits = {'test.unit': 'unit_id'}

    unit_id = fields.Many2one('test.unit', 'Unit', required=True,
                              ondelete='cascade')
    field_in_box = fields.Char('Field1')
示例#22
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)
示例#23
0
class Tags(models.Model):
    _name = "forum.tag"
    _description = "Forum Tag"
    _inherit = ['website.seo.metadata']

    name = fields.Char('Name', required=True)
    create_uid = fields.Many2one('res.users',
                                 string='Created by',
                                 readonly=True)
    forum_id = fields.Many2one('forum.forum', string='Forum', required=True)
    post_ids = fields.Many2many('forum.post',
                                'forum_tag_rel',
                                'forum_tag_id',
                                'forum_id',
                                string='Posts')
    posts_count = fields.Integer('Number of Posts',
                                 compute='_get_posts_count',
                                 store=True)

    _sql_constraints = [
        ('name_uniq', 'unique (name, forum_id)', "Tag name already exists !"),
    ]

    @api.multi
    @api.depends("post_ids.tag_ids")
    def _get_posts_count(self):
        for tag in self:
            tag.posts_count = len(tag.post_ids)
示例#24
0
class HtmlFormHistory(models.Model):

    _name = "html.form.history"
    _description = "HTML Form History"

    html_id = fields.Many2one('html.form',
                              ondelete='cascade',
                              string="HTML Form",
                              readonly=True)
    form_name = fields.Char(related="html_id.name", string="Form Name")
    ref_url = fields.Char(string="Reference URL", readonly=True)
    record_id = fields.Integer(string="Record ID", readonly=True)
    insert_data = fields.One2many('html.form.history.field',
                                  'html_id',
                                  string="HTML Fields",
                                  readonly=True)
示例#25
0
class RecruitmentStage(models.Model):
    _name = "hr.recruitment.stage"
    _description = "Stage of Recruitment"
    _order = 'sequence'

    name = fields.Char("Stage name", required=True, translate=True)
    sequence = fields.Integer(
        "Sequence",
        default=1,
        help="Gives the sequence order when displaying a list of stages.")
    job_ids = fields.Many2many(
        'hr.job',
        'job_stage_rel',
        'stage_id',
        'job_id',
        string='Job Stages',
        default=lambda self: [(4, self._context['default_job_id'])]
        if self._context.get('default_job_id') else None)
    requirements = fields.Text("Requirements")
    template_id = fields.Many2one(
        'mail.template',
        "Use template",
        help=
        "If set, a message is posted on the applicant using the template when the applicant is set to the stage."
    )
    fold = fields.Boolean(
        "Folded in Recruitment Pipe",
        help=
        "This stage is folded in the kanban view when there are no records in that stage to display."
    )
示例#26
0
文件: models.py 项目: ecoreos/hz
class Pallet(models.Model):
    _name = 'test.pallet'
    _inherits = {'test.box': 'box_id'}

    box_id = fields.Many2one('test.box', 'Box', required=True,
                             ondelete='cascade')
    field_in_pallet = fields.Char('Field2')
示例#27
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
示例#28
0
文件: pos_box.py 项目: LiberTang0/5
class CashBox(models.TransientModel):
    _register = False

    name = fields.Char(string='Reason', required=True)
    # Attention, we don't set a domain, because there is a journal_type key 
    # in the context of the action
    amount = fields.Float(string='Amount', digits=0, required=True)

    @api.multi
    def run(self):
        context = dict(self._context or {})
        active_model = context.get('active_model', False)
        active_ids = context.get('active_ids', [])

        records = self.env[active_model].browse(active_ids)

        return self._run(records)

    @api.multi
    def _run(self, records):
        for box in self:
            for record in records:
                if not record.journal_id:
                    raise UserError(_("Please check that the field 'Journal' is set on the Bank Statement"))
                if not record.journal_id.company_id.transfer_account_id:
                    raise UserError(_("Please check that the field 'Transfer Account' is set on the company."))
                box._create_bank_statement_line(record)
        return {}

    @api.one
    def _create_bank_statement_line(self, record):
        if record.state == 'confirm':
            raise UserError(_("You cannot put/take money in/out for a bank statement which is closed."))
        values = self._calculate_values_for_statement_line(record)
        return record.write({'line_ids': [(0, False, values[0])]})
示例#29
0
class EmbeddedSlide(models.Model):
    """ Embedding in third party websites. Track view count, generate statistics. """
    _name = 'slide.embed'
    _description = 'Embedded Slides View Counter'
    _rec_name = 'slide_id'

    slide_id = fields.Many2one('slide.slide',
                               string="Presentation",
                               required=True,
                               select=1)
    url = fields.Char('Third Party Website URL', required=True)
    count_views = fields.Integer('# Views', default=1)

    def add_embed_url(self, slide_id, url):
        schema = urlparse(url)
        baseurl = schema.netloc
        embeds = self.search([('url', '=', baseurl),
                              ('slide_id', '=', int(slide_id))],
                             limit=1)
        if embeds:
            embeds.count_views += 1
        else:
            embeds = self.create({
                'slide_id': slide_id,
                'url': baseurl,
            })
        return embeds.count_views
示例#30
0
class OauthAccessToken(models.Model):
    _name = 'oauth.access_token'

    application_id = fields.Many2one('oauth.application', string='Application')
    token = fields.Char('Access Token', required=True)
    user_id = fields.Many2one('res.users', string='User', required=True)
    expires = fields.Datetime('Expires', required=True)
    scope = fields.Char('Scope')

    def is_valid(self, cr, uid, ids, scopes=None, context=None):
        """
        Checks if the access token is valid.

        :param scopes: An iterable containing the scopes to check or None
        """
        res = {}
        for t in self.browse(cr, uid, ids, context=context):
            res[t.id] = t.is_expired() and self._allow_scopes(
                cr, uid, t, scopes)
        return res

    def is_expired(self, cr, uid, ids, context=None):
        res = {}
        for t in self.browse(cr, uid, ids, context=context):
            res[t.id] = datetime.now() < datetime.strptime(
                t.expires, DEFAULT_SERVER_DATETIME_FORMAT)
        return res

    def _allow_scopes(self, cr, uid, token, scopes, context=None):
        if not scopes:
            return True

        provided_scopes = set(self.scope.split())
        resource_scopes = set(scopes)

        return resource_scopes.issubset(provided_scopes)

    def allow_scopes(self, cr, uid, ids, scopes, context=None):
        """
        Check if the token allows the provided scopes

        :param scopes: An iterable containing the scopes to check
        """
        res = {}
        for t in self.browse(cr, uid, ids, context=context):
            res[t.id] = self._allow_scopes(cr, uid, t, scopes, context=context)
        return res