示例#1
0
class BaseModuleUpdate(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.multi
    def update_module(self):
        for this in self:
            updated, added = self.env['ir.module.module'].update_list()
            this.write({'updated': updated, 'added': added, '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
示例#2
0
class product_price_list(models.TransientModel):
    _name = 'product.price_list'
    _description = 'Price List'

    price_list = fields.Many2one('product.pricelist', 'PriceList', required=True)
    qty1 = fields.Integer('Quantity-1', default=1)
    qty2 = fields.Integer('Quantity-2', default=5)
    qty3 = fields.Integer('Quantity-3', default=10)
    qty4 = fields.Integer('Quantity-4', default=0)
    qty5 = fields.Integer('Quantity-5', default=0)

    @api.multi
    def print_report(self):
        """
        To get the date and print the report
        @return : return report
        """
        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."))

        datas = {'ids': self.env.context.get('active_ids', [])}
        res = self.read(['price_list', 'qty1', 'qty2', 'qty3', 'qty4', 'qty5'])
        res = res and res[0] or {}
        res['price_list'] = res['price_list'][0]
        datas['form'] = res
        return self.env.ref('product.action_report_pricelist').report_action([], data=datas)
示例#3
0
class CrmTeam(models.Model):
    _inherit = 'crm.team'

    pending_payment_transactions_count = fields.Integer(
        compute='_compute_payment_transactions',
        string='Number of pending transactions', readonly=True)
    pending_payment_transactions_amount = fields.Integer(
        compute='_compute_payment_transactions',
        string='Amount of pending transactions', readonly=True)
    authorized_payment_transactions_count = fields.Integer(
        compute='_compute_payment_transactions',
        string='Number of transactions to capture', readonly=True)
    authorized_payment_transactions_amount = fields.Integer(
        compute='_compute_payment_transactions',
        string='Amount of transactions to capture', readonly=True)

    def _compute_payment_transactions(self):
        for team in self:
            payment_data = self.env['payment.transaction'].read_group([
                ('state', 'in', ['authorized', 'pending']),
                ('sale_order_id.team_id', '=', team.id)
            ], ['amount', 'currency_id', 'state'], ['state', 'currency_id'], lazy=False)
            for datum in payment_data:
                datum_currency = self.env['res.currency'].browse(datum['currency_id'][0])
                if datum['state'] == 'authorized':
                    team.authorized_payment_transactions_count += datum['__count']
                    team.authorized_payment_transactions_amount += datum_currency.compute(datum['amount'], self.env.user.company_id.currency_id)
                elif datum['state'] == 'pending':
                    team.pending_payment_transactions_count += datum['__count']
                    team.pending_payment_transactions_amount += datum_currency.compute(datum['amount'], self.env.user.company_id.currency_id)
示例#4
0
class HrDepartment(models.Model):
    _inherit = 'hr.department'

    new_applicant_count = fields.Integer(
        compute='_compute_new_applicant_count', string='New Applicant')
    new_hired_employee = fields.Integer(
        compute='_compute_recruitment_stats', string='New Hired Employee')
    expected_employee = fields.Integer(
        compute='_compute_recruitment_stats', string='Expected Employee')

    @api.multi
    def _compute_new_applicant_count(self):
        applicant_data = self.env['hr.applicant'].read_group(
            [('department_id', 'in', self.ids), ('stage_id.sequence', '<=', '1')],
            ['department_id'], ['department_id'])
        result = dict((data['department_id'][0], data['department_id_count']) for data in applicant_data)
        for department in self:
            department.new_applicant_count = result.get(department.id, 0)

    @api.multi
    def _compute_recruitment_stats(self):
        job_data = self.env['hr.job'].read_group(
            [('department_id', 'in', self.ids)],
            ['no_of_hired_employee', 'no_of_recruitment', 'department_id'], ['department_id'])
        new_emp = dict((data['department_id'][0], data['no_of_hired_employee']) for data in job_data)
        expected_emp = dict((data['department_id'][0], data['no_of_recruitment']) for data in job_data)
        for department in self:
            department.new_hired_employee = new_emp.get(department.id, 0)
            department.expected_employee = expected_emp.get(department.id, 0)
示例#5
0
class report_paperformat(models.Model):
    _name = "report.paperformat"
    _description = "Allows customization of a report."

    name = fields.Char('Name', required=True)
    default = fields.Boolean('Default paper format ?')
    format = fields.Selection(
        [('A0', 'A0  5   841 x 1189 mm'), ('A1', 'A1  6   594 x 841 mm'),
         ('A2', 'A2  7   420 x 594 mm'), ('A3', 'A3  8   297 x 420 mm'),
         ('A4', 'A4  0   210 x 297 mm, 8.26 x 11.69 inches'),
         ('A5', 'A5  9   148 x 210 mm'), ('A6', 'A6  10  105 x 148 mm'),
         ('A7', 'A7  11  74 x 105 mm'), ('A8', 'A8  12  52 x 74 mm'),
         ('A9', 'A9  13  37 x 52 mm'), ('B0', 'B0  14  1000 x 1414 mm'),
         ('B1', 'B1  15  707 x 1000 mm'), ('B2', 'B2  17  500 x 707 mm'),
         ('B3', 'B3  18  353 x 500 mm'), ('B4', 'B4  19  250 x 353 mm'),
         ('B5', 'B5  1   176 x 250 mm, 6.93 x 9.84 inches'),
         ('B6', 'B6  20  125 x 176 mm'), ('B7', 'B7  21  88 x 125 mm'),
         ('B8', 'B8  22  62 x 88 mm'), ('B9', 'B9  23  33 x 62 mm'),
         ('B10', ':B10    16  31 x 44 mm'), ('C5E', 'C5E 24  163 x 229 mm'),
         ('Comm10E', 'Comm10E 25  105 x 241 mm, U.S. '
          'Common 10 Envelope'), ('DLE', 'DLE 26 110 x 220 mm'),
         ('Executive', 'Executive 4   7.5 x 10 inches, '
          '190.5 x 254 mm'), ('Folio', 'Folio 27  210 x 330 mm'),
         ('Ledger', 'Ledger  28  431.8 x 279.4 mm'),
         ('Legal', 'Legal    3   8.5 x 14 inches, '
          '215.9 x 355.6 mm'),
         ('Letter', 'Letter 2 8.5 x 11 inches, '
          '215.9 x 279.4 mm'), ('Tabloid', 'Tabloid 29 279.4 x 431.8 mm'),
         ('custom', 'Custom')],
        'Paper size',
        default='A4',
        help="Select Proper Paper size")
    margin_top = fields.Float('Top Margin (mm)', default=40)
    margin_bottom = fields.Float('Bottom Margin (mm)', default=20)
    margin_left = fields.Float('Left Margin (mm)', default=7)
    margin_right = fields.Float('Right Margin (mm)', default=7)
    page_height = fields.Integer('Page height (mm)', default=False)
    page_width = fields.Integer('Page width (mm)', default=False)
    orientation = fields.Selection([('Landscape', 'Landscape'),
                                    ('Portrait', 'Portrait')],
                                   'Orientation',
                                   default='Landscape')
    header_line = fields.Boolean('Display a header line', default=False)
    header_spacing = fields.Integer('Header spacing', default=35)
    dpi = fields.Integer('Output DPI', required=True, default=90)
    report_ids = fields.One2many('ir.actions.report',
                                 'paperformat_id',
                                 'Associated reports',
                                 help="Explicitly associated reports")

    @api.constrains('format')
    def _check_format_or_page(self):
        if self.filtered(lambda x: x.format != 'custom' and
                         (x.page_width or x.page_height)):
            raise ValidationError(
                _('Error ! You cannot select a format AND specific page width/height.'
                  ))
示例#6
0
class ProductViewLimit(models.Model):
    _name = 'product.view.limit'
    _order = 'sequence'

    sequence = fields.Integer(help="Gives the sequence order when "
                              "displaying a list of rules.")
    name = fields.Integer(string='Limit', required=True)

    _sql_constraints = [('name', 'unique(name)', 'This must be unique!')]
示例#7
0
class ProductTemplate(models.Model):
    _inherit = "product.template"

    bom_ids = fields.One2many('mrp.bom', 'product_tmpl_id',
                              'Bill of Materials')
    bom_count = fields.Integer('# Bill of Material',
                               compute='_compute_bom_count')
    used_in_bom_count = fields.Integer('# of BoM Where is Used',
                                       compute='_compute_used_in_bom_count')
    mo_count = fields.Integer('# Manufacturing Orders',
                              compute='_compute_mo_count')
    produce_delay = fields.Float(
        'Manufacturing Lead Time',
        default=0.0,
        help=
        "Average delay in days to produce this product. In the case of multi-level BOM, the manufacturing lead times of the components will be added."
    )

    def _compute_bom_count(self):
        read_group_res = self.env['mrp.bom'].read_group(
            [('product_tmpl_id', 'in', self.ids)], ['product_tmpl_id'],
            ['product_tmpl_id'])
        mapped_data = dict([(data['product_tmpl_id'][0],
                             data['product_tmpl_id_count'])
                            for data in read_group_res])
        for product in self:
            product.bom_count = mapped_data.get(product.id, 0)

    @api.multi
    def _compute_used_in_bom_count(self):
        for template in self:
            template.used_in_bom_count = self.env['mrp.bom'].search_count([
                ('bom_line_ids.product_id', 'in',
                 template.product_variant_ids.ids)
            ])

    @api.multi
    def action_used_in_bom(self):
        self.ensure_one()
        action = self.env.ref('mrp.mrp_bom_form_action').read()[0]
        action['domain'] = [('bom_line_ids.product_id', 'in',
                             self.product_variant_ids.ids)]
        return action

    @api.one
    def _compute_mo_count(self):
        # TDE FIXME: directly use a read_group
        self.mo_count = sum(
            self.mapped('product_variant_ids').mapped('mo_count'))

    @api.multi
    def action_view_mos(self):
        product_ids = self.mapped('product_variant_ids').ids
        action = self.env.ref('mrp.act_product_mrp_production').read()[0]
        action['domain'] = [('product_id', 'in', product_ids)]
        action['context'] = {}
        return action
示例#8
0
class ResConfigSettings(models.TransientModel):
    _inherit = 'res.config.settings'

    global_discount_invoice_line = fields.Boolean(
        "Global Discounts",
        implied_group='account_discount.global_discount_invoice_line')
    global_discount_invoice_apply = fields.Boolean(
        "Do you want to set global discount limit?",
        implied_group='account_discount.global_discount_invoice_apply')
    global_discount_fix_invoice_amount = fields.Integer(
        'Fix Amount',
        implied_group='account_discount.global_discount_invoice_apply')
    global_discount_percentage_invoice = fields.Integer(
        'Percentage (%)',
        implied_group='account_discount.global_discount_percentage_invoice')

    @api.onchange('global_discount_invoice_line')
    def onchange_global_discount_invoice_line(self):
        if not self.global_discount_invoice_line:
            self.global_discount_invoice_apply = False

    @api.onchange('global_discount_invoice_apply')
    def onchange_global_discount_invoice_apply(self):
        if not self.global_discount_invoice_apply:
            self.global_discount_fix_invoice_amount = False

    @api.model
    def get_values(self):
        res = super(ResConfigSettings, self).get_values()
        res.update(
            global_discount_invoice_line=self.env[
                'ir.config_parameter'].sudo().get_param(
                'global_discount_invoice_line'),
            global_discount_invoice_apply=self.env[
                'ir.config_parameter'].sudo().get_param(
                'global_discount_invoice_apply'),
            global_discount_fix_invoice_amount=int(self.env[
                'ir.config_parameter'].sudo().get_param(
                'global_discount_fix_invoice_amount')),
            global_discount_percentage_invoice=int(self.env[
                'ir.config_parameter'].sudo().get_param(
                'global_discount_percentage_invoice')),
        )
        return res

    def set_values(self):
        super(ResConfigSettings, self).set_values()
        params = self.env['ir.config_parameter'].sudo()
        params.set_param('global_discount_invoice_line',
                         self.global_discount_invoice_line)
        params.set_param('global_discount_invoice_apply',
                         self.global_discount_invoice_apply)
        params.set_param('global_discount_fix_invoice_amount',
                         self.global_discount_fix_invoice_amount)
        params.set_param('global_discount_percentage_invoice',
                         self.global_discount_percentage_invoice)
示例#9
0
class account_financial_report(models.Model):
    _name = "account.financial.report"
    _description = "Account Report"

    @api.multi
    @api.depends('parent_id', 'parent_id.level')
    def _get_level(self):
        '''Returns a dictionary with key=the ID of a record and value = the level of this  
           record in the tree structure.'''
        for report in self:
            level = 0
            if report.parent_id:
                level = report.parent_id.level + 1
            report.level = level

    def _get_children_by_order(self):
        '''returns a recordset of all the children computed recursively, and sorted by sequence. Ready for the printing'''
        res = self
        children = self.search([('parent_id', 'in', self.ids)], order='sequence ASC')
        if children:
            for child in children:
                res += child._get_children_by_order()
        return res

    name = fields.Char('Report Name', required=True, translate=True)
    parent_id = fields.Many2one('account.financial.report', 'Parent')
    children_ids = fields.One2many('account.financial.report', 'parent_id', 'Account Report')
    sequence = fields.Integer('Sequence')
    level = fields.Integer(compute='_get_level', string='Level', store=True)
    type = fields.Selection([
        ('sum', 'View'),
        ('accounts', 'Accounts'),
        ('account_type', 'Account Type'),
        ('account_report', 'Report Value'),
        ], 'Type', default='sum')
    account_ids = fields.Many2many('account.account', 'account_account_financial_report', 'report_line_id', 'account_id', 'Accounts')
    account_report_id = fields.Many2one('account.financial.report', 'Report Value')
    account_type_ids = fields.Many2many('account.account.type', 'account_account_financial_report_type', 'report_id', 'account_type_id', 'Account Types')
    sign = fields.Selection([(-1, 'Reverse balance sign'), (1, 'Preserve balance sign')], 'Sign on Reports', required=True, default=1,
                            help='For accounts that are typically more debited than credited and that you would like to print as negative amounts in your reports, you should reverse the sign of the balance; e.g.: Expense account. The same applies for accounts that are typically more credited than debited and that you would like to print as positive amounts in your reports; e.g.: Income account.')
    display_detail = fields.Selection([
        ('no_detail', 'No detail'),
        ('detail_flat', 'Display children flat'),
        ('detail_with_hierarchy', 'Display children with hierarchy')
        ], 'Display details', default='detail_flat')
    style_overwrite = fields.Selection([
        (0, 'Automatic formatting'),
        (1, 'Main Title 1 (bold, underlined)'),
        (2, 'Title 2 (bold)'),
        (3, 'Title 3 (bold, smaller)'),
        (4, 'Normal Text'),
        (5, 'Italic Text (smaller)'),
        (6, 'Smallest Text'),
        ], 'Financial Report Style', default=0,
        help="You can set up here the format you want this record to be displayed. If you leave the automatic formatting, it will be computed based on the financial reports hierarchy (auto-computed field 'level').")
示例#10
0
文件: models.py 项目: yasr3mr96/actpy
class OnlyOne(models.Model):
    _name = 'export.unique'

    value = fields.Integer()
    value2 = fields.Integer()
    value3 = fields.Integer()

    _sql_constraints = [
        ('value_unique', 'unique (value)', "The value must be unique"),
        ('pair_unique', 'unique (value2, value3)',
         "The values must be unique"),
    ]
示例#11
0
class Bar(models.Model):
    _name = 'test_new_api.bar'

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

    @api.depends('name')
    def _compute_foo(self):
        for bar in self:
            bar.foo = self.env['test_new_api.foo'].search(
                [('name', '=', bar.name)], limit=1)
示例#12
0
class test_inherit_property(models.Model):
    _inherit = 'test.inherit.property'

    # override property_foo with a plain normal field
    property_foo = fields.Integer(company_dependent=False)

    # override property_bar with a new-api computed field
    property_bar = fields.Integer(compute='_compute_bar', company_dependent=False)

    @api.multi
    def _compute_bar(self):
        for record in self:
            record.property_bar = 42
示例#13
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)], help="Account used to record the purchase of the asset at its original price.")
    account_depreciation_id = fields.Many2one('account.account', string='Depreciation Entries: Asset Account', required=True, domain=[('internal_type','=','other'), ('deprecated', '=', False)], help="Account used in the depreciation entries, to decrease the asset value.")
    account_depreciation_expense_id = fields.Many2one('account.account', string='Depreciation Entries: Expense Account', required=True, domain=[('internal_type','=','other'), ('deprecated', '=', False)], oldname='account_income_recognition_id', help="Account used in the periodical entries, to record a part of the asset as expense.")
    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 Entries'), ('end', 'Ending Date')], string='Time Method', required=True, default='number',
        help="Choose the method to use to compute the dates and number of entries.\n"
           "  * Number of Entries: Fix the number of entries 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='Auto-confirm Assets', help="Check this if you want to automatically confirm the assets of this category when created by invoices.")
    group_entries = fields.Boolean(string='Group Journal Entries', help="Check this if you want to group the generated entries by categories.")
    type = fields.Selection([('sale', 'Sale: Revenue Recognition'), ('purchase', 'Purchase: Asset')], required=True, index=True, default='purchase')

    @api.onchange('account_asset_id')
    def onchange_account_asset(self):
        if self.type == "purchase":
            self.account_depreciation_id = self.account_asset_id
        elif self.type == "sale":
            self.account_depreciation_expense_id = self.account_asset_id

    @api.onchange('type')
    def onchange_type(self):
        if self.type == 'sale':
            self.prorata = True
            self.method_period = 1
        else:
            self.method_period = 12

    @api.onchange('method_time')
    def _onchange_method_time(self):
        if self.method_time != 'number':
            self.prorata = False
