Ejemplo n.º 1
0
class Product(models.Model):
    _inherit = 'product.template'

    membership = fields.Boolean(
        help='Check if the product is eligible for membership.')
    membership_date_from = fields.Date(
        string='Membership Start Date',
        help='Date from which membership becomes active.')
    membership_date_to = fields.Date(
        string='Membership End Date',
        help='Date until which membership remains active.')

    _sql_constraints = [
        ('membership_date_greater',
         'check(membership_date_to >= membership_date_from)',
         'Error ! Ending Date cannot be set before Beginning Date.')
    ]

    @api.model
    def fields_view_get(self,
                        view_id=None,
                        view_type='form',
                        toolbar=False,
                        submenu=False):
        if self._context.get('product') == 'membership_product':
            if view_type == 'form':
                view_id = self.env.ref(
                    'membership.membership_products_form').id
            else:
                view_id = self.env.ref(
                    'membership.membership_products_tree').id
        return super(Product, self).fields_view_get(view_id=view_id,
                                                    view_type=view_type,
                                                    toolbar=toolbar,
                                                    submenu=submenu)
Ejemplo n.º 2
0
class PayslipLinesContributionRegister(models.TransientModel):
    _name = 'payslip.lines.contribution.register'
    _description = 'PaySlip Lines by Contribution Registers'

    date_from = fields.Date(string='Date From',
                            required=True,
                            default=datetime.now().strftime('%Y-%m-01'))
    date_to = fields.Date(
        string='Date To',
        required=True,
        default=str(datetime.now() +
                    relativedelta.relativedelta(months=+1, day=1, days=-1))
        [:10])

    @api.multi
    def print_report(self):
        active_ids = self.env.context.get('active_ids', [])
        datas = {
            'ids': active_ids,
            'model': 'hr.contribution.register',
            'form': self.read()[0]
        }
        return self.env.ref(
            'hr_payroll.action_contribution_register').report_action(
                [], data=datas)
Ejemplo n.º 3
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.º 4
0
class ProductMargin(models.TransientModel):
    _name = 'product.margin'
    _description = 'Product Margin'

    from_date = fields.Date('From', default=time.strftime('%Y-01-01'))
    to_date = fields.Date('To', default=time.strftime('%Y-12-31'))
    invoice_state = fields.Selection([
        ('paid', 'Paid'),
        ('open_paid', 'Open and Paid'),
        ('draft_open_paid', 'Draft, Open and Paid'),
    ],
                                     'Invoice State',
                                     index=True,
                                     required=True,
                                     default="open_paid")

    @api.multi
    def action_open_window(self):
        self.ensure_one()
        context = dict(self.env.context or {})

        def ref(module, xml_id):
            proxy = self.env['ir.model.data']
            return proxy.get_object_reference(module, xml_id)

        model, search_view_id = ref('product', 'product_search_form_view')
        model, graph_view_id = ref('product_margin',
                                   'view_product_margin_graph')
        model, form_view_id = ref('product_margin', 'view_product_margin_form')
        model, tree_view_id = ref('product_margin', 'view_product_margin_tree')

        context.update(invoice_state=self.invoice_state)

        if self.from_date:
            context.update(date_from=self.from_date)

        if self.to_date:
            context.update(date_to=self.to_date)

        views = [(tree_view_id, 'tree'), (form_view_id, 'form'),
                 (graph_view_id, 'graph')]
        return {
            'name': _('Product Margins'),
            'context': context,
            'view_type': 'form',
            "view_mode": 'tree,form,graph',
            'res_model': 'product.product',
            'type': 'ir.actions.act_window',
            'views': views,
            'view_id': False,
            'search_view_id': search_view_id,
        }
class AccountCommonReport(models.TransientModel):
    _name = "account.common.report"
    _description = "Account Common Report"

    company_id = fields.Many2one('res.company',
                                 string='Company',
                                 readonly=True,
                                 default=lambda self: self.env.user.company_id)
    journal_ids = fields.Many2many(
        'account.journal',
        string='Journals',
        required=True,
        default=lambda self: self.env['account.journal'].search([]))
    date_from = fields.Date(string='Start Date')
    date_to = fields.Date(string='End Date')
    target_move = fields.Selection([
        ('posted', 'All Posted Entries'),
        ('all', 'All Entries'),
    ],
                                   string='Target Moves',
                                   required=True,
                                   default='posted')

    def _build_contexts(self, data):
        result = {}
        result['journal_ids'] = 'journal_ids' in data['form'] and data['form'][
            'journal_ids'] or False
        result['state'] = 'target_move' in data['form'] and data['form'][
            'target_move'] or ''
        result['date_from'] = data['form']['date_from'] or False
        result['date_to'] = data['form']['date_to'] or False
        result['strict_range'] = True if result['date_from'] else False
        return result

    def _print_report(self, data):
        raise NotImplementedError()

    @api.multi
    def check_report(self):
        self.ensure_one()
        data = {}
        data['ids'] = self.env.context.get('active_ids', [])
        data['model'] = self.env.context.get('active_model', 'ir.ui.menu')
        data['form'] = self.read(
            ['date_from', 'date_to', 'journal_ids', 'target_move'])[0]
        used_context = self._build_contexts(data)
        data['form']['used_context'] = dict(used_context,
                                            lang=self.env.context.get('lang')
                                            or 'en_US')
        return self.with_context(discard_logo_check=True)._print_report(data)
Ejemplo n.º 6
0
class HrPayslipRun(models.Model):
    _name = 'hr.payslip.run'
    _description = 'Payslip Batches'

    name = fields.Char(required=True,
                       readonly=True,
                       states={'draft': [('readonly', False)]})
    slip_ids = fields.One2many('hr.payslip',
                               'payslip_run_id',
                               string='Payslips',
                               readonly=True,
                               states={'draft': [('readonly', False)]})
    state = fields.Selection([
        ('draft', 'Draft'),
        ('close', 'Close'),
    ],
                             string='Status',
                             index=True,
                             readonly=True,
                             copy=False,
                             default='draft')
    date_start = fields.Date(string='Date From',
                             required=True,
                             readonly=True,
                             states={'draft': [('readonly', False)]},
                             default=time.strftime('%Y-%m-01'))
    date_end = fields.Date(
        string='Date To',
        required=True,
        readonly=True,
        states={'draft': [('readonly', False)]},
        default=str(datetime.now() +
                    relativedelta.relativedelta(months=+1, day=1, days=-1))
        [:10])
    credit_note = fields.Boolean(
        string='Credit Note',
        readonly=True,
        states={'draft': [('readonly', False)]},
        help=
        "If its checked, indicates that all payslips generated from here are refund payslips."
    )

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

    @api.multi
    def close_payslip_run(self):
        return self.write({'state': 'close'})
