コード例 #1
0
ファイル: event.py プロジェクト: vituocgia/izi
class EventEvent(models.Model):
    """ Override Event model to add optional questions when buying tickets. """
    _inherit = 'event.event'

    question_ids = fields.One2many('event.question',
                                   'event_id',
                                   'Questions',
                                   copy=True)
    general_question_ids = fields.One2many('event.question',
                                           'event_id',
                                           'General Questions',
                                           domain=[('is_individual', '=',
                                                    False)])
    specific_question_ids = fields.One2many('event.question',
                                            'event_id',
                                            'Specific Questions',
                                            domain=[('is_individual', '=',
                                                     True)])

    @api.onchange('event_type_id')
    def _onchange_type(self):
        super(EventEvent, self)._onchange_type()
        if self.event_type_id.use_questions and self.event_type_id.question_ids:
            self.question_ids = [(5, 0, 0)] + [
                (0, 0, {
                    'title': question.title,
                    'sequence': question.sequence,
                    'is_individual': question.is_individual,
                }) for question in self.event_type_id.question_ids
            ]
コード例 #2
0
ファイル: models.py プロジェクト: vituocgia/izi
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')
コード例 #3
0
class Discussion(models.Model):
    _name = 'test_new_api.discussion'

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

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

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

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

    @api.onchange('messages')
    def _onchange_messages(self):
        self.message_concat = "\n".join(
            ["%s:%s" % (m.name, m.body) for m in self.messages])
コード例 #4
0
ファイル: product_attribute.py プロジェクト: vituocgia/izi
class ProductAttribute(models.Model):
    _name = "product.attribute"
    _description = "Product Attribute"
    _order = 'sequence, name'

    name = fields.Char('Name', required=True, translate=True)
    value_ids = fields.One2many('product.attribute.value', 'attribute_id', 'Values', copy=True)
    sequence = fields.Integer('Sequence', help="Determine the display order")
    attribute_line_ids = fields.One2many('product.attribute.line', 'attribute_id', 'Lines')
    create_variant = fields.Boolean(default=True, help="Check this if you want to create multiple variants for this attribute.")
