Ejemplo n.º 1
0
class IrActionsActWindowView(models.Model):
    _name = 'ir.actions.act_window.view'
    _table = 'ir_act_window_view'
    _rec_name = 'view_id'
    _order = 'sequence,id'

    sequence = fields.Integer()
    view_id = fields.Many2one('ir.ui.view', string='View')
    view_mode = fields.Selection(VIEW_TYPES, string='View Type', required=True)
    act_window_id = fields.Many2one('ir.actions.act_window',
                                    string='Action',
                                    ondelete='cascade')
    multi = fields.Boolean(
        string='On Multiple Doc.',
        help=
        "If set to true, the action will not be displayed on the right toolbar of a form view."
    )

    @api.model_cr_context
    def _auto_init(self):
        res = super(IrActionsActWindowView, self)._auto_init()
        tools.create_unique_index(self._cr,
                                  'act_window_view_unique_mode_per_action',
                                  self._table, ['act_window_id', 'view_mode'])
        return res
Ejemplo n.º 2
0
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)
Ejemplo n.º 3
0
class MultiLine(models.Model):
    _name = 'test_new_api.multi.line'

    multi = fields.Many2one('test_new_api.multi', ondelete='cascade')
    name = fields.Char()
    partner = fields.Many2one('res.partner')
    tags = fields.Many2many('test_new_api.multi.tag')
Ejemplo n.º 4
0
class LineTest(models.Model):
    _name = "base.automation.line.test"
    _description = "Action Rule Line Test"

    name = fields.Char()
    lead_id = fields.Many2one('base.automation.lead.test', ondelete='cascade')
    user_id = fields.Many2one('res.users')
Ejemplo n.º 5
0
class HrContract(models.Model):
    _inherit = 'hr.contract'
    _description = 'Employee Contract'

    analytic_account_id = fields.Many2one('account.analytic.account',
                                          'Analytic Account')
    journal_id = fields.Many2one('account.journal', 'Salary Journal')
Ejemplo n.º 6
0
class HrSalaryRuleCategory(models.Model):
    _name = 'hr.salary.rule.category'
    _description = 'Salary Rule Category'

    name = fields.Char(required=True, translate=True)
    code = fields.Char(required=True)
    parent_id = fields.Many2one(
        'hr.salary.rule.category',
        string='Parent',
        help=
        "Linking a salary category to its parent is used only for the reporting purpose."
    )
    children_ids = fields.One2many('hr.salary.rule.category',
                                   'parent_id',
                                   string='Children')
    note = fields.Text(string='Description')
    company_id = fields.Many2one(
        'res.company',
        string='Company',
        default=lambda self: self.env['res.company']._company_default_get())

    @api.constrains('parent_id')
    def _check_parent_id(self):
        if not self._check_recursion():
            raise ValidationError(
                _('Error! You cannot create recursive hierarchy of Salary Rule Category.'
                  ))
Ejemplo n.º 7
0
class ResourceCalendarLeaves(models.Model):
    _name = "resource.calendar.leaves"
    _description = "Leave Detail"

    name = fields.Char('Reason')
    company_id = fields.Many2one(
        'res.company', related='calendar_id.company_id', string="Company",
        readonly=True, store=True)
    calendar_id = fields.Many2one('resource.calendar', 'Working Hours')
    date_from = fields.Datetime('Start Date', required=True)
    date_to = fields.Datetime('End Date', required=True)
    tz = fields.Selection(
        _tz_get, string='Timezone', default=lambda self: self._context.get('tz') or self.env.user.tz or 'UTC',
        help="Timezone used when encoding the leave. It is used to correctly "
             "localize leave hours when computing time intervals.")
    resource_id = fields.Many2one(
        "resource.resource", 'Resource',
        help="If empty, this is a generic holiday for the company. If a resource is set, the holiday/leave is only for this resource")

    @api.constrains('date_from', 'date_to')
    def check_dates(self):
        if self.filtered(lambda leave: leave.date_from > leave.date_to):
            raise ValidationError(_('Error! leave start-date must be lower then leave end-date.'))

    @api.onchange('resource_id')
    def onchange_resource(self):
        if self.resource_id:
            self.calendar_id = self.resource_id.calendar_id