class HrSalaryEmployeeBymonth(models.TransientModel):

    _name = 'hr.salary.employee.month'
    _description = 'Hr Salary Employee By Month Report'

    def _get_default_category(self):
        return self.env['hr.salary.rule.category'].search(
            [('code', '=', 'NET')], limit=1)

    def _get_default_start_date(self):
        year = fields.Date.from_string(fields.Date.today()).strftime('%Y')
        return '{}-01-01'.format(year)

    def _get_default_end_date(self):
        date = fields.Date.from_string(fields.Date.today())
        return date.strftime('%Y') + '-' + date.strftime(
            '%m') + '-' + date.strftime('%d')

    start_date = fields.Date(string='Start Date',
                             required=True,
                             default=_get_default_start_date)
    end_date = fields.Date(string='End Date',
                           required=True,
                           default=_get_default_end_date)
    employee_ids = fields.Many2many('hr.employee',
                                    'payroll_year_rel',
                                    'payroll_year_id',
                                    'employee_id',
                                    string='Employees',
                                    required=True)
    category_id = fields.Many2one('hr.salary.rule.category',
                                  string='Category',
                                  required=True,
                                  default=_get_default_category)

    @api.multi
    def print_report(self):
        """
         To get the date and print the report
         @return: return report
        """
        self.ensure_one()
        data = {'ids': self.env.context.get('active_ids', [])}
        res = self.read()
        res = res and res[0] or {}
        data.update({'form': res})
        return self.env.ref(
            'l10n_in_hr_payroll.action_report_hrsalarybymonth').report_action(
                self, data=data)
Ejemplo n.º 8
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()
Ejemplo n.º 9
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.º 10
0
class Employee(models.Model):

    _inherit = "hr.employee"

    manager = fields.Boolean(string='Is a Manager')
    medic_exam = fields.Date(string='Medical Examination Date', groups="hr.group_hr_user")
    place_of_birth = fields.Char('Place of Birth', groups="hr.group_hr_user")
    children = fields.Integer(string='Number of Children', groups="hr.group_hr_user")
    vehicle = fields.Char(string='Company Vehicle', groups="hr.group_hr_user")
    vehicle_distance = fields.Integer(
        string='Home-Work Dist.', help="In kilometers", groups="hr.group_hr_user")
    contract_ids = fields.One2many('hr.contract', 'employee_id', string='Contracts')
    contract_id = fields.Many2one('hr.contract', compute='_compute_contract_id', string='Current Contract', help='Latest contract of the employee')
    contracts_count = fields.Integer(compute='_compute_contracts_count', string='Contracts')

    def _compute_contract_id(self):
        """ get the lastest contract """
        Contract = self.env['hr.contract']
        for employee in self:
            employee.contract_id = Contract.search([('employee_id', '=', employee.id)], order='date_start desc', limit=1)

    def _compute_contracts_count(self):
        # read_group as sudo, since contract count is displayed on form view
        contract_data = self.env['hr.contract'].sudo().read_group([('employee_id', 'in', self.ids)], ['employee_id'], ['employee_id'])
        result = dict((data['employee_id'][0], data['employee_id_count']) for data in contract_data)
        for employee in self:
            employee.contracts_count = result.get(employee.id, 0)
Ejemplo n.º 11
0
class ResPartner(models.Model):
    _inherit = "res.partner"

    partner_latitude = fields.Float(string='Geo Latitude', digits=(16, 5))
    partner_longitude = fields.Float(string='Geo Longitude', digits=(16, 5))
    date_localization = fields.Date(string='Geolocation Date')

    @classmethod
    def _geo_localize(cls, apikey, street='', zip='', city='', state='', country=''):
        search = geo_query_address(street=street, zip=zip, city=city, state=state, country=country)
        result = geo_find(search, apikey)
        if result is None:
            search = geo_query_address(city=city, state=state, country=country)
            result = geo_find(search, apikey)
        return result

    @api.multi
    def geo_localize(self):
        # We need country names in English below
        apikey = self.env['ir.config_parameter'].sudo().get_param('google.api_key_geocode')
        for partner in self.with_context(lang='en_US'):
            result = partner._geo_localize(apikey,
                                           partner.street,
                                           partner.zip,
                                           partner.city,
                                           partner.state_id.name,
                                           partner.country_id.name)
            if result:
                partner.write({
                    'partner_latitude': result[0],
                    'partner_longitude': result[1],
                    'date_localization': fields.Date.context_today(partner)
                })
        return True
Ejemplo n.º 12
0
class AccountMoveReversal(models.TransientModel):
    """
    Account move reversal wizard, it cancel an account move by reversing it.
    """
    _name = 'account.move.reversal'
    _description = 'Account move reversal'

    date = fields.Date(string='Reversal date',
                       default=fields.Date.context_today,
                       required=True)
    journal_id = fields.Many2one(
        'account.journal',
        string='Use Specific Journal',
        help='If empty, uses the journal of the journal entry to be reversed.')

    @api.multi
    def reverse_moves(self):
        ac_move_ids = self._context.get('active_ids', False)
        res = self.env['account.move'].browse(ac_move_ids).reverse_moves(
            self.date, self.journal_id or False)
        if res:
            return {
                'name': _('Reverse Moves'),
                'type': 'ir.actions.act_window',
                'view_type': 'form',
                'view_mode': 'tree,form',
                'res_model': 'account.move',
                'domain': [('id', 'in', res)],
            }
        return {'type': 'ir.actions.act_window_close'}