示例#14
0
class Department(models.Model):

    _inherit = 'hr.department'

    absence_of_today = fields.Integer(
        compute='_compute_leave_count', string='Absence by Today')
    leave_to_approve_count = fields.Integer(
        compute='_compute_leave_count', string='Leave to Approve')
    allocation_to_approve_count = fields.Integer(
        compute='_compute_leave_count', string='Allocation to Approve')
    total_employee = fields.Integer(
        compute='_compute_total_employee', string='Total Employee')

    @api.multi
    def _compute_leave_count(self):
        Holiday = self.env['hr.holidays']
        today_date = datetime.datetime.utcnow().date()
        today_start = fields.Datetime.to_string(today_date)  # get the midnight of the current utc day
        today_end = fields.Datetime.to_string(today_date + relativedelta(hours=23, minutes=59, seconds=59))

        leave_data = Holiday.read_group(
            [('department_id', 'in', self.ids),
             ('state', '=', 'confirm'), ('type', '=', 'remove')],
            ['department_id'], ['department_id'])
        allocation_data = Holiday.read_group(
            [('department_id', 'in', self.ids),
             ('state', '=', 'confirm'), ('type', '=', 'add')],
            ['department_id'], ['department_id'])
        absence_data = Holiday.read_group(
            [('department_id', 'in', self.ids), ('state', 'not in', ['cancel', 'refuse']),
             ('date_from', '<=', today_end), ('date_to', '>=', today_start), ('type', '=', 'remove')],
            ['department_id'], ['department_id'])

        res_leave = dict((data['department_id'][0], data['department_id_count']) for data in leave_data)
        res_allocation = dict((data['department_id'][0], data['department_id_count']) for data in allocation_data)
        res_absence = dict((data['department_id'][0], data['department_id_count']) for data in absence_data)

        for department in self:
            department.leave_to_approve_count = res_leave.get(department.id, 0)
            department.allocation_to_approve_count = res_allocation.get(department.id, 0)
            department.absence_of_today = res_absence.get(department.id, 0)

    @api.multi
    def _compute_total_employee(self):
        emp_data = self.env['hr.employee'].read_group([('department_id', 'in', self.ids)], ['department_id'], ['department_id'])
        result = dict((data['department_id'][0], data['department_id_count']) for data in emp_data)
        for department in self:
            department.total_employee = result.get(department.id, 0)
