././@PaxHeader 0000000 0000000 0000000 00000000033 00000000000 010211 x ustar 00 27 mtime=1745683276.841962
trytond_account-7.0.19/ 0000755 0001750 0001750 00000000000 15003201515 013127 5 ustar 00ced ced ././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1745683274.0
trytond_account-7.0.19/CHANGELOG 0000644 0001750 0001750 00000030213 15003201512 014335 0 ustar 00ced ced
Version 7.0.19 - 2025-04-26
---------------------------
* Bug fixes (see mercurial logs for details)
Version 7.0.18 - 2025-03-04
---------------------------
* Bug fixes (see mercurial logs for details)
Version 7.0.17 - 2025-02-01
---------------------------
* Bug fixes (see mercurial logs for details)
Version 7.0.16 - 2025-01-16
---------------------------
* Bug fixes (see mercurial logs for details)
Version 7.0.15 - 2025-01-01
---------------------------
* Bug fixes (see mercurial logs for details)
Version 7.0.14 - 2024-12-16
---------------------------
* Bug fixes (see mercurial logs for details)
Version 7.0.13 - 2024-10-18
---------------------------
* Bug fixes (see mercurial logs for details)
Version 7.0.12 - 2024-09-01
---------------------------
* Bug fixes (see mercurial logs for details)
Version 7.0.11 - 2024-07-01
---------------------------
* Bug fixes (see mercurial logs for details)
Version 7.0.10 - 2024-06-15
---------------------------
* Bug fixes (see mercurial logs for details)
Version 7.0.9 - 2024-06-02
--------------------------
* Bug fixes (see mercurial logs for details)
Version 7.0.8 - 2024-05-15
--------------------------
* Bug fixes (see mercurial logs for details)
Version 7.0.7 - 2024-05-01
--------------------------
* Bug fixes (see mercurial logs for details)
Version 7.0.6 - 2024-04-17
--------------------------
* Bug fixes (see mercurial logs for details)
Version 7.0.5 - 2024-04-04
--------------------------
* Bug fixes (see mercurial logs for details)
Version 7.0.4 - 2024-03-03
--------------------------
* Bug fixes (see mercurial logs for details)
Version 7.0.3 - 2024-01-15
--------------------------
* Bug fixes (see mercurial logs for details)
Version 7.0.2 - 2024-01-01
--------------------------
* Bug fixes (see mercurial logs for details)
Version 7.0.1 - 2023-12-16
--------------------------
* Bug fixes (see mercurial logs for details)
Version 7.0.0 - 2023-10-30
--------------------------
* Bug fixes (see mercurial logs for details)
* Add support for Python 3.12
* Use origin description as fallback description
* Post write-off and exchange moves when reconcile posted lines
* Post cancelled, grouped, rescheduled and delegated moves
* Rename close state to closed
* Ask for date when creating move from template
* Add receivable/payable to company
Version 6.8.0 - 2023-05-01
--------------------------
* Bug fixes (see mercurial logs for details)
* Support reconcile lines with currency exchange
* Add reconcile and unreconcile from general ledger lines
* Always raise exception when fiscal year or period are not found
* Remove support for Python 3.7
* Add support for Python 3.11
* Add reversal option when cancelling move
* Add cumulative balance to payable/receivable lines
* Rename reconciliation name to number
* Accrue and allocate rounding errors when there are multiple taxes
* Use match pattern to find journal
* Display general ledger information on account form
Version 6.6.0 - 2022-10-31
--------------------------
* Bug fixes (see mercurial logs for details)
* Add wizard to delegate move lines to another party
* Support date range context for account type amount
* Use context model for chart of accounts and taxes
Version 6.4.0 - 2022-05-02
--------------------------
* Bug fixes (see mercurial logs for details)
* Prevent creating fiscal year before closed one
* Add automatic reconciliation of suggestions
* Prevent to change the type of journal with posted moves
* Mute reconciled payable/receivable lines
* Add delegated amount on move lines
* Enforce same type for children account as their parent
* Show debit / credit columns in ledgers when they contain lines
* Count number of lines in Account and General Ledger
* Handle errors in move template expression
* Rename split lines into reschedule lines
* Add optional credit type on account
* Always require a date to compute taxes
* Add support for Python 3.10
* Remove support for Python 3.6
Version 6.2.0 - 2021-11-01
--------------------------
* Bug fixes (see mercurial logs for details)
* Add origin record name property on move line
* Add group to edit accounting of parties
* Rename lock buttons into lock\_
* Add split lines wizard
* Validate that all inactive accounts have no balance when closing periods
Version 6.0.0 - 2021-05-03
--------------------------
* Bug fixes (see mercurial logs for details)
* Add check to mark types as debt
* Add relate from party to general ledger accounts
* Accumulate start balance on general ledger line
* Print general journal from moves
* Add reconciliation sequence to configuration
* Add report for income statement and balance sheet
* Allow filtering general ledger by journal
* Add journal context to Move.query_get
* Add reconciliation to general ledger line
* Make move's journal read-only once numbered
* Add more term units to aged balance
Version 5.8.0 - 2020-11-02
--------------------------
* Bug fixes (see mercurial logs for details)
* Remove support for Python 3.5
* Allow defining the tax date on taxable lines
* Add General Ledger per account and party
* Add start/end date to tax rule line
* Test for lines to reconcile before showing the next account
Version 5.6.0 - 2020-05-04
--------------------------
* Bug fixes (see mercurial logs for details)
* Order account by its code and name
* Add optional debit type on account
* Show the move resulting from the GroupLines wizard
* Allow periods to end on any day of the month
* Use a wizard to select parameters when creating periods
* Modularize code in GroupLines wizard
Version 5.4.0 - 2019-11-04
--------------------------
* Bug fixes (see mercurial logs for details)
* Add default customer and supplier tax rule
* Update sequence name in renew fiscal year
* Make tax required on tax line
* Use today as default date when inside the period
Version 5.2.0 - 2019-05-06
--------------------------
* Bug fixes (see mercurial logs for details)
* Add group lines wizard
* Manage delegate reconciliation
* Remove starting wildcard when searching on codes and numbers
* Remove display balance
* Merge account kind and account type
* Add origin on move line
* Base journal cash report on account kind receivable and payable
Version 5.0.0 - 2018-10-01
--------------------------
* Bug fixes (see mercurial logs for details)
* Set party required on account payable and receivable of party
* Add writeoff method
* Remove default account from journal
* Add replacement account
* Add period on account and tax code
* Add template override mechanism to tax rules and tax rule lines
* Remove support for Python 2.7
* Remove journal type
Version 4.8.0 - 2018-04-23
--------------------------
* Bug fixes (see mercurial logs for details)
* Use tax code line for tax reporting
* Use custom clause for Tax Code sum
* Add check to modify Tax Lines
* Check receivable/payable to erase party
* Open general ledger accounts from Income Statement relate
* Add warning when creating a second chart of account
* Manage chart update per record
* Allow to reconcile many group of lines with Line.reconcile
Version 4.6.0 - 2017-10-30
--------------------------
* Bug fixes (see mercurial logs for details)
* Allow to keep original taxes when applying a tax rule
* Add legal notice on taxes
* Ease creation of new fiscalyear
* Drop required on party payable and receivable accounts
* Make tax description translatable
* Add searcher on General Ledger
* Add from and to date to General Ledger and Income Statement
* Add move filtering on date range
* Simplify default values for move line
Version 4.4.0 - 2017-05-01
--------------------------
* Bug fixes (see mercurial logs for details)
* Add definitive lock of period and fiscal year
Version 4.2.0 - 2016-11-28
--------------------------
* Bug fixes (see mercurial logs for details)
* Add test wizard for taxes
* Remove journal view
* Add amount second currency on Account
* Enforce second currency on Account
* Remove code from Fiscalyear and Period
* Remove journal option for updating posted moves
* Replace Journal-Period name by function field
* Manage readonly state on Move Line
* Add comparison amount on Balance Sheet and Income Statement
Version 4.0.0 - 2016-05-02
--------------------------
* Bug fixes (see mercurial logs for details)
* Move tax Rounding configuration from account_invoice
* Get the tax type from the base sign:
The tax signs for credit note must be inverted manually.
* New reports design: General Ledger, Trial Balance and Aged Balance
* Add Python3 support
* Merge Third Party Balance into Aged Balance
* Add date to Aged Balance
* Add date on Reconciliation
Version 3.8.0 - 2015-11-02
--------------------------
* Bug fixes (see mercurial logs for details)
* Make Chart of Account not translatable
* Add Journal Cash reporting
Version 3.6.0 - 2015-04-20
--------------------------
* Bug fixes (see mercurial logs for details)
* Add support for PyPy
* Add move template
* Improve payable/receivable lines
* Enforce same sign between amount_second_currency and debit - credit
* Allow tax modifying the unit price
* Add reverse_compute on Tax
* Add fix_party script
* Allow to display only the balance in the General Ledger
* Add TaxableMixin
* Allow to set a description to cancel move
Version 3.4.0 - 2014-10-20
--------------------------
* Bug fixes (see mercurial logs for details)
* Add option on Account for party required
* Add wizard to reconcile all accounts
* Add cancel to Account Move
Version 3.2.0 - 2014-04-21
--------------------------
* Bug fixes (see mercurial logs for details)
* Add start/end date to tax
* Use account of write-off journal as default
* Add write-off journal type
* Add description on write-off move
Version 3.0.0 - 2013-10-21
--------------------------
* Bug fixes (see mercurial logs for details)
* Add balance non-deferral wizard
* Display write-off amount in reconciliation
* Enforce same company for a chart of account
* Change tax percentage into rate
* Autoreconcile posted move with just one line of zero
* Remove centralised counterpart option and functionality
Version 2.8.0 - 2013-04-22
--------------------------
* Bug fixes (see mercurial logs for details)
* Make period's post_move_sequence optional and use fiscal year's one if empty
* Add sale, purchase or other kind on Tax Rule and Tax Group
Version 2.6.0 - 2012-10-22
--------------------------
* Bug fixes (see mercurial logs for details)
* Rename:
- Move.name into number
- Move.reference into post_number
- MoveLine.reference into description
* Remove name and active on move line
* Add origin field on Move
* Compute the aged balance over all fiscalyears and reverse dates order
* Add cumulate option for Debit/Credit on Account
* Allow to open accounts from balance sheet
* Add start/end balance to Trial balance
Version 2.4.0 - 2012-04-23
--------------------------
* Bug fixes (see mercurial logs for details)
* Add new account type stock
Version 2.2.0 - 2011-10-24
--------------------------
* Bug fixes (see mercurial logs for details)
* Add test creation of minimal chart of accounts
Version 2.0.0 - 2011-04-27
--------------------------
* Bug fixes (see mercurial logs for details)
Version 1.8.0 - 2010-11-01
--------------------------
* Bug fixes (see mercurial logs for details)
Version 1.6.0 - 2010-05-11
--------------------------
* Bug fixes (see mercurial logs for details)
* Add description field on account.tax.code.template and account.tax.code
* Add tax field on account.tax.line
* Remove unique constraint on tax group code column
* Add default search value on account move
* Remove egenix-mx-base and replace it by python-dateutil
* Improve General Ledger to compute lines for each accounts at once
Version 1.4.0 - 2009-10-19
--------------------------
* Bug fixes (see mercurial logs for details)
* Add origin_tax field on account.tax.rule
* Change get_receivable_payable on party.party to work with a list of name
* Remove blocked field on account.move.line
* Fix digits of amount on tax and tax line
Version 1.2.0 - 2009-04-20
--------------------------
* Bug fixes (see mercurial logs for details)
* Add tax rule to replace vat and supplier_vat on party
Previous vat configuration will be lost
* Allow to update chart of account from template
* Change sequence on Journal into Property for multi-company
* Allow egg installation
Version 1.0.0 - 2008-11-17
--------------------------
* Initial release
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1745683273.0
trytond_account-7.0.19/COPYRIGHT 0000644 0001750 0001750 00000001373 15003201511 014422 0 ustar 00ced ced Copyright (C) 2008-2025 Cédric Krier.
Copyright (C) 2008-2013 Bertrand Chenal.
Copyright (C) 2008-2025 B2CK SPRL.
Copyright (C) 2004-2008 Tiny SPRL.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see .
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1698685597.0
trytond_account-7.0.19/LICENSE 0000644 0001750 0001750 00000104513 14517761235 014163 0 ustar 00ced ced GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Copyright (C)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see .
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
Copyright (C)
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
.
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1698685597.0
trytond_account-7.0.19/MANIFEST.in 0000644 0001750 0001750 00000000147 14517761235 014712 0 ustar 00ced ced include CHANGELOG
include COPYRIGHT
include LICENSE
include README.rst
include icons/LICENSE
graft doc
././@PaxHeader 0000000 0000000 0000000 00000000033 00000000000 010211 x ustar 00 27 mtime=1745683276.841962
trytond_account-7.0.19/PKG-INFO 0000644 0001750 0001750 00000006076 15003201515 014235 0 ustar 00ced ced Metadata-Version: 2.4
Name: trytond_account
Version: 7.0.19
Summary: Tryton module for accounting
Home-page: http://www.tryton.org/
Download-URL: http://downloads.tryton.org/7.0/
Author: Tryton
Author-email: foundation@tryton.org
License: GPL-3
Project-URL: Bug Tracker, https://bugs.tryton.org/
Project-URL: Documentation, https://docs.tryton.org/modules-account/
Project-URL: Forum, https://www.tryton.org/forum
Project-URL: Source Code, https://code.tryton.org/tryton
Keywords: tryton account
Classifier: Development Status :: 5 - Production/Stable
Classifier: Environment :: Plugins
Classifier: Framework :: Tryton
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Financial and Insurance Industry
Classifier: Intended Audience :: Legal Industry
Classifier: License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)
Classifier: Natural Language :: Bulgarian
Classifier: Natural Language :: Catalan
Classifier: Natural Language :: Chinese (Simplified)
Classifier: Natural Language :: Czech
Classifier: Natural Language :: Dutch
Classifier: Natural Language :: English
Classifier: Natural Language :: Finnish
Classifier: Natural Language :: French
Classifier: Natural Language :: German
Classifier: Natural Language :: Hungarian
Classifier: Natural Language :: Indonesian
Classifier: Natural Language :: Italian
Classifier: Natural Language :: Persian
Classifier: Natural Language :: Polish
Classifier: Natural Language :: Portuguese (Brazilian)
Classifier: Natural Language :: Romanian
Classifier: Natural Language :: Russian
Classifier: Natural Language :: Slovenian
Classifier: Natural Language :: Spanish
Classifier: Natural Language :: Turkish
Classifier: Natural Language :: Ukrainian
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: Implementation :: CPython
Classifier: Topic :: Office/Business
Classifier: Topic :: Office/Business :: Financial :: Accounting
Requires-Python: >=3.8
License-File: LICENSE
Requires-Dist: python-dateutil
Requires-Dist: python-sql>=0.7
Requires-Dist: simpleeval
Requires-Dist: trytond_company<7.1,>=7.0
Requires-Dist: trytond_currency<7.1,>=7.0
Requires-Dist: trytond_party<7.1,>=7.0
Requires-Dist: trytond<7.1,>=7.0
Provides-Extra: test
Requires-Dist: proteus<7.1,>=7.0; extra == "test"
Dynamic: author
Dynamic: author-email
Dynamic: classifier
Dynamic: description
Dynamic: download-url
Dynamic: home-page
Dynamic: keywords
Dynamic: license
Dynamic: license-file
Dynamic: project-url
Dynamic: provides-extra
Dynamic: requires-dist
Dynamic: requires-python
Dynamic: summary
##############
Account Module
##############
The *Account Module* defines the fundamentals needed for basic double entry
accounting.
It also includes templates for a basic chart of accounts, balance sheet and
income statement.
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1698685598.0
trytond_account-7.0.19/README.rst 0000644 0001750 0001750 00000000525 14517761236 014644 0 ustar 00ced ced ##############
Account Module
##############
The *Account Module* defines the fundamentals needed for basic double entry
accounting.
It also includes templates for a basic chart of accounts, balance sheet and
income statement.
.. toctree::
:maxdepth: 2
setup
usage/index
configuration
design/index
reference
releases
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1698685597.0
trytond_account-7.0.19/__init__.py 0000644 0001750 0001750 00000007472 14517761235 015275 0 ustar 00ced ced # This file is part of Tryton. The COPYRIGHT file at the top level of
# this repository contains the full copyright notices and license terms.
from trytond.pool import Pool
from . import (
account, company, configuration, fiscalyear, journal, move, move_template,
party, period, tax)
from .move import MoveLineMixin
__all__ = ['register', 'MoveLineMixin']
def register():
Pool.register(
fiscalyear.FiscalYear,
fiscalyear.BalanceNonDeferralStart,
company.Company,
account.TypeTemplate,
account.Type,
account.AccountTemplate,
account.AccountTemplateTaxTemplate,
account.Account,
account.AccountParty,
account.AccountDeferral,
account.AccountTax,
account.AccountContext,
account.GeneralLedgerAccount,
account.GeneralLedgerAccountContext,
account.GeneralLedgerAccountParty,
account.GeneralLedgerLine,
account.GeneralLedgerLineContext,
account.BalanceSheetContext,
account.BalanceSheetComparisionContext,
account.IncomeStatementContext,
account.CreateChartStart,
account.CreateChartAccount,
account.CreateChartProperties,
account.UpdateChartStart,
account.UpdateChartSucceed,
account.AgedBalanceContext,
account.AgedBalance,
configuration.Configuration,
configuration.ConfigurationDefaultAccount,
configuration.DefaultTaxRule,
configuration.Sequence,
configuration.Journal,
period.Period,
journal.Journal,
journal.JournalSequence,
journal.JournalCashContext,
journal.JournalPeriod,
move.Move,
move.Reconciliation,
configuration.ConfigurationTaxRounding,
move.Line,
move.LineReceivablePayableContext,
move.WriteOff,
move.OpenJournalAsk,
move.ReconcileLinesWriteOff,
move.ReconcileStart,
move.ReconcileShow,
move.CancelMovesDefault,
move.GroupLinesStart,
move.RescheduleLinesStart,
move.RescheduleLinesPreview,
move.RescheduleLinesTerm,
move.DelegateLinesStart,
tax.TaxGroup,
tax.TaxCodeTemplate,
tax.TaxCode,
tax.TaxCodeLineTemplate,
tax.TaxCodeLine,
tax.TaxCodeContext,
tax.TaxTemplate,
tax.Tax,
tax.TaxLine,
tax.TaxRuleTemplate,
tax.TaxRule,
tax.TaxRuleLineTemplate,
tax.TaxRuleLine,
tax.TestTaxView,
tax.TestTaxViewResult,
move_template.MoveTemplate,
move_template.MoveTemplateKeyword,
move_template.MoveLineTemplate,
move_template.TaxLineTemplate,
move_template.CreateMoveTemplate,
move_template.CreateMoveKeywords,
party.Party,
party.PartyAccount,
fiscalyear.CreatePeriodsStart,
fiscalyear.RenewFiscalYearStart,
module='account', type_='model')
Pool.register(
account.OpenType,
fiscalyear.BalanceNonDeferral,
account.CreateChart,
account.UpdateChart,
account.OpenGeneralLedgerAccountParty,
move.OpenJournal,
move.OpenAccount,
move.ReconcileLines,
move.UnreconcileLines,
move.Reconcile,
move.CancelMoves,
move.GroupLines,
move.RescheduleLines,
move.DelegateLines,
move_template.CreateMove,
tax.OpenTaxCode,
tax.TestTax,
party.PartyReplace,
party.PartyErase,
fiscalyear.CreatePeriods,
fiscalyear.RenewFiscalYear,
module='account', type_='wizard')
Pool.register(
account.AccountTypeStatement,
account.GeneralLedger,
account.TrialBalance,
account.AgedBalanceReport,
move.GeneralJournal,
module='account', type_='report')
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1725720314.0
trytond_account-7.0.19/account.py 0000644 0001750 0001750 00000367443 14667063372 015204 0 ustar 00ced ced # This file is part of Tryton. The COPYRIGHT file at the top level of
# this repository contains the full copyright notices and license terms.
import datetime
import operator
from collections import defaultdict
from decimal import Decimal
from itertools import zip_longest
from dateutil.relativedelta import relativedelta
from sql import Column, Literal, Null, Window
from sql.aggregate import Count, Max, Min, Sum
from sql.conditionals import Case, Coalesce
from trytond import backend
from trytond.i18n import gettext
from trytond.model import (
Check, Index, ModelSQL, ModelView, Unique, fields, sequence_ordered,
sum_tree, tree)
from trytond.model.exceptions import AccessError
from trytond.modules.currency.fields import Monetary
from trytond.pool import Pool
from trytond.pyson import Bool, Eval, Id, If, PYSONEncoder
from trytond.report import Report
from trytond.tools import (
grouped_slice, is_full_text, lstrip_wildcard, reduce_ids)
from trytond.transaction import Transaction, check_access, inactive_records
from trytond.wizard import (
Button, StateAction, StateTransition, StateView, Wizard)
from .common import ActivePeriodMixin, ContextCompanyMixin, PeriodMixin
from .exceptions import (
AccountValidationError, ChartWarning, FiscalYearNotFoundError,
SecondCurrencyError)
from .move import DescriptionOriginMixin
def TypeMixin(template=False):
class Mixin:
__slots__ = ()
name = fields.Char('Name', required=True)
statement = fields.Selection([
(None, ""),
('balance', "Balance"),
('income', "Income"),
('off-balance', "Off-Balance"),
], "Statement",
states={
'required': Bool(Eval('parent')),
})
assets = fields.Boolean(
"Assets",
states={
'invisible': Eval('statement') != 'balance',
})
receivable = fields.Boolean(
"Receivable",
domain=[
If((Eval('statement') != 'balance')
| ~Eval('assets', True),
('receivable', '=', False), ()),
],
states={
'invisible': ((Eval('statement') != 'balance')
| ~Eval('assets', True)),
})
stock = fields.Boolean(
"Stock",
domain=[
If(Eval('statement') == 'off-balance',
('stock', '=', False), ()),
],
states={
'invisible': Eval('statement') == 'off-balance',
})
payable = fields.Boolean(
"Payable",
domain=[
If((Eval('statement') != 'balance')
| Eval('assets', False),
('payable', '=', False), ()),
],
states={
'invisible': ((Eval('statement') != 'balance')
| Eval('assets', False)),
})
debt = fields.Boolean(
"Debt",
domain=[
If((Eval('statement') != 'balance')
| Eval('assets', False),
('debt', '=', False), ()),
],
states={
'invisible': ((Eval('statement') != 'balance')
| Eval('assets', False)),
},
help="Check to allow booking debt via supplier invoice.")
revenue = fields.Boolean(
"Revenue",
domain=[
If(Eval('statement') != 'income',
('revenue', '=', False), ()),
],
states={
'invisible': Eval('statement') != 'income',
})
expense = fields.Boolean(
"Expense",
domain=[
If(Eval('statement') != 'income',
('expense', '=', False), ()),
],
states={
'invisible': Eval('statement') != 'income',
})
if not template:
for fname in dir(Mixin):
field = getattr(Mixin, fname)
if not isinstance(field, fields.Field):
continue
field.states['readonly'] = (
Bool(Eval('template', -1)) & ~Eval('template_override', False))
return Mixin
class TypeTemplate(
TypeMixin(template=True), sequence_ordered(), tree(separator='\\'),
ModelSQL, ModelView):
'Account Type Template'
__name__ = 'account.account.type.template'
parent = fields.Many2One(
'account.account.type.template', "Parent", ondelete='RESTRICT',
domain=['OR',
If(Eval('statement') == 'off-balance',
('statement', '=', 'off-balance'),
If(Eval('statement') == 'balance',
('statement', '=', 'balance'),
('statement', '!=', 'off-balance')),
),
('statement', '=', None),
])
childs = fields.One2Many(
'account.account.type.template', 'parent', "Children")
@classmethod
def __register__(cls, module_name):
super().__register__(module_name)
table_h = cls.__table_handler__(module_name)
# Migration from 5.0: remove display_balance
table_h.drop_column('display_balance')
def _get_type_value(self, type=None):
'''
Set the values for account creation.
'''
res = {}
if not type or type.name != self.name:
res['name'] = self.name
if not type or type.sequence != self.sequence:
res['sequence'] = self.sequence
if not type or type.statement != self.statement:
res['statement'] = self.statement
if not type or type.assets != self.assets:
res['assets'] = self.assets
for boolean in [
'receivable', 'stock', 'payable', 'revenue', 'expense',
'debt']:
if not type or getattr(type, boolean) != getattr(self, boolean):
res[boolean] = getattr(self, boolean)
if not type or type.template != self:
res['template'] = self.id
return res
def create_type(self, company_id, template2type=None):
'''
Create recursively types based on template.
template2type is a dictionary with template id as key and type id as
value, used to convert template id into type. The dictionary is filled
with new types.
'''
pool = Pool()
Type = pool.get('account.account.type')
assert self.parent is None
if template2type is None:
template2type = {}
def create(templates):
values = []
created = []
for template in templates:
if template.id not in template2type:
vals = template._get_type_value()
vals['company'] = company_id
if template.parent:
vals['parent'] = template2type[template.parent.id]
else:
vals['parent'] = None
values.append(vals)
created.append(template)
types = Type.create(values)
for template, type_ in zip(created, types):
template2type[template.id] = type_.id
childs = [self]
while childs:
create(childs)
childs = sum((c.childs for c in childs), ())
class Type(
TypeMixin(), sequence_ordered(), tree(separator='\\'),
ModelSQL, ModelView):
'Account Type'
__name__ = 'account.account.type'
parent = fields.Many2One('account.account.type', 'Parent',
ondelete="RESTRICT",
states={
'readonly': (Bool(Eval('template', -1))
& ~Eval('template_override', False)),
},
domain=[
('company', '=', Eval('company', -1)),
['OR',
If(Eval('statement') == 'off-balance',
('statement', '=', 'off-balance'),
If(Eval('statement') == 'balance',
('statement', '=', 'balance'),
('statement', '!=', 'off-balance')),
),
('statement', '=', None),
],
])
childs = fields.One2Many('account.account.type', 'parent', 'Children',
domain=[
('company', '=', Eval('company', -1)),
])
currency = fields.Function(fields.Many2One(
'currency.currency', "Currency"),
'get_currency', searcher='search_currency')
amount = fields.Function(Monetary(
"Amount", currency='currency', digits='currency'),
'get_amount')
amount_cmp = fields.Function(Monetary(
"Amount", currency='currency', digits='currency'),
'get_amount_cmp')
company = fields.Many2One('company.company', 'Company', required=True,
ondelete="RESTRICT")
template = fields.Many2One('account.account.type.template', 'Template')
template_override = fields.Boolean('Override Template',
help="Check to override template definition",
states={
'invisible': ~Bool(Eval('template', -1)),
})
@classmethod
def __setup__(cls):
super().__setup__()
table = cls.__table__()
cls._sql_indexes.update({
# Index for receivable/payable balance
Index(
table,
(table.id, Index.Range()),
where=table.receivable | table.payable),
})
@classmethod
def __register__(cls, module_name):
super().__register__(module_name)
table_h = cls.__table_handler__(module_name)
# Migration from 5.0: remove display_balance
table_h.drop_column('display_balance')
@classmethod
def default_template_override(cls):
return False
@classmethod
def default_company(cls):
return Transaction().context.get('company')
@fields.depends('parent', '_parent_parent.statement')
def on_change_parent(self):
if self.parent:
self.statement = self.parent.statement
def get_currency(self, name):
return self.company.currency.id
@classmethod
def search_currency(cls, name, clause):
return [('company.' + clause[0], *clause[1:])]
@classmethod
def get_amount(cls, types, name):
pool = Pool()
Account = pool.get('account.account')
GeneralLedger = pool.get('account.general_ledger.account')
context = Transaction().context
childs = cls.search([
('parent', 'child_of', [t.id for t in types]),
])
period_ids = from_date = to_date = None
if context.get('start_period') or context.get('end_period'):
start_period_ids = GeneralLedger.get_period_ids('start_%s' % name)
end_period_ids = GeneralLedger.get_period_ids('end_%s' % name)
period_ids = list(
set(end_period_ids).difference(set(start_period_ids)))
elif context.get('from_date') or context.get('to_date'):
from_date = context.get('from_date')
to_date = context.get('to_date')
with Transaction().set_context(
periods=period_ids, from_date=from_date, to_date=to_date):
accounts = Account.search([
('type', 'in', [t.id for t in childs]),
])
debit_credit_accounts = Account.search([
('type', '!=', None),
['OR',
('debit_type', 'in', [t.id for t in childs]),
('credit_type', 'in', [t.id for t in childs]),
],
])
values = defaultdict(Decimal)
for account in accounts:
balance = account.credit - account.debit
if ((not account.debit_type or balance > 0)
and (not account.credit_type or balance < 0)):
values[account.type.id] += balance
for account in debit_credit_accounts:
balance = account.credit - account.debit
if account.debit_type and balance < 0:
values[account.debit_type.id] += balance
elif account.credit_type and balance > 0:
values[account.credit_type.id] += balance
result = sum_tree(childs, values)
for type_ in types:
result[type_.id] = type_.currency.round(result[type_.id])
if type_.statement == 'balance' and type_.assets:
result[type_.id] *= -1
return result
@classmethod
def get_amount_cmp(cls, types, name):
transaction = Transaction()
current = transaction.context
if not current.get('comparison'):
return dict.fromkeys([t.id for t in types], None)
new = {}
for key, value in current.items():
if key.endswith('_cmp'):
new[key[:-4]] = value
with transaction.set_context(new):
return cls.get_amount(types, name)
@classmethod
def view_attributes(cls):
return super().view_attributes() + [
('/tree/field[@name="amount_cmp"]', 'tree_invisible',
~Eval('comparison', False)),
]
@classmethod
def copy(cls, types, default=None):
if default is None:
default = {}
else:
default = default.copy()
default.setdefault('template', None)
return super().copy(types, default=default)
@classmethod
def delete(cls, types):
types = cls.search([
('parent', 'child_of', [t.id for t in types]),
])
super(Type, cls).delete(types)
def update_type(self, template2type=None):
'''
Update recursively types based on template.
template2type is a dictionary with template id as key and type id as
value, used to convert template id into type. The dictionary is filled
with new types
'''
if template2type is None:
template2type = {}
values = []
childs = [self]
while childs:
for child in childs:
if child.template:
if not child.template_override:
vals = child.template._get_type_value(type=child)
if vals:
values.append([child])
values.append(vals)
template2type[child.template.id] = child.id
childs = sum((c.childs for c in childs), ())
if values:
self.write(*values)
# Update parent
to_save = []
childs = [self]
while childs:
for child in childs:
if child.template:
if not child.template_override:
if child.template.parent:
# Fallback to current parent
# to keep under the same root
parent = template2type.get(
child.template.parent.id,
child.parent)
else:
parent = None
old_parent = (
child.parent.id if child.parent else None)
if parent != old_parent:
child.parent = parent
to_save.append(child)
childs = sum((c.childs for c in childs), ())
self.__class__.save(to_save)
class OpenType(Wizard):
'Open Type'
__name__ = 'account.account.open_type'
start = StateTransition()
account = StateAction('account.act_account_balance_sheet')
ledger_account = StateAction('account.act_account_general_ledger')
def transition_start(self):
context_model = Transaction().context.get('context_model')
if context_model == 'account.balance_sheet.comparison.context':
return 'account'
elif context_model == 'account.income_statement.context':
return 'ledger_account'
return 'end'
def open_action(self, action):
pool = Pool()
action['name'] = '%s (%s)' % (action['name'], self.record.rec_name)
trans_context = Transaction().context
context = {
'active_id': trans_context.get('active_id'),
'active_ids': trans_context.get('active_ids', []),
'active_model': trans_context.get('active_model'),
}
context_model = trans_context.get('context_model')
if context_model:
Model = pool.get(context_model)
for fname in Model._fields.keys():
if fname == 'id':
continue
context[fname] = trans_context.get(fname)
action['pyson_context'] = PYSONEncoder().encode(context)
return action, {}
do_account = open_action
do_ledger_account = open_action
class AccountTypeStatement(Report):
__name__ = 'account.account.type.statement'
@classmethod
def get_context(cls, records, header, data):
pool = Pool()
Company = pool.get('company.company')
context = Transaction().context
report_context = super().get_context(records, header, data)
report_context['company'] = Company(context['company'])
if data.get('model_context') is not None:
Context = pool.get(data['model_context'])
values = {}
for field in Context._fields:
if field in context:
values[field] = context[field]
report_context['ctx'] = Context(**values)
report_context['types'] = zip_longest(
records, data.get('paths') or [], fillvalue=[])
return report_context
def AccountMixin(template=False):
class Mixin:
__slots__ = ()
_order_name = 'rec_name'
name = fields.Char("Name", required=True)
code = fields.Char("Code")
closed = fields.Boolean(
"Closed",
states={
'invisible': ~Eval('type'),
},
help="Check to prevent posting move on the account.")
reconcile = fields.Boolean(
"Reconcile",
states={
'invisible': ~Eval('type'),
},
help="Allow move lines of this account to be reconciled.")
party_required = fields.Boolean('Party Required',
domain=[
If(~Eval('type') | ~Eval('deferral', False),
('party_required', '=', False),
()),
],
states={
'invisible': ~Eval('type') | ~Eval('deferral', False),
})
general_ledger_balance = fields.Boolean('General Ledger Balance',
states={
'invisible': ~Eval('type'),
},
help="Display only the balance in the general ledger report.")
deferral = fields.Function(fields.Boolean(
"Deferral",
states={
'invisible': ~Eval('type'),
}),
'on_change_with_deferral', searcher='search_deferral')
@classmethod
def __setup__(cls):
super().__setup__()
if not cls.childs.domain:
cls.childs.domain = []
for type_ in ['type', 'debit_type']:
field = getattr(cls, type_)
field.domain = [
If(Eval('parent')
& Eval('_parent_parent.%s' % type_)
& Eval('_parent_parent.parent'),
('id', '=', Eval('_parent_parent.%s' % type_)),
()),
]
field.states['required'] = (
Eval('parent')
& Eval('_parent_parent.%s' % type_)
& Eval('_parent_parent.parent'))
cls.childs.domain.append(
If(Eval(type_) & Eval('parent'),
(type_, '=', Eval(type_)),
()))
@classmethod
def default_closed(cls):
return False
@classmethod
def default_reconcile(cls):
return False
@classmethod
def default_party_required(cls):
return False
@classmethod
def default_general_ledger_balance(cls):
return False
@fields.depends('type')
def on_change_with_deferral(self, name=None):
return (self.type
and self.type.statement in {'balance', 'off-balance'})
@classmethod
def search_deferral(cls, name, clause):
_, operator, value = clause
if operator in {'in', 'not in'}:
if operator == 'in':
operator = '='
else:
operator = '!='
if True in value and False not in value:
value = '=', True
elif False in value and True not in value:
value = '=', False
else:
return [('id', operator, None)]
if ((operator == '=' and value)
or (operator == '!=' and not value)):
return [
('type.statement', 'in', ['balance', 'off-balance']),
]
else:
return ['OR',
('type', '=', None),
('type.statement', 'not in', ['balance', 'off-balance']),
]
def get_rec_name(self, name):
if self.code:
return self.code + ' - ' + self.name
else:
return self.name
@classmethod
def search_rec_name(cls, name, clause):
_, operator, operand, *extra = clause
if operator.startswith('!') or operator.startswith('not '):
bool_op = 'AND'
else:
bool_op = 'OR'
code_value = operand
if operator.endswith('like') and is_full_text(operand):
code_value = lstrip_wildcard(operand)
return [bool_op,
('code', operator, code_value, *extra),
(cls._rec_name, operator, operand, *extra),
]
@staticmethod
def order_rec_name(tables):
table, _ = tables[None]
return [table.code, table.name]
if not template:
for fname in dir(Mixin):
field = getattr(Mixin, fname)
if (not isinstance(field, fields.Field)
or isinstance(field, fields.Function)):
continue
field.states['readonly'] = (
Bool(Eval('template', -1)) & ~Eval('template_override', False))
return Mixin
class AccountTemplate(
AccountMixin(template=True), PeriodMixin, tree(), ModelSQL, ModelView):
'Account Template'
__name__ = 'account.account.template'
type = fields.Many2One(
'account.account.type.template', "Type", ondelete="RESTRICT")
debit_type = fields.Many2One(
'account.account.type.template', "Debit Type", ondelete="RESTRICT")
credit_type = fields.Many2One(
'account.account.type.template', "Credit Type", ondelete="RESTRICT")
parent = fields.Many2One(
'account.account.template', "Parent", ondelete="RESTRICT")
childs = fields.One2Many('account.account.template', 'parent', 'Children')
taxes = fields.Many2Many('account.account.template-account.tax.template',
'account', 'tax', 'Default Taxes',
domain=[('parent', '=', None)])
replaced_by = fields.Many2One(
'account.account.template', "Replaced By",
states={
'invisible': ~Eval('end_date'),
})
@classmethod
def __setup__(cls):
super(AccountTemplate, cls).__setup__()
cls._order.insert(0, ('code', 'ASC'))
cls._order.insert(1, ('name', 'ASC'))
table = cls.__table__()
cls._sql_constraints.append(
('only_one_debit_credit_types', Check(
table, (table.debit_type + table.credit_type) == Null),
'account.msg_only_one_debit_credit_types'))
@classmethod
def __register__(cls, module_name):
super().__register__(module_name)
table_h = cls.__table_handler__(module_name)
# Migration from 5.0: remove kind
table_h.drop_column('kind')
def _get_account_value(self, account=None):
'''
Set the values for account creation.
'''
res = {}
if not account or account.name != self.name:
res['name'] = self.name
if not account or account.code != self.code:
res['code'] = self.code
if not account or account.start_date != self.start_date:
res['start_date'] = self.start_date
if not account or account.end_date != self.end_date:
res['end_date'] = self.end_date
if not account or account.closed != self.closed:
res['closed'] = self.closed
if not account or account.reconcile != self.reconcile:
res['reconcile'] = self.reconcile
if not account or account.party_required != self.party_required:
res['party_required'] = self.party_required
if (not account
or account.general_ledger_balance
!= self.general_ledger_balance):
res['general_ledger_balance'] = self.general_ledger_balance
if not account or account.template != self:
res['template'] = self.id
return res
def create_account(self, company_id, template2account=None,
template2type=None):
'''
Create recursively accounts based on template.
template2account is a dictionary with template id as key and account id
as value, used to convert template id into account. The dictionary is
filled with new accounts
template2type is a dictionary with type template id as key and type id
as value, used to convert type template id into type.
'''
pool = Pool()
Account = pool.get('account.account')
assert self.parent is None
if template2account is None:
template2account = {}
if template2type is None:
template2type = {}
def create(templates):
values = []
created = []
for template in templates:
if template.id not in template2account:
vals = template._get_account_value()
vals['company'] = company_id
if template.parent:
vals['parent'] = template2account[template.parent.id]
else:
vals['parent'] = None
if template.type:
vals['type'] = template2type.get(template.type.id)
else:
vals['type'] = None
if template.debit_type:
vals['debit_type'] = template2type.get(
template.debit_type.id)
else:
vals['debit_type'] = None
if template.credit_type:
vals['credit_type'] = template2type.get(
template.credit_type.id)
else:
vals['credit_type'] = None
values.append(vals)
created.append(template)
accounts = Account.create(values)
for template, account in zip(created, accounts):
template2account[template.id] = account.id
childs = [self]
while childs:
create(childs)
childs = sum((c.childs for c in childs), ())
def update_account2(self, template2account, template2tax,
template_done=None):
'''
Update recursively account taxes and replaced_by based on template.
template2account is a dictionary with template id as key and account id
as value, used to convert template id into account.
template2tax is a dictionary with tax template id as key and tax id as
value, used to convert tax template id into tax.
template_done is a list of template id already updated. The list is
filled.
'''
Account = Pool().get('account.account')
if template2account is None:
template2account = {}
if template2tax is None:
template2tax = {}
if template_done is None:
template_done = []
def update(templates):
to_write = []
for template in templates:
if template.id not in template_done:
template_done.append(template.id)
account = Account(template2account[template.id])
if account.template_override:
continue
values = {}
if template.taxes:
tax_ids = [template2tax[x.id] for x in template.taxes]
values['taxes'] = [('add', tax_ids)]
if template.replaced_by:
values['replaced_by'] = template2account[
template.replaced_by.id]
if values:
to_write.append([account])
to_write.append(values)
if to_write:
Account.write(*to_write)
childs = [self]
while childs:
update(childs)
childs = sum((c.childs for c in childs), ())
class AccountTemplateTaxTemplate(ModelSQL):
'Account Template - Tax Template'
__name__ = 'account.account.template-account.tax.template'
_table = 'account_account_template_tax_rel'
account = fields.Many2One(
'account.account.template', "Account Template",
ondelete='CASCADE', required=True)
tax = fields.Many2One(
'account.tax.template', "Tax Template",
ondelete='RESTRICT', required=True)
class Account(
AccountMixin(), ContextCompanyMixin, ActivePeriodMixin, tree(),
ModelSQL, ModelView):
'Account'
__name__ = 'account.account'
_states = {
'readonly': (Bool(Eval('template', -1))
& ~Eval('template_override', False)),
}
company = fields.Many2One('company.company', 'Company', required=True,
ondelete="RESTRICT")
currency = fields.Function(fields.Many2One(
'currency.currency', "Currency"),
'get_currency', searcher='search_currency')
second_currency = fields.Many2One(
'currency.currency', "Second Currency", ondelete="RESTRICT",
domain=[
('id', '!=', Eval('currency', -1)),
],
states={
'readonly': _states['readonly'],
'invisible': ~Eval('deferral', False),
},
help="Force all moves for this account to have this second currency.")
type = fields.Many2One(
'account.account.type', "Type", ondelete='RESTRICT',
states={
'readonly': _states['readonly'],
},
domain=[
('company', '=', Eval('company')),
])
debit_type = fields.Many2One(
'account.account.type', "Debit Type", ondelete='RESTRICT',
states={
'readonly': _states['readonly'],
'invisible': (
~Eval('type') | Eval('credit_type')
| (_states['readonly']) & ~Eval('debit_type')),
},
domain=[
('company', '=', Eval('company')),
],
help="The type used if not empty and debit > credit.")
credit_type = fields.Many2One(
'account.account.type', "Credit Type", ondelete='RESTRICT',
states={
'readonly': _states['readonly'],
'invisible': (
~Eval('type') | Eval('debit_type')
| (_states['readonly']) & ~Eval('credit_type')),
},
domain=[
('company', '=', Eval('company')),
],
help="The type used if not empty and debit < credit.")
parent = fields.Many2One(
'account.account', "Parent",
left="left", right="right", ondelete="RESTRICT", states=_states,
domain=[
('company', '=', Eval('company', -1)),
])
left = fields.Integer("Left", required=True)
right = fields.Integer("Right", required=True)
childs = fields.One2Many(
'account.account', 'parent', "Children",
domain=[
('company', '=', Eval('company', -1)),
])
balance = fields.Function(Monetary(
"Balance", currency='currency', digits='currency'),
'get_balance')
credit = fields.Function(Monetary(
"Credit", currency='currency', digits='currency',
states={
'invisible': ~Eval('line_count', -1),
}),
'get_credit_debit')
debit = fields.Function(Monetary(
"Debit", currency='currency', digits='currency',
states={
'invisible': ~Eval('line_count', -1),
}),
'get_credit_debit')
amount_second_currency = fields.Function(Monetary(
"Amount Second Currency",
currency='second_currency', digits='second_currency',
states={
'invisible': ~Eval('second_currency'),
}),
'get_credit_debit')
line_count = fields.Function(
fields.Integer("Line Count"), 'get_credit_debit')
note = fields.Text('Note')
deferrals = fields.One2Many(
'account.account.deferral', 'account', "Deferrals", readonly=True,
states={
'invisible': ~Eval('type'),
})
taxes = fields.Many2Many('account.account-account.tax',
'account', 'tax', 'Default Taxes',
domain=[
('company', '=', Eval('company')),
('parent', '=', None),
],
help="Default tax for manual encoding of move lines\n"
'for journal types: "expense" and "revenue".')
replaced_by = fields.Many2One(
'account.account', "Replaced By",
domain=[('company', '=', Eval('company', -1))],
states={
'readonly': _states['readonly'],
'invisible': ~Eval('end_date'),
})
template = fields.Many2One('account.account.template', 'Template')
template_override = fields.Boolean('Override Template',
help="Check to override template definition",
states={
'invisible': ~Bool(Eval('template', -1)),
})
del _states
@classmethod
def __setup__(cls):
super(Account, cls).__setup__()
for date in [cls.start_date, cls.end_date]:
date.states = {
'readonly': (Bool(Eval('template', -1))
& ~Eval('template_override', False)),
}
cls._order.insert(0, ('code', 'ASC'))
cls._order.insert(1, ('name', 'ASC'))
table = cls.__table__()
cls._sql_constraints.append(
('only_one_debit_credit_types', Check(
table, (table.debit_type + table.credit_type) == Null),
'account.msg_only_one_debit_credit_types'))
cls._sql_indexes.add(
Index(
table,
(table.left, Index.Range()),
(table.right, Index.Range())))
@classmethod
def __register__(cls, module_name):
super().__register__(module_name)
table_h = cls.__table_handler__(module_name)
# Migration from 5.0: remove kind
table_h.drop_column('kind')
@classmethod
def validate_fields(cls, accounts, field_names):
super().validate_fields(accounts, field_names)
cls.check_second_currency(accounts, field_names)
cls.check_move_domain(accounts, field_names)
@staticmethod
def default_left():
return 0
@staticmethod
def default_right():
return 0
@staticmethod
def default_company():
return Transaction().context.get('company') or None
@classmethod
def default_template_override(cls):
return False
def get_currency(self, name):
return self.company.currency.id
@classmethod
def search_currency(cls, name, clause):
return [('company.' + clause[0], *clause[1:])]
@classmethod
def get_balance(cls, accounts, name):
pool = Pool()
MoveLine = pool.get('account.move.line')
FiscalYear = pool.get('account.fiscalyear')
cursor = Transaction().connection.cursor()
table_a = cls.__table__()
table_c = cls.__table__()
line = MoveLine.__table__()
ids = [a.id for a in accounts]
balances = dict((i, Decimal(0)) for i in ids)
line_query, fiscalyear_ids = MoveLine.query_get(line)
for sub_ids in grouped_slice(ids):
red_sql = reduce_ids(table_a.id, sub_ids)
cursor.execute(*table_a.join(table_c,
condition=(table_c.left >= table_a.left)
& (table_c.right <= table_a.right)
).join(line, condition=line.account == table_c.id
).select(
table_a.id,
Sum(Coalesce(line.debit, 0) - Coalesce(line.credit, 0)),
where=red_sql & line_query,
group_by=table_a.id))
balances.update(dict(cursor))
for account in accounts:
# SQLite uses float for SUM
if not isinstance(balances[account.id], Decimal):
balances[account.id] = Decimal(str(balances[account.id]))
balances[account.id] = account.currency.round(balances[account.id])
fiscalyears = FiscalYear.browse(fiscalyear_ids)
def func(accounts, names):
return {names[0]: cls.get_balance(accounts, names[0])}
return cls._cumulate(fiscalyears, accounts, [name], {name: balances},
func)[name]
@classmethod
def get_credit_debit(cls, accounts, names):
'''
Function to compute debit, credit for accounts.
If cumulate is set in the context, it is the cumulate amount over all
previous fiscal year.
'''
pool = Pool()
MoveLine = pool.get('account.move.line')
FiscalYear = pool.get('account.fiscalyear')
cursor = Transaction().connection.cursor()
result = {}
ids = [a.id for a in accounts]
for name in names:
if name not in {
'credit', 'debit', 'amount_second_currency', 'line_count'}:
raise ValueError('Unknown name: %s' % name)
col_type = int if name == 'line_count' else Decimal
result[name] = defaultdict(col_type)
table = cls.__table__()
line = MoveLine.__table__()
line_query, fiscalyear_ids = MoveLine.query_get(line)
columns = [table.id]
for name in names:
if name == 'line_count':
columns.append(Count(Literal('*')))
else:
columns.append(Sum(Coalesce(Column(line, name), 0)))
for sub_ids in grouped_slice(ids):
red_sql = reduce_ids(table.id, sub_ids)
cursor.execute(*table.join(line, 'LEFT',
condition=line.account == table.id
).select(*columns,
where=red_sql & line_query,
group_by=table.id))
for row in cursor:
account_id = row[0]
for i, name in enumerate(names, 1):
# SQLite uses float for SUM
if (name != 'line_count'
and not isinstance(row[i], Decimal)):
result[name][account_id] = Decimal(str(row[i]))
else:
result[name][account_id] = row[i]
for account in accounts:
for name in names:
if name == 'line_count':
continue
if (name == 'amount_second_currency'
and account.second_currency):
currency = account.second_currency
else:
currency = account.currency
result[name][account.id] = currency.round(
result[name][account.id])
cumulate_names = []
if Transaction().context.get('cumulate'):
cumulate_names = names
elif 'amount_second_currency' in names:
cumulate_names = ['amount_second_currency']
if cumulate_names:
fiscalyears = FiscalYear.browse(fiscalyear_ids)
return cls._cumulate(fiscalyears, accounts, cumulate_names, result,
cls.get_credit_debit)
else:
return result
@classmethod
def _cumulate(
cls, fiscalyears, accounts, names, values, func,
deferral='account.account.deferral'):
"""
Cumulate previous fiscalyear values into values
func is the method to compute values
"""
pool = Pool()
FiscalYear = pool.get('account.fiscalyear')
youngest_fiscalyear = None
for fiscalyear in fiscalyears:
if (not youngest_fiscalyear
or (youngest_fiscalyear.start_date
> fiscalyear.start_date)):
youngest_fiscalyear = fiscalyear
fiscalyear = None
if youngest_fiscalyear:
fiscalyears = FiscalYear.search([
('end_date', '<', youngest_fiscalyear.start_date),
('company', '=', youngest_fiscalyear.company),
], order=[('end_date', 'DESC')], limit=1)
if fiscalyears:
fiscalyear, = fiscalyears
if not fiscalyear:
return values
if fiscalyear.state == 'closed' and deferral:
Deferral = pool.get(deferral)
id2deferral = {}
ids = [a.id for a in accounts]
for sub_ids in grouped_slice(ids):
deferrals = Deferral.search([
('fiscalyear', '=', fiscalyear.id),
('account', 'in', list(sub_ids)),
])
for deferral in deferrals:
id2deferral[deferral.account.id] = deferral
for account in accounts:
if account.id in id2deferral:
deferral = id2deferral[account.id]
for name in names:
values[name][account.id] += getattr(deferral, name)
else:
with Transaction().set_context(fiscalyear=fiscalyear.id,
date=None, periods=None, from_date=None, to_date=None):
previous_result = func(accounts, names)
for name in names:
vals = values[name]
for account in accounts:
vals[account.id] += previous_result[name][account.id]
return values
__on_change_parent_fields = ['name', 'code', 'company', 'type',
'debit_type', 'credit_type', 'reconcile', 'deferral', 'party_required',
'general_ledger_balance', 'taxes']
@fields.depends('parent', *(__on_change_parent_fields
+ ['_parent_parent.%s' % f for f in __on_change_parent_fields]))
def on_change_parent(self):
if not self.parent:
return
if self.id is not None and self.id >= 0:
return
for field in self.__on_change_parent_fields:
if (not getattr(self, field)
or field in {'reconcile', 'deferral',
'party_required', 'general_ledger_balance'}):
setattr(self, field, getattr(self.parent, field))
@classmethod
def check_second_currency(cls, accounts, field_names=None):
pool = Pool()
Line = pool.get('account.move.line')
if field_names and not (
field_names & (
{'second_currency', 'type'}
| set(cls.deferral.validation_depends))):
return
for account in accounts:
if not account.second_currency:
continue
if (not account.type
or account.type.payable
or account.type.revenue
or account.type.receivable
or account.type.expense):
raise SecondCurrencyError(
gettext('account.msg_account_invalid_type_second_currency',
account=account.rec_name))
if not account.deferral:
raise SecondCurrencyError(
gettext('account'
'.msg_account_invalid_deferral_second_currency',
account=account.rec_name))
lines = Line.search([
('account', '=', account.id),
('second_currency', '!=', account.second_currency.id),
], order=[], limit=1)
if lines:
raise SecondCurrencyError(
gettext('account'
'.msg_account_invalid_lines_second_currency',
currency=account.second_currency.rec_name,
account=account.rec_name))
@classmethod
def check_move_domain(cls, accounts, field_names=None):
pool = Pool()
Line = pool.get('account.move.line')
if field_names and not (field_names & {'closed', 'type'}):
return
accounts = [a for a in accounts if a.closed or not a.type]
for sub_accounts in grouped_slice(accounts):
sub_accounts = list(sub_accounts)
if Line.search([
('account', 'in', [a.id for a in sub_accounts]),
], order=[], limit=1):
for account in sub_accounts:
if not account.closed:
continue
lines = Line.search([
('account', '=', account.id),
], order=[], limit=1)
if lines:
if account.closed:
raise AccountValidationError(gettext(
'account.msg_account_closed_lines',
account=account.rec_name))
elif account.type:
raise AccountValidationError(gettext(
'account.msg_account_no_type_lines',
account=account.rec_name))
@classmethod
def copy(cls, accounts, default=None):
if default is None:
default = {}
else:
default = default.copy()
default.setdefault('template', None)
default.setdefault('deferrals', [])
new_accounts = super(Account, cls).copy(accounts, default=default)
cls._rebuild_tree('parent', None, 0)
return new_accounts
@classmethod
def delete(cls, accounts):
MoveLine = Pool().get('account.move.line')
childs = cls.search([
('parent', 'child_of', [a.id for a in accounts]),
])
lines = MoveLine.search([
('account', 'in', [a.id for a in childs]),
])
if lines:
raise AccessError(
gettext('account.msg_delete_account_with_move_lines',
account=lines[0].account.rec_name))
super(Account, cls).delete(accounts)
def update_account(self, template2account=None, template2type=None):
'''
Update recursively accounts based on template.
template2account is a dictionary with template id as key and account id
as value, used to convert template id into account. The dictionary is
filled with new accounts.
template2type is a dictionary with type template id as key and type id
as value, used to convert type template id into type.
'''
if template2account is None:
template2account = {}
if template2type is None:
template2type = {}
values = []
childs = [self]
while childs:
for child in childs:
if child.template:
if not child.template_override:
vals = child.template._get_account_value(account=child)
current_type = child.type.id if child.type else None
if child.template.type:
template_type = template2type.get(
child.template.type.id)
else:
template_type = None
if current_type != template_type:
vals['type'] = template_type
current_debit_type = (
child.debit_type.id if child.debit_type else None)
if child.template.debit_type:
template_debit_type = template2type.get(
child.template.debit_type.id)
else:
template_debit_type = None
if current_debit_type != template_debit_type:
vals['debit_type'] = template_debit_type
current_credit_type = (
child.credit_type.id if child.credit_type
else None)
if child.template.credit_type:
template_credit_type = template2type.get(
child.template.credit_type.id)
else:
template_credit_type = None
if current_credit_type != template_credit_type:
vals['credit_type'] = template_credit_type
if vals:
values.append([child])
values.append(vals)
template2account[child.template.id] = child.id
childs = sum((c.childs for c in childs), ())
if values:
self.write(*values)
def update_account2(self, template2account, template2tax):
'''
Update recursively account taxes and replaced_by base on template.
template2account is a dictionary with template id as key and account id
as value, used to convert template id into account.
template2tax is a dictionary with tax template id as key and tax id as
value, used to convert tax template id into tax.
'''
if template2account is None:
template2account = {}
if template2tax is None:
template2tax = {}
to_write = []
childs = [self]
while childs:
for child in childs:
if not child.template:
continue
values = {}
tax_ids = [template2tax[x.id] for x in child.template.taxes
if x.id in template2tax]
old_tax_ids = [x.id for x in child.taxes]
taxes_to_add = [x for x in tax_ids if x not in old_tax_ids]
taxes_to_remove = [x for x in old_tax_ids if x not in tax_ids]
if taxes_to_add or taxes_to_remove:
values['taxes'] = [
('add', taxes_to_add),
('remove', taxes_to_remove),
]
if child.template.parent:
parent = template2account[child.template.parent.id]
else:
parent = None
old_parent = child.parent.id if child.parent else None
if parent != old_parent:
values['parent'] = parent
if child.template.replaced_by:
replaced_by = template2account[
child.template.replaced_by.id]
else:
replaced_by = None
old_replaced_by = (
child.replaced_by.id if child.replaced_by else None)
if old_replaced_by != replaced_by:
values['replaced_by'] = replaced_by
if values:
to_write.append([child])
to_write.append(values)
childs = sum((c.childs for c in childs), ())
if to_write:
self.write(*to_write)
def current(self, date=None):
"Return the actual account for the date"
pool = Pool()
Date = pool.get('ir.date')
context = Transaction().context
if date is None:
with Transaction().set_context(company=self.company.id):
date = context.get('date') or Date.today()
if self.start_date and date < self.start_date:
return None
elif self.end_date and self.end_date < date:
if self.replaced_by:
return self.replaced_by.current(date=date)
else:
return None
else:
return self
@classmethod
def view_attributes(cls):
return super().view_attributes() + [
('//page[@id="general_ledger"]', 'states', {
'invisible': ((Eval('id', -1) < 0)
| ~Id('account', 'group_account').in_(
Eval('context', {}).get('groups', []))),
}),
('//link[@name="account.act_general_ledger_account_party_form"]',
'states', {
'invisible': ~Eval('party_required', False),
}),
]
class AccountParty(ActivePeriodMixin, ModelSQL):
"Account Party"
__name__ = 'account.account.party'
account = fields.Many2One('account.account', "Account")
party = fields.Many2One(
'party.party', "Party",
context={
'company': Eval('company', -1),
},
depends={'company'})
name = fields.Char("Name")
code = fields.Char("Code")
company = fields.Many2One('company.company', "Company")
type = fields.Many2One('account.account.type', "Type")
debit_type = fields.Many2One('account.account.type', "Debit Type")
credit_type = fields.Many2One('account.account.type', "Credit Type")
closed = fields.Boolean("Closed")
balance = fields.Function(Monetary(
"Balance", currency='currency', digits='currency'),
'get_balance')
credit = fields.Function(Monetary(
"Credit", currency='currency', digits='currency'),
'get_credit_debit')
debit = fields.Function(Monetary(
"Debit", currency='currency', digits='currency'),
'get_credit_debit')
amount_second_currency = fields.Function(Monetary(
"Amount Second Currency",
currency='second_currency', digits='second_currency',
states={
'invisible': ~Eval('second_currency'),
}),
'get_credit_debit')
line_count = fields.Function(
fields.Integer("Line Count"), 'get_credit_debit')
second_currency = fields.Many2One(
'currency.currency', "Secondary Currency")
currency = fields.Function(fields.Many2One(
'currency.currency', "Currency"),
'get_currency', searcher='search_currency')
@classmethod
def table_query(cls):
pool = Pool()
Line = pool.get('account.move.line')
Account = pool.get('account.account')
line = Line.__table__()
account = Account.__table__()
account_party = line.select(
Min(line.id).as_('id'), line.account, line.party,
where=line.party != Null,
group_by=[line.account, line.party])
columns = []
for fname, field in cls._fields.items():
if not hasattr(field, 'set'):
if fname in {'id', 'account', 'party'}:
column = Column(account_party, fname)
else:
column = Column(account, fname)
columns.append(column.as_(fname))
return (
account_party.join(
account, condition=account_party.account == account.id)
.select(
*columns,
where=account.party_required))
@classmethod
def get_balance(cls, records, name):
pool = Pool()
Account = pool.get('account.account')
MoveLine = pool.get('account.move.line')
FiscalYear = pool.get('account.fiscalyear')
cursor = Transaction().connection.cursor()
table_a = Account.__table__()
table_c = Account.__table__()
line = MoveLine.__table__()
ids = [a.id for a in records]
account_ids = {a.account.id for a in records}
party_ids = {a.party.id for a in records}
account_party2id = {(a.account.id, a.party.id): a.id for a in records}
balances = dict((i, Decimal(0)) for i in ids)
line_query, fiscalyear_ids = MoveLine.query_get(line)
for sub_account_ids in grouped_slice(account_ids):
account_sql = reduce_ids(table_a.id, sub_account_ids)
for sub_party_ids in grouped_slice(party_ids):
party_sql = reduce_ids(line.party, sub_party_ids)
cursor.execute(*table_a.join(table_c,
condition=(table_c.left >= table_a.left)
& (table_c.right <= table_a.right)
).join(line, condition=line.account == table_c.id
).select(
table_a.id,
line.party,
Sum(
Coalesce(line.debit, 0)
- Coalesce(line.credit, 0)),
where=account_sql & party_sql & line_query,
group_by=[table_a.id, line.party]))
for account_id, party_id, balance in cursor:
try:
id_ = account_party2id[(account_id, party_id)]
except KeyError:
# There can be more combinations of account-party in
# the database than from records
continue
balances[id_] = balance
for record in records:
# SQLite uses float for SUM
if not isinstance(balances[record.id], Decimal):
balances[record.id] = Decimal(str(balances[record.id]))
balances[record.id] = record.currency.round(balances[record.id])
fiscalyears = FiscalYear.browse(fiscalyear_ids)
def func(records, names):
return {names[0]: cls.get_balance(records, names[0])}
return Account._cumulate(
fiscalyears, records, [name], {name: balances}, func,
deferral=None)[name]
@classmethod
def get_credit_debit(cls, records, names):
pool = Pool()
Account = pool.get('account.account')
MoveLine = pool.get('account.move.line')
FiscalYear = pool.get('account.fiscalyear')
cursor = Transaction().connection.cursor()
result = {}
for name in names:
if name not in {
'credit', 'debit', 'amount_second_currency', 'line_count'}:
raise ValueError('Unknown name: %s' % name)
column_type = int if name == 'line_count' else Decimal
result[name] = defaultdict(column_type)
account_ids = {a.account.id for a in records}
party_ids = {a.party.id for a in records}
account_party2id = {(a.account.id, a.party.id): a.id for a in records}
table = Account.__table__()
line = MoveLine.__table__()
line_query, fiscalyear_ids = MoveLine.query_get(line)
columns = [table.id, line.party]
for name in names:
if name == 'line_count':
columns.append(Count(Literal('*')))
else:
columns.append(Sum(Coalesce(Column(line, name), 0)))
for sub_account_ids in grouped_slice(account_ids):
account_sql = reduce_ids(table.id, sub_account_ids)
for sub_party_ids in grouped_slice(party_ids):
party_sql = reduce_ids(line.party, sub_party_ids)
cursor.execute(*table.join(line, 'LEFT',
condition=line.account == table.id
).select(*columns,
where=account_sql & party_sql & line_query,
group_by=[table.id, line.party]))
for row in cursor:
try:
id_ = account_party2id[tuple(row[0:2])]
except KeyError:
# There can be more combinations of account-party in
# the database than from records
continue
for i, name in enumerate(names, 2):
# SQLite uses float for SUM
if (name != 'line_count'
and not isinstance(row[i], Decimal)):
result[name][id_] = Decimal(str(row[i]))
else:
result[name][id_] = row[i]
for record in records:
for name in names:
if name == 'line_count':
continue
if name == 'amount_second_currency' and record.second_currency:
currency = record.second_currency
else:
currency = record.currency
result[name][record.id] = currency.round(
result[name][record.id])
cumulate_names = []
if Transaction().context.get('cumulate'):
cumulate_names = names
elif 'amount_second_currency' in names:
cumulate_names = ['amount_second_currency']
if cumulate_names:
fiscalyears = FiscalYear.browse(fiscalyear_ids)
return Account._cumulate(
fiscalyears, records, cumulate_names, result,
cls.get_credit_debit, deferral=None)
else:
return result
def get_currency(self, name):
return self.company.currency.id
@classmethod
def search_currency(cls, name, clause):
return [('company.' + clause[0], *clause[1:])]
class AccountDeferral(ModelSQL, ModelView):
'''
Account Deferral
It is used to deferral the debit/credit of account by fiscal year.
'''
__name__ = 'account.account.deferral'
account = fields.Many2One('account.account', "Account", required=True)
fiscalyear = fields.Many2One(
'account.fiscalyear', "Fiscal Year", required=True)
debit = Monetary(
"Debit", currency='currency', digits='currency', required=True)
credit = Monetary(
"Credit", currency='currency', digits='currency', required=True)
balance = fields.Function(Monetary(
"Balance", currency='currency', digits='currency'),
'get_balance')
currency = fields.Function(fields.Many2One(
'currency.currency', "Currency"),
'get_currency', searcher='search_currency')
amount_second_currency = Monetary(
"Amount Second Currency",
currency='second_currency', digits='second_currency', required=True,
states={
'invisible': ~Eval('second_currency'),
})
line_count = fields.Integer("Line Count", required=True)
second_currency = fields.Function(fields.Many2One(
'currency.currency', "Second Currency"), 'get_second_currency')
@classmethod
def __setup__(cls):
super(AccountDeferral, cls).__setup__()
t = cls.__table__()
cls._sql_constraints += [
('deferral_uniq', Unique(t, t.account, t.fiscalyear),
'account.msg_deferral_unique'),
]
cls._sql_indexes.add(
Index(
t,
(t.fiscalyear, Index.Equality()),
(t.account, Index.Equality())))
@classmethod
def __register__(cls, module_name):
pool = Pool()
MoveLine = pool.get('account.move.line')
Move = pool.get('account.move')
Period = pool.get('account.period')
cursor = Transaction().connection.cursor()
deferral = cls.__table__()
move_line = MoveLine.__table__()
move = Move.__table__()
period = Period.__table__()
exist = backend.TableHandler.table_exist(cls._table)
table_h = cls.__table_handler__(module_name)
created_line_count = exist and not table_h.column_exist('line_count')
super().__register__(module_name)
# Migration from 6.2: add line_count on deferrals
if created_line_count:
counting_query = (move_line
.join(move, condition=move_line.move == move.id)
.join(period, condition=move.period == period.id)
.select(
move_line.account, period.fiscalyear,
Count(Literal('*')).as_('line_count'),
group_by=[move_line.account, period.fiscalyear]))
cursor.execute(*deferral.update(
[deferral.line_count], [counting_query.line_count],
from_=[counting_query],
where=((deferral.account == counting_query.account)
& (deferral.fiscalyear == counting_query.fiscalyear))))
@classmethod
def default_amount_second_currency(cls):
return Decimal(0)
@classmethod
def default_line_count(cls):
return 0
@classmethod
def get_balance(cls, deferrals, name):
pool = Pool()
Account = pool.get('account.account')
cursor = Transaction().connection.cursor()
table = cls.__table__()
table_child = cls.__table__()
account = Account.__table__()
account_child = Account.__table__()
balances = defaultdict(Decimal)
for sub_deferrals in grouped_slice(deferrals):
red_sql = reduce_ids(table.id, [d.id for d in sub_deferrals])
cursor.execute(*table
.join(account, condition=table.account == account.id)
.join(account_child,
condition=(account_child.left >= account.left)
& (account_child.right <= account.right))
.join(table_child,
condition=(table_child.account == account_child.id)
& (table_child.fiscalyear == table.fiscalyear))
.select(
table.id,
Sum(table_child.debit - table_child.credit),
where=red_sql,
group_by=table.id))
balances.update(dict(cursor))
for id_, balance in balances.items():
if not isinstance(balance, Decimal):
balances[id_] = Decimal(str(balance))
return balances
def get_currency(self, name):
return self.account.currency.id
@classmethod
def search_currency(cls, name, clause):
return [('account.' + clause[0], *clause[1:])]
def get_second_currency(self, name):
if self.account.second_currency:
return self.account.second_currency.id
def get_rec_name(self, name):
return '%s - %s' % (self.account.rec_name, self.fiscalyear.rec_name)
@classmethod
def search_rec_name(cls, name, clause):
if clause[1].startswith('!') or clause[1].startswith('not '):
bool_op = 'AND'
else:
bool_op = 'OR'
return [bool_op,
('account.rec_name',) + tuple(clause[1:]),
('fiscalyear.rec_name',) + tuple(clause[1:]),
]
@classmethod
def write(cls, deferrals, values, *args):
raise AccessError(gettext('account.msg_write_deferral'))
class AccountTax(ModelSQL):
'Account - Tax'
__name__ = 'account.account-account.tax'
_table = 'account_account_tax_rel'
account = fields.Many2One(
'account.account', "Account", ondelete='CASCADE', required=True)
tax = fields.Many2One(
'account.tax', "Tax", ondelete='RESTRICT', required=True)
class AccountContext(ModelView):
'Account Context'
__name__ = 'account.account.context'
company = fields.Many2One('company.company', "Company", required=True)
fiscalyear = fields.Many2One(
'account.fiscalyear', "Fiscal Year",
domain=[
('company', '=', Eval('company', -1)),
],
help="Leave empty for all open fiscal year.")
posted = fields.Boolean('Posted Moves', help="Only include posted moves.")
@classmethod
def default_company(cls):
return Transaction().context.get('company')
@fields.depends('company', 'fiscalyear')
def on_change_company(self):
if self.fiscalyear and self.fiscalyear.company != self.company:
self.fiscalyear = None
@classmethod
def default_posted(cls):
return False
class _GeneralLedgerAccount(ActivePeriodMixin, ModelSQL, ModelView):
account = fields.Many2One('account.account', "Account")
company = fields.Many2One('company.company', 'Company')
start_debit = fields.Function(Monetary(
"Start Debit", currency='currency', digits='currency',
states={
'invisible': ~Eval('line_count', -1),
}),
'get_account', searcher='search_account')
debit = fields.Function(Monetary(
"Debit", currency='currency', digits='currency',
states={
'invisible': ~Eval('line_count', -1),
}),
'get_debit_credit', searcher='search_debit_credit')
end_debit = fields.Function(Monetary(
"End Debit", currency='currency', digits='currency',
states={
'invisible': ~Eval('line_count', -1),
}),
'get_account', searcher='search_account')
start_credit = fields.Function(Monetary(
"Start Credit", currency='currency', digits='currency',
states={
'invisible': ~Eval('line_count', -1),
}),
'get_account', searcher='search_account')
credit = fields.Function(Monetary(
"Credit", currency='currency', digits='currency',
states={
'invisible': ~Eval('line_count', -1),
}),
'get_debit_credit', searcher='search_debit_credit')
end_credit = fields.Function(Monetary(
"End Credit", currency='currency', digits='currency',
states={
'invisible': ~Eval('line_count', -1),
}),
'get_account', searcher='search_account')
line_count = fields.Function(
fields.Integer("Line Count"),
'get_debit_credit', searcher='search_debit_credit')
start_balance = fields.Function(Monetary(
"Start Balance", currency='currency', digits='currency'),
'get_account', searcher='search_account')
end_balance = fields.Function(Monetary(
"End Balance", currency='currency', digits='currency'),
'get_account', searcher='search_account')
currency = fields.Function(fields.Many2One(
'currency.currency', "Currency"),
'get_currency', searcher='search_currency')
@classmethod
def __setup__(cls):
super().__setup__()
cls._order.insert(0, ('account', 'ASC'))
@classmethod
def table_query(cls):
pool = Pool()
LedgerAccountContext = pool.get(
'account.general_ledger.account.context')
context = LedgerAccountContext.get_context()
Account = cls._get_account()
account = Account.__table__()
columns = []
for fname, field in cls._fields.items():
if not hasattr(field, 'set'):
if (isinstance(field, fields.Many2One)
and field.get_target() == Account):
column = Column(account, 'id')
else:
column = Column(account, fname)
columns.append(column.as_(fname))
return account.select(*columns,
where=(account.company == context.get('company'))
& (account.type != Null)
& (account.closed != Literal(True)))
@classmethod
def get_period_ids(cls, name):
pool = Pool()
Period = pool.get('account.period')
LedgerAccountContext = pool.get(
'account.general_ledger.account.context')
context = LedgerAccountContext.get_context()
period = None
if name.startswith('start_'):
period_ids = []
if context.get('start_period'):
period = Period(context['start_period'])
elif name.startswith('end_'):
period_ids = []
if context.get('end_period'):
period = Period(context['end_period'])
else:
periods = Period.search([
('fiscalyear', '=', context.get('fiscalyear')),
('type', '=', 'standard'),
],
order=[('start_date', 'DESC')], limit=1)
if periods:
period, = periods
if period:
if name.startswith('start_'):
date_clause = ('end_date', '<=', period.start_date)
else:
date_clause = [
('end_date', '<=', period.end_date),
('start_date', '<', period.end_date),
]
periods = Period.search([
('fiscalyear', '=', context.get('fiscalyear')),
date_clause,
])
if period.start_date == period.end_date:
periods.append(period)
if periods:
period_ids = [p.id for p in periods]
if name.startswith('end_'):
# Always include ending period
period_ids.append(period.id)
return period_ids
@classmethod
def get_dates(cls, name):
pool = Pool()
LedgerAccountContext = pool.get(
'account.general_ledger.account.context')
context = LedgerAccountContext.get_context()
if name.startswith('start_'):
from_date = context.get('from_date') or datetime.date.min
if from_date:
try:
from_date -= datetime.timedelta(days=1)
except OverflowError:
pass
return None, from_date
elif name.startswith('end_'):
return None, context.get('to_date')
return None, None
@classmethod
def get_account(cls, records, name):
pool = Pool()
LedgerAccountContext = pool.get(
'account.general_ledger.account.context')
Account = cls._get_account()
period_ids, from_date, to_date = None, None, None
context = LedgerAccountContext.get_context()
if context.get('start_period') or context.get('end_period'):
period_ids = cls.get_period_ids(name)
elif context.get('from_date') or context.get('to_date'):
from_date, to_date = cls.get_dates(name)
else:
if name.startswith('start_'):
period_ids = []
with Transaction().set_context(
periods=period_ids,
from_date=from_date, to_date=to_date):
accounts = Account.browse(records)
fname = name
for test in ['start_', 'end_']:
if name.startswith(test):
fname = name[len(test):]
break
return {a.id: getattr(a, fname) for a in accounts}
@classmethod
def search_account(cls, name, domain):
Account = cls._get_account()
period_ids = cls.get_period_ids(name)
with Transaction().set_context(periods=period_ids):
accounts = Account.search([], order=[])
_, operator_, operand = domain
operator_ = {
'=': operator.eq,
'>=': operator.ge,
'>': operator.gt,
'<=': operator.le,
'<': operator.lt,
'!=': operator.ne,
'in': lambda v, l: v in l,
'not in': lambda v, l: v not in l,
}.get(operator_, lambda v, l: False)
fname = name
for test in ['start_', 'end_']:
if name.startswith(test):
fname = name[len(test):]
break
ids = [a.id for a in accounts
if operand is not None and operator_(getattr(a, fname), operand)]
return [('id', 'in', ids)]
@classmethod
def _debit_credit_context(cls):
pool = Pool()
LedgerAccountContext = pool.get(
'account.general_ledger.account.context')
period_ids, from_date, to_date = None, None, None
context = LedgerAccountContext.get_context()
if context.get('start_period') or context.get('end_period'):
start_period_ids = set(cls.get_period_ids('start_balance'))
end_period_ids = set(cls.get_period_ids('end_balance'))
period_ids = list(end_period_ids.difference(start_period_ids))
elif context.get('from_date') or context.get('to_date'):
from_date = context.get('from_date')
to_date = context.get('to_date')
return {
'periods': period_ids,
'from_date': from_date,
'to_date': to_date,
}
@classmethod
def get_debit_credit(cls, records, name):
Account = cls._get_account()
with Transaction().set_context(cls._debit_credit_context()):
accounts = Account.browse(records)
return {a.id: getattr(a, name) for a in accounts}
@classmethod
def search_debit_credit(cls, name, domain):
Account = cls._get_account()
with Transaction().set_context(cls._debit_credit_context()):
accounts = Account.search([], order=[])
_, operator_, operand = domain
operator_ = {
'=': operator.eq,
'>=': operator.ge,
'>': operator.gt,
'<=': operator.le,
'<': operator.lt,
'!=': operator.ne,
'in': lambda v, l: v in l,
'not in': lambda v, l: v not in l,
}.get(operator_, lambda v, l: False)
ids = [a.id for a in accounts
if operand is not None and operator_(getattr(a, name), operand)]
return [('id', 'in', ids)]
def get_currency(self, name):
return self.company.currency.id
@classmethod
def search_currency(cls, name, clause):
return [('company.' + clause[0], *clause[1:])]
def get_rec_name(self, name):
return self.account.rec_name
@classmethod
def search_rec_name(cls, name, clause):
return [('account.rec_name',) + tuple(clause[1:])]
class GeneralLedgerAccount(_GeneralLedgerAccount):
'General Ledger Account'
__name__ = 'account.general_ledger.account'
type = fields.Many2One('account.account.type', "Type")
debit_type = fields.Many2One('account.account.type', "Debit Type")
credit_type = fields.Many2One('account.account.type', "Credit Type")
lines = fields.One2Many(
'account.general_ledger.line', 'account', "Lines", readonly=True)
general_ledger_balance = fields.Boolean("General Ledger Balance")
@classmethod
def _get_account(cls):
pool = Pool()
return pool.get('account.account')
class GeneralLedgerAccountContext(ModelView):
'General Ledger Account Context'
__name__ = 'account.general_ledger.account.context'
fiscalyear = fields.Many2One('account.fiscalyear', 'Fiscal Year',
required=True,
domain=[
('company', '=', Eval('company')),
],
depends=['company'])
start_period = fields.Many2One('account.period', 'Start Period',
domain=[
('fiscalyear', '=', Eval('fiscalyear')),
('start_date', '<=', (Eval('end_period'), 'start_date')),
],
states={
'invisible': Eval('from_date', False) | Eval('to_date', False),
})
end_period = fields.Many2One('account.period', 'End Period',
domain=[
('fiscalyear', '=', Eval('fiscalyear')),
('start_date', '>=', (Eval('start_period'), 'start_date'))
],
states={
'invisible': Eval('from_date', False) | Eval('to_date', False),
})
from_date = fields.Date("From Date",
domain=[
If(Eval('to_date') & Eval('from_date'),
('from_date', '<=', Eval('to_date')),
()),
],
states={
'invisible': (Eval('start_period', False)
| Eval('end_period', False)),
})
to_date = fields.Date("To Date",
domain=[
If(Eval('from_date') & Eval('to_date'),
('to_date', '>=', Eval('from_date')),
()),
],
states={
'invisible': (Eval('start_period', False)
| Eval('end_period', False)),
})
company = fields.Many2One('company.company', 'Company', required=True)
posted = fields.Boolean('Posted Moves', help="Only include posted moves.")
journal = fields.Many2One(
'account.journal', "Journal",
context={
'company': Eval('company', -1),
},
depends={'company'},
help="Only include moves from the journal.")
@classmethod
def default_fiscalyear(cls):
pool = Pool()
FiscalYear = pool.get('account.fiscalyear')
Period = pool.get('account.period')
context = Transaction().context
fiscalyear_id = context.get('fiscalyear')
period_id = context.get('period')
if fiscalyear_id is not None and fiscalyear_id >= 0:
return fiscalyear_id
elif period_id is not None and period_id >= 0:
period = Period(period_id)
return period.fiscalyear.id
else:
try:
fiscalyear = FiscalYear.find(
context.get('company'), test_state=False)
except FiscalYearNotFoundError:
return None
return fiscalyear.id
@classmethod
def default_start_period(cls):
return Transaction().context.get('start_period')
@classmethod
def default_end_period(cls):
return Transaction().context.get('end_period')
@classmethod
def default_company(cls):
return Transaction().context.get('company')
@classmethod
def default_posted(cls):
return Transaction().context.get('posted', False)
@classmethod
def default_journal(cls):
return Transaction().context.get('journal')
@classmethod
def default_from_date(cls):
return Transaction().context.get('from_date')
@classmethod
def default_to_date(cls):
return Transaction().context.get('to_date')
@fields.depends('company', 'fiscalyear', methods=['on_change_fiscalyear'])
def on_change_company(self):
if self.fiscalyear and self.fiscalyear.company != self.company:
self.fiscalyear = None
self.on_change_fiscalyear()
@fields.depends('fiscalyear', 'start_period', 'end_period')
def on_change_fiscalyear(self):
if (self.start_period
and self.start_period.fiscalyear != self.fiscalyear):
self.start_period = None
if (self.end_period
and self.end_period.fiscalyear != self.fiscalyear):
self.end_period = None
@fields.depends('start_period')
def on_change_start_period(self):
if self.start_period:
self.from_date = self.to_date = None
@fields.depends('end_period')
def on_change_end_period(self):
if self.end_period:
self.from_date = self.to_date = None
@fields.depends('from_date')
def on_change_from_date(self):
if self.from_date:
self.start_period = self.end_period = None
@fields.depends('to_date')
def on_change_to_date(self):
if self.to_date:
self.start_period = self.end_period = None
@classmethod
def get_context(cls, fields_names=None):
fields_names = fields_names.copy() if fields_names is not None else []
fields_names += [
'fiscalyear', 'start_period', 'end_period', 'from_date', 'to_date',
'company', 'posted', 'journal']
return cls.default_get(fields_names, with_rec_name=False)
class GeneralLedgerAccountParty(_GeneralLedgerAccount):
"General Ledger Account Party"
__name__ = 'account.general_ledger.account.party'
party = fields.Many2One(
'party.party', "Party",
context={
'company': Eval('company', -1),
},
depends={'company'})
@classmethod
def __setup__(cls):
super().__setup__()
cls._order.insert(2, ('party', 'ASC'))
@classmethod
def _get_account(cls):
pool = Pool()
return pool.get('account.account.party')
def get_rec_name(self, name):
return ' - '.join((self.account.rec_name, self.party.rec_name))
@classmethod
def search_rec_name(cls, name, clause):
if clause[1].startswith('!') or clause[1].startswith('not '):
bool_op = 'AND'
else:
bool_op = 'OR'
return [bool_op,
('account.rec_name',) + tuple(clause[1:]),
('party.rec_name',) + tuple(clause[1:]),
]
class OpenGeneralLedgerAccountParty(Wizard):
"Open General Ledger Account Party"
__name__ = 'account.general_ledger.account.party.open'
start_state = 'open'
open = StateAction('account.act_general_ledger_line_form')
def do_open(self, action):
action['name'] = '%s (%s)' % (action['name'], self.record.rec_name)
domain = [
('account', '=', self.record.account.id),
('party', '=', self.record.party.id),
]
action['pyson_domain'] = PYSONEncoder().encode(domain)
action['context_model'] = 'account.general_ledger.account.context'
action['pyson_context'] = PYSONEncoder().encode({
'party_cumulate': True,
})
return action, {}
class GeneralLedgerLine(DescriptionOriginMixin, ModelSQL, ModelView):
'General Ledger Line'
__name__ = 'account.general_ledger.line'
move = fields.Many2One('account.move', 'Move')
date = fields.Date('Date')
account = fields.Many2One('account.general_ledger.account', 'Account')
party = fields.Many2One('party.party', 'Party',
states={
'invisible': ~Eval('party_required', False),
},
context={
'company': Eval('company', -1),
},
depends={'company'})
party_required = fields.Boolean('Party Required')
account_party = fields.Function(
fields.Many2One(
'account.general_ledger.account.party', "Account Party"),
'get_account_party')
company = fields.Many2One('company.company', 'Company')
debit = Monetary(
"Debit", currency='currency', digits='currency')
credit = Monetary(
"Credit", currency='currency', digits='currency')
internal_balance = Monetary(
"Internal Balance", currency='currency', digits='currency')
balance = fields.Function(Monetary(
"Balance", currency='currency', digits='currency'),
'get_balance')
origin = fields.Reference('Origin', selection='get_origin')
description = fields.Char('Description')
move_description_used = fields.Function(
fields.Char("Move Description"),
'get_move_field',
searcher='search_move_field')
amount_second_currency = Monetary(
"Amount Second Currency",
currency='second_currency', digits='second_currency')
second_currency = fields.Many2One('currency.currency', 'Second Currency')
reconciliation = fields.Many2One(
'account.move.reconciliation', "Reconciliation")
state = fields.Selection([
('draft', 'Draft'),
('posted', 'Posted'),
], "State", sort=False)
state_string = state.translated('state')
currency = fields.Function(fields.Many2One(
'currency.currency', "Currency"),
'get_currency', searcher='search_currency')
@classmethod
def __setup__(cls):
super(GeneralLedgerLine, cls).__setup__()
cls.__access__.add('account')
cls._order.insert(0, ('date', 'ASC'))
cls.description_used.setter = None
@classmethod
def table_query(cls):
pool = Pool()
Line = pool.get('account.move.line')
Move = pool.get('account.move')
LedgerAccount = pool.get('account.general_ledger.account')
LedgerLineContext = pool.get(
'account.general_ledger.line.context')
Account = pool.get('account.account')
transaction = Transaction()
database = transaction.database
context = LedgerLineContext.get_context()
line = Line.__table__()
move = Move.__table__()
account = Account.__table__()
columns = []
for fname, field in cls._fields.items():
if hasattr(field, 'set'):
continue
field_line = getattr(Line, fname, None)
if fname == 'internal_balance':
if database.has_window_functions():
w_columns = [line.account]
if context.get('party_cumulate', False):
w_columns.append(line.party)
column = Sum(line.debit - line.credit,
window=Window(w_columns,
order_by=[move.date.asc, line.id])).as_(
'internal_balance')
else:
column = (line.debit - line.credit).as_('internal_balance')
elif fname == 'move_description':
column = Column(move, 'description').as_(fname)
elif fname == 'party_required':
column = Column(account, 'party_required').as_(fname)
elif (not field_line
or fname == 'state'
or isinstance(field_line, fields.Function)):
column = Column(move, fname).as_(fname)
else:
column = Column(line, fname).as_(fname)
columns.append(column)
with Transaction().set_context(
context, **LedgerAccount._debit_credit_context()):
line_query, fiscalyear_ids = Line.query_get(line)
return line.join(move, condition=line.move == move.id
).join(account, condition=line.account == account.id
).select(*columns, where=line_query)
def get_move_field(self, name):
field = getattr(self.__class__, name)
if name.startswith('move_'):
name = name[5:]
value = getattr(self.move, name)
if isinstance(value, ModelSQL):
if field._type == 'reference':
return str(value)
return value.id
return value
@classmethod
def search_move_field(cls, name, clause):
nested = clause[0][len(name):]
if name.startswith('move_'):
name = name[5:]
return [('move.' + name + nested, *clause[1:])]
def get_currency(self, name):
return self.company.currency.id
@classmethod
def search_currency(cls, name, clause):
return [('company.' + clause[0], *clause[1:])]
@classmethod
def get_origin(cls):
Line = Pool().get('account.move.line')
return Line.get_origin()
def get_balance(self, name):
pool = Pool()
LedgerLineContext = pool.get(
'account.general_ledger.line.context')
transaction = Transaction()
context = LedgerLineContext.get_context()
database = transaction.database
balance = self.internal_balance
if database.has_window_functions():
if context.get('party_cumulate', False) and self.account_party:
balance += self.account_party.start_balance
else:
balance += self.account.start_balance
return balance
@classmethod
def get_account_party(cls, records, name):
pool = Pool()
AccountParty = pool.get('account.general_ledger.account.party')
account_party = AccountParty.__table__()
cursor = Transaction().connection.cursor()
account_parties = {}
account_party2ids = defaultdict(list)
account_ids, party_ids = set(), set()
for r in records:
account_parties[r.id] = None
if not r.party:
continue
account_party2ids[r.account.id, r.party.id].append(r.id)
account_ids.add(r.account.id)
party_ids.add(r.party.id)
query = account_party.select(
account_party.account, account_party.party, account_party.id)
for sub_account_ids in grouped_slice(account_ids):
account_where = reduce_ids(account_party.account, sub_account_ids)
for sub_party_ids in grouped_slice(party_ids):
query.where = (account_where
& reduce_ids(account_party.party, sub_party_ids))
cursor.execute(*query)
for account, party, id_ in cursor:
key = (account, party)
try:
account_party_ids = account_party2ids[key]
except KeyError:
# There can be more combinations of account-party in
# the database than from records
continue
for record_id in account_party_ids:
account_parties[record_id] = id_
return account_parties
@classmethod
def reconcile(cls, *lines_list, **kwargs):
pool = Pool()
Line = pool.get('account.move.line')
lines_list = [Line.browse(l) for l in lines_list]
return Line.reconcile(*lines_list, **kwargs)
class GeneralLedgerLineContext(GeneralLedgerAccountContext):
'General Ledger Line Context'
__name__ = 'account.general_ledger.line.context'
party_cumulate = fields.Boolean('Cumulate per Party')
@classmethod
def default_party_cumulate(cls):
return Transaction().context.get('party_cumulate', False)
@classmethod
def get_context(cls, fields_names=None):
fields_names = fields_names.copy() if fields_names is not None else []
fields_names.append('party_cumulate')
return super().get_context(fields_names=fields_names)
class GeneralLedger(Report):
__name__ = 'account.general_ledger'
@classmethod
def get_context(cls, records, header, data):
pool = Pool()
Company = pool.get('company.company')
Fiscalyear = pool.get('account.fiscalyear')
Period = pool.get('account.period')
context = Transaction().context
report_context = super().get_context(records, header, data)
report_context['company'] = Company(context['company'])
report_context['fiscalyear'] = Fiscalyear(context['fiscalyear'])
for period in ['start_period', 'end_period']:
if context.get(period):
report_context[period] = Period(context[period])
else:
report_context[period] = None
report_context['from_date'] = context.get('from_date')
report_context['to_date'] = context.get('to_date')
report_context['accounts'] = records
return report_context
class TrialBalance(Report):
__name__ = 'account.trial_balance'
@classmethod
def get_context(cls, records, header, data):
pool = Pool()
Company = pool.get('company.company')
Fiscalyear = pool.get('account.fiscalyear')
Period = pool.get('account.period')
context = Transaction().context
report_context = super().get_context(records, header, data)
report_context['company'] = Company(context['company'])
report_context['fiscalyear'] = Fiscalyear(context['fiscalyear'])
for period in ['start_period', 'end_period']:
if context.get(period):
report_context[period] = Period(context[period])
else:
report_context[period] = None
report_context['from_date'] = context.get('from_date')
report_context['to_date'] = context.get('to_date')
report_context['accounts'] = records
report_context['sum'] = cls.sum
return report_context
@classmethod
def sum(cls, accounts, field):
return sum((getattr(a, field) for a in accounts), Decimal('0'))
class BalanceSheetContext(ModelView):
'Balance Sheet Context'
__name__ = 'account.balance_sheet.context'
date = fields.Date('Date', required=True)
company = fields.Many2One('company.company', 'Company', required=True)
posted = fields.Boolean('Posted Moves', help="Only include posted moves.")
@staticmethod
def default_date():
Date_ = Pool().get('ir.date')
return Transaction().context.get('date', Date_.today())
@staticmethod
def default_company():
return Transaction().context.get('company')
@staticmethod
def default_posted():
return Transaction().context.get('posted', False)
class BalanceSheetComparisionContext(BalanceSheetContext):
'Balance Sheet Context'
__name__ = 'account.balance_sheet.comparison.context'
comparison = fields.Boolean('Comparison')
date_cmp = fields.Date('Date', states={
'required': Eval('comparison', False),
'invisible': ~Eval('comparison', False),
})
@classmethod
def default_comparison(cls):
return False
@fields.depends('comparison', 'date', 'date_cmp')
def on_change_comparison(self):
self.date_cmp = None
if self.comparison and self.date:
self.date_cmp = self.date - relativedelta(years=1)
@classmethod
def view_attributes(cls):
return super().view_attributes() + [
('/form/separator[@id="comparison"]', 'states', {
'invisible': ~Eval('comparison', False),
}),
]
class IncomeStatementContext(ModelView):
'Income Statement Context'
__name__ = 'account.income_statement.context'
fiscalyear = fields.Many2One('account.fiscalyear', 'Fiscal Year',
required=True,
domain=[
('company', '=', Eval('company')),
])
start_period = fields.Many2One('account.period', 'Start Period',
domain=[
('fiscalyear', '=', Eval('fiscalyear')),
('start_date', '<=', (Eval('end_period'), 'start_date'))
],
states={
'invisible': Eval('from_date', False) | Eval('to_date', False),
})
end_period = fields.Many2One('account.period', 'End Period',
domain=[
('fiscalyear', '=', Eval('fiscalyear')),
('start_date', '>=', (Eval('start_period'), 'start_date')),
],
states={
'invisible': Eval('from_date', False) | Eval('to_date', False),
})
from_date = fields.Date("From Date",
domain=[
If(Eval('to_date') & Eval('from_date'),
('from_date', '<=', Eval('to_date')),
()),
],
states={
'invisible': (
Eval('start_period', False) | Eval('end_period', False)),
})
to_date = fields.Date("To Date",
domain=[
If(Eval('from_date') & Eval('to_date'),
('to_date', '>=', Eval('from_date')),
()),
],
states={
'invisible': (
Eval('start_period', False) | Eval('end_period', False)),
})
company = fields.Many2One('company.company', 'Company', required=True)
posted = fields.Boolean('Posted Move', help="Only include posted moves.")
comparison = fields.Boolean('Comparison')
fiscalyear_cmp = fields.Many2One('account.fiscalyear', 'Fiscal Year',
states={
'required': Eval('comparison', False),
'invisible': ~Eval('comparison', False),
},
domain=[
('company', '=', Eval('company')),
])
start_period_cmp = fields.Many2One('account.period', 'Start Period',
domain=[
('fiscalyear', '=', Eval('fiscalyear_cmp')),
('start_date', '<=', (Eval('end_period_cmp'), 'start_date'))
],
states={
'invisible': ~Eval('comparison', False),
})
end_period_cmp = fields.Many2One('account.period', 'End Period',
domain=[
('fiscalyear', '=', Eval('fiscalyear_cmp')),
('start_date', '>=', (Eval('start_period_cmp'), 'start_date')),
],
states={
'invisible': ~Eval('comparison', False),
})
from_date_cmp = fields.Date("From Date",
domain=[
If(Eval('to_date_cmp') & Eval('from_date_cmp'),
('from_date_cmp', '<=', Eval('to_date_cmp')),
()),
],
states={
'invisible': ~Eval('comparison', False),
})
to_date_cmp = fields.Date("To Date",
domain=[
If(Eval('from_date_cmp') & Eval('to_date_cmp'),
('to_date_cmp', '>=', Eval('from_date_cmp')),
()),
],
states={
'invisible': ~Eval('comparison', False),
})
@classmethod
def default_fiscalyear(cls):
pool = Pool()
FiscalYear = pool.get('account.fiscalyear')
try:
fiscalyear = FiscalYear.find(
cls.default_company(), test_state=False)
except FiscalYearNotFoundError:
return None
return fiscalyear.id
@staticmethod
def default_company():
return Transaction().context.get('company')
@staticmethod
def default_posted():
return False
@classmethod
def default_comparison(cls):
return False
@fields.depends('company', 'fiscalyear', methods=['on_change_fiscalyear'])
def on_change_company(self):
if self.fiscalyear and self.fiscalyear.company != self.company:
self.fiscalyear = None
self.on_change_fiscalyear()
@fields.depends('fiscalyear', 'start_period', 'end_period')
def on_change_fiscalyear(self):
if (self.start_period
and self.start_period.fiscalyear != self.fiscalyear):
self.start_period = None
if (self.end_period
and self.end_period.fiscalyear != self.fiscalyear):
self.end_period = None
@fields.depends('start_period')
def on_change_start_period(self):
if self.start_period:
self.from_date = self.to_date = None
@fields.depends('end_period')
def on_change_end_period(self):
if self.end_period:
self.from_date = self.to_date = None
@fields.depends('from_date')
def on_change_from_date(self):
if self.from_date:
self.start_period = self.end_period = None
@fields.depends('to_date')
def on_change_to_date(self):
if self.to_date:
self.start_period = self.end_period = None
@classmethod
def view_attributes(cls):
return super().view_attributes() + [
('/form/separator[@id="comparison"]', 'states', {
'invisible': ~Eval('comparison', False),
}),
]
class AgedBalanceContext(ModelView):
'Aged Balance Context'
__name__ = 'account.aged_balance.context'
type = fields.Selection([
('customer', 'Customers'),
('supplier', 'Suppliers'),
('customer_supplier', 'Customers and Suppliers'),
],
"Type", required=True)
date = fields.Date('Date', required=True)
term1 = fields.Integer("First Term", required=True)
term2 = fields.Integer("Second Term", required=True,
domain=[
('term2', '>', Eval('term1', 0)),
])
term3 = fields.Integer("Third Term", required=True,
domain=[
('term3', '>', Eval('term2', 0)),
])
unit = fields.Selection([
('day', 'Days'),
('week', "Weeks"),
('month', 'Months'),
('year', "Years"),
], "Unit", required=True, sort=False)
company = fields.Many2One('company.company', 'Company', required=True)
posted = fields.Boolean('Posted Move', help="Only include posted moves.")
@classmethod
def default_type(cls):
return 'customer'
@classmethod
def default_posted(cls):
return False
@classmethod
def default_date(cls):
return Pool().get('ir.date').today()
@classmethod
def default_term1(cls):
return cls._default_terms(cls.default_unit())[0]
@classmethod
def default_term2(cls):
return cls._default_terms(cls.default_unit())[1]
@classmethod
def default_term3(cls):
return cls._default_terms(cls.default_unit())[2]
@classmethod
def default_unit(cls):
return 'day'
@fields.depends('unit')
def on_change_unit(self):
self.term1, self.term2, self.term3 = self._default_terms(self.unit)
@classmethod
def _default_terms(cls, unit):
terms = None, None, None
if unit == 'day':
terms = 30, 60, 90
elif unit == 'week':
terms = 4, 8, 12
elif unit in {'month', 'year'}:
terms = 1, 2, 3
return terms
@staticmethod
def default_company():
return Transaction().context.get('company')
class AgedBalance(ModelSQL, ModelView):
'Aged Balance'
__name__ = 'account.aged_balance'
party = fields.Many2One(
'party.party', 'Party',
context={
'company': Eval('company', -1),
},
depends={'company'})
company = fields.Many2One('company.company', 'Company')
term0 = Monetary(
"Now", currency='currency', digits='currency')
term1 = Monetary(
"First Term", currency='currency', digits='currency')
term2 = Monetary(
"Second Term", currency='currency', digits='currency')
term3 = Monetary(
"Third Term", currency='currency', digits='currency')
balance = Monetary(
"Balance", currency='currency', digits='currency')
currency = fields.Function(fields.Many2One(
'currency.currency', "Currency"),
'get_currency', searcher='search_currency')
@classmethod
def __setup__(cls):
super(AgedBalance, cls).__setup__()
cls._order.insert(0, ('party', 'ASC'))
@classmethod
def table_query(cls):
pool = Pool()
context = Transaction().context
MoveLine = pool.get('account.move.line')
Move = pool.get('account.move')
Reconciliation = pool.get('account.move.reconciliation')
Account = pool.get('account.account')
Type = pool.get('account.account.type')
line = MoveLine.__table__()
move = Move.__table__()
reconciliation = Reconciliation.__table__()
account = Account.__table__()
type_ = Type.__table__()
debit_type = Type.__table__()
credit_type = Type.__table__()
company_id = context.get('company')
date = context.get('date')
kind = cls.get_kind(type_)
debit_kind = (
cls.get_kind(debit_type)
& (line.debit != 0))
credit_kind = (
cls.get_kind(credit_type)
& (line.credit != 0))
columns = [
line.party.as_('id'),
Literal(0).as_('create_uid'),
Max(line.create_date).as_('create_date'),
Literal(0).as_('write_uid'),
Max(line.write_date).as_('write_date'),
line.party.as_('party'),
move.company.as_('company'),
(Sum(line.debit) - Sum(line.credit)).as_('balance'),
]
terms = cls.get_terms()
factor = cls.get_unit_factor()
# Ensure None are before 0 to get the next index pointing to the next
# value and not a None value
term_values = sorted(
list(terms.values()), key=lambda x: ((x is not None), x or 0))
line_date = Coalesce(line.maturity_date, move.date)
for name, value in terms.items():
if value is None or factor is None or date is None:
columns.append(Literal(None).as_(name))
continue
cond = line_date <= (date - value * factor)
idx = term_values.index(value)
if idx + 1 < len(terms):
cond &= line_date > (
date - (term_values[idx + 1] or 0) * factor)
columns.append(
Sum(Case((cond, line.debit - line.credit), else_=0)).as_(name))
return line.join(move, condition=line.move == move.id
).join(account, condition=line.account == account.id
).join(type_, condition=account.type == type_.id
).join(debit_type, 'LEFT',
condition=account.debit_type == debit_type.id
).join(credit_type, 'LEFT',
condition=account.credit_type == credit_type.id
).join(reconciliation, 'LEFT',
condition=reconciliation.id == line.reconciliation
).select(*columns,
where=(line.party != Null)
& (kind | debit_kind | credit_kind)
& ((line.reconciliation == Null)
| (reconciliation.date > date))
& (move.date <= date)
& (account.company == company_id),
group_by=(line.party, move.company))
@classmethod
def get_terms(cls):
context = Transaction().context
return {
'term0': 0,
'term1': context.get('term1'),
'term2': context.get('term2'),
'term3': context.get('term3'),
}
@classmethod
def get_unit_factor(cls):
context = Transaction().context
return {
'year': relativedelta(years=1),
'month': relativedelta(months=1),
'week': relativedelta(weeks=1),
'day': relativedelta(days=1)
}.get(context.get('unit', 'day'))
@classmethod
def get_kind(cls, account_type):
context = Transaction().context
type_ = context.get('type', 'customer')
if type_ == 'customer_supplier':
return account_type.payable | account_type.receivable
elif type_ == 'supplier':
return account_type.payable
elif type_ == 'customer':
return account_type.receivable
else:
return Literal(False)
def get_currency(self, name):
return self.company.currency.id
@classmethod
def search_currency(cls, name, clause):
return [('company.' + clause[0], *clause[1:])]
class AgedBalanceReport(Report):
__name__ = 'account.aged_balance'
@classmethod
def get_context(cls, records, header, data):
pool = Pool()
Company = pool.get('company.company')
Context = pool.get('account.aged_balance.context')
AgedBalance = pool.get('account.aged_balance')
context = Transaction().context
report_context = super().get_context(records, header, data)
context_fields = Context.fields_get(['type', 'unit'])
report_context['company'] = Company(context['company'])
report_context['date'] = context['date']
report_context['type'] = dict(
context_fields['type']['selection'])[context['type']]
report_context['unit'] = dict(
context_fields['unit']['selection'])[context['unit']]
report_context.update(AgedBalance.get_terms())
report_context['sum'] = cls.sum
return report_context
@classmethod
def sum(cls, records, field):
return sum((getattr(r, field) for r in records), Decimal('0'))
class CreateChartStart(ModelView):
'Create Chart'
__name__ = 'account.create_chart.start'
class CreateChartAccount(ModelView):
'Create Chart'
__name__ = 'account.create_chart.account'
company = fields.Many2One('company.company', 'Company', required=True)
account_template = fields.Many2One('account.account.template',
'Account Template', required=True, domain=[('parent', '=', None)])
@staticmethod
def default_company():
return Transaction().context.get('company')
class CreateChartProperties(ModelView):
'Create Chart'
__name__ = 'account.create_chart.properties'
company = fields.Many2One('company.company', 'Company')
account_receivable = fields.Many2One('account.account',
'Default Receivable Account',
domain=[
('closed', '!=', True),
('type.receivable', '=', True),
('party_required', '=', True),
('company', '=', Eval('company')),
])
account_payable = fields.Many2One('account.account',
'Default Payable Account',
domain=[
('closed', '!=', True),
('type.payable', '=', True),
('party_required', '=', True),
('company', '=', Eval('company')),
])
class CreateChart(Wizard):
'Create Chart'
__name__ = 'account.create_chart'
start = StateView('account.create_chart.start',
'account.create_chart_start_view_form', [
Button('Cancel', 'end', 'tryton-cancel'),
Button('OK', 'account', 'tryton-ok', default=True),
])
account = StateView('account.create_chart.account',
'account.create_chart_account_view_form', [
Button('Cancel', 'end', 'tryton-cancel'),
Button('Create', 'create_account', 'tryton-ok', default=True),
])
create_account = StateTransition()
properties = StateView('account.create_chart.properties',
'account.create_chart_properties_view_form', [
Button('Cancel', 'end', 'tryton-cancel'),
Button('Create', 'create_properties', 'tryton-ok', default=True),
])
create_properties = StateTransition()
def transition_create_account(self):
pool = Pool()
TaxCodeTemplate = pool.get('account.tax.code.template')
TaxCodeLineTemplate = pool.get('account.tax.code.line.template')
TaxTemplate = pool.get('account.tax.template')
TaxRuleTemplate = pool.get('account.tax.rule.template')
TaxRuleLineTemplate = \
pool.get('account.tax.rule.line.template')
Config = pool.get('ir.configuration')
Account = pool.get('account.account')
Warning = pool.get('res.user.warning')
transaction = Transaction()
company = self.account.company
# Skip access rule
with transaction.set_user(0):
accounts = Account.search([('company', '=', company.id)], limit=1)
if accounts:
key = 'duplicated_chart.%d' % company.id
if Warning.check(key):
raise ChartWarning(key,
gettext('account.msg_account_chart_exists',
company=company.rec_name))
with transaction.set_context(language=Config.get_language(),
company=company.id):
account_template = self.account.account_template
# Create account types
template2type = {}
account_template.type.create_type(
company.id,
template2type=template2type)
# Create accounts
template2account = {}
account_template.create_account(
company.id,
template2account=template2account,
template2type=template2type)
# Create taxes
template2tax = {}
TaxTemplate.create_tax(
account_template.id, company.id,
template2account=template2account,
template2tax=template2tax)
# Create tax codes
template2tax_code = {}
TaxCodeTemplate.create_tax_code(
account_template.id, company.id,
template2tax_code=template2tax_code)
# Create tax code lines
template2tax_code_line = {}
TaxCodeLineTemplate.create_tax_code_line(
account_template.id,
template2tax=template2tax,
template2tax_code=template2tax_code,
template2tax_code_line=template2tax_code_line)
# Update taxes and replaced_by on accounts
account_template.update_account2(template2account, template2tax)
# Create tax rules
template2rule = {}
TaxRuleTemplate.create_rule(
account_template.id, company.id,
template2rule=template2rule)
# Create tax rule lines
template2rule_line = {}
TaxRuleLineTemplate.create_rule_line(
account_template.id, template2tax, template2rule,
template2rule_line=template2rule_line)
return 'properties'
def get_account(self, template_id):
pool = Pool()
Account = pool.get('account.account')
ModelData = pool.get('ir.model.data')
template_id = ModelData.get_id(template_id)
account, = Account.search([
('template', '=', template_id),
('company', '=', self.account.company.id),
], limit=1)
return account.id
def default_properties(self, fields):
pool = Pool()
Account = pool.get('account.account')
defaults = {
'company': self.account.company.id,
}
receivable_accounts = Account.search([
('type.receivable', '=', True),
('company', '=', self.account.company.id),
], limit=2)
payable_accounts = Account.search([
('type.payable', '=', True),
('company', '=', self.account.company.id),
], limit=2)
if len(receivable_accounts) == 1:
defaults['account_receivable'] = receivable_accounts[0].id
else:
defaults['account_receivable'] = None
if len(payable_accounts) == 1:
defaults['account_payable'] = payable_accounts[0].id
else:
defaults['account_payable'] = None
return defaults
def transition_create_properties(self):
pool = Pool()
Configuration = pool.get('account.configuration')
with Transaction().set_context(company=self.properties.company.id):
account_receivable = self.properties.account_receivable
account_payable = self.properties.account_payable
config = Configuration(1)
config.default_account_receivable = account_receivable
config.default_account_payable = account_payable
config.save()
return 'end'
class UpdateChartStart(ModelView):
'Update Chart'
__name__ = 'account.update_chart.start'
account = fields.Many2One(
'account.account', "Root Account", required=True,
domain=[
('parent', '=', None),
('template', '!=', None),
])
class UpdateChartSucceed(ModelView):
'Update Chart'
__name__ = 'account.update_chart.succeed'
class UpdateChart(Wizard):
'Update Chart'
__name__ = 'account.update_chart'
start = StateView('account.update_chart.start',
'account.update_chart_start_view_form', [
Button('Cancel', 'end', 'tryton-cancel'),
Button('Update', 'update', 'tryton-ok', default=True),
])
update = StateTransition()
succeed = StateView('account.update_chart.succeed',
'account.update_chart_succeed_view_form', [
Button('OK', 'end', 'tryton-ok', default=True),
])
@check_access
def default_start(self, fields):
pool = Pool()
Account = pool.get('account.account')
defaults = {}
charts = Account.search([
('parent', '=', None),
('template', '!=', None),
], limit=2)
if len(charts) == 1:
defaults['account'] = charts[0].id
return defaults
@inactive_records
def transition_update(self):
pool = Pool()
Account = pool.get('account.account')
TaxCode = pool.get('account.tax.code')
TaxCodeTemplate = pool.get('account.tax.code.template')
TaxCodeLine = pool.get('account.tax.code.line')
TaxCodeLineTemplate = pool.get('account.tax.code.line.template')
Tax = pool.get('account.tax')
TaxTemplate = pool.get('account.tax.template')
TaxRule = pool.get('account.tax.rule')
TaxRuleTemplate = pool.get('account.tax.rule.template')
TaxRuleLine = pool.get('account.tax.rule.line')
TaxRuleLineTemplate = \
pool.get('account.tax.rule.line.template')
# re-browse to have inactive context
account = Account(self.start.account.id)
company = account.company
template2type = {}
# Update account types
account.type.update_type(template2type=template2type)
# Create missing account types
if account.type.template:
account.type.template.create_type(
company.id,
template2type=template2type)
# Update again to set new parent
account.type.update_type(template2type=template2type)
# Update accounts
template2account = {}
account.update_account(template2account=template2account,
template2type=template2type)
# Create missing accounts
if account.template:
account.template.create_account(
company.id,
template2account=template2account,
template2type=template2type)
# Update taxes
template2tax = {}
Tax.update_tax(
company.id,
template2account=template2account,
template2tax=template2tax)
# Create missing taxes
if account.template:
TaxTemplate.create_tax(
account.template.id, account.company.id,
template2account=template2account,
template2tax=template2tax)
# Update again to set new parent
Tax.update_tax(
company.id,
template2account=template2account,
template2tax=template2tax)
# Update tax codes
template2tax_code = {}
TaxCode.update_tax_code(
company.id,
template2tax_code=template2tax_code)
# Create missing tax codes
if account.template:
TaxCodeTemplate.create_tax_code(
account.template.id, company.id,
template2tax_code=template2tax_code)
# Update again to set new parent
TaxCode.update_tax_code(
company.id,
template2tax_code=template2tax_code)
# Update tax code lines
template2tax_code_line = {}
TaxCodeLine.update_tax_code_line(
company.id,
template2tax=template2tax,
template2tax_code=template2tax_code,
template2tax_code_line=template2tax_code_line)
# Create missing tax code lines
if account.template:
TaxCodeLineTemplate.create_tax_code_line(
account.template.id,
template2tax=template2tax,
template2tax_code=template2tax_code,
template2tax_code_line=template2tax_code_line)
# Update parent, taxes and replaced_by on accounts
account.update_account2(template2account, template2tax)
# Update tax rules
template2rule = {}
TaxRule.update_rule(company.id, template2rule=template2rule)
# Create missing tax rules
if account.template:
TaxRuleTemplate.create_rule(
account.template.id, account.company.id,
template2rule=template2rule)
# Update tax rule lines
template2rule_line = {}
TaxRuleLine.update_rule_line(
company.id, template2tax, template2rule,
template2rule_line=template2rule_line)
# Create missing tax rule lines
if account.template:
TaxRuleLineTemplate.create_rule_line(
account.template.id, template2tax, template2rule,
template2rule_line=template2rule_line)
return 'succeed'
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1698685597.0
trytond_account-7.0.19/account.xml 0000644 0001750 0001750 00000134133 14517761235 015335 0 ustar 00ced ced
Account
Accounting Party
Account Administration
tryton-account
icons/tryton-account.svg
tryton-account-open
icons/tryton-account-open.svg
tryton-account-close
icons/tryton-account-close.svg
tryton-account-block
icons/tryton-account-block.svg
account.account.type.template
form
account_type_template_form
account.account.type.template
tree
account_type_template_list
account.account.type.template
tree
childs
account_type_template_tree
Account Types
account.account.type.template
account.account.type
form
account_type_form
account.account.type
tree
childs
account_type_tree
account.account.type
tree
account_type_list
Account Types
account.account.type
Account Types
account.account.type
User in companies
Statement
listed
account.account.type
account.account.type.statement
account/type_statement.fodt
form_print
account.account.type,-1
account.account.template
form
account_template_form
account.account.template
tree
account_template_list
account.account.template
tree
childs
account_template_tree
Accounts
account.account.template
account.account.deferral
form
account_deferral_form
account.account.deferral
tree
account_deferral_tree
account.create_chart.start
form
create_chart_start_form
account.create_chart.account
form
create_chart_account_form
account.create_chart.properties
form
create_chart_properties_form
Create Chart of Accounts from Template
account.create_chart
account.update_chart.start
form
update_chart_start_form
account.update_chart.succeed
form
update_chart_succeed_form
Update Chart of Accounts from Template
account.update_chart
account.account
form
account_form
account.account
tree
childs
account_tree
account.account
tree
account_list
Accounts
account.account
Accounts
account.account
account.account
tree
account_list_balance_sheet
Accounts
account.account
account.balance_sheet.context
Open Type
account.account.open_type
account.account.type
tree_open
account.account.type,-1
account.account
tree
childs
account_tree_chart
Chart of Accounts
account.account
account.account.context
User in companies
account.account.context
form
account_context_form
General Ledger
listed
account.general_ledger.account
account.general_ledger
account/general_ledger.fodt
form_print
account.general_ledger.account,-1
Trial Balance
listed
account.general_ledger.account
account.trial_balance
account/trial_balance.fodt
form_print
account.general_ledger.account,-1
account.general_ledger.account
tree
general_ledger_account_list
General Ledger - Accounts
account.general_ledger.account
account.general_ledger.account.context
Accounts
account.general_ledger.account
account.general_ledger.account.context
User in companies
account.general_ledger.account.party
general_ledger_account_party_list
General Ledger - Account Parties
account.general_ledger.account.party
account.general_ledger.account.context
tree_open
account.general_ledger.account,-1
form_relate
account.account,-1
Open General Ledger Account Parties
account.general_ledger.account.party.open
tree_open
account.general_ledger.account.party,-1
Accounts
account.general_ledger.account.party
account.general_ledger.account.context
form_relate
party.party,-1
User in companies
account.general_ledger.line
tree
general_ledger_line_list
General Ledger - Lines
account.general_ledger.line
account.general_ledger.line.context
tree_open
account.general_ledger.account,-1
form_relate
account.account,-1
User in companies
account.general_ledger.account.context
form
general_ledger_account_context_form
account.general_ledger.line.context
general_ledger_line_context_form
account.account.type
tree
childs
account_balance_sheet_tree
Balance Sheet
account.account.type
account.balance_sheet.comparison.context
account.balance_sheet.context
form
balance_sheet_context_form
account.balance_sheet.comparison.context
balance_sheet_context_comparison_form
account.account.type
tree
childs
account_income_statement_tree
Income Statement
account.account.type
account.income_statement.context
account.income_statement.context
form
income_statement_context_form
account.aged_balance
tree
aged_balance_list
Aged Balance
account.aged_balance
account.aged_balance.context
User in companies
account.aged_balance.context
form
aged_balance_context_form
Aged Balance
account.aged_balance
account.aged_balance
account/aged_balance.fodt
form_print
account.aged_balance,-1
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1698685598.0
trytond_account-7.0.19/aged_balance.fodt 0000644 0001750 0001750 00000145030 14517761236 016401 0 ustar 00ced ced
LibreOffice/5.2.7.2$Linux_X86_64 LibreOffice_project/20m0$Build-22008-08-27T16:35:462008-08-27T16:52:261PT0S
0
0
43760
21691
true
false
view2
8162
5443
0
0
43759
21689
0
0
false
100
false
false
true
true
true
0
true
true
false
false
false
false
false
false
false
false
false
false
false
false
false
true
false
true
true
false
false
false
false
false
false
true
false
false
false
false
false
false
true
2183537
false
true
false
false
true
true
false
true
0
false
true
high-resolution
false
false
false
true
true
true
true
false
false
true
false
false
false
false
false
765130
false
1
true
false
false
0
false
false
false
Company: <company.rec_name>
Aged Balance for <type>
Print Date: <format_date(datetime.date.today(), user.language)> at <datetime.datetime.now().strftime('%H:%M:%S')>
User: <user.rec_name>
1/1
Aged Balance for <type>
Date: <format_date(date, user.language)>
Party
<str(term0)> <unit>
<str(term1)> <unit>
<str(term2)> <unit>
<str(term3)>+ <unit>
Balance
<for each="record in records">
<record.party.rec_name>
<format_currency(record.term0, user.language, currency=company.currency)or ''>
<format_currency(record.term1, user.language, currency=company.currency) or ''>
<format_currency(record.term2, user.language, currency=company.currency) or ''>
<format_currency(record.term3, user.language, currency=company.currency) or ''>
<format_currency(record.balance, user.language, currency=company.currency) or ''>
</for>
Total
<format_currency(sum(records, 'term0'), user.language, currency=company.currency)>
<format_currency(sum(records, 'term1'), user.language, currency=company.currency)>
<format_currency(sum(records, 'term2'), user.language, currency=company.currency)>
<format_currency(sum(records, 'term3'), user.language, currency=company.currency)>
<format_currency(sum(records, 'balance'), user.language, currency=company.currency)>