Ejemplo n.º 8
0
class FleetVehicleOdometer(models.Model):
    _name = 'fleet.vehicle.odometer'
    _description = 'Odometer log for a vehicle'
    _order = 'date desc'

    name = fields.Char(compute='_compute_vehicle_log_name', store=True)
    date = fields.Date(default=fields.Date.context_today)
    value = fields.Float('Odometer Value', group_operator="max")
    vehicle_id = fields.Many2one('fleet.vehicle', 'Vehicle', required=True)
    unit = fields.Selection(related='vehicle_id.odometer_unit', string="Unit", readonly=True)
    driver_id = fields.Many2one(related="vehicle_id.driver_id", string="Driver")

    @api.depends('vehicle_id', 'date')
    def _compute_vehicle_log_name(self):
        for record in self:
            name = record.vehicle_id.name
            if not name:
                name = record.date
            elif record.date:
                name += ' / ' + record.date
            record.name = name

    @api.onchange('vehicle_id')
    def _onchange_vehicle(self):
        if self.vehicle_id:
            self.unit = self.vehicle_id.odometer_unit
Ejemplo n.º 9
0
class LunchCashMove(models.Model):
    """ Two types of cashmoves: payment (credit) or order (debit) """
    _name = 'lunch.cashmove'
    _description = 'lunch cashmove'

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

    @api.multi
    def name_get(self):
        return [(cashmove.id,
                 '%s %s' % (_('Lunch Cashmove'), '#%d' % cashmove.id))
                for cashmove in self]
Ejemplo n.º 10
0
class ReportEventRegistrationQuestions(models.Model):
    _name = "event.question.report"
    _auto = False

    attendee_id = fields.Many2one(comodel_name='event.registration',
                                  string='Registration')
    question_id = fields.Many2one(comodel_name='event.question',
                                  string='Question')
    answer_id = fields.Many2one(comodel_name='event.answer', string='Answer')
    event_id = fields.Many2one(comodel_name='event.event', string='Event')

    @api.model_cr
    def init(self):
        """ Event Question main report """
        tools.drop_view_if_exists(self._cr, 'event_question_report')
        self._cr.execute(""" CREATE VIEW event_question_report AS (
            SELECT
                att_answer.id as id,
                att_answer.event_registration_id as attendee_id,
                answer.question_id as question_id,
                answer.id as answer_id,
                question.event_id as event_id
            FROM
                event_registration_answer as att_answer
            LEFT JOIN
                event_answer as answer ON answer.id = att_answer.event_answer_id
            LEFT JOIN
                event_question as question ON question.id = answer.question_id
            GROUP BY
                attendee_id,
                event_id,
                question_id,
                answer_id,
                att_answer.id
        )""")
Ejemplo n.º 11
0
class LandedCostLine(models.Model):
    _name = 'stock.landed.cost.lines'
    _description = 'Stock Landed Cost Lines'

    name = fields.Char('Description')
    cost_id = fields.Many2one('stock.landed.cost',
                              'Landed Cost',
                              required=True,
                              ondelete='cascade')
    product_id = fields.Many2one('product.product', 'Product', required=True)
    price_unit = fields.Float('Cost',
                              digits=dp.get_precision('Product Price'),
                              required=True)
    split_method = fields.Selection(product.SPLIT_METHOD,
                                    string='Split Method',
                                    required=True)
    account_id = fields.Many2one('account.account',
                                 'Account',
                                 domain=[('deprecated', '=', False)])

    @api.onchange('product_id')
    def onchange_product_id(self):
        if not self.product_id:
            self.quantity = 0.0
        self.name = self.product_id.name or ''
        self.split_method = self.product_id.split_method or 'equal'
        self.price_unit = self.product_id.standard_price or 0.0
        self.account_id = self.product_id.property_account_expense_id.id or self.product_id.categ_id.property_account_expense_categ_id.id
