1052 lines
43 KiB
Python
1052 lines
43 KiB
Python
# -*- coding: utf-8 -*-
|
|
"""DN Accounting — fiscal year closing and period locking.
|
|
|
|
Independent implementation for Odoo 20 Community, LGPL-3.
|
|
|
|
Community already ships the lock date fields on ``res.company``
|
|
(``fiscalyear_lock_date``, ``tax_lock_date``, ``sale_lock_date``,
|
|
``purchase_lock_date``, ``hard_lock_date``). What community does *not* ship is
|
|
the closing entry that transfers the profit and loss balance to retained
|
|
earnings. That is what this module adds, together with a guided wizard and a
|
|
lock-date overview.
|
|
"""
|
|
import logging
|
|
from datetime import date, timedelta
|
|
|
|
from odoo import _, api, fields, models
|
|
from odoo.exceptions import UserError
|
|
from odoo.fields import Domain
|
|
from odoo.tools import date_utils, float_is_zero
|
|
|
|
_logger = logging.getLogger(__name__)
|
|
|
|
PL_GROUPS = ("income", "income_other", "expense", "expense_other",
|
|
"expense_depreciation", "expense_direct_cost")
|
|
|
|
#: The four lock dates a user exception may be granted on. Kept in sync with
|
|
#: ``res.company`` and with ``account.lock_exception``; the hard lock date is
|
|
#: deliberately absent, it cannot be excepted from.
|
|
SOFT_LOCK_DATE_FIELDS = (
|
|
"fiscalyear_lock_date",
|
|
"tax_lock_date",
|
|
"sale_lock_date",
|
|
"purchase_lock_date",
|
|
)
|
|
|
|
#: Every lock date, soft ones first. ``res.company.write`` validates whatever
|
|
#: is present here, so the hard lock is included even though it has no
|
|
#: exception mechanism.
|
|
LOCK_DATE_FIELDS = SOFT_LOCK_DATE_FIELDS + ("hard_lock_date",)
|
|
|
|
#: Human labels, matching the enterprise wording word for word so the screen
|
|
#: reads the same to anyone who has used the standard product.
|
|
LOCK_DATE_LABELS = {
|
|
"fiscalyear_lock_date": "Lock Everything",
|
|
"tax_lock_date": "Lock Tax Return",
|
|
"sale_lock_date": "Lock Sales",
|
|
"purchase_lock_date": "Lock Purchases",
|
|
"hard_lock_date": "Hard Lock",
|
|
}
|
|
|
|
EXCEPTION_DURATIONS = {
|
|
"5min": timedelta(minutes=5),
|
|
"15min": timedelta(minutes=15),
|
|
"1h": timedelta(hours=1),
|
|
"24h": timedelta(hours=24),
|
|
# "forever" has no end datetime at all.
|
|
}
|
|
|
|
|
|
class AccountMove(models.Model):
|
|
"""Tag the entries generated by this module so they can be found again."""
|
|
|
|
_inherit = "account.move"
|
|
|
|
dn_is_closing_entry = fields.Boolean(
|
|
string="Year-End Closing Entry", readonly=True, copy=False,
|
|
help="Entry generated by the year-end closing wizard.",
|
|
)
|
|
dn_closing_fiscal_year_id = fields.Many2one(
|
|
"dn.fiscal.year", string="Fiscal Year", readonly=True, copy=False,
|
|
ondelete="set null",
|
|
)
|
|
|
|
|
|
class DnFiscalYearClosingLine(models.TransientModel):
|
|
"""One preview row: a profit and loss account and the amount to close."""
|
|
|
|
_name = "dn.fiscal.year.closing.line"
|
|
_description = "DN Fiscal Year Closing Preview Line"
|
|
_order = "account_code"
|
|
|
|
wizard_id = fields.Many2one(
|
|
"dn.fiscal.year.closing", required=True, ondelete="cascade",
|
|
)
|
|
currency_id = fields.Many2one(related="wizard_id.currency_id")
|
|
account_id = fields.Many2one("account.account", string="Account", readonly=True)
|
|
account_code = fields.Char(related="account_id.code", string="Code")
|
|
account_name = fields.Char(related="account_id.name", string="Account Name")
|
|
balance = fields.Monetary(string="Current Balance", readonly=True)
|
|
closing_amount = fields.Monetary(string="Closing Amount", readonly=True)
|
|
|
|
|
|
class DnFiscalYearClosing(models.TransientModel):
|
|
"""Generate the year-end entry that zeroes out profit and loss accounts."""
|
|
|
|
_name = "dn.fiscal.year.closing"
|
|
_description = "DN Fiscal Year Closing"
|
|
|
|
company_id = fields.Many2one(
|
|
"res.company", required=True, default=lambda self: self.env.company,
|
|
)
|
|
currency_id = fields.Many2one(related="company_id.currency_id")
|
|
date_from = fields.Date(string="Fiscal Year Start", required=True)
|
|
date_to = fields.Date(string="Fiscal Year End", required=True)
|
|
journal_id = fields.Many2one(
|
|
"account.journal", string="Closing Journal", required=True,
|
|
domain="[('type', '=', 'general'), ('company_id', '=', company_id)]",
|
|
)
|
|
retained_earnings_account_id = fields.Many2one(
|
|
"account.account", string="Retained Earnings Account", required=True,
|
|
domain="[('account_type', 'in', ['equity', 'equity_unaffected', 'equity_retained']), ('company_ids', 'in', company_id)]",
|
|
)
|
|
fiscal_year_id = fields.Many2one(
|
|
"dn.fiscal.year", string="Fiscal Year Record",
|
|
help="Optional. On success the fiscal year is flagged as closed and "
|
|
"linked to this closing entry.",
|
|
)
|
|
post_move = fields.Boolean(string="Post Immediately", default=True)
|
|
lock_after_close = fields.Boolean(
|
|
string="Lock the Period After Closing",
|
|
help="Move the general lock date to the fiscal year end once the entry "
|
|
"is posted, so nothing else can be booked into the period.",
|
|
)
|
|
move_id = fields.Many2one("account.move", string="Closing Entry", readonly=True)
|
|
amount = fields.Monetary(string="Period Result", compute="_compute_amount")
|
|
line_count = fields.Integer(string="P&L Accounts", compute="_compute_amount")
|
|
preview_line_ids = fields.One2many(
|
|
"dn.fiscal.year.closing.line", "wizard_id", string="Closing Details",
|
|
readonly=True,
|
|
)
|
|
|
|
# ------------------------------------------------------------------ setup
|
|
@api.onchange("company_id")
|
|
def _onchange_company(self):
|
|
if self.company_id:
|
|
fiscal = self.company_id.compute_fiscalyear_dates(
|
|
fields.Date.context_today(self)
|
|
)
|
|
self.date_from = fiscal["date_from"]
|
|
self.date_to = fiscal["date_to"]
|
|
self.journal_id = self.env["account.journal"].search([
|
|
("type", "=", "general"),
|
|
("company_id", "=", self.company_id.id),
|
|
], limit=1)
|
|
self.retained_earnings_account_id = self._default_retained_account()
|
|
|
|
def _default_retained_account(self):
|
|
return self.env["account.account"].search([
|
|
("company_ids", "in", self.company_id.id),
|
|
("account_type", "=", "equity_unaffected"),
|
|
], limit=1)
|
|
|
|
# ------------------------------------------------------------- calculation
|
|
@api.depends("date_from", "date_to", "company_id")
|
|
def _compute_amount(self):
|
|
for wizard in self:
|
|
balances = wizard._get_pl_balances()
|
|
# `amount` reads as the period result in the usual accounting
|
|
# sense: positive for a profit. Balances are debit-positive, so a
|
|
# profit shows up as a negative sum and has to be flipped.
|
|
wizard.amount = -sum(balances.values())
|
|
wizard.line_count = len(balances)
|
|
|
|
def _get_pl_balances(self):
|
|
"""Return {account_id: balance} for profit and loss accounts."""
|
|
self.ensure_one()
|
|
domain = [
|
|
("company_id", "=", self.company_id.id),
|
|
("parent_state", "=", "posted"),
|
|
("display_type", "not in", ["line_section", "line_note", "line_subsection"]),
|
|
("account_id.account_type", "in", list(PL_GROUPS)),
|
|
]
|
|
if self.date_from:
|
|
domain.append(("date", ">=", self.date_from))
|
|
if self.date_to:
|
|
domain.append(("date", "<=", self.date_to))
|
|
groups = self.env["account.move.line"]._read_group(
|
|
domain, groupby=["account_id"], aggregates=["balance:sum"],
|
|
)
|
|
return {
|
|
account.id: balance
|
|
for account, balance in groups
|
|
if not float_is_zero(balance, precision_rounding=self.currency_id.rounding)
|
|
}
|
|
|
|
def _get_fiscal_lock_date(self):
|
|
self.ensure_one()
|
|
return self.company_id._get_user_fiscal_lock_date(self.journal_id)
|
|
|
|
def _find_existing_closing(self):
|
|
"""Return an already generated closing entry for this period, if any."""
|
|
self.ensure_one()
|
|
return self.env["account.move"].search([
|
|
("dn_is_closing_entry", "=", True),
|
|
("company_id", "=", self.company_id.id),
|
|
("date", "=", self.date_to),
|
|
("state", "!=", "cancel"),
|
|
], limit=1)
|
|
|
|
# ---------------------------------------------------------------- actions
|
|
def _refresh_preview(self):
|
|
"""Rebuild the preview rows so the user can see what will be closed."""
|
|
self.ensure_one()
|
|
self.preview_line_ids.unlink()
|
|
balances = self._get_pl_balances()
|
|
Account = self.env["account.account"]
|
|
rows = sorted(
|
|
balances.items(),
|
|
key=lambda kv: Account.browse(kv[0]).code or "",
|
|
)
|
|
commands = [(0, 0, {
|
|
"wizard_id": self.id,
|
|
"account_id": account_id,
|
|
"balance": balance,
|
|
"closing_amount": -balance,
|
|
}) for account_id, balance in rows]
|
|
if commands:
|
|
self.env["dn.fiscal.year.closing.line"].create([
|
|
dict(cmd[2]) for cmd in commands
|
|
])
|
|
return len(rows)
|
|
|
|
def action_preview(self):
|
|
"""Refresh the preview rows and reload the wizard."""
|
|
self.ensure_one()
|
|
count = self._refresh_preview()
|
|
if not count:
|
|
raise UserError(_("This period has no profit and loss balance, "
|
|
"there is nothing to close."))
|
|
return {
|
|
"type": "ir.actions.act_window",
|
|
"name": _("Year-End Closing"),
|
|
"res_model": "dn.fiscal.year.closing",
|
|
"res_id": self.id,
|
|
"view_mode": "form",
|
|
"target": "current",
|
|
}
|
|
|
|
def action_close(self):
|
|
"""Create (and optionally post) the closing entry."""
|
|
self.ensure_one()
|
|
if self.move_id:
|
|
raise UserError(_("This wizard has already generated a closing entry."))
|
|
|
|
existing = self._find_existing_closing()
|
|
if existing:
|
|
raise UserError(_(
|
|
"A closing entry already exists for this fiscal year: %s. "
|
|
"Reverse it first if you need to close the period again.",
|
|
existing.display_name,
|
|
))
|
|
|
|
lock_date = self._get_fiscal_lock_date()
|
|
if self.date_to <= lock_date:
|
|
raise UserError(_(
|
|
"The fiscal year ends on %(to)s, which is already inside the "
|
|
"locked period (locked up to %(lock)s). The system would move "
|
|
"the entry past the lock date and the profit and loss accounts "
|
|
"would not be cleared. Release the lock date first.",
|
|
to=self.date_to, lock=lock_date,
|
|
))
|
|
|
|
balances = self._get_pl_balances()
|
|
if not balances:
|
|
raise UserError(_("This period has no profit and loss balance, "
|
|
"there is nothing to close."))
|
|
|
|
label = _("Year-end closing %s", self.date_to)
|
|
line_vals = []
|
|
total = 0.0
|
|
for account_id, balance in balances.items():
|
|
# Reverse the balance so the account ends the year at zero.
|
|
line_vals.append((0, 0, {
|
|
"account_id": account_id,
|
|
"name": label,
|
|
"balance": -balance,
|
|
"company_id": self.company_id.id,
|
|
}))
|
|
total += balance
|
|
line_vals.append((0, 0, {
|
|
"account_id": self.retained_earnings_account_id.id,
|
|
"name": label,
|
|
"balance": total,
|
|
"company_id": self.company_id.id,
|
|
}))
|
|
|
|
move = self.env["account.move"].create({
|
|
"journal_id": self.journal_id.id,
|
|
"date": self.date_to,
|
|
"ref": _("Year-end closing %(from)s — %(to)s",
|
|
**{"from": self.date_from, "to": self.date_to}),
|
|
"company_id": self.company_id.id,
|
|
"dn_is_closing_entry": True,
|
|
"dn_closing_fiscal_year_id": self.fiscal_year_id.id or False,
|
|
"line_ids": line_vals,
|
|
})
|
|
if self.post_move:
|
|
move.action_post()
|
|
if move.state == "posted" and move.date != self.date_to:
|
|
# Posting silently moves an entry out of a locked period. We
|
|
# guard against it above, but never leave a mis-dated closing
|
|
# entry behind if some other lock slipped in between.
|
|
move.button_draft()
|
|
move.unlink()
|
|
raise UserError(_(
|
|
"The closing entry was moved to %s by the system, so this "
|
|
"run has been cancelled. Check the lock dates and retry.",
|
|
move.date,
|
|
))
|
|
|
|
self.move_id = move
|
|
if self.fiscal_year_id:
|
|
self.fiscal_year_id.write({
|
|
"state": "closed",
|
|
"closing_move_id": move.id,
|
|
})
|
|
if self.lock_after_close and (not lock_date or lock_date < self.date_to):
|
|
self.company_id.write({"fiscalyear_lock_date": self.date_to})
|
|
|
|
return {
|
|
"type": "ir.actions.act_window",
|
|
"name": _("Closing Entry"),
|
|
"res_model": "account.move",
|
|
"res_id": move.id,
|
|
"view_mode": "form",
|
|
"target": "current",
|
|
}
|
|
|
|
|
|
class DnLockDateWizard(models.TransientModel):
|
|
"""Change the lock dates, with time-boxed exceptions.
|
|
|
|
Community already ships the five lock date fields on ``res.company`` and
|
|
the ``account.lock_exception`` model that records temporary releases, but
|
|
it ships no screen to drive them: the ``account.change.lock.date`` wizard
|
|
lives in the enterprise ``account_accountant`` module. This is an
|
|
independent implementation of that screen, with the same behaviour:
|
|
|
|
* Setting a lock date *forward* is a plain write on the company.
|
|
* Setting it *backward* — or clearing it — is only possible through an
|
|
exception, because silently unlocking a closed period would defeat the
|
|
point of having locked it. The user says who the exception is for
|
|
(themselves or everyone), for how long, and why.
|
|
* "Everyone, forever" is special-cased: it is indistinguishable from a
|
|
normal lock date change, so no exception record is created.
|
|
* The hard lock date can never move backwards and has no exceptions.
|
|
|
|
All of the arithmetic on the exception lives in
|
|
``account.lock_exception``; this wizard only decides *whether* one is
|
|
needed and *what* it should contain.
|
|
"""
|
|
|
|
_name = "dn.lock.date.wizard"
|
|
_description = "Change Lock Date"
|
|
|
|
company_id = fields.Many2one(
|
|
"res.company", required=True, readonly=True,
|
|
default=lambda self: self.env.company,
|
|
)
|
|
|
|
# -------------------------------------------------------- the lock dates
|
|
# Each soft lock date comes with four companions:
|
|
# <field>_for_me / <field>_for_everyone the effective date granted by
|
|
# the tightest active exception
|
|
# min_<field>_exception_{for_me,for_everyone}_id
|
|
# that very exception record, so
|
|
# the view can offer a Revoke
|
|
# link and the user can inspect
|
|
# its reason and expiry
|
|
fiscalyear_lock_date = fields.Date(
|
|
string="Lock Everything",
|
|
default=lambda self: self.env.company.fiscalyear_lock_date,
|
|
help="Any entry up to and including that date will be postponed to a "
|
|
"later time, in accordance with its journal's sequence.",
|
|
)
|
|
fiscalyear_lock_date_for_me = fields.Date(
|
|
string="Lock Everything For Me", compute="_compute_lock_date_exceptions",
|
|
)
|
|
fiscalyear_lock_date_for_everyone = fields.Date(
|
|
string="Lock Everything For Everyone", compute="_compute_lock_date_exceptions",
|
|
)
|
|
min_fiscalyear_lock_date_exception_for_me_id = fields.Many2one(
|
|
"account.lock_exception", compute="_compute_lock_date_exceptions",
|
|
)
|
|
min_fiscalyear_lock_date_exception_for_everyone_id = fields.Many2one(
|
|
"account.lock_exception", compute="_compute_lock_date_exceptions",
|
|
)
|
|
|
|
tax_lock_date = fields.Date(
|
|
string="Lock Tax Return",
|
|
default=lambda self: self.env.company.tax_lock_date,
|
|
help="Any entry with taxes up to and including that date will be "
|
|
"postponed to a later time, in accordance with its journal's "
|
|
"sequence. The tax lock date is automatically set when the tax "
|
|
"closing entry is posted.",
|
|
)
|
|
tax_lock_date_for_me = fields.Date(
|
|
string="Lock Tax Return For Me", compute="_compute_lock_date_exceptions",
|
|
)
|
|
tax_lock_date_for_everyone = fields.Date(
|
|
string="Lock Tax Return For Everyone", compute="_compute_lock_date_exceptions",
|
|
)
|
|
min_tax_lock_date_exception_for_me_id = fields.Many2one(
|
|
"account.lock_exception", compute="_compute_lock_date_exceptions",
|
|
)
|
|
min_tax_lock_date_exception_for_everyone_id = fields.Many2one(
|
|
"account.lock_exception", compute="_compute_lock_date_exceptions",
|
|
)
|
|
|
|
sale_lock_date = fields.Date(
|
|
string="Lock Sales",
|
|
default=lambda self: self.env.company.sale_lock_date,
|
|
help="Any sales entry prior to and including this date will be "
|
|
"postponed to a later date, in accordance with its journal's "
|
|
"sequence.",
|
|
)
|
|
sale_lock_date_for_me = fields.Date(
|
|
string="Lock Sales For Me", compute="_compute_lock_date_exceptions",
|
|
)
|
|
sale_lock_date_for_everyone = fields.Date(
|
|
string="Lock Sales For Everyone", compute="_compute_lock_date_exceptions",
|
|
)
|
|
min_sale_lock_date_exception_for_me_id = fields.Many2one(
|
|
"account.lock_exception", compute="_compute_lock_date_exceptions",
|
|
)
|
|
min_sale_lock_date_exception_for_everyone_id = fields.Many2one(
|
|
"account.lock_exception", compute="_compute_lock_date_exceptions",
|
|
)
|
|
|
|
purchase_lock_date = fields.Date(
|
|
string="Lock Purchases",
|
|
default=lambda self: self.env.company.purchase_lock_date,
|
|
help="Any purchase entry prior to and including this date will be "
|
|
"postponed to a later date, in accordance with its journal's "
|
|
"sequence.",
|
|
)
|
|
purchase_lock_date_for_me = fields.Date(
|
|
string="Lock Purchases For Me", compute="_compute_lock_date_exceptions",
|
|
)
|
|
purchase_lock_date_for_everyone = fields.Date(
|
|
string="Lock Purchases For Everyone", compute="_compute_lock_date_exceptions",
|
|
)
|
|
min_purchase_lock_date_exception_for_me_id = fields.Many2one(
|
|
"account.lock_exception", compute="_compute_lock_date_exceptions",
|
|
)
|
|
min_purchase_lock_date_exception_for_everyone_id = fields.Many2one(
|
|
"account.lock_exception", compute="_compute_lock_date_exceptions",
|
|
)
|
|
|
|
hard_lock_date = fields.Date(
|
|
string="Hard Lock",
|
|
default=lambda self: self.env.company.hard_lock_date,
|
|
help="Any entry up to and including that date will be postponed to a "
|
|
"later time, in accordance with its journal sequence. This lock "
|
|
"date is irreversible and does not allow any exception.",
|
|
)
|
|
current_hard_lock_date = fields.Date(
|
|
string="Current Hard Lock", related="company_id.hard_lock_date",
|
|
readonly=True,
|
|
)
|
|
|
|
# ----------------------------------------------------- the exception form
|
|
exception_needed_fields = fields.Char(
|
|
# Comma separated list of the lock date fields the user is trying to
|
|
# move backwards. The view uses it to highlight them and to decide
|
|
# whether the exception block is shown at all.
|
|
compute="_compute_exception_needed_fields",
|
|
)
|
|
exception_applies_to = fields.Selection(
|
|
string="Exception applies",
|
|
selection=[("me", "for me"), ("everyone", "for everyone")],
|
|
default="me", required=True,
|
|
)
|
|
exception_duration = fields.Selection(
|
|
string="Exception Duration",
|
|
selection=[
|
|
("5min", "for 5 minutes"),
|
|
("15min", "for 15 minutes"),
|
|
("1h", "for 1 hour"),
|
|
("24h", "for 24 hours"),
|
|
("forever", "forever"),
|
|
],
|
|
default="5min", required=True,
|
|
)
|
|
exception_reason = fields.Char(string="Exception Reason")
|
|
|
|
# ------------------------------------------------------------- warnings
|
|
show_draft_entries_warning = fields.Boolean(
|
|
string="Show Draft Entries Warning",
|
|
compute="_compute_show_draft_entries_warning",
|
|
)
|
|
show_posted_tax_closing_warning = fields.Boolean(
|
|
compute="_compute_show_posted_tax_closing_warning",
|
|
)
|
|
|
|
# A convenience read-out of what is still open in the period. Not part of
|
|
# the enterprise wizard, kept because the closing workflow in this module
|
|
# needs it: locking a period whose profit and loss balance has not been
|
|
# closed yet means the closing entry can no longer be booked into it.
|
|
draft_move_count = fields.Integer(
|
|
string="Draft Entries Inside the Lock", compute="_compute_counts",
|
|
)
|
|
unreconciled_count = fields.Integer(
|
|
string="Unreconciled Items", compute="_compute_counts",
|
|
)
|
|
unreconciled_statement_count = fields.Integer(
|
|
string="Unreconciled Bank Transactions", compute="_compute_counts",
|
|
)
|
|
has_pl_balance = fields.Boolean(
|
|
string="Period Still Has a P&L Balance", compute="_compute_counts",
|
|
help="Locking is not recommended while a profit and loss balance "
|
|
"remains: the closing entry could not be booked into the period.",
|
|
)
|
|
|
|
# ------------------------------------------------------------- computing
|
|
@api.depends("company_id")
|
|
@api.depends_context("uid", "allowed_company_ids")
|
|
def _compute_lock_date_exceptions(self):
|
|
"""Expose the tightest active exception, per field and per audience.
|
|
|
|
``account.lock_exception`` stores one record per changed field, so a
|
|
field can carry several live exceptions at once — say one for me and
|
|
one for everyone. The effective date for a given reader is the lowest
|
|
of them (lowest = least locked), which is exactly the record the
|
|
``min_*_id`` fields point at, and exactly the one the Revoke link must
|
|
target. Picking the *minimum* rather than the latest is what the
|
|
company-level ``_get_user_lock_date`` does too, so the summary on this
|
|
screen can never claim a wider unlock than the one actually applied.
|
|
"""
|
|
Exception = self.env["account.lock_exception"]
|
|
for wizard in self:
|
|
exceptions = Exception.search(
|
|
Exception._get_active_exceptions_domain(
|
|
wizard.company_id, SOFT_LOCK_DATE_FIELDS,
|
|
)
|
|
)
|
|
for field in SOFT_LOCK_DATE_FIELDS:
|
|
field_exceptions = exceptions.filtered(
|
|
lambda e, field=field: e.lock_date_field == field
|
|
)
|
|
for_me = field_exceptions.filtered(
|
|
lambda e: e.user_id.id == self.env.user.id
|
|
)
|
|
for_everyone = field_exceptions.filtered(lambda e: not e.user_id.id)
|
|
min_for_me = (
|
|
min(for_me, key=lambda e, field=field: e[field] or date.min)
|
|
if for_me else False
|
|
)
|
|
min_for_everyone = (
|
|
min(for_everyone, key=lambda e, field=field: e[field] or date.min)
|
|
if for_everyone else False
|
|
)
|
|
wizard[f"min_{field}_exception_for_me_id"] = min_for_me
|
|
wizard[f"min_{field}_exception_for_everyone_id"] = min_for_everyone
|
|
wizard[f"{field}_for_me"] = min_for_me.lock_date if min_for_me else False
|
|
wizard[f"{field}_for_everyone"] = (
|
|
min_for_everyone.lock_date if min_for_everyone else False
|
|
)
|
|
|
|
@api.depends(*SOFT_LOCK_DATE_FIELDS)
|
|
def _compute_exception_needed_fields(self):
|
|
for wizard in self:
|
|
wizard.exception_needed_fields = ",".join(
|
|
wizard._get_changes_needing_exception()
|
|
)
|
|
|
|
def _get_draft_moves_in_locked_period_domain(self):
|
|
"""Draft entries that would sit inside the period being locked.
|
|
|
|
The domain is a union, not an intersection: an entry is a problem if
|
|
it falls before *any* of the dates the user is about to lock. The sale
|
|
and purchase dates only cover their own journal type — locking sales
|
|
up to the 30th says nothing about a purchase entry on the 28th — while
|
|
the general and hard dates cover every journal.
|
|
"""
|
|
self.ensure_one()
|
|
lock_date_domains = []
|
|
if self.hard_lock_date:
|
|
lock_date_domains.append([("date", "<=", self.hard_lock_date)])
|
|
if self.fiscalyear_lock_date:
|
|
lock_date_domains.append([("date", "<=", self.fiscalyear_lock_date)])
|
|
if self.sale_lock_date:
|
|
lock_date_domains.append([
|
|
("date", "<=", self.sale_lock_date),
|
|
("journal_id.type", "=", "sale"),
|
|
])
|
|
if self.purchase_lock_date:
|
|
lock_date_domains.append([
|
|
("date", "<=", self.purchase_lock_date),
|
|
("journal_id.type", "=", "purchase"),
|
|
])
|
|
if not lock_date_domains:
|
|
# No date is set, so nothing is being locked. An impossible domain
|
|
# reads better in the window action than "no domain" would: an
|
|
# empty domain on ``account.move`` means every draft entry in the
|
|
# database, which is the opposite of what the user asked for.
|
|
return [("id", "=", False)]
|
|
return (
|
|
Domain("company_id", "child_of", self.env.company.id)
|
|
& Domain("state", "=", "draft")
|
|
& Domain.OR(lock_date_domains)
|
|
)
|
|
|
|
@api.depends(
|
|
"fiscalyear_lock_date", "tax_lock_date", "sale_lock_date",
|
|
"purchase_lock_date", "hard_lock_date",
|
|
)
|
|
def _compute_show_draft_entries_warning(self):
|
|
for wizard in self:
|
|
wizard.show_draft_entries_warning = bool(
|
|
self.env["account.move"].search(
|
|
wizard._get_draft_moves_in_locked_period_domain(), limit=1,
|
|
)
|
|
)
|
|
|
|
def _get_posted_tax_closings_in_locked_period_domain(self):
|
|
"""Tax closings posted *after* the tax lock date.
|
|
|
|
Only meaningful on an installation that has tax returns. Community
|
|
does not ship the ``account.return`` model, so the field is probed for
|
|
rather than assumed — the warning simply never fires without it.
|
|
"""
|
|
self.ensure_one()
|
|
if "closing_return_id" not in self.env["account.move"]._fields:
|
|
# No tax-return module installed, so there is nothing to warn
|
|
# about. Probing the field rather than wrapping the whole method in
|
|
# a try/except keeps the "no domain" case explicit.
|
|
return [("id", "=", False)]
|
|
return [
|
|
("date", ">", self.tax_lock_date),
|
|
("state", "=", "posted"),
|
|
("closing_return_id", "!=", False),
|
|
]
|
|
|
|
@api.depends("tax_lock_date")
|
|
def _compute_show_posted_tax_closing_warning(self):
|
|
for wizard in self:
|
|
wizard.show_posted_tax_closing_warning = bool(
|
|
wizard.tax_lock_date
|
|
and self.env["account.move"].search_count(
|
|
wizard._get_posted_tax_closings_in_locked_period_domain()
|
|
)
|
|
)
|
|
|
|
@api.depends("company_id", "fiscalyear_lock_date")
|
|
def _compute_counts(self):
|
|
Move = self.env["account.move"]
|
|
Line = self.env["account.move.line"]
|
|
for wizard in self:
|
|
lock = wizard.fiscalyear_lock_date
|
|
company_domain = [("company_id", "=", wizard.company_id.id)]
|
|
|
|
draft_domain = company_domain + [("state", "=", "draft")]
|
|
if lock:
|
|
draft_domain.append(("date", "<=", lock))
|
|
wizard.draft_move_count = Move.search_count(draft_domain)
|
|
|
|
line_domain = company_domain + [
|
|
("account_id.reconcile", "=", True),
|
|
("reconciled", "=", False),
|
|
("parent_state", "=", "posted"),
|
|
]
|
|
if lock:
|
|
line_domain.append(("date", "<=", lock))
|
|
wizard.unreconciled_count = Line.search_count(line_domain)
|
|
|
|
st_domain = company_domain + [("is_reconciled", "=", False)]
|
|
if lock:
|
|
st_domain.append(("date", "<=", lock))
|
|
wizard.unreconciled_statement_count = self.env[
|
|
"account.bank.statement.line"
|
|
].search_count(st_domain)
|
|
|
|
pl_domain = company_domain + [
|
|
("parent_state", "=", "posted"),
|
|
("display_type", "not in",
|
|
["line_section", "line_note", "line_subsection"]),
|
|
("account_id.account_type", "in", list(PL_GROUPS)),
|
|
]
|
|
if lock:
|
|
pl_domain.append(("date", "<=", lock))
|
|
# Count the net movement, not the number of lines: once a period is
|
|
# closed its profit and loss lines still exist, they simply cancel
|
|
# out. Only a non-zero sum means something is left to close.
|
|
groups = Line._read_group(pl_domain, aggregates=["balance:sum"])
|
|
net = groups[0][0] if groups else 0.0
|
|
wizard.has_pl_balance = bool(
|
|
net and not float_is_zero(
|
|
net, precision_rounding=wizard.company_id.currency_id.rounding
|
|
)
|
|
)
|
|
|
|
# -------------------------------------------------------------- applying
|
|
def _get_changes_needing_exception(self):
|
|
"""Lock dates the user is trying to move *backwards* (or clear).
|
|
|
|
Only the soft dates: the hard lock has no exception mechanism, it is
|
|
validated and rejected outright instead.
|
|
"""
|
|
self.ensure_one()
|
|
company = self.env.company
|
|
return {
|
|
field: self[field]
|
|
for field in SOFT_LOCK_DATE_FIELDS
|
|
if company[field] and (not self[field] or self[field] < company[field])
|
|
}
|
|
|
|
def _prepare_exception_values(self):
|
|
"""Build the ``account.lock_exception`` rows this wizard would create.
|
|
|
|
Returns ``False`` when no exception is needed, which covers two very
|
|
different situations that happen to produce the same outcome:
|
|
|
|
* nothing is being moved backwards;
|
|
* the user asked for "everyone, forever" — which is not an exception
|
|
at all but an ordinary widening of the lock date, so it is written
|
|
straight onto the company like any other forward move.
|
|
"""
|
|
self.ensure_one()
|
|
changes_needing_exception = self._get_changes_needing_exception()
|
|
if not changes_needing_exception:
|
|
return False
|
|
|
|
if self.exception_applies_to == "everyone" and self.exception_duration == "forever":
|
|
return False
|
|
|
|
errors = []
|
|
if not self.exception_applies_to:
|
|
errors.append(_("You need to select who the exception applies to."))
|
|
if not self.exception_duration:
|
|
errors.append(_("You need to select a duration for the exception."))
|
|
if errors:
|
|
raise UserError("\n".join(errors))
|
|
|
|
base_values = {
|
|
"company_id": self.env.company.id,
|
|
# An exception with no user is an exception for everyone; that is
|
|
# how ``res.company._get_user_lock_date`` reads it.
|
|
"user_id": {"me": self.env.user.id, "everyone": False}[
|
|
self.exception_applies_to
|
|
],
|
|
}
|
|
|
|
duration = EXCEPTION_DURATIONS.get(self.exception_duration)
|
|
if duration:
|
|
# ``forever`` has no end datetime at all, which is also why the
|
|
# record still counts as active years later.
|
|
base_values["end_datetime"] = self.env.cr.now() + duration
|
|
if self.exception_reason:
|
|
base_values["reason"] = self.exception_reason
|
|
|
|
# One exception per changed field: the model stores a single
|
|
# ``lock_date_field`` / ``lock_date`` pair per record.
|
|
return [
|
|
{**base_values, field: value}
|
|
for field, value in changes_needing_exception.items()
|
|
]
|
|
|
|
def _prepare_lock_date_values(self, exception_vals_list=None):
|
|
"""Lock date values to write on the company, after validation.
|
|
|
|
The three rules enforced here are the ones that protect the audit
|
|
trail; everything else (unreconciled statements, draft entries) is
|
|
re-checked by ``res.company.write`` with a message that offers to show
|
|
the offending records, so it is not duplicated.
|
|
"""
|
|
self.ensure_one()
|
|
company = self.env.company
|
|
|
|
if company.hard_lock_date and (
|
|
not self.hard_lock_date or self.hard_lock_date < company.hard_lock_date
|
|
):
|
|
raise UserError(
|
|
_("It is not possible to decrease or remove the Hard Lock Date.")
|
|
)
|
|
|
|
lock_date_values = {
|
|
field: self[field]
|
|
for field in LOCK_DATE_FIELDS
|
|
if self[field] != company[field]
|
|
}
|
|
|
|
today = fields.Date.context_today(self)
|
|
for lock_date in lock_date_values.values():
|
|
if lock_date and lock_date > today:
|
|
raise UserError(_("You cannot set a Lock Date in the future."))
|
|
|
|
# A field handled by an exception keeps its company value: the
|
|
# relaxation lives in the exception record, not on the company.
|
|
if exception_vals_list:
|
|
for exception_vals in exception_vals_list:
|
|
for field in LOCK_DATE_FIELDS:
|
|
if field in exception_vals:
|
|
lock_date_values.pop(field, None)
|
|
|
|
return lock_date_values
|
|
|
|
def _get_current_period_dates(self, lock_date_field):
|
|
"""The window a lock date is about to close, as ``(date_from, date_to)``."""
|
|
self.ensure_one()
|
|
company_lock_date = self.env.company[lock_date_field]
|
|
if company_lock_date:
|
|
date_from = company_lock_date + timedelta(days=1)
|
|
else:
|
|
date_from = date_utils.get_fiscal_year(self[lock_date_field])[0]
|
|
return date_from, self[lock_date_field]
|
|
|
|
def _change_lock_date(self, lock_date_values=None):
|
|
self.ensure_one()
|
|
if lock_date_values is None:
|
|
lock_date_values = self._prepare_lock_date_values()
|
|
# ``sudo`` mirrors the enterprise wizard: the caller has already been
|
|
# checked against ``group_account_manager``, and a plain accounting
|
|
# user cannot write ``res.company`` at all.
|
|
self.env.company.sudo().write(lock_date_values)
|
|
|
|
def action_apply(self):
|
|
"""Apply the lock date changes, creating exceptions where needed."""
|
|
self.ensure_one()
|
|
if not self.env.user.has_group("account.group_account_manager"):
|
|
raise UserError(
|
|
_("Only Billing Administrators are allowed to change lock dates!")
|
|
)
|
|
exception_vals_list = self._prepare_exception_values()
|
|
lock_date_values = self._prepare_lock_date_values(
|
|
exception_vals_list=exception_vals_list
|
|
)
|
|
if exception_vals_list:
|
|
self.env["account.lock_exception"].create(exception_vals_list)
|
|
self._change_lock_date(lock_date_values)
|
|
return {"type": "ir.actions.act_window_close"}
|
|
|
|
# --------------------------------------------------------------- drill-in
|
|
def action_show_draft_moves_in_locked_period(self):
|
|
self.ensure_one()
|
|
return {
|
|
"type": "ir.actions.act_window",
|
|
"name": _("Draft Entries"),
|
|
"res_model": "account.move",
|
|
"view_mode": "list,form",
|
|
"domain": self._get_draft_moves_in_locked_period_domain(),
|
|
"search_view_id": self.env.ref("account.view_account_move_filter").id,
|
|
"views": [
|
|
(self.env.ref("account.view_move_tree_multi_edit").id, "list"),
|
|
(self.env.ref("account.view_move_form").id, "form"),
|
|
],
|
|
}
|
|
|
|
def action_show_posted_tax_closing_in_locked_period(self):
|
|
self.ensure_one()
|
|
domain = self._get_posted_tax_closings_in_locked_period_domain()
|
|
return {
|
|
"type": "ir.actions.act_window",
|
|
"name": _("Tax Closings"),
|
|
"res_model": "account.move",
|
|
"view_mode": "list,form",
|
|
"domain": domain,
|
|
}
|
|
|
|
def action_show_draft_moves(self):
|
|
"""Kept for the closing checklist, which locks by fiscal year only."""
|
|
self.ensure_one()
|
|
domain = [
|
|
("company_id", "=", self.company_id.id),
|
|
("state", "=", "draft"),
|
|
]
|
|
if self.fiscalyear_lock_date:
|
|
domain.append(("date", "<=", self.fiscalyear_lock_date))
|
|
return {
|
|
"type": "ir.actions.act_window",
|
|
"name": _("Draft Entries Inside the Lock"),
|
|
"res_model": "account.move",
|
|
"view_mode": "list,form",
|
|
"domain": domain,
|
|
}
|
|
|
|
def action_show_unreconciled(self):
|
|
self.ensure_one()
|
|
domain = [
|
|
("company_id", "=", self.company_id.id),
|
|
("account_id.reconcile", "=", True),
|
|
("reconciled", "=", False),
|
|
("parent_state", "=", "posted"),
|
|
]
|
|
if self.fiscalyear_lock_date:
|
|
domain.append(("date", "<=", self.fiscalyear_lock_date))
|
|
return {
|
|
"type": "ir.actions.act_window",
|
|
"name": _("Unreconciled Items"),
|
|
"res_model": "account.move.line",
|
|
"view_mode": "list,form",
|
|
"domain": domain,
|
|
}
|
|
|
|
def action_show_unreconciled_statements(self):
|
|
self.ensure_one()
|
|
domain = [
|
|
("company_id", "=", self.company_id.id),
|
|
("is_reconciled", "=", False),
|
|
]
|
|
if self.fiscalyear_lock_date:
|
|
domain.append(("date", "<=", self.fiscalyear_lock_date))
|
|
return {
|
|
"type": "ir.actions.act_window",
|
|
"name": _("Unreconciled Bank Transactions"),
|
|
"res_model": "account.bank.statement.line",
|
|
"view_mode": "list,form",
|
|
"domain": domain,
|
|
}
|
|
|
|
# -------------------------------------------------------------- exceptions
|
|
def action_reopen_wizard(self):
|
|
"""Re-open this same wizard, used after a side action changed data."""
|
|
return {
|
|
"type": "ir.actions.act_window",
|
|
"res_model": self._name,
|
|
"res_id": self.id,
|
|
"view_mode": "form",
|
|
"target": "new",
|
|
}
|
|
|
|
def _action_revoke_min_exception(self, exception_field):
|
|
self.ensure_one()
|
|
exception = self[exception_field]
|
|
if exception:
|
|
exception.action_revoke()
|
|
# The revoked exception disappears from the active set, so the
|
|
# "For me" / "For everyone" summary has to be recomputed before the
|
|
# dialog comes back, otherwise it keeps advertising the exception
|
|
# the user just removed.
|
|
self._compute_lock_date_exceptions()
|
|
return self.action_reopen_wizard()
|
|
|
|
def action_revoke_min_sale_lock_date_exception_for_me(self):
|
|
return self._action_revoke_min_exception(
|
|
"min_sale_lock_date_exception_for_me_id"
|
|
)
|
|
|
|
def action_revoke_min_purchase_lock_date_exception_for_me(self):
|
|
return self._action_revoke_min_exception(
|
|
"min_purchase_lock_date_exception_for_me_id"
|
|
)
|
|
|
|
def action_revoke_min_tax_lock_date_exception_for_me(self):
|
|
return self._action_revoke_min_exception(
|
|
"min_tax_lock_date_exception_for_me_id"
|
|
)
|
|
|
|
def action_revoke_min_fiscalyear_lock_date_exception_for_me(self):
|
|
return self._action_revoke_min_exception(
|
|
"min_fiscalyear_lock_date_exception_for_me_id"
|
|
)
|
|
|
|
def action_revoke_min_sale_lock_date_exception_for_everyone(self):
|
|
return self._action_revoke_min_exception(
|
|
"min_sale_lock_date_exception_for_everyone_id"
|
|
)
|
|
|
|
def action_revoke_min_purchase_lock_date_exception_for_everyone(self):
|
|
return self._action_revoke_min_exception(
|
|
"min_purchase_lock_date_exception_for_everyone_id"
|
|
)
|
|
|
|
def action_revoke_min_tax_lock_date_exception_for_everyone(self):
|
|
return self._action_revoke_min_exception(
|
|
"min_tax_lock_date_exception_for_everyone_id"
|
|
)
|
|
|
|
def action_revoke_min_fiscalyear_lock_date_exception_for_everyone(self):
|
|
return self._action_revoke_min_exception(
|
|
"min_fiscalyear_lock_date_exception_for_everyone_id"
|
|
)
|
|
|
|
|
|
class DnFiscalYear(models.Model):
|
|
"""A light fiscal year registry so users can see closed periods at a glance."""
|
|
|
|
_name = "dn.fiscal.year"
|
|
_description = "DN Fiscal Year"
|
|
_order = "date_from desc"
|
|
|
|
name = fields.Char(required=True)
|
|
date_from = fields.Date(required=True)
|
|
date_to = fields.Date(required=True)
|
|
company_id = fields.Many2one(
|
|
"res.company", required=True, default=lambda self: self.env.company,
|
|
)
|
|
state = fields.Selection([
|
|
("open", "Open"),
|
|
("closed", "Closed"),
|
|
], default="open", required=True)
|
|
closing_move_id = fields.Many2one("account.move", string="Closing Entry")
|
|
locked = fields.Boolean(compute="_compute_locked")
|
|
profit = fields.Monetary(string="Period Result", compute="_compute_profit",
|
|
currency_field="currency_id")
|
|
currency_id = fields.Many2one(related="company_id.currency_id")
|
|
|
|
_dates_check = models.Constraint(
|
|
"CHECK(date_to >= date_from)",
|
|
"The fiscal year end date must be after its start date.",
|
|
)
|
|
|
|
@api.depends("company_id.fiscalyear_lock_date", "date_to")
|
|
def _compute_locked(self):
|
|
for year in self:
|
|
lock = year.company_id.fiscalyear_lock_date
|
|
year.locked = bool(lock and year.date_to and year.date_to <= lock)
|
|
|
|
@api.depends("date_from", "date_to", "company_id", "state")
|
|
def _compute_profit(self):
|
|
"""Period result, ignoring the closing entries this module creates.
|
|
|
|
Without that exclusion the closing entry cancels the very balances it
|
|
reports, and a closed year would always show a profit of zero.
|
|
"""
|
|
for year in self:
|
|
if not (year.date_from and year.date_to):
|
|
year.profit = 0.0
|
|
continue
|
|
groups = self.env["account.move.line"]._read_group([
|
|
("company_id", "=", year.company_id.id),
|
|
("parent_state", "=", "posted"),
|
|
("display_type", "not in",
|
|
["line_section", "line_note", "line_subsection"]),
|
|
("account_id.account_type", "in", list(PL_GROUPS)),
|
|
("move_id.dn_is_closing_entry", "=", False),
|
|
("date", ">=", year.date_from),
|
|
("date", "<=", year.date_to),
|
|
], aggregates=["balance:sum"])
|
|
year.profit = -(groups[0][0] or 0.0) if groups else 0.0
|
|
|
|
def action_open_closing_wizard(self):
|
|
self.ensure_one()
|
|
return {
|
|
"type": "ir.actions.act_window",
|
|
"name": _("Year-End Closing"),
|
|
"res_model": "dn.fiscal.year.closing",
|
|
"view_mode": "form",
|
|
"target": "current",
|
|
"context": {
|
|
"default_company_id": self.company_id.id,
|
|
"default_date_from": self.date_from,
|
|
"default_date_to": self.date_to,
|
|
"default_fiscal_year_id": self.id,
|
|
},
|
|
}
|
|
|
|
def action_reopen(self):
|
|
"""Mark the year as open again, keeping the closing entry for audit."""
|
|
self.ensure_one()
|
|
self.state = "open"
|