#-*- coding:utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.

from odoo import api, fields, models, _
from odoo.exceptions import UserError
from odoo.tools import float_compare, float_is_zero


class HrPayslipLine(models.Model):
    _inherit = 'hr.payslip.line'

    def _get_partner_id(self, credit_account):
        """
        Get partner_id of slip line to use in account_move_line
        """
        # use partner of salary rule or fallback on employee's address
        register_partner_id = self.salary_rule_id.register_id.partner_id
        partner_id = register_partner_id.id or self.slip_id.employee_id.address_home_id.id
        if credit_account:
            if register_partner_id or self.salary_rule_id.account_credit.internal_type in ('receivable', 'payable'):
                return partner_id
        else:
            if register_partner_id or self.salary_rule_id.account_debit.internal_type in ('receivable', 'payable'):
                return partner_id
        return False

class HrPayslip(models.Model):
    _inherit = 'hr.payslip'

    date = fields.Date('Date Account', states={'draft': [('readonly', False)]}, readonly=True,
        help="Keep empty to use the period of the validation(Payslip) date.")
    journal_id = fields.Many2one('account.journal', 'Salary Journal', readonly=True, required=True,
        states={'draft': [('readonly', False)]}, default=lambda self: self.env['account.journal'].search([('type', '=', 'general')], limit=1))
    move_id = fields.Many2one('account.move', 'Accounting Entry', readonly=True, copy=False)

    @api.model
    def create(self, vals):
        if 'journal_id' in self.env.context:
            vals['journal_id'] = self.env.context.get('journal_id')
        return super(HrPayslip, self).create(vals)

    @api.onchange('contract_id')
    def onchange_contract(self):
        super(HrPayslip, self).onchange_contract()
        self.journal_id = self.contract_id.journal_id.id or (not self.contract_id and self.default_get(['journal_id'])['journal_id'])

    @api.multi
    def action_payslip_cancel(self):
        moves = self.mapped('move_id')
        moves.filtered(lambda x: x.state == 'posted').button_cancel()
        moves.unlink()
        return super(HrPayslip, self).action_payslip_cancel()

    @api.multi
    def action_payslip_done(self):
        res = super(HrPayslip, self).action_payslip_done()

        for slip in self:
            line_ids = []
            debit_sum = 0.0
            credit_sum = 0.0
            date = slip.date or slip.date_to
            currency = slip.company_id.currency_id or slip.journal_id.company_id.currency_id

            name = _('Payslip of %s') % (slip.employee_id.name)
            move_dict = {
                'narration': name,
                'ref': slip.number,
                'journal_id': slip.journal_id.id,
                'date': date,
            }
            for line in slip.details_by_salary_rule_category:
                amount = currency.round(slip.credit_note and -line.total or line.total)
                if currency.is_zero(amount):
                    continue
                debit_account_id = line.salary_rule_id.account_debit.id
                credit_account_id = line.salary_rule_id.account_credit.id

                if debit_account_id:
                    debit_line = (0, 0, {
                        'name': line.name,
                        'partner_id': line._get_partner_id(credit_account=False),
                        'account_id': debit_account_id,
                        'journal_id': slip.journal_id.id,
                        'date': date,
                        'debit': amount > 0.0 and amount or 0.0,
                        'credit': amount < 0.0 and -amount or 0.0,
                        'analytic_account_id': line.salary_rule_id.analytic_account_id.id or slip.contract_id.analytic_account_id.id,
                        'tax_line_id': line.salary_rule_id.account_tax_id.id,
                    })
                    line_ids.append(debit_line)
                    debit_sum += debit_line[2]['debit'] - debit_line[2]['credit']

                if credit_account_id:
                    credit_line = (0, 0, {
                        'name': line.name,
                        'partner_id': line._get_partner_id(credit_account=True),
                        'account_id': credit_account_id,
                        'journal_id': slip.journal_id.id,
                        'date': date,
                        'debit': amount < 0.0 and -amount or 0.0,
                        'credit': amount > 0.0 and amount or 0.0,
                        'analytic_account_id': line.salary_rule_id.analytic_account_id.id or slip.contract_id.analytic_account_id.id,
                        'tax_line_id': line.salary_rule_id.account_tax_id.id,
                    })
                    line_ids.append(credit_line)
                    credit_sum += credit_line[2]['credit'] - credit_line[2]['debit']

            if currency.compare_amounts(credit_sum, debit_sum) == -1:
                acc_id = slip.journal_id.default_credit_account_id.id
                if not acc_id:
                    raise UserError(_('The Expense Journal "%s" has not properly configured the Credit Account!') % (slip.journal_id.name))
                adjust_credit = (0, 0, {
                    'name': _('Adjustment Entry'),
                    'partner_id': False,
                    'account_id': acc_id,
                    'journal_id': slip.journal_id.id,
                    'date': date,
                    'debit': 0.0,
                    'credit': currency.round(debit_sum - credit_sum),
                })
                line_ids.append(adjust_credit)

            elif currency.compare_amounts(debit_sum, credit_sum) == -1:
                acc_id = slip.journal_id.default_debit_account_id.id
                if not acc_id:
                    raise UserError(_('The Expense Journal "%s" has not properly configured the Debit Account!') % (slip.journal_id.name))
                adjust_debit = (0, 0, {
                    'name': _('Adjustment Entry'),
                    'partner_id': False,
                    'account_id': acc_id,
                    'journal_id': slip.journal_id.id,
                    'date': date,
                    'debit': currency.round(credit_sum - debit_sum),
                    'credit': 0.0,
                })
                line_ids.append(adjust_debit)
            move_dict['line_ids'] = line_ids
            move = self.env['account.move'].create(move_dict)
            slip.write({'move_id': move.id, 'date': date})
            move.post()
        return res