コード例 #5
0
class Route(models.Model):
    _name = 'stock.location.route'
    _description = "Inventory Routes"
    _order = 'sequence'

    name = fields.Char('Route Name', required=True, translate=True)
    active = fields.Boolean('Active', default=True, help="If the active field is set to False, it will allow you to hide the route without removing it.")
    sequence = fields.Integer('Sequence', default=0)
    pull_ids = fields.One2many('procurement.rule', 'route_id', 'Procurement Rules', copy=True, 
        help="The demand represented by a procurement from e.g. a sale order, a reordering rule, another move, needs to be solved by applying a procurement rule. Depending on the action on the procurement rule,"\
        "this triggers a purchase order, manufacturing order or another move. This way we create chains in the reverse order from the endpoint with the original demand to the starting point. "\
        "That way, it is always known where we need to go and that is why they are preferred over push rules.")
    push_ids = fields.One2many('stock.location.path', 'route_id', 'Push Rules', copy=True, 
        help="When a move is foreseen to a location, the push rule will automatically create a move to a next location after. This is mainly only needed when creating manual operations e.g. 2/3 step manual purchase order or 2/3 step finished product manual manufacturing order. In other cases, it is important to use pull rules where you know where you are going based on a demand.")
    product_selectable = fields.Boolean('Applicable on Product', default=True, help="When checked, the route will be selectable in the Inventory tab of the Product form.  It will take priority over the Warehouse route. ")
    product_categ_selectable = fields.Boolean('Applicable on Product Category', help="When checked, the route will be selectable on the Product Category.  It will take priority over the Warehouse route. ")
    warehouse_selectable = fields.Boolean('Applicable on Warehouse', help="When a warehouse is selected for this route, this route should be seen as the default route when products pass through this warehouse.  This behaviour can be overridden by the routes on the Product/Product Categories or by the Preferred Routes on the Procurement")
    supplied_wh_id = fields.Many2one('stock.warehouse', 'Supplied Warehouse')
    supplier_wh_id = fields.Many2one('stock.warehouse', 'Supplying Warehouse')
    company_id = fields.Many2one(
        'res.company', 'Company',
        default=lambda self: self.env['res.company']._company_default_get('stock.location.route'), index=True,
        help='Leave this field empty if this route is shared between all companies')
    product_ids = fields.Many2many('product.template', 'stock_route_product', 'route_id', 'product_id', 'Products')
    categ_ids = fields.Many2many('product.category', 'stock_location_route_categ', 'route_id', 'categ_id', 'Product Categories')
    warehouse_ids = fields.Many2many('stock.warehouse', 'stock_route_warehouse', 'route_id', 'warehouse_id', 'Warehouses')

    def write(self, values):
        '''when a route is deactivated, deactivate also its pull and push rules'''
        res = super(Route, self).write(values)
        if 'active' in values:
            self.mapped('push_ids').filtered(lambda path: path.active != values['active']).write({'active': values['active']})
            self.mapped('pull_ids').filtered(lambda rule: rule.active != values['active']).write({'active': values['active']})
        return res

    def view_product_ids(self):
        return {
            'name': _('Products'),
            'view_type': 'form',
            'view_mode': 'tree,form',
            'res_model': 'product.template',
            'type': 'ir.actions.act_window',
            'domain': [('route_ids', 'in', self.ids)],
        }

    def view_categ_ids(self):
        return {
            'name': _('Product Categories'),
            'view_type': 'form',
            'view_mode': 'tree,form',
            'res_model': 'product.category',
            'type': 'ir.actions.act_window',
            'domain': [('route_ids', 'in', self.ids)],
        }
コード例 #6
0
ファイル: module.py プロジェクト: vituocgia/izi
class ModuleCategory(models.Model):
    _name = "ir.module.category"
    _description = "Application"
    _order = 'name'

    @api.depends('module_ids')
    def _compute_module_nr(self):
        cr = self._cr
        cr.execute(
            'SELECT category_id, COUNT(*) \
                      FROM ir_module_module \
                     WHERE category_id IN %(ids)s \
                        OR category_id IN (SELECT id \
                                             FROM ir_module_category \
                                            WHERE parent_id IN %(ids)s) \
                     GROUP BY category_id', {'ids': tuple(self.ids)})
        result = dict(cr.fetchall())
        for cat in self.filtered('id'):
            cr.execute('SELECT id FROM ir_module_category WHERE parent_id=%s',
                       (cat.id, ))
            cat.module_nr = sum([result.get(c, 0) for (c, ) in cr.fetchall()],
                                result.get(cat.id, 0))

    name = fields.Char(string='Name',
                       required=True,
                       translate=True,
                       index=True)
    parent_id = fields.Many2one('ir.module.category',
                                string='Parent Application',
                                index=True)
    child_ids = fields.One2many('ir.module.category',
                                'parent_id',
                                string='Child Applications')
    module_nr = fields.Integer(string='Number of Apps',
                               compute='_compute_module_nr')
    module_ids = fields.One2many('ir.module.module',
                                 'category_id',
                                 string='Modules')
    description = fields.Text(string='Description', translate=True)
    sequence = fields.Integer(string='Sequence')
    visible = fields.Boolean(string='Visible', default=True)
    exclusive = fields.Boolean(string='Exclusive')
    xml_id = fields.Char(string='External ID', compute='_compute_xml_id')

    def _compute_xml_id(self):
        xml_ids = defaultdict(list)
        domain = [('model', '=', self._name), ('res_id', 'in', self.ids)]
        for data in self.env['ir.model.data'].sudo().search_read(
                domain, ['module', 'name', 'res_id']):
            xml_ids[data['res_id']].append("%s.%s" %
                                           (data['module'], data['name']))
        for cat in self:
            cat.xml_id = xml_ids.get(cat.id, [''])[0]