示例#15
0
class ResPartner(models.Model):
    _inherit = 'res.partner'

    sale_order_count = fields.Integer(compute='_compute_sale_order_count',
                                      string='# of Sales Order')
    sale_order_ids = fields.One2many('sale.order', 'partner_id', 'Sales Order')
    sale_warn = fields.Selection(WARNING_MESSAGE,
                                 'Sales Order',
                                 default='no-message',
                                 help=WARNING_HELP,
                                 required=True)
    sale_warn_msg = fields.Text('Message for Sales Order')

    def _compute_sale_order_count(self):
        sale_data = self.env['sale.order'].read_group(domain=[
            ('partner_id', 'child_of', self.ids)
        ],
                                                      fields=['partner_id'],
                                                      groupby=['partner_id'])
        # read to keep the child/parent relation while aggregating the read_group result in the loop
        partner_child_ids = self.read(['child_ids'])
        mapped_data = dict([(m['partner_id'][0], m['partner_id_count'])
                            for m in sale_data])
        for partner in self:
            # let's obtain the partner id and all its child ids from the read up there
            item = next(p for p in partner_child_ids if p['id'] == partner.id)
            partner_ids = [partner.id] + item.get('child_ids')
            # then we can sum for all the partner's child
            partner.sale_order_count = sum(
                mapped_data.get(child, 0) for child in partner_ids)