Ejemplo n.º 12
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='Sales 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', index=True)

    @api.multi
    def get_registration_data(self):
        self.ensure_one()
        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,
        }
Ejemplo n.º 13
0
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)
Ejemplo n.º 14
0
class grant_badge_wizard(models.TransientModel):
    """ Wizard allowing to grant a badge to a user"""
    _name = 'gamification.badge.user.wizard'

    user_id = fields.Many2one("res.users", string='User', required=True)
    badge_id = fields.Many2one("gamification.badge",
                               string='Badge',
                               required=True)
    comment = fields.Text('Comment')

    @api.multi
    def action_grant_badge(self):
        """Wizard action for sending a badge to a chosen user"""

        BadgeUser = self.env['gamification.badge.user']

        uid = self.env.uid
        for wiz in self:
            if uid == wiz.user_id.id:
                raise exceptions.UserError(
                    _('You can not grant a badge to yourself'))

            #create the badge
            BadgeUser.create({
                'user_id': wiz.user_id.id,
                'sender_id': uid,
                'badge_id': wiz.badge_id.id,
                'comment': wiz.comment,
            })._send_badge()

        return True
Ejemplo n.º 15
0
class Documentation(models.Model):
    _name = 'forum.documentation.toc'
    _description = 'Documentation ToC'
    _inherit = ['website.seo.metadata']
    _order = "parent_left"
    _parent_order = "sequence, name"
    _parent_store = True

    sequence = fields.Integer('Sequence')
    name = fields.Char('Name', required=True, translate=True)
    introduction = fields.Html('Introduction', translate=True)
    parent_id = fields.Many2one('forum.documentation.toc', string='Parent Table Of Content', ondelete='cascade')
    child_ids = fields.One2many('forum.documentation.toc', 'parent_id', string='Children Table Of Content')
    parent_left = fields.Integer(string='Left Parent', index=True)
    parent_right = fields.Integer(string='Right Parent', index=True)
    post_ids = fields.One2many('forum.post', 'documentation_toc_id', string='Posts')
    forum_id = fields.Many2one('forum.forum', string='Forum', required=True)

    @api.multi
    def name_get(self):
        res = []
        for record in self:
            name = record.name
            if record.parent_id:
                name = record.parent_id.name + ' / ' + name
            res.append((record.id, name))
        return res

    @api.constrains('parent_id')
    def _check_parent_id(self):
        if not self._check_recursion():
            raise ValidationError(_('Error ! You cannot create recursive categories.'))
Ejemplo n.º 16
0
class StockScrap(models.Model):
    _inherit = 'stock.scrap'

    production_id = fields.Many2one(
        'mrp.production', 'Manufacturing Order',
        states={'done': [('readonly', True)]})
    workorder_id = fields.Many2one(
        'mrp.workorder', 'Work Order',
        states={'done': [('readonly', True)]},
        help='Not to restrict or prefer quants, but informative.')

    @api.onchange('workorder_id')
    def _onchange_workorder_id(self):
        if self.workorder_id:
            self.location_id = self.workorder_id.production_id.location_src_id.id

    @api.onchange('production_id')
    def _onchange_production_id(self):
        if self.production_id:
            self.location_id = self.production_id.move_raw_ids.filtered(lambda x: x.state not in ('done', 'cancel')) and self.production_id.location_src_id.id or self.production_id.location_dest_id.id

    def _prepare_move_values(self):
        vals = super(StockScrap, self)._prepare_move_values()
        if self.production_id:
            vals['origin'] = vals['origin'] or self.production_id.name
            if self.product_id in self.production_id.move_finished_ids.mapped('product_id'):
                vals.update({'production_id': self.production_id.id})
            else:
                vals.update({'raw_material_production_id': self.production_id.id})
        return vals

    def _get_origin_moves(self):
        return super(StockScrap, self)._get_origin_moves() or self.production_id and self.production_id.move_raw_ids.filtered(lambda x: x.product_id == self.product_id)