コード例 #7
0
ファイル: sale_quote.py プロジェクト: vituocgia/izi
class SaleQuoteTemplate(models.Model):
    _name = "sale.quote.template"
    _description = "Sale Quotation Template"

    name = fields.Char('Quotation Template', required=True)
    website_description = fields.Html('Description',
                                      translate=html_translate,
                                      sanitize_attributes=False)
    quote_line = fields.One2many('sale.quote.line',
                                 'quote_id',
                                 'Quotation Template Lines',
                                 copy=True)
    note = fields.Text('Terms and conditions')
    options = fields.One2many('sale.quote.option',
                              'template_id',
                              'Optional Products Lines',
                              copy=True)
    number_of_days = fields.Integer(
        'Quotation Duration',
        help='Number of days for the validity date computation of the quotation'
    )
    require_payment = fields.Selection(
        [(0, 'Online Signature'), (1, 'Online Payment')],
        default=0,
        string='Confirmation Mode',
        help=
        "Choose how you want to confirm an order to launch the delivery process. You can either "
        "request a digital signature or an upfront payment. With a digital signature, you can "
        "request the payment when issuing the invoice.")
    mail_template_id = fields.Many2one(
        'mail.template',
        'Confirmation Mail',
        domain=[('model', '=', 'sale.order')],
        help=
        "This e-mail template will be sent on confirmation. Leave empty to send nothing."
    )
    active = fields.Boolean(
        default=True,
        help=
        "If unchecked, it will allow you to hide the quotation template without removing it."
    )

    @api.multi
    def open_template(self):
        self.ensure_one()
        return {
            'type': 'ir.actions.act_url',
            'target': 'self',
            'url': '/quote/template/%d' % self.id
        }
コード例 #8
0
class Holidays(models.Model):
    _inherit = "hr.holidays"

    timesheet_ids = fields.One2many('account.analytic.line',
                                    'holiday_id',
                                    string="Analytic Lines")

    def _validate_leave_request(self):
        """ Timesheet will be generated on leave validation only if a timesheet_project_id and a
            timesheet_task_id are set on the corresponding leave type. The generated timesheet will
            be attached to this project/task.
        """
        # create the timesheet on the vacation project
        for holiday in self.filtered(
                lambda request: request.type == 'remove' and request.
                holiday_type == 'employee' and request.holiday_status_id.
                timesheet_project_id and request.holiday_status_id.
                timesheet_task_id):
            holiday_project = holiday.holiday_status_id.timesheet_project_id
            holiday_task = holiday.holiday_status_id.timesheet_task_id

            work_hours_data = [
                item for item in holiday.employee_id.iter_work_hours_count(
                    fields.Datetime.from_string(holiday.date_from),
                    fields.Datetime.from_string(holiday.date_to))
            ]
            for index, (day_date,
                        work_hours_count) in enumerate(work_hours_data):
                self.env['account.analytic.line'].create({
                    'name':
                    "%s (%s/%s)" %
                    (holiday.name or '', index + 1, len(work_hours_data)),
                    'project_id':
                    holiday_project.id,
                    'task_id':
                    holiday_task.id,
                    'account_id':
                    holiday_project.analytic_account_id.id,
                    'unit_amount':
                    work_hours_count,
                    'user_id':
                    holiday.employee_id.user_id.id,
                    'date':
                    fields.Date.to_string(day_date),
                    'holiday_id':
                    holiday.id,
                    'employee_id':
                    holiday.employee_id.id,
                })

        return super(Holidays, self)._validate_leave_request()

    @api.multi
    def action_refuse(self):
        """ Remove the timesheets linked to the refused holidays """
        result = super(Holidays, self).action_refuse()
        timesheets = self.sudo().mapped('timesheet_ids')
        timesheets.write({'holiday_id': False})
        timesheets.unlink()
        return result