示例#16
0
class ResPartner(models.Model):
    _inherit = 'res.partner'

    barcode = fields.Char(string='Barcode', oldname='ean13')
    pos_order_count = fields.Integer(
        compute='_compute_pos_order',
        help="The number of point of sales orders related to this customer",
        groups="point_of_sale.group_pos_user",
    )

    def _compute_pos_order(self):
        partners_data = self.env['pos.order'].read_group([('partner_id', 'in', self.ids)], ['partner_id'], ['partner_id'])
        mapped_data = dict([(partner['partner_id'][0], partner['partner_id_count']) for partner in partners_data])
        for partner in self:
            partner.pos_order_count = mapped_data.get(partner.id, 0)

    @api.model
    def create_from_ui(self, partner):
        """ create or modify a partner from the point of sale ui.
            partner contains the partner's fields. """
        # image is a dataurl, get the data after the comma
        if partner.get('image'):
            partner['image'] = partner['image'].split(',')[1]
        partner_id = partner.pop('id', False)
        if partner_id:  # Modifying existing partner
            self.browse(partner_id).write(partner)
        else:
            partner['lang'] = self.env.user.lang
            partner_id = self.create(partner).id
        return partner_id
示例#17
0
文件: slides.py 项目: yasr3mr96/actpy
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,
                               index=True)
    url = fields.Char('Third Party Website URL', required=True)
    count_views = fields.Integer('# Views', default=1)

    def add_embed_url(self, slide_id, url):
        baseurl = urls.url_parse(url).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