Ejemplo n.º 17
0
class StockLocation(models.Model):
    _inherit = "stock.location"

    valuation_in_account_id = fields.Many2one(
        'account.account',
        'Stock Valuation Account (Incoming)',
        domain=[('internal_type', '=', 'other'), ('deprecated', '=', False)],
        help=
        "Used for real-time inventory valuation. When set on a virtual location (non internal type), "
        "this account will be used to hold the value of products being moved from an internal location "
        "into this location, instead of the generic Stock Output Account set on the product. "
        "This has no effect for internal locations.")
    valuation_out_account_id = fields.Many2one(
        'account.account',
        'Stock Valuation Account (Outgoing)',
        domain=[('internal_type', '=', 'other'), ('deprecated', '=', False)],
        help=
        "Used for real-time inventory valuation. When set on a virtual location (non internal type), "
        "this account will be used to hold the value of products being moved out of this location "
        "and into an internal location, instead of the generic Stock Output Account set on the product. "
        "This has no effect for internal locations.")

    def _should_be_valued(self):
        """ This method returns a boolean reflecting whether the products stored in `self` should
        be considered when valuating the stock of a company.
        """
        self.ensure_one()
        if self.usage == 'internal' or (self.usage == 'transit'
                                        and self.company_id):
            return True
        return False
Ejemplo n.º 18
0
class Notification(models.Model):
    _name = 'mail.notification'
    _table = 'mail_message_res_partner_needaction_rel'
    _rec_name = 'res_partner_id'
    _log_access = False
    _description = 'Message Notifications'

    mail_message_id = fields.Many2one(
        'mail.message', 'Message', index=True, ondelete='cascade', required=True)
    res_partner_id = fields.Many2one(
        'res.partner', 'Needaction Recipient', index=True, ondelete='cascade', required=True)
    is_read = fields.Boolean('Is Read', index=True)
    is_email = fields.Boolean('Sent by Email', index=True)
    email_status = fields.Selection([
        ('ready', 'Ready to Send'),
        ('sent', 'Sent'),
        ('bounce', 'Bounced'),
        ('exception', 'Exception')], 'Email Status',
        default='ready', index=True)

    @api.model_cr
    def init(self):
        self._cr.execute('SELECT indexname FROM pg_indexes WHERE indexname = %s', ('mail_notification_res_partner_id_is_read_email_status_mail_message_id',))
        if not self._cr.fetchone():
            self._cr.execute('CREATE INDEX mail_notification_res_partner_id_is_read_email_status_mail_message_id ON mail_message_res_partner_needaction_rel (res_partner_id, is_read, email_status, mail_message_id)')
Ejemplo n.º 19
0
class ResConfigSettings(models.TransientModel):
    _inherit = 'res.config.settings'

    def _get_crm_default_team_domain(self):
        if self.env.user.has_group('crm.group_use_lead'):
            return [('use_leads', '=', True)]
        else:
            return [('use_opportunities', '=', True)]

    crm_default_team_id = fields.Many2one(
        'crm.team',
        string='Default Sales Channel',
        related='website_id.crm_default_team_id',
        domain=lambda self: self._get_crm_default_team_domain(),
        help=
        'Default sales channel for new leads created through the Contact Us form.'
    )
    crm_default_user_id = fields.Many2one(
        'res.users',
        string='Default Salesperson',
        related='website_id.crm_default_user_id',
        domain=[('share', '=', False)],
        help=
        'Default salesperson for new leads created through the Contact Us form.'
    )