コード例 #9
0
ファイル: res_partner.py プロジェクト: vituocgia/izi
class Partner(models.Model):

    _inherit = 'res.partner'

    team_id = fields.Many2one('crm.team', string='Sales Channel', oldname='section_id')
    opportunity_ids = fields.One2many('crm.lead', 'partner_id', string='Opportunities', domain=[('type', '=', 'opportunity')])
    meeting_ids = fields.Many2many('calendar.event', 'calendar_event_res_partner_rel', 'res_partner_id', 'calendar_event_id', string='Meetings', copy=False)
    opportunity_count = fields.Integer("Opportunity", compute='_compute_opportunity_count')
    meeting_count = fields.Integer("# Meetings", compute='_compute_meeting_count')

    @api.multi
    def _compute_opportunity_count(self):
        for partner in self:
            operator = 'child_of' if partner.is_company else '='  # the opportunity count should counts the opportunities of this company and all its contacts
            partner.opportunity_count = self.env['crm.lead'].search_count([('partner_id', operator, partner.id), ('type', '=', 'opportunity')])

    @api.multi
    def _compute_meeting_count(self):
        for partner in self:
            partner.meeting_count = len(partner.meeting_ids)

    @api.multi
    def schedule_meeting(self):
        partner_ids = self.ids
        partner_ids.append(self.env.user.partner_id.id)
        action = self.env.ref('calendar.action_calendar_event').read()[0]
        action['context'] = {
            'search_default_partner_ids': self._context['partner_name'],
            'default_partner_ids': partner_ids,
        }
        return action
コード例 #10
0
ファイル: account_invoice.py プロジェクト: vituocgia/izi
class AccountInvoice(models.Model):
    _inherit = 'account.invoice'

    payment_tx_ids = fields.One2many('payment.transaction', 'account_invoice_id', string='Transactions')
    payment_tx_id = fields.Many2one('payment.transaction', string='Last Transaction', copy=False)
    payment_acquirer_id = fields.Many2one(
        'payment.acquirer', string='Payment Acquirer',
        related='payment_tx_id.acquirer_id', store=True)
    payment_tx_count = fields.Integer(string="Number of payment transactions", compute='_compute_payment_tx_count')

    def _compute_payment_tx_count(self):
        tx_data = self.env['payment.transaction'].read_group(
            [('account_invoice_id', 'in', self.ids)],
            ['account_invoice_id'], ['account_invoice_id']
        )
        mapped_data = dict([(m['account_invoice_id'][0], m['account_invoice_id_count']) for m in tx_data])
        for invoice in self:
            invoice.payment_tx_count = mapped_data.get(invoice.id, 0)

    def action_view_transactions(self):
        action = {
            'name': _('Payment Transactions'),
            'type': 'ir.actions.act_window',
            'res_model': 'payment.transaction',
            'target': 'current',
        }
        tx = self.env['payment.transaction'].search([('account_invoice_id', 'in', self.ids)])
        if len(tx) == 1:
            action['res_id'] = tx.ids[0]
            action['view_mode'] = 'form'
        else:
            action['view_mode'] = 'tree,form'
            action['domain'] = [('account_invoice_id', 'in', self.ids)]
        return action
コード例 #11
0
class Movie(models.Model):
    _name = 'test_new_api.creativework.movie'

    name = fields.Char()
    editions = fields.One2many('test_new_api.creativework.edition',
                               'res_id',
                               domain=[('res_model', '=', _name)])
コード例 #12
0
class ResUsers(models.Model):
    _inherit = 'res.users'

    resource_ids = fields.One2many('resource.resource', 'user_id', 'Resources')
    resource_calendar_id = fields.Many2one('resource.calendar',
                                           'Default Working Hours',
                                           related='resource_ids.calendar_id')