class HrHolidaysRemainingLeavesUser(models.Model):

    _name = "hr.holidays.remaining.leaves.user"
    _description = "Total holidays by type"
    _auto = False

    name = fields.Char('Employee', readonly=True)
    no_of_leaves = fields.Integer('Remaining leaves', readonly=True)
    user_id = fields.Many2one('res.users', string='User', readonly=True)
    leave_type = fields.Char('Leave Type', readonly=True)

    def init(self):
        tools.drop_view_if_exists(self._cr,
                                  'hr_holidays_remaining_leaves_user')
        self._cr.execute("""
            CREATE or REPLACE view hr_holidays_remaining_leaves_user as (
                 SELECT
                    min(hrs.id) as id,
                    rr.name as name,
                    sum(hrs.number_of_days) as no_of_leaves,
                    rr.user_id as user_id,
                    hhs.name as leave_type
                FROM
                    hr_holidays as hrs, hr_employee as hre,
                    resource_resource as rr,hr_holidays_status as hhs
                WHERE
                    hrs.employee_id = hre.id and
                    hre.resource_id =  rr.id and
                    hhs.id = hrs.holiday_status_id
                GROUP BY
                    rr.name,rr.user_id,hhs.name
            )
        """)
示例#19
0
class SponsorType(models.Model):
    _name = "event.sponsor.type"
    _description = 'Event Sponsor Type'
    _order = "sequence"

    name = fields.Char('Sponsor Type', required=True, translate=True)
    sequence = fields.Integer('Sequence')