Ejemplo n.º 13
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.º 14
0
class FinancialYearOpeningWizard(models.TransientModel):
    _name = 'account.financial.year.op'

    company_id = fields.Many2one(comodel_name='res.company', required=True)
    opening_move_posted = fields.Boolean(string='Opening Move Posted', compute='_compute_opening_move_posted')
    opening_date = fields.Date(string='Opening Date', required=True, related='company_id.account_opening_date', help="Date from which the accounting is managed in NobleCRM. It is the date of the opening entry.")
    fiscalyear_last_day = fields.Integer(related="company_id.fiscalyear_last_day", required=True,
                                         help="The last day of the month will be taken if the chosen day doesn't exist.")
    fiscalyear_last_month = fields.Selection(selection=[(1, 'January'), (2, 'February'), (3, 'March'), (4, 'April'), (5, 'May'), (6, 'June'), (7, 'July'), (8, 'August'), (9, 'September'), (10, 'October'), (11, 'November'), (12, 'December')],
                                             related="company_id.fiscalyear_last_month",
                                             required=True,
                                             help="The last day of the month will be taken if the chosen day doesn't exist.")
    account_setup_fy_data_done = fields.Boolean(string='Financial year setup marked as done', compute="_compute_setup_marked_done")

    @api.depends('company_id.account_setup_fy_data_done')
    def _compute_setup_marked_done(self):
        for record in self:
            record.account_setup_fy_data_done = record.company_id.account_setup_fy_data_done

    @api.depends('company_id.account_opening_move_id')
    def _compute_opening_move_posted(self):
        for record in self:
            record.opening_move_posted = record.company_id.opening_move_posted()

    def mark_as_done(self):
        """ Forces fiscal year setup state to 'done'."""
        self.company_id.account_setup_fy_data_done = True

    def unmark_as_done(self):
        """ Forces fiscal year setup state to 'undone'."""
        self.company_id.account_setup_fy_data_done = False
class HolidaysSummaryDept(models.TransientModel):

    _name = 'hr.holidays.summary.dept'
    _description = 'HR Leaves Summary Report By Department'

    date_from = fields.Date(string='From',
                            required=True,
                            default=lambda *a: time.strftime('%Y-%m-01'))
    depts = fields.Many2many('hr.department',
                             'summary_dept_rel',
                             'sum_id',
                             'dept_id',
                             string='Department(s)')
    holiday_type = fields.Selection([('Approved', 'Approved'),
                                     ('Confirmed', 'Confirmed'),
                                     ('both', 'Both Approved and Confirmed')],
                                    string='Leave Type',
                                    required=True,
                                    default='Approved')

    @api.multi
    def print_report(self):
        self.ensure_one()
        [data] = self.read()
        if not data.get('depts'):
            raise UserError(
                _('You have to select at least one Department. And try again.')
            )
        departments = self.env['hr.department'].browse(data['depts'])
        datas = {'ids': [], 'model': 'hr.department', 'form': data}
        return self.env.ref(
            'hr_holidays.action_report_holidayssummary').with_context(
                from_transient_model=True).report_action(departments,
                                                         data=datas)
class AccountAnalyticDefault(models.Model):
    _name = "account.analytic.default"
    _description = "Analytic Distribution"
    _rec_name = "analytic_id"
    _order = "sequence"

    sequence = fields.Integer(string='Sequence', help="Gives the sequence order when displaying a list of analytic distribution")
    analytic_id = fields.Many2one('account.analytic.account', string='Analytic Account')
    product_id = fields.Many2one('product.product', string='Product', ondelete='cascade', help="Select a product which will use analytic account specified in analytic default (e.g. create new customer invoice or Sales order if we select this product, it will automatically take this as an analytic account)")
    partner_id = fields.Many2one('res.partner', string='Partner', ondelete='cascade', help="Select a partner which will use analytic account specified in analytic default (e.g. create new customer invoice or Sales order if we select this partner, it will automatically take this as an analytic account)")
    user_id = fields.Many2one('res.users', string='User', ondelete='cascade', help="Select a user which will use analytic account specified in analytic default.")
    company_id = fields.Many2one('res.company', string='Company', ondelete='cascade', help="Select a company which will use analytic account specified in analytic default (e.g. create new customer invoice or Sales order if we select this company, it will automatically take this as an analytic account)")
    date_start = fields.Date(string='Start Date', help="Default start date for this Analytic Account.")
    date_stop = fields.Date(string='End Date', help="Default end date for this Analytic Account.")

    @api.model
    def account_get(self, product_id=None, partner_id=None, user_id=None, date=None, company_id=None):
        domain = []
        if product_id:
            domain += ['|', ('product_id', '=', product_id)]
        domain += [('product_id', '=', False)]
        if partner_id:
            domain += ['|', ('partner_id', '=', partner_id)]
        domain += [('partner_id', '=', False)]
        if company_id:
            domain += ['|', ('company_id', '=', company_id)]
        domain += [('company_id', '=', False)]
        if user_id:
            domain += ['|', ('user_id', '=', user_id)]
        domain += [('user_id', '=', False)]
        if date:
            domain += ['|', ('date_start', '<=', date), ('date_start', '=', False)]
            domain += ['|', ('date_stop', '>=', date), ('date_stop', '=', False)]
        best_index = -1
        res = self.env['account.analytic.default']
        for rec in self.search(domain):
            index = 0
            if rec.product_id: index += 1
            if rec.partner_id: index += 1
            if rec.company_id: index += 1
            if rec.user_id: index += 1
            if rec.date_start: index += 1
            if rec.date_stop: index += 1
            if index > best_index:
                res = rec
                best_index = index
        return res