コード例 #13
0
ファイル: test_models.py プロジェクト: vituocgia/izi
class LeadTest(models.Model):
    _name = "base.automation.lead.test"
    _description = "Action Rule Test"

    name = fields.Char(string='Subject', required=True, index=True)
    user_id = fields.Many2one('res.users', string='Responsible')
    state = fields.Selection([('draft', 'New'), ('cancel', 'Cancelled'),
                              ('open', 'In Progress'), ('pending', 'Pending'),
                              ('done', 'Closed')],
                             string="Status",
                             readonly=True,
                             default='draft')
    active = fields.Boolean(default=True)
    partner_id = fields.Many2one('res.partner', string='Partner')
    date_action_last = fields.Datetime(string='Last Action', readonly=True)
    customer = fields.Boolean(related='partner_id.customer',
                              readonly=True,
                              store=True)
    line_ids = fields.One2many('base.automation.line.test', 'lead_id')

    priority = fields.Boolean()
    deadline = fields.Boolean(compute='_compute_deadline', store=True)
    is_assigned_to_admin = fields.Boolean(string='Assigned to admin user')

    @api.depends('priority')
    def _compute_deadline(self):
        for record in self:
            if not record.priority:
                record.deadline = False
            else:
                record.deadline = fields.Datetime.from_string(
                    record.create_date) + relativedelta.relativedelta(days=3)
コード例 #14
0
class ResPartner(models.Model):
    _inherit = 'res.partner'

    wishlist_ids = fields.One2many('product.wishlist',
                                   'partner_id',
                                   string='Wishlist',
                                   domain=[('active', '=', True)])
コード例 #15
0
class EventType(models.Model):
    _inherit = 'event.type'

    @api.model
    def _get_default_event_ticket_ids(self):
        product = self.env.ref('event_sale.product_product_event', raise_if_not_found=False)
        if not product:
            return False
        return [(0, 0, {
            'name': _('Registration'),
            'product_id': product.id,
            'price': 0,
        })]

    use_ticketing = fields.Boolean('Ticketing')
    event_ticket_ids = fields.One2many(
        'event.event.ticket', 'event_type_id',
        string='Tickets', default=_get_default_event_ticket_ids)

    @api.onchange('name')
    def _onchange_name(self):
        if self.name:
            self.event_ticket_ids.filtered(lambda ticket: ticket.name == _('Registration')).update({
                'name': _('Registration for %s') % self.name
            })
コード例 #16
0
class Event(models.Model):
    _inherit = 'event.event'

    event_ticket_ids = fields.One2many(
        'event.event.ticket', 'event_id', string='Event Ticket',
        copy=True)

    @api.onchange('event_type_id')
    def _onchange_type(self):
        super(Event, self)._onchange_type()
        if self.event_type_id.use_ticketing:
            self.event_ticket_ids = [(5, 0, 0)] + [
                (0, 0, {
                    'name': self.name and _('Registration for %s') % self.name or ticket.name,
                    'product_id': ticket.product_id.id,
                    'price': ticket.price,
                })
                for ticket in self.event_type_id.event_ticket_ids]

    @api.multi
    def _is_event_registrable(self):
        self.ensure_one()
        if not self.event_ticket_ids:
            return True
        return all(self.event_ticket_ids.with_context(active_test=False).mapped(lambda t: t.product_id.active))
コード例 #17
0
ファイル: res_partner.py プロジェクト: vituocgia/izi
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)
コード例 #18
0
class ResCompany(models.Model):
    _inherit = 'res.company'

    resource_calendar_ids = fields.One2many('resource.calendar', 'company_id',
                                            'Working Hours')
    resource_calendar_id = fields.Many2one('resource.calendar',
                                           'Default Working Hours',
                                           ondelete='restrict')

    @api.model
    def _init_data_resource_calendar(self):
        for company in self.search([('resource_calendar_id', '=', False)]):
            company.resource_calendar_id = self.env[
                'resource.calendar'].create({
                    'name': _('Standard 40 hours/week')
                }).id

    @api.model
    def create(self, values):
        if not values.get('resource_calendar_id'):
            values['resource_calendar_id'] = self.env[
                'resource.calendar'].create({
                    'name': _('Standard 40 hours/week')
                }).id
        company = super(ResCompany, self).create(values)
        # calendar created from form view: no company_id set because record was still not created
        if not company.resource_calendar_id.company_id:
            company.resource_calendar_id.company_id = company.id
        return company