示例#20
0
class ProductAttributeCategory(models.Model):
    _name = "product.attribute.category"
    _description = "Product Attribute Category"
    _order = 'sequence'

    name = fields.Char("Category Name", required=True)
    sequence = fields.Integer("Sequence", default=10)
示例#21
0
文件: models.py 项目: yasr3mr96/actpy
class One2ManyMultiple(models.Model):
    _name = 'export.one2many.multiple'

    parent_id = fields.Many2one('export.one2many.recursive')
    const = fields.Integer(default=36)
    child1 = fields.One2many('export.one2many.child.1', 'parent_id')
    child2 = fields.One2many('export.one2many.child.2', 'parent_id')
示例#22
0
class ConverterTest(models.Model):
    _name = 'web_editor.converter.test'

    # disable translation export for those brilliant field labels and values
    _translate = False

    char = fields.Char()
    integer = fields.Integer()
    float = fields.Float()
    numeric = fields.Float(digits=(16, 2))
    many2one = fields.Many2one('web_editor.converter.test.sub')
    binary = fields.Binary()
    date = fields.Date()
    datetime = fields.Datetime()
    selection = fields.Selection([
        (1, "réponse A"),
        (2, "réponse B"),
        (3, "réponse C"),
        (4, "réponse <D>"),
    ])
    selection_str = fields.Selection(
        [
            ('A', "Qu'il n'est pas arrivé à Toronto"),
            ('B', "Qu'il était supposé arriver à Toronto"),
            ('C', "Qu'est-ce qu'il fout ce maudit pancake, tabernacle ?"),
            ('D', "La réponse D"),
        ],
        string=u"Lorsqu'un pancake prend l'avion à destination de Toronto et "
        u"qu'il fait une escale technique à St Claude, on dit:")
    html = fields.Html()
    text = fields.Text()