Ejemplo n.º 20
0
class MrpProductionMessage(models.Model):
    _name = "mrp.message"
    _description = "Production Message"

    @api.model
    def _default_valid_until(self):
        return datetime.today() + relativedelta(days=7)

    name = fields.Text(compute='_get_note_first_line', store=True)
    message = fields.Html(required=True)
    product_tmpl_id = fields.Many2one('product.template', 'Product Template')
    product_id = fields.Many2one('product.product', string="Product")
    bom_id = fields.Many2one(
        'mrp.bom',
        'Bill of Material',
        domain=
        "['|', ('product_id', '=', product_id), ('product_tmpl_id.product_variant_ids','=', product_id)]"
    )
    workcenter_id = fields.Many2one('mrp.workcenter', string='Work Center')
    valid_until = fields.Date('Validity Date',
                              default=_default_valid_until,
                              required=True)
    routing_id = fields.Many2one('mrp.routing', string='Routing')

    @api.depends('message')
    def _get_note_first_line(self):
        for message in self:
            message.name = (message.message and html2plaintext(message.message)
                            or "").strip().replace('*', '').split("\n")[0]

    @api.multi
    def save(self):
        """ Used in a wizard-like form view, manual save button when in edit mode """
        return True
Ejemplo n.º 21
0
class HrPayrollAdviceLine(models.Model):
    '''
    Bank Advice Lines
    '''
    _name = 'hr.payroll.advice.line'
    _description = 'Bank Advice Lines'

    advice_id = fields.Many2one('hr.payroll.advice', string='Bank Advice')
    name = fields.Char('Bank Account No.', required=True)
    ifsc_code = fields.Char(string='IFSC Code')
    employee_id = fields.Many2one('hr.employee',
                                  string='Employee',
                                  required=True)
    bysal = fields.Float(string='By Salary',
                         digits=dp.get_precision('Payroll'))
    debit_credit = fields.Char(string='C/D', default='C')
    company_id = fields.Many2one('res.company',
                                 related='advice_id.company_id',
                                 string='Company',
                                 store=True)
    ifsc = fields.Boolean(related='advice_id.neft', string='IFSC')

    @api.onchange('employee_id')
    def onchange_employee_id(self):
        self.name = self.employee_id.bank_account_id.acc_number
        self.ifsc_code = self.employee_id.bank_account_id.bank_bic or ''
Ejemplo n.º 22
0
class LinkTracker(models.Model):
    _inherit = "link.tracker"

    mass_mailing_id = fields.Many2one('mail.mass_mailing',
                                      string='Mass Mailing')
    mass_mailing_campaign_id = fields.Many2one('mail.mass_mailing.campaign',
                                               string='Mass Mailing Campaign')
Ejemplo n.º 23
0
class LinkTrackerClick(models.Model):
    _inherit = "link.tracker.click"

    mail_stat_id = fields.Many2one('mail.mail.statistics',
                                   string='Mail Statistics')
    mass_mailing_id = fields.Many2one('mail.mass_mailing',
                                      string='Mass Mailing')
    mass_mailing_campaign_id = fields.Many2one('mail.mass_mailing.campaign',
                                               string='Mass Mailing Campaign')

    @api.model
    def add_click(self, code, ip, country_code, stat_id=False):
        res = super(LinkTrackerClick, self).add_click(code,
                                                      ip,
                                                      country_code,
                                                      stat_id=stat_id)
        if stat_id:
            stat_sudo = self.env['mail.mail.statistics'].sudo().browse(stat_id)
            stat_sudo.set_opened()
            stat_sudo.set_clicked()
        return res

    def _get_click_values_from_route(self, route_values):
        click_values = super(LinkTrackerClick,
                             self)._get_click_values_from_route(route_values)
        if route_values['stat_id']:
            mail_stat = self.env['mail.mail.statistics'].browse(
                route_values['stat_id'])
            click_values['mail_stat_id'] = mail_stat.id
            if mail_stat.mass_mailing_campaign_id:
                click_values[
                    'mass_mailing_campaign_id'] = mail_stat.mass_mailing_campaign_id.id
            if mail_stat.mass_mailing_id:
                click_values['mass_mailing_id'] = mail_stat.mass_mailing_id.id
        return click_values