Ejemplo n.º 17
0
class ResPartner(models.Model):
    _inherit = "res.partner"

    partner_weight = fields.Integer(
        'Level Weight',
        default=lambda *args: 0,
        help=
        "Gives the probability to assign a lead to this partner. (0 means no assignation.)"
    )
    grade_id = fields.Many2one('res.partner.grade', 'Level')
    grade_sequence = fields.Integer(related='grade_id.sequence',
                                    readonly=True,
                                    store=True)
    activation = fields.Many2one('res.partner.activation',
                                 'Activation',
                                 index=True)
    date_partnership = fields.Date('Partnership Date')
    date_review = fields.Date('Latest Partner Review')
    date_review_next = fields.Date('Next Partner Review')
    # customer implementation
    assigned_partner_id = fields.Many2one(
        'res.partner',
        'Implemented by',
    )
    implemented_partner_ids = fields.One2many(
        'res.partner',
        'assigned_partner_id',
        string='Implementation References',
    )
    implemented_count = fields.Integer(
        compute='_compute_implemented_partner_count', store=True)

    @api.one
    @api.depends('implemented_partner_ids',
                 'implemented_partner_ids.website_published',
                 'implemented_partner_ids.active')
    def _compute_implemented_partner_count(self):
        self.implemented_count = len(
            self.implemented_partner_ids.filtered('website_published'))

    @api.onchange('grade_id')
    def _onchange_grade_id(self):
        grade = self.grade_id
        self.partner_weight = grade.partner_weight if grade else 0
Ejemplo n.º 18
0
class PurchaseRequisitionLine(models.Model):
    _name = "purchase.requisition.line"
    _description = "Purchase Requisition Line"
    _rec_name = 'product_id'

    product_id = fields.Many2one('product.product', string='Product', domain=[('purchase_ok', '=', True)], required=True)
    product_uom_id = fields.Many2one('product.uom', string='Product Unit of Measure')
    product_qty = fields.Float(string='Quantity', digits=dp.get_precision('Product Unit of Measure'))
    price_unit = fields.Float(string='Unit Price', digits=dp.get_precision('Product Price'))
    qty_ordered = fields.Float(compute='_compute_ordered_qty', string='Ordered Quantities')
    requisition_id = fields.Many2one('purchase.requisition', string='Purchase Agreement', ondelete='cascade')
    company_id = fields.Many2one('res.company', related='requisition_id.company_id', string='Company', store=True, readonly=True, default= lambda self: self.env['res.company']._company_default_get('purchase.requisition.line'))
    account_analytic_id = fields.Many2one('account.analytic.account', string='Analytic Account')
    schedule_date = fields.Date(string='Scheduled Date')
    move_dest_id = fields.Many2one('stock.move', 'Downstream Move')

    @api.multi
    @api.depends('requisition_id.purchase_ids.state')
    def _compute_ordered_qty(self):
        for line in self:
            total = 0.0
            for po in line.requisition_id.purchase_ids.filtered(lambda purchase_order: purchase_order.state in ['purchase', 'done']):
                for po_line in po.order_line.filtered(lambda order_line: order_line.product_id == line.product_id):
                    if po_line.product_uom != line.product_uom_id:
                        total += po_line.product_uom._compute_quantity(po_line.product_qty, line.product_uom_id)
                    else:
                        total += po_line.product_qty
            line.qty_ordered = total

    @api.onchange('product_id')
    def _onchange_product_id(self):
        if self.product_id:
            self.product_uom_id = self.product_id.uom_id
            self.product_qty = 1.0
        if not self.account_analytic_id:
            self.account_analytic_id = self.requisition_id.account_analytic_id
        if not self.schedule_date:
            self.schedule_date = self.requisition_id.schedule_date

    @api.multi
    def _prepare_purchase_order_line(self, name, product_qty=0.0, price_unit=0.0, taxes_ids=False):
        self.ensure_one()
        requisition = self.requisition_id
        return {
            'name': name,
            'product_id': self.product_id.id,
            'product_uom': self.product_id.uom_po_id.id,
            'product_qty': product_qty,
            'price_unit': price_unit,
            'taxes_id': [(6, 0, taxes_ids)],
            'date_planned': requisition.schedule_date or fields.Date.today(),
            'account_analytic_id': self.account_analytic_id.id,
            'move_dest_ids': self.move_dest_id and [(4, self.move_dest_id.id)] or []
        }
class YearlySalaryDetail(models.TransientModel):
    _name = 'yearly.salary.detail'
    _description = 'Hr Salary Employee By Category Report'

    def _get_default_date_from(self):
        year = fields.Date.from_string(fields.Date.today()).strftime('%Y')
        return '{}-01-01'.format(year)

    def _get_default_date_to(self):
        date = fields.Date.from_string(fields.Date.today())
        return date.strftime('%Y') + '-' + date.strftime(
            '%m') + '-' + date.strftime('%d')

    employee_ids = fields.Many2many('hr.employee',
                                    'payroll_emp_rel',
                                    'payroll_id',
                                    'employee_id',
                                    string='Employees',
                                    required=True)
    date_from = fields.Date(string='Start Date',
                            required=True,
                            default=_get_default_date_from)
    date_to = fields.Date(string='End Date',
                          required=True,
                          default=_get_default_date_to)

    @api.multi
    def print_report(self):
        """
         To get the date and print the report
         @return: return report
        """
        self.ensure_one()
        data = {'ids': self.env.context.get('active_ids', [])}
        res = self.read()
        res = res and res[0] or {}
        data.update({'form': res})
        return self.env.ref(
            'l10n_in_hr_payroll.action_report_hryearlysalary').report_action(
                self, data=data)
Ejemplo n.º 20
0
class ResourceCalendarAttendance(models.Model):
    _name = "resource.calendar.attendance"
    _description = "Work Detail"
    _order = 'dayofweek, hour_from'

    name = fields.Char(required=True)
    dayofweek = fields.Selection([
        ('0', 'Monday'),
        ('1', 'Tuesday'),
        ('2', 'Wednesday'),
        ('3', 'Thursday'),
        ('4', 'Friday'),
        ('5', 'Saturday'),
        ('6', 'Sunday')
        ], 'Day of Week', required=True, index=True, default='0')
    date_from = fields.Date(string='Starting Date')
    date_to = fields.Date(string='End Date')
    hour_from = fields.Float(string='Work from', required=True, index=True,
        help="Start and End time of working.\n"
             "A specific value of 24:00 is interpreted as 23:59:59.999999.")
    hour_to = fields.Float(string='Work to', required=True)
    calendar_id = fields.Many2one("resource.calendar", string="Resource's Calendar", required=True, ondelete='cascade')