コード例 #19
0
ファイル: res_users.py プロジェクト: vituocgia/izi
class ChangePasswordWizard(models.TransientModel):
    """ A wizard to manage the change of users' passwords. """
    _name = "change.password.wizard"
    _description = "Change Password Wizard"

    def _default_user_ids(self):
        user_ids = self._context.get(
            'active_model') == 'res.users' and self._context.get(
                'active_ids') or []
        return [(0, 0, {
            'user_id': user.id,
            'user_login': user.login
        }) for user in self.env['res.users'].browse(user_ids)]

    user_ids = fields.One2many('change.password.user',
                               'wizard_id',
                               string='Users',
                               default=_default_user_ids)

    @api.multi
    def change_password_button(self):
        self.ensure_one()
        self.user_ids.change_password_button()
        if self.env.user in self.mapped('user_ids.user_id'):
            return {'type': 'ir.actions.client', 'tag': 'reload'}
        return {'type': 'ir.actions.act_window_close'}
コード例 #20
0
ファイル: ir_exports.py プロジェクト: vituocgia/izi
class IrExports(models.Model):
    _name = "ir.exports"
    _order = 'name'

    name = fields.Char(string='Export Name')
    resource = fields.Char(index=True)
    export_fields = fields.One2many('ir.exports.line', 'export_id', string='Export ID', copy=True)
コード例 #21
0
ファイル: product_attribute.py プロジェクト: vituocgia/izi
class ProductAttributevalue(models.Model):
    _name = "product.attribute.value"
    _order = 'sequence, attribute_id, id'

    name = fields.Char('Value', required=True, translate=True)
    sequence = fields.Integer('Sequence', help="Determine the display order")
    attribute_id = fields.Many2one('product.attribute', 'Attribute', ondelete='cascade', required=True)
    product_ids = fields.Many2many('product.product', string='Variants', readonly=True)
    price_extra = fields.Float(
        'Attribute Price Extra', compute='_compute_price_extra', inverse='_set_price_extra',
        default=0.0, digits=dp.get_precision('Product Price'),
        help="Price Extra: Extra price for the variant with this attribute value on sale price. eg. 200 price extra, 1000 + 200 = 1200.")
    price_ids = fields.One2many('product.attribute.price', 'value_id', 'Attribute Prices', readonly=True)

    _sql_constraints = [
        ('value_company_uniq', 'unique (name,attribute_id)', 'This attribute value already exists !')
    ]

    @api.one
    def _compute_price_extra(self):
        if self._context.get('active_id'):
            price = self.price_ids.filtered(lambda price: price.product_tmpl_id.id == self._context['active_id'])
            self.price_extra = price.price_extra
        else:
            self.price_extra = 0.0

    def _set_price_extra(self):
        if not self._context.get('active_id'):
            return

        AttributePrice = self.env['product.attribute.price']
        prices = AttributePrice.search([('value_id', 'in', self.ids), ('product_tmpl_id', '=', self._context['active_id'])])
        updated = prices.mapped('value_id')
        if prices:
            prices.write({'price_extra': self.price_extra})
        else:
            for value in self - updated:
                AttributePrice.create({
                    'product_tmpl_id': self._context['active_id'],
                    'value_id': value.id,
                    'price_extra': self.price_extra,
                })

    @api.multi
    def name_get(self):
        if not self._context.get('show_attribute', True):  # TDE FIXME: not used
            return super(ProductAttributevalue, self).name_get()
        return [(value.id, "%s: %s" % (value.attribute_id.name, value.name)) for value in self]

    @api.multi
    def unlink(self):
        linked_products = self.env['product.product'].with_context(active_test=False).search([('attribute_value_ids', 'in', self.ids)])
        if linked_products:
            raise UserError(_('The operation cannot be completed:\nYou are trying to delete an attribute value with a reference on a product variant.'))
        return super(ProductAttributevalue, self).unlink()

    @api.multi
    def _variant_name(self, variable_attributes):
        return ", ".join([v.name for v in self if v.attribute_id in variable_attributes])