class HrSalaryRule(models.Model):
    _inherit = 'hr.salary.rule'

    analytic_account_id = fields.Many2one('account.analytic.account', 'Analytic Account')
    account_tax_id = fields.Many2one('account.tax', 'Tax')
    account_debit = fields.Many2one('account.account', 'Debit Account', domain=[('deprecated', '=', False)])
    account_credit = fields.Many2one('account.account', 'Credit Account', domain=[('deprecated', '=', False)])

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')

class HrPayslipRun(models.Model):
    _inherit = 'hr.payslip.run'

    journal_id = fields.Many2one('account.journal', 'Salary Journal', states={'draft': [('readonly', False)]}, readonly=True,
        required=True, default=lambda self: self.env['account.journal'].search([('type', '=', 'general')], limit=1))

[((30, 11, 31, 77), 'odoo.fields.Date', 'fields.Date', (), '', False, 'from odoo import api, fields, models, _\n'), ((34, 14, 34, 92), 'odoo.fields.Many2one', 'fields.Many2one', (), '', False, 'from odoo import api, fields, models, _\n'), ((42, 5, 42, 32), 'odoo.api.onchange', 'api.onchange', ({(42, 18, 42, 31): '"""contract_id"""'}, {}), "('contract_id')", False, 'from odoo import api, fields, models, _\n'), ((148, 26, 148, 89), 'odoo.fields.Many2one', 'fields.Many2one', ({(148, 42, 148, 68): '"""account.analytic.account"""', (148, 70, 148, 88): '"""Analytic Account"""'}, {}), "('account.analytic.account', 'Analytic Account')", False, 'from odoo import api, fields, models, _\n'), ((149, 21, 149, 58), 'odoo.fields.Many2one', 'fields.Many2one', ({(149, 37, 149, 50): '"""account.tax"""', (149, 52, 149, 57): '"""Tax"""'}, {}), "('account.tax', 'Tax')", False, 'from odoo import api, fields, models, _\n'), ((150, 20, 150, 108), 'odoo.fields.Many2one', 'fields.Many2one', (), '', False, 'from odoo import api, fields, models, _\n'), ((151, 21, 151, 110), 'odoo.fields.Many2one', 'fields.Many2one', (), '', False, 'from odoo import api, fields, models, _\n'), ((157, 26, 157, 89), 'odoo.fields.Many2one', 'fields.Many2one', ({(157, 42, 157, 68): '"""account.analytic.account"""', (157, 70, 157, 88): '"""Analytic Account"""'}, {}), "('account.analytic.account', 'Analytic Account')", False, 'from odoo import api, fields, models, _\n'), ((158, 17, 158, 69), 'odoo.fields.Many2one', 'fields.Many2one', ({(158, 33, 158, 50): '"""account.journal"""', (158, 52, 158, 68): '"""Salary Journal"""'}, {}), "('account.journal', 'Salary Journal')", False, 'from odoo import api, fields, models, _\n'), ((65, 19, 65, 37), 'odoo._', '_', ({(65, 21, 65, 36): '"""Payslip of %s"""'}, {}), "('Payslip of %s')", False, 'from odoo import api, fields, models, _\n'), ((114, 28, 114, 49), 'odoo._', '_', ({(114, 30, 114, 48): '"""Adjustment Entry"""'}, {}), "('Adjustment Entry')", False, 'from odoo import api, fields, models, _\n'), ((112, 36, 112, 113), 'odoo._', '_', ({(112, 38, 112, 112): '"""The Expense Journal "%s" has not properly configured the Credit Account!"""'}, {}), '(\'The Expense Journal "%s" has not properly configured the Credit Account!\')', False, 'from odoo import api, fields, models, _\n'), ((129, 28, 129, 49), 'odoo._', '_', ({(129, 30, 129, 48): '"""Adjustment Entry"""'}, {}), "('Adjustment Entry')", False, 'from odoo import api, fields, models, _\n'), ((127, 36, 127, 112), 'odoo._', '_', ({(127, 38, 127, 111): '"""The Expense Journal "%s" has not properly configured the Debit Account!"""'}, {}), '(\'The Expense Journal "%s" has not properly configured the Debit Account!\')', False, 'from odoo import api, fields, models, _\n')]