Ejemplo n.º 21
0
class link_tracker_click(models.Model):
    _name = "link.tracker.click"
    _rec_name = "link_id"

    click_date = fields.Date(string='Create Date')
    link_id = fields.Many2one('link.tracker',
                              'Link',
                              required=True,
                              ondelete='cascade')
    ip = fields.Char(string='Internet Protocol')
    country_id = fields.Many2one('res.country', 'Country')

    @api.model
    def add_click(self, code, ip, country_code, stat_id=False):
        self = self.sudo()
        code_rec = self.env['link.tracker.code'].search([('code', '=', code)])

        if not code_rec:
            return None

        again = self.search_count([('link_id', '=', code_rec.link_id.id),
                                   ('ip', '=', ip)])

        if not again:
            self.create(
                self._get_click_values_from_route(
                    dict(
                        code=code,
                        ip=ip,
                        country_code=country_code,
                        stat_id=stat_id,
                    )))

    def _get_click_values_from_route(self, route_values):
        code = self.env['link.tracker.code'].search(
            [('code', '=', route_values['code'])], limit=1)
        country = self.env['res.country'].search(
            [('code', '=', route_values['country_code'])], limit=1)

        return {
            'link_id': code.link_id.id,
            'create_date': datetime.date.today(),
            'ip': route_values['ip'],
            'country_id': country.id,
        }
class TimesheetAttendance(models.Model):
    _name = 'hr.timesheet.attendance.report'
    _auto = False

    user_id = fields.Many2one('res.users')
    date = fields.Date()
    total_timesheet = fields.Float()
    total_attendance = fields.Float()
    total_difference = fields.Float()

    @api.model_cr
    def init(self):
        self._cr.execute("""CREATE OR REPLACE VIEW %s AS (
            SELECT
                max(id) AS id,
                t.user_id,
                t.date,
                coalesce(sum(t.attendance), 0) AS total_attendance,
                coalesce(sum(t.timesheet), 0) AS total_timesheet,
                coalesce(sum(t.attendance), 0) - coalesce(sum(t.timesheet), 0) as total_difference
            FROM (
                SELECT
                    -hr_attendance.id AS id,
                    resource_resource.user_id AS user_id,
                    hr_attendance.worked_hours AS attendance,
                    NULL AS timesheet,
                    date_trunc('day', hr_attendance.check_in) AS date
                FROM hr_attendance
                LEFT JOIN hr_employee ON hr_employee.id = hr_attendance.employee_id
                LEFT JOIN resource_resource on resource_resource.id = hr_employee.resource_id
            UNION ALL
                SELECT
                    ts.id AS id,
                    ts.user_id AS user_id,
                    NULL AS attendance,
                    ts.unit_amount AS timesheet,
                    date_trunc('day', ts.date) AS date
                FROM account_analytic_line AS ts
                WHERE ts.project_id IS NOT NULL
            ) AS t
            GROUP BY t.user_id, t.date
            ORDER BY t.date
        )
        """ % self._table)
Ejemplo n.º 23
0
class AccountAgedTrialBalance(models.TransientModel):

    _name = 'account.aged.trial.balance'
    _inherit = 'account.common.partner.report'
    _description = 'Account Aged Trial balance Report'

    period_length = fields.Integer(string='Period Length (days)',
                                   required=True,
                                   default=30)
    journal_ids = fields.Many2many('account.journal',
                                   string='Journals',
                                   required=True)
    date_from = fields.Date(default=lambda *a: time.strftime('%Y-%m-%d'))

    def _print_report(self, data):
        res = {}
        data = self.pre_print_report(data)
        data['form'].update(self.read(['period_length'])[0])
        period_length = data['form']['period_length']
        if period_length <= 0:
            raise UserError(_('You must set a period length greater than 0.'))
        if not data['form']['date_from']:
            raise UserError(_('You must set a start date.'))

        start = datetime.strptime(data['form']['date_from'], "%Y-%m-%d")

        for i in range(5)[::-1]:
            stop = start - relativedelta(days=period_length - 1)
            res[str(i)] = {
                'name': (i != 0 and (str(
                    (5 - (i + 1)) * period_length) + '-' + str(
                        (5 - i) * period_length))
                         or ('+' + str(4 * period_length))),
                'stop':
                start.strftime('%Y-%m-%d'),
                'start': (i != 0 and stop.strftime('%Y-%m-%d') or False),
            }
            start = stop - relativedelta(days=1)
        data['form'].update(res)
        return self.env.ref(
            'account.action_report_aged_partner_balance').with_context(
                landscape=True).report_action(self, data=data)
Ejemplo n.º 24
0
class AccountAnalyticLine(models.Model):
    _name = 'account.analytic.line'
    _description = 'Analytic Line'
    _order = 'date desc, id desc'

    @api.model
    def _default_user(self):
        return self.env.context.get('user_id', self.env.user.id)

    name = fields.Char('Description', required=True)
    date = fields.Date('Date',
                       required=True,
                       index=True,
                       default=fields.Date.context_today)
    amount = fields.Monetary('Amount', required=True, default=0.0)
    unit_amount = fields.Float('Quantity', default=0.0)
    account_id = fields.Many2one('account.analytic.account',
                                 'Analytic Account',
                                 required=True,
                                 ondelete='restrict',
                                 index=True)
    partner_id = fields.Many2one('res.partner', string='Partner')
    user_id = fields.Many2one('res.users',
                              string='User',
                              default=_default_user)

    tag_ids = fields.Many2many('account.analytic.tag',
                               'account_analytic_line_tag_rel',
                               'line_id',
                               'tag_id',
                               string='Tags',
                               copy=True)

    company_id = fields.Many2one(related='account_id.company_id',
                                 string='Company',
                                 store=True,
                                 readonly=True)
    currency_id = fields.Many2one(related="company_id.currency_id",
                                  string="Currency",
                                  readonly=True)