コード例 #22
0
class ProductCategory(models.Model):
    _name = "product.category"
    _description = "Product Category"
    _parent_name = "parent_id"
    _parent_store = True
    _parent_order = 'name'
    _rec_name = 'complete_name'
    _order = 'parent_left'

    name = fields.Char('Name', index=True, required=True, translate=True)
    complete_name = fields.Char('Complete Name',
                                compute='_compute_complete_name',
                                store=True)
    parent_id = fields.Many2one('product.category',
                                'Parent Category',
                                index=True,
                                ondelete='cascade')
    child_id = fields.One2many('product.category', 'parent_id',
                               'Child Categories')
    parent_left = fields.Integer('Left Parent', index=1)
    parent_right = fields.Integer('Right Parent', index=1)
    product_count = fields.Integer(
        '# Products',
        compute='_compute_product_count',
        help=
        "The number of products under this category (Does not consider the children categories)"
    )

    @api.depends('name', 'parent_id.complete_name')
    def _compute_complete_name(self):
        for category in self:
            if category.parent_id:
                category.complete_name = '%s / %s' % (
                    category.parent_id.complete_name, category.name)
            else:
                category.complete_name = category.name

    def _compute_product_count(self):
        read_group_res = self.env['product.template'].read_group(
            [('categ_id', 'child_of', self.ids)], ['categ_id'], ['categ_id'])
        group_data = dict((data['categ_id'][0], data['categ_id_count'])
                          for data in read_group_res)
        for categ in self:
            product_count = 0
            for sub_categ_id in categ.search([('id', 'child_of', categ.id)
                                              ]).ids:
                product_count += group_data.get(sub_categ_id, 0)
            categ.product_count = product_count

    @api.constrains('parent_id')
    def _check_category_recursion(self):
        if not self._check_recursion():
            raise ValidationError(
                _('Error ! You cannot create recursive categories.'))
        return True

    @api.model
    def name_create(self, name):
        return self.create({'name': name}).name_get()[0]
コード例 #23
0
ファイル: res_company.py プロジェクト: vituocgia/izi
class ResCompany(models.Model):
    _inherit = "res.company"

    ldaps = fields.One2many('res.company.ldap',
                            'company',
                            string='LDAP Parameters',
                            copy=True,
                            groups="base.group_system")
コード例 #24
0
ファイル: event.py プロジェクト: vituocgia/izi
class EventType(models.Model):
    _inherit = 'event.type'

    use_questions = fields.Boolean('Questions to Attendees')
    question_ids = fields.One2many('event.question',
                                   'event_type_id',
                                   string='Questions',
                                   copy=True)