示例#23
0
class ResPartnerBank(models.Model):
    _inherit = 'res.partner.bank'

    aba_routing = fields.Integer(string="ABA/Routing", help="American Bankers Association Routing Number")

    def _check_aba_routing(self, aba_routing):
        if aba_routing and not re.match(r'^\d{1,9}$', aba_routing):
            raise UserError(_('ABA/Routing should only contains numbers (maximum 9 digits).'))
        return aba_routing

    # ONLY FOR v11. DO NOT FORWARDPORT!
    @api.model
    def create(self, vals):
        if vals.get('aba_routing'):
            vals['aba_routing'] = int(self._check_aba_routing(vals['aba_routing']))
        return super(ResPartnerBank, self).create(vals)

    @api.multi
    def write(self, vals):
        if vals.get('aba_routing'):
            vals['aba_routing'] = int(self._check_aba_routing(vals['aba_routing']))
        return super(ResPartnerBank, self).write(vals)

    @api.multi
    def read(self, fields=None, load='_classic_read'):
        result = super(ResPartnerBank, self).read(fields, load=load)
        for record in result:
            if record.get('aba_routing'):
                record['aba_routing'] = str(record['aba_routing'])
        return result
示例#24
0
class PurchaseRequisitionType(models.Model):
    _name = "purchase.requisition.type"
    _description = "Purchase Agreement Type"
    _order = "sequence"

    name = fields.Char(string='Agreement Type', required=True, translate=True)
    sequence = fields.Integer(default=1)
    exclusive = fields.Selection(
        [('exclusive', 'Select only one RFQ (exclusive)'),
         ('multiple', 'Select multiple RFQ')],
        string='Agreement Selection Type',
        required=True,
        default='multiple',
        help=
        """Select only one RFQ (exclusive):  when a purchase order is confirmed, cancel the remaining purchase order.\n
                    Select multiple RFQ: allows multiple purchase orders. On confirmation of a purchase order it does not cancel the remaining orders"""
    )
    quantity_copy = fields.Selection([('copy', 'Use quantities of agreement'),
                                      ('none', 'Set quantities manually')],
                                     string='Quantities',
                                     required=True,
                                     default='none')
    line_copy = fields.Selection(
        [('copy', 'Use lines of agreement'),
         ('none', 'Do not create RfQ lines automatically')],
        string='Lines',
        required=True,
        default='copy')