Ejemplo n.º 25
0
class StockInventory(models.Model):
    _inherit = "stock.inventory"

    accounting_date = fields.Date(
        'Force Accounting Date',
        help="Choose the accounting date at which you want to value the stock "
        "moves created by the inventory instead of the default one (the "
        "inventory end date)")

    @api.multi
    def post_inventory(self):
        acc_inventories = self.filtered(
            lambda inventory: inventory.accounting_date)
        for inventory in acc_inventories:
            res = super(
                StockInventory,
                inventory.with_context(force_period_date=inventory.
                                       accounting_date)).post_inventory()
        other_inventories = self - acc_inventories
        if other_inventories:
            res = super(StockInventory, other_inventories).post_inventory()
        return res
class AssetDepreciationConfirmationWizard(models.TransientModel):
    _name = "asset.depreciation.confirmation.wizard"
    _description = "asset.depreciation.confirmation.wizard"

    date = fields.Date(
        'Account Date',
        required=True,
        help=
        "Choose the period for which you want to automatically post the depreciation lines of running assets",
        default=fields.Date.context_today)

    @api.multi
    def asset_compute(self):
        self.ensure_one()
        context = self._context
        created_move_ids = self.env[
            'account.asset.asset'].compute_generated_entries(
                self.date, asset_type=context.get('asset_type'))

        return {
            'name':
            _('Created Asset Moves') if context.get('asset_type') == 'purchase'
            else _('Created Revenue Moves'),
            'view_type':
            'form',
            'view_mode':
            'tree,form',
            'res_model':
            'account.move',
            'view_id':
            False,
            'domain':
            "[('id','in',[" + ','.join(str(id)
                                       for id in created_move_ids) + "])]",
            'type':
            'ir.actions.act_window',
        }
Ejemplo n.º 27
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
Ejemplo n.º 28
0
class MaintenanceRequest(models.Model):
    _name = 'maintenance.request'
    _inherit = ['mail.thread', 'mail.activity.mixin']
    _description = 'Maintenance Requests'
    _order = "id desc"

    @api.returns('self')
    def _default_stage(self):
        return self.env['maintenance.stage'].search([], limit=1)

    @api.multi
    def _track_subtype(self, init_values):
        self.ensure_one()
        if 'stage_id' in init_values and self.stage_id.sequence <= 1:
            return 'maintenance.mt_req_created'
        elif 'stage_id' in init_values and self.stage_id.sequence > 1:
            return 'maintenance.mt_req_status'
        return super(MaintenanceRequest, self)._track_subtype(init_values)

    def _get_default_team_id(self):
        return self.env.ref('maintenance.equipment_team_maintenance',
                            raise_if_not_found=False)

    name = fields.Char('Subjects', required=True)
    description = fields.Text('Description')
    request_date = fields.Date(
        'Request Date',
        track_visibility='onchange',
        default=fields.Date.context_today,
        help="Date requested for the maintenance to happen")
    owner_user_id = fields.Many2one('res.users',
                                    string='Created by',
                                    default=lambda s: s.env.uid)
    category_id = fields.Many2one('maintenance.equipment.category',
                                  related='equipment_id.category_id',
                                  string='Category',
                                  store=True,
                                  readonly=True)
    equipment_id = fields.Many2one('maintenance.equipment',
                                   string='Equipment',
                                   index=True)
    technician_user_id = fields.Many2one('res.users',
                                         string='Owner',
                                         track_visibility='onchange',
                                         oldname='user_id')
    stage_id = fields.Many2one('maintenance.stage',
                               string='Stage',
                               track_visibility='onchange',
                               group_expand='_read_group_stage_ids',
                               default=_default_stage)
    priority = fields.Selection([('0', 'Very Low'), ('1', 'Low'),
                                 ('2', 'Normal'), ('3', 'High')],
                                string='Priority')
    color = fields.Integer('Color Index')
    close_date = fields.Date('Close Date',
                             help="Date the maintenance was finished. ")
    kanban_state = fields.Selection([('normal', 'In Progress'),
                                     ('blocked', 'Blocked'),
                                     ('done', 'Ready for next stage')],
                                    string='Kanban State',
                                    required=True,
                                    default='normal',
                                    track_visibility='onchange')
    # active = fields.Boolean(default=True, help="Set active to false to hide the maintenance request without deleting it.")
    archive = fields.Boolean(
        default=False,
        help=
        "Set archive to true to hide the maintenance request without deleting it."
    )
    maintenance_type = fields.Selection([('corrective', 'Corrective'),
                                         ('preventive', 'Preventive')],
                                        string='Maintenance Type',
                                        default="corrective")
    schedule_date = fields.Datetime(
        'Scheduled Date',
        help=
        "Date the maintenance team plans the maintenance.  It should not differ much from the Request Date. "
    )
    maintenance_team_id = fields.Many2one('maintenance.team',
                                          string='Team',
                                          required=True,
                                          default=_get_default_team_id)
    duration = fields.Float(help="Duration in minutes and seconds.")

    @api.multi
    def archive_equipment_request(self):
        self.write({'archive': True})

    @api.multi
    def reset_equipment_request(self):
        """ Reinsert the maintenance request into the maintenance pipe in the first stage"""
        first_stage_obj = self.env['maintenance.stage'].search(
            [], order="sequence asc", limit=1)
        # self.write({'active': True, 'stage_id': first_stage_obj.id})
        self.write({'archive': False, 'stage_id': first_stage_obj.id})

    @api.onchange('equipment_id')
    def onchange_equipment_id(self):
        if self.equipment_id:
            self.technician_user_id = self.equipment_id.technician_user_id if self.equipment_id.technician_user_id else self.equipment_id.category_id.technician_user_id
            self.category_id = self.equipment_id.category_id
            if self.equipment_id.maintenance_team_id:
                self.maintenance_team_id = self.equipment_id.maintenance_team_id.id

    @api.onchange('category_id')
    def onchange_category_id(self):
        if not self.technician_user_id or not self.equipment_id or (
                self.technician_user_id
                and not self.equipment_id.technician_user_id):
            self.technician_user_id = self.category_id.technician_user_id

    @api.model
    def create(self, vals):
        # context: no_log, because subtype already handle this
        self = self.with_context(mail_create_nolog=True)
        request = super(MaintenanceRequest, self).create(vals)
        if request.owner_user_id or request.technician_user_id:
            request._add_followers()
        if request.equipment_id and not request.maintenance_team_id:
            request.maintenance_team_id = request.equipment_id.maintenance_team_id
        return request

    @api.multi
    def write(self, vals):
        # Overridden to reset the kanban_state to normal whenever
        # the stage (stage_id) of the Maintenance Request changes.
        if vals and 'kanban_state' not in vals and 'stage_id' in vals:
            vals['kanban_state'] = 'normal'
        res = super(MaintenanceRequest, self).write(vals)
        if vals.get('owner_user_id') or vals.get('technician_user_id'):
            self._add_followers()
        if 'stage_id' in vals:
            self.filtered(lambda m: m.stage_id.done).write(
                {'close_date': fields.Date.today()})
        return res

    def _add_followers(self):
        for request in self:
            user_ids = (request.owner_user_id + request.technician_user_id).ids
            request.message_subscribe_users(user_ids=user_ids)

    @api.model
    def _read_group_stage_ids(self, stages, domain, order):
        """ Read group customization in order to display all the stages in the
            kanban view, even if they are empty
        """
        stage_ids = stages._search([],
                                   order=order,
                                   access_rights_uid=SUPERUSER_ID)
        return stages.browse(stage_ids)