Ejemplo n.º 24
0
class EventTypeMail(models.Model):
    """ Template of event.mail to attach to event.type. Those will be copied
    upon all events created in that type to ease event creation. """
    _name = 'event.type.mail'
    _description = 'Mail Scheduling on Event Type'

    event_type_id = fields.Many2one('event.type',
                                    string='Event Type',
                                    ondelete='cascade',
                                    required=True)
    interval_nbr = fields.Integer('Interval', default=1)
    interval_unit = fields.Selection([('now', 'Immediately'),
                                      ('hours', 'Hour(s)'), ('days', 'Day(s)'),
                                      ('weeks', 'Week(s)'),
                                      ('months', 'Month(s)')],
                                     string='Unit',
                                     default='hours',
                                     required=True)
    interval_type = fields.Selection([('after_sub', 'After each registration'),
                                      ('before_event', 'Before the event'),
                                      ('after_event', 'After the event')],
                                     string='Trigger',
                                     default="before_event",
                                     required=True)
    template_id = fields.Many2one(
        'mail.template',
        string='Email Template',
        domain=[('model', '=', 'event.registration')],
        required=True,
        ondelete='restrict',
        help=
        'This field contains the template of the mail that will be automatically sent'
    )
Ejemplo n.º 25
0
class ProductTemplate(models.Model):
    _inherit = "product.template"

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

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

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

    @api.multi
    def get_product_accounts(self, fiscal_pos=None):
        accounts = self._get_product_accounts()
        if not fiscal_pos:
            fiscal_pos = self.env['account.fiscal.position']
        return fiscal_pos.map_accounts(accounts)
Ejemplo n.º 26
0
class CrmLeadConvert2Task(models.TransientModel):
    """ wizard to convert a Lead into a Project task and move the Mail Thread """

    _name = "crm.lead.convert2task"
    _inherit = 'crm.partner.binding'

    @api.model
    def default_get(self, fields):
        result = super(CrmLeadConvert2Task, self).default_get(fields)
        lead_id = self.env.context.get('active_id')
        if lead_id:
            result['lead_id'] = lead_id
        return result

    lead_id = fields.Many2one('crm.lead',
                              string='Lead',
                              domain=[('type', '=', 'lead')])
    project_id = fields.Many2one('project.project', string='Project')

    @api.multi
    def action_lead_to_project_task(self):
        self.ensure_one()
        # get the lead to transform
        lead = self.lead_id
        partner_id = self._find_matching_partner()
        if not partner_id and (lead.partner_name or lead.contact_name):
            partner_id = lead.handle_partner_assignation()[lead.id]
        # create new project.task
        vals = {
            "name": lead.name,
            "description": lead.description,
            "email_from": lead.email_from,
            "project_id": self.project_id.id,
            "partner_id": partner_id,
            "user_id": None
        }
        task = self.env['project.task'].create(vals)
        # move the mail thread
        lead.message_change_thread(task)
        # move attachments
        attachments = self.env['ir.attachment'].search([
            ('res_model', '=', 'crm.lead'), ('res_id', '=', lead.id)
        ])
        attachments.write({'res_model': 'project.task', 'res_id': task.id})
        # archive the lead
        lead.write({'active': False})
        # return the action to go to the form view of the new Task
        view = self.env.ref('project.view_task_form2')
        return {
            'name': 'Task created',
            'view_type': 'form',
            'view_mode': 'form',
            'view_id': view.id,
            'res_model': 'project.task',
            'type': 'ir.actions.act_window',
            'res_id': task.id,
            'context': self.env.context
        }