示例#25
0
class RestaurantFloor(models.Model):

    _name = 'restaurant.floor'

    name = fields.Char(
        'Floor Name',
        required=True,
        help='An internal identification of the restaurant floor')
    pos_config_id = fields.Many2one('pos.config', string='Point of Sale')
    background_image = fields.Binary(
        'Background Image',
        attachment=True,
        help=
        'A background image used to display a floor layout in the point of sale interface'
    )
    background_color = fields.Char(
        'Background Color',
        help=
        'The background color of the floor layout, (must be specified in a html-compatible format)',
        default='rgb(210, 210, 210)')
    table_ids = fields.One2many('restaurant.table',
                                'floor_id',
                                string='Tables',
                                help='The list of tables in this floor')
    sequence = fields.Integer('Sequence',
                              help='Used to sort Floors',
                              default=1)
示例#26
0
文件: event.py 项目: yasr3mr96/actpy
class EventQuestion(models.Model):
    _name = 'event.question'
    _rec_name = 'title'
    _order = 'sequence,id'

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

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

    @api.model
    def create(self, vals):
        event_id = vals.get('event_id', False)
        if event_id:
            event = self.env['event.event'].browse([event_id])
            if event.event_type_id.use_questions and event.event_type_id.question_ids:
                vals['answer_ids'] = vals.get('answer_ids', []) + [(0, 0, {
                    'name': answer.name,
                    'sequence': answer.sequence,
                }) for answer in event.event_type_id.question_ids.filtered(lambda question: question.title == vals.get('title')).mapped('answer_ids')]
        return super(EventQuestion, self).create(vals)
示例#27
0
文件: event.py 项目: yasr3mr96/actpy
class EventAnswer(models.Model):
    _name = 'event.answer'
    _order = 'sequence,id'

    name = fields.Char('Answer', required=True, translate=True)
    question_id = fields.Many2one('event.question', required=True, ondelete='cascade')
    sequence = fields.Integer(default=10)
示例#28
0
class AccountRegisterPayments(models.TransientModel):
    _inherit = "account.register.payments"

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

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

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

    def _prepare_payment_vals(self, invoices):
        res = super(AccountRegisterPayments, self)._prepare_payment_vals(invoices)
        if self.payment_method_id == self.env.ref('account_check_printing.account_payment_method_check'):
            res.update({
                'check_amount_in_words': self.currency_id.amount_to_text(res['amount']) if self.multi else self.check_amount_in_words,
                'check_manual_sequencing': self.check_manual_sequencing,
            })
        return res
示例#29
0
文件: forum.py 项目: yasr3mr96/actpy
class Tags(models.Model):
    _name = "forum.tag"
    _description = "Forum Tag"
    _inherit = ['mail.thread', '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', domain=[('state', '=', 'active')])
    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", "post_ids.state")
    def _get_posts_count(self):
        for tag in self:
            tag.posts_count = len(tag.post_ids)

    @api.model
    def create(self, vals):
        forum = self.env['forum.forum'].browse(vals.get('forum_id'))
        if self.env.user.karma < forum.karma_tag_create:
            raise KarmaError(_('Not enough karma to create a new Tag'))
        return super(Tags, self.with_context(mail_create_nolog=True, mail_create_nosubscribe=True)).create(vals)
示例#30
0
class AccountInvoiceLine(models.Model):
    _inherit = 'account.invoice.line'
    _order = 'invoice_id, layout_category_id, sequence, id'

    @api.depends('price_unit', 'discount', 'invoice_line_tax_ids', 'quantity',
                 'product_id', 'invoice_id.partner_id',
                 'invoice_id.currency_id', 'invoice_id.company_id',
                 'invoice_id.date_invoice')
    def _compute_total_price(self):
        for line in self:
            price = line.price_unit * (1 - (line.discount or 0.0) / 100.0)
            taxes = line.invoice_line_tax_ids.compute_all(
                price,
                line.invoice_id.currency_id,
                line.quantity,
                product=line.product_id,
                partner=line.invoice_id.partner_id)
            line.price_total = taxes['total_included']

    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')
    # TODO: remove layout_category_sequence in master or make it work properly
    price_total = fields.Monetary(compute='_compute_total_price',
                                  string='Total Amount',
                                  store=True)