Ejemplo n.º 29
0
class MaintenanceEquipment(models.Model):
    _name = 'maintenance.equipment'
    _inherit = ['mail.thread', 'mail.activity.mixin']
    _description = 'Equipment'

    @api.multi
    def _track_subtype(self, init_values):
        self.ensure_one()
        if 'owner_user_id' in init_values and self.owner_user_id:
            return 'maintenance.mt_mat_assign'
        return super(MaintenanceEquipment, self)._track_subtype(init_values)

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

    @api.model
    def name_search(self, name, args=None, operator='ilike', limit=100):
        args = args or []
        recs = self.browse()
        if name:
            recs = self.search([('name', '=', name)] + args, limit=limit)
        if not recs:
            recs = self.search([('name', operator, name)] + args, limit=limit)
        return recs.name_get()

    name = fields.Char('Equipment Name', required=True, translate=True)
    active = fields.Boolean(default=True)
    technician_user_id = fields.Many2one('res.users',
                                         string='Technician',
                                         track_visibility='onchange',
                                         oldname='user_id')
    owner_user_id = fields.Many2one('res.users',
                                    string='Owner',
                                    track_visibility='onchange')
    category_id = fields.Many2one('maintenance.equipment.category',
                                  string='Equipment Category',
                                  track_visibility='onchange',
                                  group_expand='_read_group_category_ids')
    partner_id = fields.Many2one('res.partner',
                                 string='Vendor',
                                 domain="[('supplier', '=', 1)]")
    partner_ref = fields.Char('Vendor Reference')
    location = fields.Char('Location')
    model = fields.Char('Model')
    serial_no = fields.Char('Serial Number', copy=False)
    assign_date = fields.Date('Assigned Date', track_visibility='onchange')
    cost = fields.Float('Cost')
    note = fields.Text('Note')
    warranty = fields.Date('Warranty')
    color = fields.Integer('Color Index')
    scrap_date = fields.Date('Scrap Date')
    maintenance_ids = fields.One2many('maintenance.request', 'equipment_id')
    maintenance_count = fields.Integer(compute='_compute_maintenance_count',
                                       string="Maintenance",
                                       store=True)
    maintenance_open_count = fields.Integer(
        compute='_compute_maintenance_count',
        string="Current Maintenance",
        store=True)
    period = fields.Integer('Days between each preventive maintenance')
    next_action_date = fields.Date(
        compute='_compute_next_maintenance',
        string='Date of the next preventive maintenance',
        store=True)
    maintenance_team_id = fields.Many2one('maintenance.team',
                                          string='Maintenance Team')
    maintenance_duration = fields.Float(help="Maintenance Duration in hours.")

    @api.depends('period', 'maintenance_ids.request_date',
                 'maintenance_ids.close_date')
    def _compute_next_maintenance(self):

        date_now = fields.Date.context_today(self)
        for equipment in self.filtered(lambda x: x.period > 0):
            next_maintenance_todo = self.env['maintenance.request'].search(
                [('equipment_id', '=', equipment.id),
                 ('maintenance_type', '=', 'preventive'),
                 ('stage_id.done', '!=', True), ('close_date', '=', False)],
                order="request_date asc",
                limit=1)
            last_maintenance_done = self.env['maintenance.request'].search(
                [('equipment_id', '=', equipment.id),
                 ('maintenance_type', '=', 'preventive'),
                 ('stage_id.done', '=', True), ('close_date', '!=', False)],
                order="close_date desc",
                limit=1)
            if next_maintenance_todo and last_maintenance_done:
                next_date = next_maintenance_todo.request_date
                date_gap = fields.Date.from_string(
                    next_maintenance_todo.request_date
                ) - fields.Date.from_string(last_maintenance_done.close_date)
                # If the gap between the last_maintenance_done and the next_maintenance_todo one is bigger than 2 times the period and next request is in the future
                # We use 2 times the period to avoid creation too closed request from a manually one created
                if date_gap > timedelta(0) and date_gap > timedelta(
                        days=equipment.period) * 2 and fields.Date.from_string(
                            next_maintenance_todo.request_date
                        ) > fields.Date.from_string(date_now):
                    # If the new date still in the past, we set it for today
                    if fields.Date.from_string(
                            last_maintenance_done.close_date) + timedelta(
                                days=equipment.period
                            ) < fields.Date.from_string(date_now):
                        next_date = date_now
                    else:
                        next_date = fields.Date.to_string(
                            fields.Date.from_string(
                                last_maintenance_done.close_date) +
                            timedelta(days=equipment.period))
            elif next_maintenance_todo:
                next_date = next_maintenance_todo.request_date
                date_gap = fields.Date.from_string(
                    next_maintenance_todo.request_date
                ) - fields.Date.from_string(date_now)
                # If next maintenance to do is in the future, and in more than 2 times the period, we insert an new request
                # We use 2 times the period to avoid creation too closed request from a manually one created
                if date_gap > timedelta(0) and date_gap > timedelta(
                        days=equipment.period) * 2:
                    next_date = fields.Date.to_string(
                        fields.Date.from_string(date_now) +
                        timedelta(days=equipment.period))
            elif last_maintenance_done:
                next_date = fields.Date.from_string(
                    last_maintenance_done.close_date) + timedelta(
                        days=equipment.period)
                # If when we add the period to the last maintenance done and we still in past, we plan it for today
                if next_date < fields.Date.from_string(date_now):
                    next_date = date_now
            else:
                next_date = fields.Date.to_string(
                    fields.Date.from_string(date_now) +
                    timedelta(days=equipment.period))

            equipment.next_action_date = next_date

    @api.one
    @api.depends('maintenance_ids.stage_id.done')
    def _compute_maintenance_count(self):
        self.maintenance_count = len(self.maintenance_ids)
        self.maintenance_open_count = len(
            self.maintenance_ids.filtered(lambda x: not x.stage_id.done))

    @api.onchange('category_id')
    def _onchange_category_id(self):
        self.technician_user_id = self.category_id.technician_user_id

    _sql_constraints = [
        ('serial_no', 'unique(serial_no)',
         "Another asset already exists with this serial number!"),
    ]

    @api.model
    def create(self, vals):
        equipment = super(MaintenanceEquipment, self).create(vals)
        if equipment.owner_user_id:
            equipment.message_subscribe_users(
                user_ids=[equipment.owner_user_id.id])
        return equipment

    @api.multi
    def write(self, vals):
        if vals.get('owner_user_id'):
            self.message_subscribe_users(user_ids=[vals['owner_user_id']])
        return super(MaintenanceEquipment, self).write(vals)

    @api.model
    def _message_get_auto_subscribe_fields(self,
                                           updated_fields,
                                           auto_follow_fields=None):
        """ mail.thread override so user_id which has no special access allowance is not
            automatically subscribed.
        """
        if auto_follow_fields is None:
            auto_follow_fields = []
        return super(MaintenanceEquipment,
                     self)._message_get_auto_subscribe_fields(
                         updated_fields, auto_follow_fields)

    @api.model
    def _read_group_category_ids(self, categories, domain, order):
        """ Read group customization in order to display all the categories in
            the kanban view, even if they are empty.
        """
        category_ids = categories._search([],
                                          order=order,
                                          access_rights_uid=SUPERUSER_ID)
        return categories.browse(category_ids)

    def _create_new_request(self, date):
        self.ensure_one()
        self.env['maintenance.request'].create({
            'name':
            _('Preventive Maintenance - %s') % self.name,
            'request_date':
            date,
            'schedule_date':
            date,
            'category_id':
            self.category_id.id,
            'equipment_id':
            self.id,
            'maintenance_type':
            'preventive',
            'owner_user_id':
            self.owner_user_id.id,
            'technician_user_id':
            self.technician_user_id.id,
            'maintenance_team_id':
            self.maintenance_team_id.id,
            'duration':
            self.maintenance_duration,
        })

    @api.model
    def _cron_generate_requests(self):
        """
            Generates maintenance request on the next_action_date or today if none exists
        """
        for equipment in self.search([('period', '>', 0)]):
            next_requests = self.env['maintenance.request'].search([
                ('stage_id.done', '=', False),
                ('equipment_id', '=', equipment.id),
                ('maintenance_type', '=', 'preventive'),
                ('request_date', '=', equipment.next_action_date)
            ])
            if not next_requests:
                equipment._create_new_request(equipment.next_action_date)