コード例 #25
0
ファイル: account_budget.py プロジェクト: vituocgia/izi
class CrossoveredBudget(models.Model):
    _name = "crossovered.budget"
    _description = "Budget"
    _inherit = ['mail.thread']

    name = fields.Char('Budget Name',
                       required=True,
                       states={'done': [('readonly', True)]})
    creating_user_id = fields.Many2one('res.users',
                                       'Responsible',
                                       default=lambda self: self.env.user)
    date_from = fields.Date('Start Date',
                            required=True,
                            states={'done': [('readonly', True)]})
    date_to = fields.Date('End Date',
                          required=True,
                          states={'done': [('readonly', True)]})
    state = fields.Selection([('draft', 'Draft'), ('cancel', 'Cancelled'),
                              ('confirm', 'Confirmed'),
                              ('validate', 'Validated'), ('done', 'Done')],
                             'Status',
                             default='draft',
                             index=True,
                             required=True,
                             readonly=True,
                             copy=False,
                             track_visibility='always')
    crossovered_budget_line = fields.One2many(
        'crossovered.budget.lines',
        'crossovered_budget_id',
        'Budget Lines',
        states={'done': [('readonly', True)]},
        copy=True)
    company_id = fields.Many2one('res.company',
                                 'Company',
                                 required=True,
                                 default=lambda self: self.env['res.company'].
                                 _company_default_get('account.budget.post'))

    @api.multi
    def action_budget_confirm(self):
        self.write({'state': 'confirm'})

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

    @api.multi
    def action_budget_validate(self):
        self.write({'state': 'validate'})

    @api.multi
    def action_budget_cancel(self):
        self.write({'state': 'cancel'})

    @api.multi
    def action_budget_done(self):
        self.write({'state': 'done'})
コード例 #26
0
ファイル: product.py プロジェクト: vituocgia/izi
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
コード例 #27
0
ファイル: mrp_bom.py プロジェクト: vituocgia/izi
class MrpBom(models.Model):
    _name = 'mrp.bom'
    _description = 'Bill of Material'
    _inherit = 'mrp.bom'

    sub_products = fields.One2many('mrp.subproduct',
                                   'bom_id',
                                   'Byproducts',
                                   copy=True)
コード例 #28
0
ファイル: sale_order.py プロジェクト: vituocgia/izi
class SaleOrderLine(models.Model):
    _inherit = "sale.order.line"

    linked_line_id = fields.Many2one('sale.order.line',
                                     string='Linked Order Line',
                                     domain="[('order_id', '!=', order_id)]",
                                     ondelete='cascade')
    option_line_ids = fields.One2many('sale.order.line',
                                      'linked_line_id',
                                      string='Options Linked')
コード例 #29
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)
コード例 #30
0
class PortalWizard(models.TransientModel):
    """
        A wizard to manage the creation/removal of portal users.
    """

    _name = 'portal.wizard'
    _description = 'Portal Access Management'

    def _default_portal(self):
        return self.env['res.groups'].search([('is_portal', '=', True)],
                                             limit=1)

    portal_id = fields.Many2one(
        'res.groups',
        domain=[('is_portal', '=', True)],
        required=True,
        string='Portal',
        default=_default_portal,
        help="The portal that users can be added in or removed from.")
    user_ids = fields.One2many('portal.wizard.user',
                               'wizard_id',
                               string='Users')
    welcome_message = fields.Text(
        'Invitation Message',
        help=
        "This text is included in the email sent to new users of the portal.")

    @api.onchange('portal_id')
    def onchange_portal_id(self):
        # for each partner, determine corresponding portal.wizard.user records
        partner_ids = self.env.context.get('active_ids', [])
        contact_ids = set()
        user_changes = []
        for partner in self.env['res.partner'].sudo().browse(partner_ids):
            contact_partners = partner.child_ids or [partner]
            for contact in contact_partners:
                # make sure that each contact appears at most once in the list
                if contact.id not in contact_ids:
                    contact_ids.add(contact.id)
                    in_portal = False
                    if contact.user_ids:
                        in_portal = self.portal_id in contact.user_ids[
                            0].groups_id
                    user_changes.append((0, 0, {
                        'partner_id': contact.id,
                        'email': contact.email,
                        'in_portal': in_portal,
                    }))
        self.user_ids = user_changes

    @api.multi
    def action_apply(self):
        self.ensure_one()
        self.user_ids.action_apply()
        return {'type': 'ir.actions.act_window_close'}