Ejemplo n.º 27
0
class ChooseDeliveryPackage(models.TransientModel):
    _name = 'choose.delivery.package'
    _description = 'Delivery Package Selection Wizard'

    stock_quant_package_id = fields.Many2one(
        'stock.quant.package',
        string="Physical Package",
        default=lambda self: self._default_stock_quant_package_id())
    delivery_packaging_id = fields.Many2one(
        'product.packaging',
        default=lambda self: self._default_delivery_packaging_id())
    shipping_weight = fields.Float(
        string='Shipping Weight',
        default=lambda self: self._default_shipping_weight())

    def _default_stock_quant_package_id(self):
        if self.env.context.get('default_stock_quant_package_id'):
            return self.env['stock.quant.package'].browse(
                self.env.context['stock_quant_package_id'])

    def _default_delivery_packaging_id(self):
        res = None
        if self.env.context.get('default_delivery_packaging_id'):
            res = self.env['product.packaging'].browse(
                self.env.context['default_delivery_packaging_id'])
        if self.env.context.get('default_stock_quant_package_id'):
            stock_quant_package = self.env['stock.quant.package'].browse(
                self.env.context['default_stock_quant_package_id'])
            res = stock_quant_package.packaging_id
        return res

    def _default_shipping_weight(self):
        if self.env.context.get('default_stock_quant_package_id'):
            stock_quant_package = self.env['stock.quant.package'].browse(
                self.env.context['default_stock_quant_package_id'])
            return stock_quant_package.shipping_weight
        else:
            picking_id = self.env['stock.picking'].browse(
                self.env.context['active_id'])
            move_line_ids = [
                po for po in picking_id.move_line_ids
                if po.qty_done > 0 and not po.result_package_id
            ]
            total_weight = sum(
                [po.qty_done * po.product_id.weight for po in move_line_ids])
            return total_weight

    def put_in_pack(self):
        picking_id = self.env['stock.picking'].browse(
            self.env.context['active_id'])
        if not self.stock_quant_package_id:
            stock_quant_package = picking_id._put_in_pack()
            self.stock_quant_package_id = stock_quant_package
        # write shipping weight and product_packaging on 'stock_quant_package' if needed
        if self.delivery_packaging_id:
            self.stock_quant_package_id.packaging_id = self.delivery_packaging_id
            if self.shipping_weight:
                self.stock_quant_package_id.shipping_weight = self.shipping_weight
Ejemplo n.º 28
0
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'})
Ejemplo n.º 29
0
class AccountBankStatement(models.Model):
    _inherit = 'account.bank.statement'

    pos_session_id = fields.Many2one('pos.session',
                                     string="Session",
                                     copy=False)
    account_id = fields.Many2one('account.account',
                                 related='journal_id.default_debit_account_id',
                                 readonly=True)
Ejemplo n.º 30
0
class OpeningAccountMoveWizard(models.TransientModel):
    _name = 'account.opening'

    company_id = fields.Many2one(comodel_name='res.company', required=True)
    opening_move_id = fields.Many2one(
        string='Opening Journal Entry',
        comodel_name='account.move',
        related='company_id.account_opening_move_id')
    currency_id = fields.Many2one(comodel_name='res.currency',
                                  related='opening_move_id.currency_id')
    opening_move_line_ids = fields.One2many(string='Opening Journal Items',
                                            related="opening_move_id.line_ids")
    journal_id = fields.Many2one(string='Journal',
                                 comodel_name='account.journal',
                                 required=True,
                                 related='opening_move_id.journal_id')
    date = fields.Date(string='Opening Date',
                       required=True,
                       related='opening_move_id.date')

    def validate(self):
        self.opening_move_id.post()

    @api.onchange('opening_move_line_ids')
    def opening_move_line_ids_changed(self):
        debit_diff, credit_diff = self.company_id.get_opening_move_differences(
            self.opening_move_line_ids)

        unaffected_earnings_account = self.company_id.get_unaffected_earnings_account(
        )
        balancing_line = self.opening_move_line_ids.filtered(
            lambda x: x.account_id == unaffected_earnings_account)

        if balancing_line:
            if not self.opening_move_line_ids == balancing_line and (
                    debit_diff or credit_diff):
                balancing_line.debit = credit_diff
                balancing_line.credit = debit_diff
            else:
                self.opening_move_line_ids -= balancing_line
        elif debit_diff or credit_diff:
            balancing_line = self.env['account.move.line'].new({
                'name':
                _('Automatic Balancing Line'),
                'move_id':
                self.company_id.account_opening_move_id.id,
                'account_id':
                unaffected_earnings_account.id,
                'debit':
                credit_diff,
                'credit':
                debit_diff,
                'company_id':
                self.company_id,
            })
            self.opening_move_line_ids += balancing_line