Ejemplo n.º 30
0
class PayslipReport(models.Model):
    _name = "payslip.report"
    _description = "Payslip Analysis"
    _auto = False

    name = fields.Char(readonly=True)
    date_from = fields.Date(string='Date From', readonly=True)
    date_to = fields.Date(string='Date To', readonly=True)
    year = fields.Char(size=4, readonly=True)
    month = fields.Selection([('01', 'January'), ('02', 'February'), ('03', 'March'), ('04', 'April'),
        ('05', 'May'), ('06', 'June'), ('07', 'July'), ('08', 'August'), ('09', 'September'),
        ('10', 'October'), ('11', 'November'), ('12', 'December')], readonly=True)
    day = fields.Char(size=128, readonly=True)
    state = fields.Selection([
        ('draft', 'Draft'),
        ('done', 'Done'),
        ('cancel', 'Rejected'),
    ], string='Status', readonly=True)
    employee_id = fields.Many2one('hr.employee', string='Employee', readonly=True)
    nbr = fields.Integer(string='# Payslip lines', readonly=True)
    number = fields.Char(readonly=True)
    struct_id = fields.Many2one('hr.payroll.structure', string='Structure', readonly=True)
    company_id = fields.Many2one('res.company', string='Company', readonly=True)
    paid = fields.Boolean(string='Made Payment Order ? ', readonly=True)
    total = fields.Float(readonly=True)
    category_id = fields.Many2one('hr.salary.rule.category', string='Category', readonly=True)

    @api.model_cr
    def init(self):
        drop_view_if_exists(self.env.cr, self._table)
        self.env.cr.execute("""
            create or replace view payslip_report as (
                select
                    min(l.id) as id,
                    l.name,
                    p.struct_id,
                    p.state,
                    p.date_from,
                    p.date_to,
                    p.number,
                    p.company_id,
                    p.paid,
                    l.category_id,
                    l.employee_id,
                    sum(l.total) as total,
                    to_char(p.date_from, 'YYYY') as year,
                    to_char(p.date_from, 'MM') as month,
                    to_char(p.date_from, 'YYYY-MM-DD') as day,
                    to_char(p.date_to, 'YYYY') as to_year,
                    to_char(p.date_to, 'MM') as to_month,
                    to_char(p.date_to, 'YYYY-MM-DD') as to_day,
                    1 AS nbr
                from
                    hr_payslip as p
                    left join hr_payslip_line as l on (p.id=l.slip_id)
                where
                    l.employee_id IS NOT NULL
                group by
                    p.number,l.name,p.date_from,p.date_to,p.state,p.company_id,p.paid,
                    l.employee_id,p.struct_id,l.category_id
            )
        """)