././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1633127074.3659985 proteus-6.0.3/0000755000175000017500000000000000000000000011272 5ustar00cedced././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1632778607.0 proteus-6.0.3/.drone.yml0000644000175000017500000000203400000000000013201 0ustar00cedcedclone: hg: image: plugins/hg environment: - HG_SHARE_POOL=/root/.cache/hg volumes: - cache:/root/.cache pipeline: tox: image: ${IMAGE} environment: - CFLAGS=-O0 - TOX_TESTENV_PASSENV=CFLAGS CI_BUILD_NUMBER CI_JOB_NUMBER CI_JOB_ID commands: - echo "[extensions]" >> /root/.hgrc - echo "hgext.share =" >> /root/.hgrc - echo "[share]" >> /root/.hgrc - echo "pool = /root/.cache/hg" >> /root/.hgrc - pip install tox pydot - tox -e "${TOXENV}" volumes: - cache:/root/.cache check_dist: image: ${IMAGE} commands: - pip install twine - python setup.py sdist - twine check dist/* matrix: include: - IMAGE: python:3.6 TOXENV: py36 - IMAGE: python:3.7 TOXENV: py37 - IMAGE: python:3.8 TOXENV: py38 - IMAGE: python:3.9 TOXENV: py39 ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1632778607.0 proteus-6.0.3/.flake80000644000175000017500000000005600000000000012446 0ustar00cedced[flake8] ignore=E123,E124,E126,E128,E741,W503 ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1633127073.0 proteus-6.0.3/.hgtags0000644000175000017500000000222700000000000012553 0ustar00cedced3974f546b848d4ac59551db9f733d8ed62946dfd 1.8.0 c8fdae3b2338b744fce709572958884a95de87b3 2.0.0 120d0435125cf3a3c28280321962571924ad422f 2.2.0 ef9846cb18afe62182de446d8e4fa7b8393f7168 2.4.0 648c43939fd698988bde5b54f7a1dff9d47922af 2.6.0 5625ce03643f9f2b69659907754e5b0e924c689f 2.8.0 31740f7e08a0c449ce6715e1ef15392fb6326ce9 3.0.0 40affcdda4629de37997d0e5c7d3fe9ca2806b12 3.2.0 61013c4482fc95a61d2a15a8b21574a706755b10 3.4.0 2a2503ebd25887ff3668d470809c00c5bcf2c6c7 3.6.0 1e741a18e2a1f29fcc66e9ab4878554a4e63a355 3.8.0 403f21dd1bb7059a0928c46c8b21a97c14f9c720 4.0.0 d5b1e8f047748526d9a2cd354da0e86d617ec4c7 4.2.0 365af7e74c2baae38e96bc0afb1deae2d2b44ac0 4.4.0 cd4731fb373698d480a625a286de776a0b9bdc6e 4.6.0 3867b51d50056fda52882150a017a9dce6811264 4.8.0 e86f9d540f29dfcd39e8f198b50940c8b91250d6 5.0.0 f4a0b0e282f39c013c44e5012e6b85e4b8a4ae40 5.2.0 03daaf3994610fde107d98d8458b2731e03c5306 5.4.0 a8061a1d268776766c44ceb97094d229dbe31962 5.6.0 8bc88e82ff9edc33725d08bc0c6f2862f221a127 5.8.0 ac15e7f1881fd78d30eac0d7c772638265830c77 6.0.0 14cd94a3e75463a9e4ab4c562cce82470070731b 6.0.1 b579da9fa80282eaf0657e6d2826147c2c6c2f3d 6.0.2 dc3d781b552d24dcfb7b0ced4322b1ba17e6ca09 6.0.3 ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1633127072.0 proteus-6.0.3/CHANGELOG0000644000175000017500000000610600000000000012507 0ustar00cedcedVersion 6.0.3 - 2021-10-01 * Bug fixes (see mercurial logs for details) Version 6.0.2 - 2021-07-01 * Bug fixes (see mercurial logs for details) Version 6.0.1 - 2021-05-15 * Bug fixes (see mercurial logs for details) Version 6.0.0 - 2021-05-03 * Bug fixes (see mercurial logs for details) * Add support for Python 3.9 * Unify PYSON string format Version 5.8.0 - 2020-11-02 * Bug fixes (see mercurial logs for details) * Remove support for Python 3.5 * Support PYSON comparison of date and datetime Version 5.6.0 - 2020-05-04 * Bug fixes (see mercurial logs for details) * Add support for Python 3.8 * Use same __str__ as trytond instances Version 5.4.0 - 2019-11-04 * Bug fixes (see mercurial logs for details) * Support dot notation on PYSON Eval * Add __slots__ Version 5.2.0 - 2019-05-06 * Bug fixes (see mercurial logs for details) * Remove support for Python 3.4 Version 5.0.0 - 2018-10-01 * Bug fixes (see mercurial logs for details) * Add support for Python 3.7 * Remove support for Python 2.7 Version 4.8.0 - 2018-04-23 * Bug fixes (see mercurial logs for details) * Always use the context and config of the instance * Add support for search_* attributes in ModelList Version 4.6.0 - 2017-10-30 * Bug fixes (see mercurial logs for details) * Add set_sequence method to ModelList * Add __int__ to Model * Allow to use keyword arguments with trytond configuration Version 4.4.0 - 2017-05-01 * Bug fixes (see mercurial logs for details) Version 4.2.0 - 2016-11-28 * Bug fixes (see mercurial logs for details) * Fill default Report data Version 4.0.0 - 2016-05-02 * Bug fixes (see mercurial logs for details) * Add Python3 support Version 3.8.0 - 2015-11-02 * Bug fixes (see mercurial logs for details) * Add StateAction support to Wizard Version 3.6.0 - 2015-04-20 * Bug fixes (see mercurial logs for details) * Add support for PyPy * Allow to provide extra keyword arguments to set_xmlrpc() * Add support of fields.TimeDelta * Remove password on set_trytond * Manage reload, save, delete, duplicate and click as class and instance method Version 3.4.0 - 2014-10-20 * Bug fixes (see mercurial logs for details) * New configuration syntax * Add Report * Explicitly set value of parent field * Add duplicate method Version 3.2.0 - 2014-04-21 * Bug fixes (see mercurial logs for details) * Models cache depends also on user * Drop support of Python 2.6 * Allow to pass field values to new method * Add click method for buttons Version 3.0.0 - 2013-10-21 * Bug fixes (see mercurial logs for details) Version 2.8.0 - 2013-04-22 * Bug fixes (see mercurial logs for details) * Add support of fields.Dict Version 2.6.0 - 2012-10-22 * Bug fixes (see mercurial logs for details) Version 2.4.0 - 2012-04-23 * Bug fixes (see mercurial logs for details) * Use loading attribute * Add support of _buttons * Add support of fields.Time Version 2.2.0 - 2011-10-25 * Bug fixes (see mercurial logs for details) * Change license to LGPL-3 * Drop support of Python 2.5 Version 2.0.0 - 2011-04-28 * Bug fixes (see mercurial logs for details) * Manage default values of trytond configuration Version 1.8.0 - 2010-12-24 * Initial release ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1633127072.0 proteus-6.0.3/COPYRIGHT0000644000175000017500000000126600000000000012572 0ustar00cedcedCopyright (C) 2010-2021 Cédric Krier. Copyright (C) 2010-2021 B2CK SPRL. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser 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 . ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1620052473.0 proteus-6.0.3/LICENSE0000644000175000017500000012344400000000000012307 0ustar00cedced GNU LESSER 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. This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below. 0. Additional Definitions. As used herein, "this License" refers to version 3 of the GNU Lesser General Public License, and the "GNU GPL" refers to version 3 of the GNU General Public License. "The Library" refers to a covered work governed by this License, other than an Application or a Combined Work as defined below. An "Application" is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library. A "Combined Work" is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the "Linked Version". The "Minimal Corresponding Source" for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version. The "Corresponding Application Code" for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work. 1. Exception to Section 3 of the GNU GPL. You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL. 2. Conveying Modified Versions. If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version: a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy. 3. Object Code Incorporating Material from Library Header Files. The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following: a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the object code with a copy of the GNU GPL and this license document. 4. Combined Works. You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following: a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the Combined Work with a copy of the GNU GPL and this license document. c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document. d) Do one of the following: 0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source. 1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version. e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.) 5. Combined Libraries. You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License. b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 6. Revised Versions of the GNU Lesser General Public License. The Free Software Foundation may publish revised and/or new versions of the GNU Lesser 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 Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation. If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library. 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 . ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1632778607.0 proteus-6.0.3/MANIFEST.in0000644000175000017500000000012500000000000013026 0ustar00cedcedinclude CHANGELOG include COPYRIGHT include LICENSE include README.rst include doc/* ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1633127074.3626652 proteus-6.0.3/PKG-INFO0000644000175000017500000001265300000000000012376 0ustar00cedcedMetadata-Version: 2.1 Name: proteus Version: 6.0.3 Summary: Library to access Tryton server as a client Home-page: http://www.tryton.org/ Author: Tryton Author-email: bugs@tryton.org License: LGPL-3 Download-URL: http://downloads.tryton.org/6.0/ Project-URL: Bug Tracker, https://bugs.tryton.org/ Project-URL: Documentation, https://docs.tryton.org/ Project-URL: Forum, https://www.tryton.org/forum Project-URL: Source Code, https://hg.tryton.org/proteus Description: ======================= Tryton Scripting Client ======================= A library to access Tryton's models like a client. Example of usage ---------------- >>> from proteus import config, Model, Wizard, Report Configuration ~~~~~~~~~~~~~ Configuration to connect to a sqlite memory database using trytond as module. >>> config = config.set_trytond('sqlite:///:memory:') Activating a module ~~~~~~~~~~~~~~~~~~~ Find the module, call the activate button and run the upgrade wizard. >>> Module = Model.get('ir.module') >>> party_module, = Module.find([('name', '=', 'party')]) >>> party_module.click('activate') >>> Wizard('ir.module.activate_upgrade').execute('upgrade') Creating a party ~~~~~~~~~~~~~~~~ First instanciate a new Party: >>> Party = Model.get('party.party') >>> party = Party() >>> party.id < 0 True Fill the fields: >>> party.name = 'ham' Save the instance into the server: >>> party.save() >>> party.name 'ham' >>> party.id > 0 True Setting the language of the party ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The language on party is a `Many2One` relation field. So it requires to get a `Model` instance as value. >>> Lang = Model.get('ir.lang') >>> en, = Lang.find([('code', '=', 'en')]) >>> party.lang = en >>> party.save() >>> party.lang.code 'en' Creating an address for the party ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Addresses are store on party with a `One2Many` field. So the new address just needs to be appended to the list `addresses`. >>> address = party.addresses.new(postal_code='42') >>> party.save() >>> party.addresses #doctest: +ELLIPSIS [proteus.Model.get('party.address')(...)] Adding category to the party ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Categories are linked to party with a `Many2Many` field. So first create a category >>> Category = Model.get('party.category') >>> category = Category() >>> category.name = 'spam' >>> category.save() Append it to categories of the party >>> party.categories.append(category) >>> party.save() >>> party.categories #doctest: +ELLIPSIS [proteus.Model.get('party.category')(...)] Print party label ~~~~~~~~~~~~~~~~~ There is a label report on `Party`. >>> label = Report('party.label') The report is executed with a list of records and some extra data. >>> type_, data, print_, name = label.execute([party], {}) Sorting addresses and register order ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Addresses are ordered by sequence which means they can be stored following a specific order. The `set_sequence` method stores the current order. >>> address = party.addresses.new(postal_code='69') >>> party.save() >>> address = party.addresses.new(postal_code='23') >>> party.save() Now changing the order. >>> reversed_addresses = list(reversed(party.addresses)) >>> while party.addresses: ... _ = party.addresses.pop() >>> party.addresses.extend(reversed_addresses) >>> party.addresses.set_sequence() >>> party.save() >>> party.addresses == reversed_addresses True Keywords: tryton library cli Platform: any 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 Library or Lesser General Public License (LGPL) Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.6 Classifier: Programming Language :: Python :: 3.7 Classifier: Programming Language :: Python :: 3.8 Classifier: Programming Language :: Python :: 3.9 Classifier: Programming Language :: Python :: Implementation :: CPython Classifier: Programming Language :: Python :: Implementation :: PyPy Classifier: Topic :: Office/Business Requires-Python: >=3.6 Provides-Extra: trytond ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1632778607.0 proteus-6.0.3/README.rst0000644000175000017500000000610700000000000012765 0ustar00cedced======================= Tryton Scripting Client ======================= A library to access Tryton's models like a client. Example of usage ---------------- >>> from proteus import config, Model, Wizard, Report Configuration ~~~~~~~~~~~~~ Configuration to connect to a sqlite memory database using trytond as module. >>> config = config.set_trytond('sqlite:///:memory:') Activating a module ~~~~~~~~~~~~~~~~~~~ Find the module, call the activate button and run the upgrade wizard. >>> Module = Model.get('ir.module') >>> party_module, = Module.find([('name', '=', 'party')]) >>> party_module.click('activate') >>> Wizard('ir.module.activate_upgrade').execute('upgrade') Creating a party ~~~~~~~~~~~~~~~~ First instanciate a new Party: >>> Party = Model.get('party.party') >>> party = Party() >>> party.id < 0 True Fill the fields: >>> party.name = 'ham' Save the instance into the server: >>> party.save() >>> party.name 'ham' >>> party.id > 0 True Setting the language of the party ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The language on party is a `Many2One` relation field. So it requires to get a `Model` instance as value. >>> Lang = Model.get('ir.lang') >>> en, = Lang.find([('code', '=', 'en')]) >>> party.lang = en >>> party.save() >>> party.lang.code 'en' Creating an address for the party ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Addresses are store on party with a `One2Many` field. So the new address just needs to be appended to the list `addresses`. >>> address = party.addresses.new(postal_code='42') >>> party.save() >>> party.addresses #doctest: +ELLIPSIS [proteus.Model.get('party.address')(...)] Adding category to the party ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Categories are linked to party with a `Many2Many` field. So first create a category >>> Category = Model.get('party.category') >>> category = Category() >>> category.name = 'spam' >>> category.save() Append it to categories of the party >>> party.categories.append(category) >>> party.save() >>> party.categories #doctest: +ELLIPSIS [proteus.Model.get('party.category')(...)] Print party label ~~~~~~~~~~~~~~~~~ There is a label report on `Party`. >>> label = Report('party.label') The report is executed with a list of records and some extra data. >>> type_, data, print_, name = label.execute([party], {}) Sorting addresses and register order ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Addresses are ordered by sequence which means they can be stored following a specific order. The `set_sequence` method stores the current order. >>> address = party.addresses.new(postal_code='69') >>> party.save() >>> address = party.addresses.new(postal_code='23') >>> party.save() Now changing the order. >>> reversed_addresses = list(reversed(party.addresses)) >>> while party.addresses: ... _ = party.addresses.pop() >>> party.addresses.extend(reversed_addresses) >>> party.addresses.set_sequence() >>> party.save() >>> party.addresses == reversed_addresses True ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1633127074.3493319 proteus-6.0.3/doc/0000755000175000017500000000000000000000000012037 5ustar00cedced././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1632778607.0 proteus-6.0.3/doc/index.rst0000644000175000017500000000610700000000000013704 0ustar00cedced======================= Tryton Scripting Client ======================= A library to access Tryton's models like a client. Example of usage ---------------- >>> from proteus import config, Model, Wizard, Report Configuration ~~~~~~~~~~~~~ Configuration to connect to a sqlite memory database using trytond as module. >>> config = config.set_trytond('sqlite:///:memory:') Activating a module ~~~~~~~~~~~~~~~~~~~ Find the module, call the activate button and run the upgrade wizard. >>> Module = Model.get('ir.module') >>> party_module, = Module.find([('name', '=', 'party')]) >>> party_module.click('activate') >>> Wizard('ir.module.activate_upgrade').execute('upgrade') Creating a party ~~~~~~~~~~~~~~~~ First instanciate a new Party: >>> Party = Model.get('party.party') >>> party = Party() >>> party.id < 0 True Fill the fields: >>> party.name = 'ham' Save the instance into the server: >>> party.save() >>> party.name 'ham' >>> party.id > 0 True Setting the language of the party ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The language on party is a `Many2One` relation field. So it requires to get a `Model` instance as value. >>> Lang = Model.get('ir.lang') >>> en, = Lang.find([('code', '=', 'en')]) >>> party.lang = en >>> party.save() >>> party.lang.code 'en' Creating an address for the party ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Addresses are store on party with a `One2Many` field. So the new address just needs to be appended to the list `addresses`. >>> address = party.addresses.new(postal_code='42') >>> party.save() >>> party.addresses #doctest: +ELLIPSIS [proteus.Model.get('party.address')(...)] Adding category to the party ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Categories are linked to party with a `Many2Many` field. So first create a category >>> Category = Model.get('party.category') >>> category = Category() >>> category.name = 'spam' >>> category.save() Append it to categories of the party >>> party.categories.append(category) >>> party.save() >>> party.categories #doctest: +ELLIPSIS [proteus.Model.get('party.category')(...)] Print party label ~~~~~~~~~~~~~~~~~ There is a label report on `Party`. >>> label = Report('party.label') The report is executed with a list of records and some extra data. >>> type_, data, print_, name = label.execute([party], {}) Sorting addresses and register order ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Addresses are ordered by sequence which means they can be stored following a specific order. The `set_sequence` method stores the current order. >>> address = party.addresses.new(postal_code='69') >>> party.save() >>> address = party.addresses.new(postal_code='23') >>> party.save() Now changing the order. >>> reversed_addresses = list(reversed(party.addresses)) >>> while party.addresses: ... _ = party.addresses.pop() >>> party.addresses.extend(reversed_addresses) >>> party.addresses.set_sequence() >>> party.save() >>> party.addresses == reversed_addresses True ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1633127074.3559985 proteus-6.0.3/proteus/0000755000175000017500000000000000000000000012773 5ustar00cedced././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1632778607.0 proteus-6.0.3/proteus/__init__.py0000644000175000017500000013614600000000000015117 0ustar00cedced# This file is part of Tryton. The COPYRIGHT file at the top level of # this repository contains the full copyright notices and license terms. ''' A library to access Tryton's models like a client. ''' import threading import datetime import functools from decimal import Decimal import proteus.config __version__ = "6.0.3" __all__ = ['Model', 'Wizard', 'Report'] _MODELS = threading.local() class _EvalEnvironment(dict): 'Dictionary for evaluation' __slots__ = ('parent', 'eval_type') def __init__(self, parent, eval_type='eval'): super(_EvalEnvironment, self).__init__() self.parent = parent assert eval_type in ('eval', 'on_change') self.eval_type = eval_type def __getitem__(self, item): if item == 'id': return self.parent.id if item == '_parent_' + self.parent._parent_name \ and self.parent._parent: return _EvalEnvironment(self.parent._parent, eval_type=self.eval_type) if self.eval_type == 'eval': return self.parent._get_eval()[item] else: return self.parent._get_on_change_values(fields=[item])[item] def __getattr__(self, item): try: return self.__getitem__(item) except KeyError: raise AttributeError(item) def get(self, item, default=None): try: return self.__getitem__(item) except KeyError: pass return super(_EvalEnvironment, self).get(item, default) def __bool__(self): return True def __str__(self): return str(self.parent) def __repr__(self): return repr(self.parent) def __contains__(self, item): if item == 'id': return True if item == '_parent_' + self.parent._parent_name \ and self.parent._parent: return True if self.eval_type == 'eval': return item in self.parent._get_eval() else: return item in self.parent._fields class dualmethod(object): """Descriptor implementing combination of class and instance method When called on an instance, the class is passed as the first argument and a list with the instance as the second. When called on a class, the class itself is passed as the first argument. >>> class Example(object): ... @dualmethod ... def method(cls, instances): ... print(len(instances)) ... >>> Example.method([Example()]) 1 >>> Example().method() 1 """ __slots__ = ('func') def __init__(self, func): self.func = func def __get__(self, instance, owner): @functools.wraps(self.func) def newfunc(*args, **kwargs): if instance: return self.func(owner, [instance], *args, **kwargs) else: return self.func(owner, *args, **kwargs) return newfunc class FieldDescriptor(object): default = None def __init__(self, name, definition): super(FieldDescriptor, self).__init__() self.name = name self.definition = definition self.__doc__ = definition['string'] def __get__(self, instance, owner): if instance.id >= 0: instance._read(self.name) return instance._values.get(self.name, self.default) def __set__(self, instance, value): if instance.id >= 0: instance._read(self.name) previous = getattr(instance, self.name) instance._values[self.name] = value if previous != getattr(instance, self.name): instance._changed.add(self.name) instance._on_change([self.name]) if instance._parent: instance._parent._changed.add(instance._parent_field_name) instance._parent._on_change([instance._parent_field_name]) class BooleanDescriptor(FieldDescriptor): default = False def __set__(self, instance, value): assert isinstance(value, bool) super(BooleanDescriptor, self).__set__(instance, value) class CharDescriptor(FieldDescriptor): default = None def __set__(self, instance, value): assert isinstance(value, str) or value is None super(CharDescriptor, self).__set__(instance, value or '') class BinaryDescriptor(FieldDescriptor): default = None def __set__(self, instance, value): assert isinstance(value, (bytes, bytearray)) or value is None super(BinaryDescriptor, self).__set__(instance, value) class IntegerDescriptor(FieldDescriptor): def __set__(self, instance, value): assert isinstance(value, (int, type(None))) super(IntegerDescriptor, self).__set__(instance, value) class FloatDescriptor(FieldDescriptor): def __set__(self, instance, value): assert isinstance(value, (int, float, Decimal, type(None))) if value is not None: value = float(value) super(FloatDescriptor, self).__set__(instance, value) class NumericDescriptor(FieldDescriptor): def __set__(self, instance, value): assert isinstance(value, (type(None), Decimal)) # TODO add digits validation super(NumericDescriptor, self).__set__(instance, value) class SelectionDescriptor(FieldDescriptor): def __set__(self, instance, value): assert isinstance(value, str) or value is None # TODO add selection validation super().__set__(instance, value) class MultiSelectionDescriptor(FieldDescriptor): def __set__(self, instance, value): assert isinstance(value, (list, type(None))) # TODO add selection validation super().__set__(instance, value) class ReferenceDescriptor(FieldDescriptor): def __get__(self, instance, owner): value = super(ReferenceDescriptor, self).__get__(instance, owner) if isinstance(value, str): model_name, id = value.split(',', 1) if model_name: Relation = Model.get(model_name, instance._config) config = Relation._config with config.reset_context(), \ config.set_context(instance._context): value = Relation(int(id)) instance._values[self.name] = value return value def __set__(self, instance, value): assert isinstance(value, (Model, type(None), str)) if isinstance(value, str): assert value.startswith(',') elif isinstance(value, Model): assert value._config == instance._config super(ReferenceDescriptor, self).__set__(instance, value) class DateDescriptor(FieldDescriptor): def __get__(self, instance, owner): value = super(DateDescriptor, self).__get__(instance, owner) if isinstance(value, datetime.datetime): value = value.date() instance._values[self.name] = value return value def __set__(self, instance, value): assert isinstance(value, datetime.date) or value is None super(DateDescriptor, self).__set__(instance, value) class DateTimeDescriptor(FieldDescriptor): def __set__(self, instance, value): assert isinstance(value, datetime.datetime) or value is None super(DateTimeDescriptor, self).__set__(instance, value) class TimeDescriptor(FieldDescriptor): def __set__(self, instance, value): assert isinstance(value, datetime.time) or value is None super(TimeDescriptor, self).__set__(instance, value) class TimeDeltaDescriptor(FieldDescriptor): def __set__(self, instance, value): assert isinstance(value, datetime.timedelta) or value is None super(TimeDeltaDescriptor, self).__set__(instance, value) class DictDescriptor(FieldDescriptor): def __get__(self, instance, owner): value = super(DictDescriptor, self).__get__(instance, owner) if value: value = value.copy() return value def __set__(self, instance, value): assert isinstance(value, dict) or value is None super(DictDescriptor, self).__set__(instance, value) class Many2OneDescriptor(FieldDescriptor): def __get__(self, instance, owner): Relation = Model.get(self.definition['relation'], instance._config) value = super(Many2OneDescriptor, self).__get__(instance, owner) if isinstance(value, int): config = Relation._config with config.reset_context(), config.set_context(instance._context): value = Relation(value) if self.name in instance._values: instance._values[self.name] = value return value def __set__(self, instance, value): assert isinstance(value, (Model, type(None))) if value: assert value._config == instance._config super(Many2OneDescriptor, self).__set__(instance, value) class One2OneDescriptor(Many2OneDescriptor): pass class One2ManyDescriptor(FieldDescriptor): default = [] def __get__(self, instance, owner): from .pyson import PYSONDecoder Relation = Model.get(self.definition['relation'], instance._config) value = super(One2ManyDescriptor, self).__get__(instance, owner) if not isinstance(value, ModelList): ctx = instance._context.copy() if instance._context else {} if self.definition.get('context'): decoder = PYSONDecoder(_EvalEnvironment(instance)) ctx.update(decoder.decode(self.definition.get('context'))) config = Relation._config with config.reset_context(), config.set_context(ctx): value = ModelList(self.definition, (Relation(id) for id in value or []), instance, self.name) instance._values[self.name] = value return value def __set__(self, instance, value): raise AttributeError class Many2ManyDescriptor(One2ManyDescriptor): pass class ValueDescriptor(object): def __init__(self, name, definition): super(ValueDescriptor, self).__init__() self.name = name self.definition = definition def __get__(self, instance, owner): return getattr(instance, self.name) class ReferenceValueDescriptor(ValueDescriptor): def __get__(self, instance, owner): value = super(ReferenceValueDescriptor, self).__get__(instance, owner) if isinstance(value, Model): value = '%s,%s' % (value.__class__.__name__, value.id) return value or None class Many2OneValueDescriptor(ValueDescriptor): def __get__(self, instance, owner): value = super(Many2OneValueDescriptor, self).__get__(instance, owner) return value and value.id or None class One2OneValueDescriptor(Many2OneValueDescriptor): pass class One2ManyValueDescriptor(ValueDescriptor): def __get__(self, instance, owner): value = [] value_list = getattr(instance, self.name) parent_name = self.definition.get('relation_field', '') to_add = [] to_create = [] to_write = [] for record in value_list: if record.id >= 0: values = record._get_values(fields=record._changed) values.pop(parent_name, None) if record._changed and values: to_write.extend(([record.id], values)) to_add.append(record.id) else: values = record._get_values() values.pop(parent_name, None) to_create.append(values) if to_add: value.append(('add', to_add)) if to_create: value.append(('create', to_create)) if to_write: value.append(('write',) + tuple(to_write)) if value_list.record_removed: value.append(('remove', [x.id for x in value_list.record_removed])) if value_list.record_deleted: value.append(('delete', [x.id for x in value_list.record_deleted])) return value class Many2ManyValueDescriptor(One2ManyValueDescriptor): pass class EvalDescriptor(object): def __init__(self, name, definition): super(EvalDescriptor, self).__init__() self.name = name self.definition = definition def __get__(self, instance, owner): return getattr(instance, self.name) class ReferenceEvalDescriptor(EvalDescriptor): def __get__(self, instance, owner): value = super(ReferenceEvalDescriptor, self).__get__(instance, owner) if isinstance(value, Model): value = '%s,%s' % (value.__class__.__name__, value.id) return value or None class Many2OneEvalDescriptor(EvalDescriptor): def __get__(self, instance, owner): value = super(Many2OneEvalDescriptor, self).__get__(instance, owner) if value: return value.id return None class One2OneEvalDescriptor(Many2OneEvalDescriptor): pass class One2ManyEvalDescriptor(EvalDescriptor): def __get__(self, instance, owner): # Directly use _values to prevent infinite recursion with # One2ManyDescriptor which could evaluate this field to decode the # context value = instance._values.get(self.name, []) if isinstance(value, ModelList): return [x.id for x in value] else: return value class Many2ManyEvalDescriptor(One2ManyEvalDescriptor): pass class MetaModelFactory(object): descriptors = { 'boolean': BooleanDescriptor, 'char': CharDescriptor, 'text': CharDescriptor, 'binary': BinaryDescriptor, 'selection': SelectionDescriptor, 'multiselection': MultiSelectionDescriptor, 'integer': IntegerDescriptor, 'biginteger': IntegerDescriptor, 'float': FloatDescriptor, 'numeric': NumericDescriptor, 'reference': ReferenceDescriptor, 'date': DateDescriptor, 'datetime': DateTimeDescriptor, 'timestamp': DateTimeDescriptor, 'time': TimeDescriptor, 'timedelta': TimeDeltaDescriptor, 'dict': DictDescriptor, 'many2one': Many2OneDescriptor, 'one2many': One2ManyDescriptor, 'many2many': Many2ManyDescriptor, 'one2one': One2OneDescriptor, } value_descriptors = { 'reference': ReferenceValueDescriptor, 'many2one': Many2OneValueDescriptor, 'one2many': One2ManyValueDescriptor, 'many2many': Many2ManyValueDescriptor, 'one2one': One2OneValueDescriptor, } eval_descriptors = { 'reference': ReferenceEvalDescriptor, 'many2one': Many2OneEvalDescriptor, 'one2many': One2ManyEvalDescriptor, 'many2many': Many2ManyEvalDescriptor, 'one2one': One2OneEvalDescriptor, } def __init__(self, model_name, config=None): super(MetaModelFactory, self).__init__() self.model_name = model_name self.config = config or proteus.config.get_config() def __call__(self): models_key = 'c%su%s' % (id(self.config), self.config.user) if not hasattr(_MODELS, models_key): setattr(_MODELS, models_key, {}) class MetaModel(type): 'Meta class for Model' __slots__ = () def __new__(mcs, name, bases, dict): if self.model_name in getattr(_MODELS, models_key): return getattr(_MODELS, models_key)[self.model_name] proxy = self.config.get_proxy(self.model_name) context = self.config.context name = self.model_name dict['_proxy'] = proxy dict['_config'] = self.config dict['_fields'] = proxy.fields_get(None, context) for field_name, definition in dict['_fields'].items(): if field_name == 'id': continue Descriptor = self.descriptors.get(definition['type'], FieldDescriptor) dict[field_name] = Descriptor(field_name, definition) VDescriptor = self.value_descriptors.get( definition['type'], ValueDescriptor) dict['__%s_value' % field_name] = VDescriptor( field_name, definition) EDescriptor = self.eval_descriptors.get( definition['type'], EvalDescriptor) dict['__%s_eval' % field_name] = EDescriptor( field_name, definition) for method in self.config.get_proxy_methods(self.model_name): setattr(mcs, method, getattr(proxy, method)) res = type.__new__(mcs, name, bases, dict) getattr(_MODELS, models_key)[self.model_name] = res return res __new__.__doc__ = type.__new__.__doc__ return MetaModel class ModelList(list): 'List for Model' __slots__ = ('model_name', 'parent', 'parent_field_name', 'parent_name', 'domain', 'context', 'add_remove', 'search_order', 'search_context', 'record_removed', 'record_deleted') def __init__(self, definition, sequence=None, parent=None, parent_field_name=''): self.model_name = definition['relation'] if sequence is None: sequence = [] self.parent = parent if parent: assert parent_field_name self.parent_field_name = parent_field_name self.parent_name = definition.get('relation_field', '') self.domain = definition.get('domain', []) self.context = definition.get('context') self.add_remove = definition.get('add_remove') self.search_order = definition.get('search_order', 'null') self.search_context = definition.get('search_context', '{}') self.record_removed = set() self.record_deleted = set() result = super(ModelList, self).__init__(sequence) self.__check(self, on_change=False) return result __init__.__doc__ = list.__init__.__doc__ def _changed(self): 'Signal change to parent' if self.parent: self.parent._changed.add(self.parent_field_name) self.parent._on_change([self.parent_field_name]) def _get_context(self): from .pyson import PYSONDecoder decoder = PYSONDecoder(_EvalEnvironment(self.parent)) ctx = self.parent._context.copy() if self.parent._context else {} ctx.update(decoder.decode(self.context) if self.context else {}) return ctx def __check(self, records, on_change=True): config = None for record in records: assert isinstance(record, Model) assert record.__class__.__name__ == self.model_name if self.parent: assert record._config == self.parent._config elif self: assert record._config == self[0]._config elif config: assert record._config == config else: config = record._config if record._group is not self: assert record._group is None record._group = self for record in records: # Set parent field to trigger on_change if (on_change and self.parent and self.parent_name in record._fields): definition = record._fields[self.parent_name] if definition['type'] in ('many2one', 'reference'): setattr(record, self.parent_name, self.parent) self.record_removed.difference_update(records) self.record_deleted.difference_update(records) def append(self, record): self.__check([record]) res = super(ModelList, self).append(record) self._changed() return res append.__doc__ = list.append.__doc__ def extend(self, iterable): iterable = list(iterable) self.__check(iterable) res = super(ModelList, self).extend(iterable) self._changed() return res extend.__doc__ = list.extend.__doc__ def insert(self, index, record): raise NotImplementedError insert.__doc__ = list.insert.__doc__ def pop(self, index=-1, _changed=True): self.record_removed.add(self[index]) self[index]._group = None res = super(ModelList, self).pop(index) if _changed: self._changed() return res pop.__doc__ = list.pop.__doc__ def remove(self, record, _changed=True): if record.id >= 0: self.record_deleted.add(record) record._group = None res = super(ModelList, self).remove(record) if _changed: self._changed() return res remove.__doc__ = list.remove.__doc__ def reverse(self): raise NotImplementedError reverse.__doc__ = list.reverse.__doc__ def sort(self): raise NotImplementedError sort.__doc__ = list.sort.__doc__ def new(self, **kwargs): 'Adds a new record to the ModelList and returns it' Relation = Model.get(self.model_name, self.parent._config) config = Relation._config with config.reset_context(), config.set_context(self._get_context()): # Set parent for on_change calls from default_get new_record = Relation(_group=self, **kwargs) self.append(new_record) return new_record def find(self, condition=None, offset=0, limit=None, order=None): 'Returns records matching condition taking into account list domain' from .pyson import PYSONDecoder decoder = PYSONDecoder(_EvalEnvironment(self.parent)) Relation = Model.get(self.model_name, self.parent._config) if condition is None: condition = [] field_domain = decoder.decode(self.domain) add_remove_domain = (decoder.decode(self.add_remove) if self.add_remove else []) new_domain = [field_domain, add_remove_domain, condition] context = self._get_context() context.update(decoder.decode(self.search_context)) order = order if order else decoder.decode(self.search_order) config = Relation._config with config.reset_context(), config.set_context(context): return Relation.find(new_domain, offset, limit, order) def set_sequence(self, field='sequence'): changed = False prev = None for record in self: if prev: index = getattr(prev, field) else: index = None update = False value = getattr(record, field) if value is None: if index: update = True elif prev and record.id >= 0: update = record.id < prev.id elif value == index: if prev and record.id >= 0: update = record.id < prev.id elif value <= (index or 0): update = True if update: if index is None: index = 0 index += 1 setattr(record, field, index) changed = record prev = record if changed: self._changed() class Model(object): 'Model class for Tryton records' __slots__ = ('__id', '_values', '_changed', '_group', '__context') __counter = -1 _proxy = None _config = None _fields = None def __init__(self, id=None, _default=True, _group=None, **kwargs): super(Model, self).__init__() if id is not None: assert not kwargs self.__id = id if id is not None else Model.__counter if self.__id < 0: Model.__counter -= 1 self._values = {} # store the values of fields self._changed = set() # store the changed fields self._group = _group # store the parent group self.__context = self._config.context # store the context if self.id < 0 and _default: self._default_get() for field_name, value in kwargs.items(): definition = self._fields[field_name] if definition['type'] in ('one2many', 'many2many'): relation = Model.get(definition['relation'], self._config) def instantiate(v): if isinstance(v, int): return relation(v) elif isinstance(v, dict): return relation(_default=_default, **v) else: return v value = [instantiate(x) for x in value] getattr(self, field_name).extend(value) else: if definition['type'] == 'many2one': if isinstance(value, int): relation = Model.get( definition['relation'], self._config) value = relation(value) setattr(self, field_name, value) __init__.__doc__ = object.__init__.__doc__ @property def _parent(self): if self._group is not None: return self._group.parent @property def _parent_field_name(self): if self._group is not None: return self._group.parent_field_name return '' @property def _parent_name(self): if self._group is not None: return self._group.parent_name return '' @property def _context(self): if self._group: context = self._group._get_context() else: context = self.__context return context @classmethod def get(cls, name, config=None): 'Get a class for the named Model' if (bytes == str) and isinstance(name, str): name = name.encode('utf-8') class Spam(Model, metaclass=MetaModelFactory(name, config=config)()): __slots__ = () return Spam @classmethod def reset(cls, config=None, *names): 'Reset class definition for Models named' config = config or proteus.config.get_config() models_key = 'c%su%s' % (id(config), config.user) if not names: setattr(_MODELS, models_key, {}) else: models = getattr(_MODELS, models_key, {}) for name in names: del models[name] def __str__(self): return '%s,%d' % (self.__class__.__name__, self.id) def __repr__(self): if self._config == proteus.config.get_config(): return "proteus.Model.get('%s')(%d)" % (self.__class__.__name__, self.id) return "proteus.Model.get('%s', %s)(%d)" % (self.__class__.__name__, repr(self._config), self.id) def __eq__(self, other): if isinstance(other, Model): return ((self.__class__.__name__, self.id) == (other.__class__.__name__, other.id)) return NotImplemented def __ne__(self, other): return not self == other def __hash__(self): return hash(self.__class__.__name__) ^ hash(self.id) def __int__(self): return self.id @property def id(self): 'The unique ID' return self.__id @id.setter def id(self, value): assert self.__id < 0 self.__id = int(value) @classmethod def find(cls, condition=None, offset=0, limit=None, order=None): 'Return records matching condition' if condition is None: condition = [] ids = cls._proxy.search(condition, offset, limit, order, cls._config.context) return [cls(id) for id in ids] @dualmethod def reload(cls, records): 'Reload record' for record in records: record._values = {} record._changed = set() @dualmethod def save(cls, records): 'Save records' if not records: return proxy = records[0]._proxy config = records[0]._config context = records[0]._context.copy() create, write = [], [] for record in records: assert proxy == record._proxy assert config == record._config assert context == record._context if record.id < 0: create.append(record) elif record._changed: write.append(record) if create: values = [r._get_values() for r in create] ids = proxy.create(values, context) for record, id_ in zip(create, ids): record.id = id_ if write: values = [] context['_timestamp'] = {} for record in write: values.append([record.id]) values.append(record._get_values(fields=record._changed)) context['_timestamp'].update(record._get_timestamp()) values.append(context) proxy.write(*values) for record in records: record.reload() @dualmethod def delete(cls, records): 'Delete records' if not records: return proxy = records[0]._proxy config = records[0]._config context = records[0]._context.copy() timestamp = {} delete = [] for record in records: assert proxy == record._proxy assert config == record._config assert context == record._context if record.id >= 0: timestamp.update(record._get_timestamp()) delete.append(record.id) context['_timestamp'] = timestamp if delete: proxy.delete(delete, context) cls.reload(records) @dualmethod def duplicate(cls, records, default=None): 'Duplicate the record' ids = cls._proxy.copy([r.id for r in records], default, cls._config.context) return [cls(id) for id in ids] @dualmethod def click(cls, records, button, change=None): 'Click on button' if not records: return proxy = records[0]._proxy config = records[0]._config context = records[0]._context.copy() for record in records: assert proxy == record._proxy assert config == record._config assert context == record._context if change is None: cls.save(records) cls.reload(records) # Force reload because save doesn't always return getattr(proxy, button)([r.id for r in records], context) else: record, = records values = record._on_change_args(change) changes = getattr(proxy, button)(values, context) record._set_on_change(changes) def _get_values(self, fields=None): 'Return dictionary values' if fields is None: fields = self._values.keys() values = {} for name in fields: if name in ['id', '_timestamp']: continue definition = self._fields[name] if definition.get('readonly') and definition['type'] != 'one2many': continue values[name] = getattr(self, '__%s_value' % name) # Sending an empty X2Many fields breaks ModelFieldAccess.check if (definition['type'] in {'one2many', 'many2many'} and not values[name]): del values[name] return values @property def _timestamp(self): 'Get _timestamp' return self._values.get('_timestamp') def _get_timestamp(self): 'Return dictionary with timestamps' result = {'%s,%s' % (self.__class__.__name__, self.id): self._timestamp} for field, definition in self._fields.items(): if field not in self._values: continue if definition['type'] in ('one2many', 'many2many'): for record in getattr(self, field): result.update(record._get_timestamp()) return result def _read(self, name): 'Read field' fields = [name] if name in self._values: return loading = self._fields[name]['loading'] if loading == 'eager': fields = [x for x, y in self._fields.items() if y['loading'] == 'eager'] fields.append('_timestamp') self._values.update( self._proxy.read([self.id], fields, self._context)[0]) for field in fields: if (field in self._fields and self._fields[field]['type'] == 'float' and isinstance(self._values[field], Decimal)): # XML-RPC return Decimal for double self._values[field] = float(self._values[field]) def _default_get(self): 'Set default values' fields = list(self._fields.keys()) self._default_set( self._proxy.default_get(fields, False, self._context)) def _default_set(self, values): fieldnames = [] for field, value in values.items(): if '.' in field: continue definition = self._fields[field] if definition['type'] in ('one2many', 'many2many'): if value and len(value) and isinstance(value[0], int): self._values[field] = value else: Relation = Model.get(definition['relation'], self._config) self._values[field] = records = ModelList( definition, [], self, field) for vals in (value or []): record = Relation() record._default_set(vals) records.append(record) else: self._values[field] = value fieldnames.append(field) self._on_change(sorted(fieldnames)) def _get_eval(self): values = dict((x, getattr(self, '__%s_eval' % x)) for x in self._fields if x != 'id') values['id'] = self.id return values def _get_on_change_values(self, skip=None, fields=None): values = {'id': self.id} if fields: definitions = ((f, self._fields[f]) for f in fields) else: definitions = self._fields.items() for field, definition in definitions: if field == 'id': continue if not fields: if skip and field in skip: continue if (self.id >= 0 and (field not in self._values or field not in self._changed)): continue if definition['type'] == 'one2many': values[field] = [x._get_on_change_values( skip={definition.get('relation_field', '')}) for x in getattr(self, field)] elif (definition['type'] in ('many2one', 'reference') and self._parent_name == definition['name'] and self._parent): values[field] = self._parent._get_on_change_values( skip={self._parent_field_name}) if definition['type'] == 'reference': values[field] = ( self._parent.__class__.__name__, values[field]) else: values[field] = getattr(self, '__%s_eval' % field) return values def _on_change_args(self, args): # Ensure arguments has been read for arg in args: record = self for i in arg.split('.'): if i in record._fields: getattr(record, i) elif i == '_parent_' + record._parent_name: getattr(record, record._parent_name) record = record._parent res = {} values = _EvalEnvironment(self, 'on_change') for arg in args: scope = values for i in arg.split('.'): if i not in scope: break scope = scope[i] else: res[arg] = scope return res def _on_change_set(self, field, value): if (self._fields[field]['type'] in ('one2many', 'many2many') and not isinstance(value, (list, tuple))): if value and value.get('delete'): for record_id in value['delete']: for record in getattr(self, field): if record.id == record_id: getattr(self, field).remove(record, _changed=False) if value and value.get('remove'): for record_id in value['remove']: for i, record in enumerate(getattr(self, field)): if record.id == record_id: getattr(self, field).pop(i, _changed=False) if value and (value.get('add') or value.get('update')): for index, vals in value.get('add', []): group = getattr(self, field) Relation = Model.get( self._fields[field]['relation'], self._config) config = Relation._config id_ = vals.pop('id', None) with config.reset_context(), \ config.set_context(self._context): record = Relation(id=id_, _group=group, _default=False) try: idx = group.index(record) except ValueError: # append without signal if index == -1: list.append(group, record) else: list.insert(group, index, record) else: record = group[idx] group.record_removed.discard(record) group.record_deleted.discard(record) record._set_on_change(vals) for vals in value.get('update', []): if 'id' not in vals: continue for record in getattr(self, field): if record.id == vals['id']: record._set_on_change(vals) elif (self._fields[field]['type'] in ('one2many', 'many2many') and len(value) and not isinstance(value[0], int)): self._values[field] = [] for vals in value: Relation = Model.get( self._fields[field]['relation'], self._config) config = Relation._config records = getattr(self, field) with config.reset_context(), \ config.set_context(records._get_context()): record = Relation(_default=False, **vals) records.append(record) else: self._values[field] = value self._changed.add(field) def _set_on_change(self, values): later = {} for field, value in values.items(): if field not in self._fields: continue if self._fields[field]['type'] in ('one2many', 'many2many'): later[field] = value continue self._on_change_set(field, value) for field, value in later.items(): self._on_change_set(field, value) def _on_change(self, names): 'Call on_change for field' # Import locally to not break installation from proteus.pyson import PYSONDecoder values = {} for name in names: definition = self._fields[name] on_change = definition.get('on_change') if not on_change: continue if isinstance(on_change, str): definition['on_change'] = on_change = PYSONDecoder().decode( on_change) values.update(self._on_change_args(on_change)) if values: context = self._context changes = getattr(self._proxy, 'on_change')(values, names, context) for change in changes: self._set_on_change(change) values = {} fieldnames = set(names) to_change = set() later = set() for field, definition in self._fields.items(): on_change_with = definition.get('on_change_with') if not on_change_with: continue if not fieldnames & set(on_change_with): continue if to_change & set(on_change_with): later.add(field) continue to_change.add(field) values.update(self._on_change_args(on_change_with)) if to_change: context = self._context changes = getattr(self._proxy, 'on_change_with')(values, list(to_change), context) self._set_on_change(changes) for field in later: on_change_with = self._fields[field]['on_change_with'] values = self._on_change_args(on_change_with) context = self._context result = getattr(self._proxy, 'on_change_with_%s' % field)(values, context) self._on_change_set(field, result) if self._parent: self._parent._changed.add(self._parent_field_name) self._parent._on_change([self._parent_field_name]) class Wizard(object): 'Wizard class for Tryton wizards' __slots__ = ('name', 'form', 'form_state', 'actions', '_config', '_context', '_proxy', 'session_id', 'start_state', 'end_state', 'states', 'state', 'models', 'action') def __init__(self, name, models=None, action=None, config=None, context=None): if models: assert len(set(type(x) for x in models)) == 1 super(Wizard, self).__init__() self.name = name self.form = None self.form_state = None self.actions = [] self._config = config or proteus.config.get_config() self._context = self._config.context if context: self._context.update(context) self._proxy = self._config.get_proxy(name, type='wizard') result = self._proxy.create(self._context) self.session_id, self.start_state, self.end_state = result self.states = [self.start_state] self.models = models self.action = action self.execute(self.start_state) def execute(self, state): assert state in self.states self.state = state while self.state != self.end_state: ctx = self._context.copy() if self.models: ctx['active_id'] = self.models[0].id ctx['active_ids'] = [model.id for model in self.models] ctx['active_model'] = self.models[0].__class__.__name__ else: ctx['active_id'] = None ctx['active_ids'] = None ctx['active_model'] = None if self.action: ctx['action_id'] = self.action['id'] else: ctx['action_id'] = None if self.form: data = {self.form_state: self.form._get_on_change_values()} else: data = {} result = self._proxy.execute(self.session_id, data, self.state, ctx) if 'view' in result: view = result['view'] self.form = Model.get( view['fields_view']['model'], self._config)() self.form._default_set(view['defaults']) self.states = [b['state'] for b in view['buttons']] self.form_state = view['state'] else: self.state = self.end_state self.actions = [] for action in result.get('actions', []): proteus_action = _convert_action(*action, context=self._context) if proteus_action: self.actions.append(proteus_action) if 'view' in result: return if self.state == self.end_state: self._proxy.delete(self.session_id, self._context) if self.models: for record in self.models: record.reload() class Report(object): 'Report class for Tryton reports' __slots__ = ('name', '_config', '_context', '_proxy') def __init__(self, name, config=None, context=None): super(Report, self).__init__() self.name = name self._config = config or proteus.config.get_config() self._context = self._config.context if context: self._context.update(context) self._proxy = self._config.get_proxy(name, type='report') def execute(self, models=None, data=None): ids = [m.id for m in models] if models else data.get('ids', []) if data is None: data = { 'id': ids[0], 'ids': ids, } if models: data['model'] = models[0].__class__.__name__ return self._proxy.execute(ids, data, self._context) def _convert_action(action, data=None, context=None, config=None): if config is None: config = proteus.config.get_config() if data is None: data = {} else: data = data.copy() if 'type' not in (action or {}): return None data['action_id'] = action['id'] if action['type'] == 'ir.action.act_window': from .pyson import PYSONDecoder action.setdefault('pyson_domain', '[]') ctx = { 'active_model': data.get('model'), 'active_id': data.get('id'), 'active_ids': data.get('ids', []), } ctx.update(config.context) ctx['_user'] = config.user decoder = PYSONDecoder(ctx) action_ctx = decoder.decode(action.get('pyson_context') or '{}') ctx.update(action_ctx) ctx.update(context) action_ctx.update(context) if 'date_format' not in action_ctx: action_ctx['date_format'] = config.context.get( 'locale', {}).get('date', '%x') ctx['context'] = ctx decoder = PYSONDecoder(ctx) domain = decoder.decode(action['pyson_domain']) res_model = action.get('res_model', data.get('res_model')) res_id = action.get('res_id', data.get('res_id')) Model_ = Model.get(res_model, config) config = Model_._config with config.reset_context(), config.set_context(action_ctx): if res_id is None: return Model_.find(domain) elif isinstance(res_id, int): return [Model_(res_id)] else: return [Model_(id_) for id_ in res_id] elif action['type'] == 'ir.action.wizard': kwargs = { 'action': action, 'config': config, 'context': context, } if 'model' in data: Model_ = Model.get(data['model'], config) config = Model_._config with config.reset_context(), config.set_context(context): kwargs['models'] = [Model_(id_) for id_ in data.get('ids', [])] return Wizard(action['wiz_name'], **kwargs) elif action['type'] == 'ir.action.report': ActionReport = Report(action['report_name'], context=context) return ActionReport.execute(data=data) elif action['type'] == 'ir.action.url': return action.get('url') ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1632778607.0 proteus-6.0.3/proteus/config.py0000644000175000017500000002663000000000000014621 0ustar00cedced# This file is part of Tryton. The COPYRIGHT file at the top level of # this repository contains the full copyright notices and license terms. """ Configuration functions for the proteus package for Tryton. """ import datetime import os import threading import urllib.parse import xmlrpc.client from decimal import Decimal __all__ = ['set_trytond', 'set_xmlrpc', 'get_config'] def dump_decimal(self, value, write): value = {'__class__': 'Decimal', 'decimal': str(value), } self.dump_struct(value, write) def dump_date(self, value, write): value = {'__class__': 'date', 'year': value.year, 'month': value.month, 'day': value.day, } self.dump_struct(value, write) def dump_time(self, value, write): value = {'__class__': 'time', 'hour': value.hour, 'minute': value.minute, 'second': value.second, 'microsecond': value.microsecond, } self.dump_struct(value, write) def dump_timedelta(self, value, write): value = {'__class__': 'timedelta', 'seconds': value.total_seconds(), } self.dump_struct(value, write) def dump_long(self, value, write): try: self.dump_long(value, write) except OverflowError: write('') write(str(int(value))) write('\n') xmlrpc.client.Marshaller.dispatch[Decimal] = dump_decimal xmlrpc.client.Marshaller.dispatch[datetime.date] = dump_date xmlrpc.client.Marshaller.dispatch[datetime.time] = dump_time xmlrpc.client.Marshaller.dispatch[datetime.timedelta] = dump_timedelta xmlrpc.client.Marshaller.dispatch[int] = dump_long def dump_struct(self, value, write, escape=xmlrpc.client.escape): converted_value = {} for k, v in value.items(): if isinstance(k, int): k = str(k) elif isinstance(k, float): k = repr(k) converted_value[k] = v return self.dump_struct(converted_value, write, escape=escape) xmlrpc.client.Marshaller.dispatch[dict] = dump_struct class XMLRPCDecoder(object): decoders = {} @classmethod def register(cls, klass, decoder): assert klass not in cls.decoders cls.decoders[klass] = decoder def __call__(self, dct): if dct.get('__class__') in self.decoders: return self.decoders[dct['__class__']](dct) return dct XMLRPCDecoder.register('date', lambda dct: datetime.date(dct['year'], dct['month'], dct['day'])) XMLRPCDecoder.register('time', lambda dct: datetime.time(dct['hour'], dct['minute'], dct['second'], dct['microsecond'])) XMLRPCDecoder.register('timedelta', lambda dct: datetime.timedelta(seconds=dct['seconds'])) XMLRPCDecoder.register('Decimal', lambda dct: Decimal(dct['decimal'])) def end_struct(self, data): mark = self._marks.pop() # map structs to Python dictionaries dct = {} items = self._stack[mark:] for i in range(0, len(items), 2): dct[items[i]] = items[i + 1] dct = XMLRPCDecoder()(dct) self._stack[mark:] = [dct] self._value = 0 xmlrpc.client.Unmarshaller.dispatch['struct'] = end_struct _CONFIG = threading.local() _CONFIG.current = None class ContextManager(object): 'Context Manager for the tryton context' def __init__(self, config): self.config = config self.context = config.context def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): self.config._context = self.context class Config(object): 'Config interface' def __init__(self): super(Config, self).__init__() self._context = {} @property def context(self): return self._context.copy() def set_context(self, context=None, **kwargs): ctx_manager = ContextManager(self) if context is None: context = {} self._context = self.context self._context.update(context) self._context.update(kwargs) return ctx_manager def reset_context(self): ctx_manager = ContextManager(self) self._context = {} return ctx_manager def get_proxy(self, name): raise NotImplementedError def get_proxy_methods(self, name): raise NotImplementedError class _TrytondMethod(object): def __init__(self, name, model, config): super(_TrytondMethod, self).__init__() self._name = name self._object = model self._config = config def __call__(self, *args, **kwargs): from trytond.rpc import RPC from trytond.tools import is_instance_method from trytond.transaction import Transaction from trytond.worker import run_task if self._name in self._object.__rpc__: rpc = self._object.__rpc__[self._name] elif self._name in getattr(self._object, '_buttons', {}): rpc = RPC(readonly=False, instantiate=0) else: raise TypeError('%s is not callable' % self._name) with Transaction().start(self._config.database_name, self._config.user, readonly=rpc.readonly) as transaction: args, kwargs, transaction.context, transaction.timestamp = \ rpc.convert(self._object, *args, **kwargs) meth = getattr(self._object, self._name) if (rpc.instantiate is None or not is_instance_method(self._object, self._name)): result = rpc.result(meth(*args, **kwargs)) else: assert rpc.instantiate == 0 inst = args.pop(0) if hasattr(inst, self._name): result = rpc.result(meth(inst, *args, **kwargs)) else: result = [rpc.result(meth(i, *args, **kwargs)) for i in inst] transaction.commit() while transaction.tasks: task_id = transaction.tasks.pop() run_task(self._config.database_name, task_id) return result class TrytondProxy(object): 'Proxy for function call for trytond' def __init__(self, name, config, type='model'): super(TrytondProxy, self).__init__() self._config = config self._object = config.pool.get(name, type=type) __init__.__doc__ = object.__init__.__doc__ def __getattr__(self, name): 'Return attribute value' return _TrytondMethod(name, self._object, self._config) class TrytondConfig(Config): 'Configuration for trytond' def __init__(self, database=None, user='admin', config_file=None): super(TrytondConfig, self).__init__() if not database: database = os.environ.get('TRYTOND_DATABASE_URI') elif (os.environ.get('TRYTOND_DATABASE_URI') and not urllib.parse.urlparse(database).scheme): url = urllib.parse.urlparse(os.environ['TRYTOND_DATABASE_URI']) os.environ['TRYTOND_DATABASE_URI'] = urllib.parse.urlunparse( url._replace(path=database)) else: os.environ['TRYTOND_DATABASE_URI'] = database if not config_file: config_file = os.environ.get('TRYTOND_CONFIG') from trytond.config import config config.update_etc(config_file) from trytond.pool import Pool from trytond.transaction import Transaction self.database = database database_name = None if database: uri = urllib.parse.urlparse(database) database_name = uri.path.strip('/') if not database_name: database_name = os.environ['DB_NAME'] self.database_name = database_name self._user = user self.config_file = config_file Pool.start() self.pool = Pool(database_name) self.pool.init() with Transaction().start(self.database_name, 0) as transaction: User = self.pool.get('res.user') transaction.context = self.context with transaction.set_context(active_test=False): self.user = User.search([ ('login', '=', user), ], limit=1)[0].id with transaction.set_user(self.user): self._context = User.get_preferences(context_only=True) __init__.__doc__ = object.__init__.__doc__ def __repr__(self): return ("proteus.config.TrytondConfig" "(%s, %s, config_file=%s)" % (repr(self.database), repr(self._user), repr(self.config_file))) __repr__.__doc__ = object.__repr__.__doc__ def __eq__(self, other): if not isinstance(other, TrytondConfig): raise NotImplementedError return (self.database_name == other.database_name and self._user == other._user and self.database == other.database and self.config_file == other.config_file) def __hash__(self): return hash((self.database_name, self._user, self.database, self.config_file)) def get_proxy(self, name, type='model'): 'Return Proxy class' return TrytondProxy(name, self, type=type) def get_proxy_methods(self, name, type='model'): 'Return list of methods' proxy = self.get_proxy(name, type=type) methods = [x for x in proxy._object.__rpc__] if hasattr(proxy._object, '_buttons'): methods += [x for x in proxy._object._buttons] return methods def set_trytond(database=None, user='admin', config_file=None): 'Set trytond package as backend' _CONFIG.current = TrytondConfig(database, user, config_file=config_file) return _CONFIG.current class XmlrpcProxy(object): 'Proxy for function call for XML-RPC' def __init__(self, name, config, type='model'): super(XmlrpcProxy, self).__init__() self._config = config self._object = getattr(config.server, '%s.%s' % (type, name)) __init__.__doc__ = object.__init__.__doc__ def __getattr__(self, name): 'Return attribute value' return getattr(self._object, name) class XmlrpcConfig(Config): 'Configuration for XML-RPC' def __init__(self, url, **kwargs): super(XmlrpcConfig, self).__init__() self.url = url self.server = xmlrpc.client.ServerProxy( url, allow_none=True, use_builtin_types=True, **kwargs) # TODO add user self.user = None self._context = self.server.model.res.user.get_preferences(True, {}) __init__.__doc__ = object.__init__.__doc__ def __repr__(self): return "proteus.config.XmlrpcConfig(%s)" % repr(self.url) __repr__.__doc__ = object.__repr__.__doc__ def __eq__(self, other): if not isinstance(other, XmlrpcConfig): raise NotImplementedError return self.url == other.url def __hash__(self): return hash(self.url) def get_proxy(self, name, type='model'): 'Return Proxy class' return XmlrpcProxy(name, self, type=type) def get_proxy_methods(self, name, type='model'): 'Return list of methods' object_ = '%s.%s' % (type, name) return [x[len(object_) + 1:] for x in self.server.system.listMethods() if x.startswith(object_) and '.' not in x[len(object_) + 1:]] def set_xmlrpc(url, **kwargs): ''' Set XML-RPC as backend. It pass the keyword arguments received to xmlrpclib.ServerProxy() ''' _CONFIG.current = XmlrpcConfig(url, **kwargs) return _CONFIG.current def get_config(): return _CONFIG.current ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1632778607.0 proteus-6.0.3/proteus/pyson.py0000644000175000017500000005165600000000000014532 0ustar00cedced# 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 json import datetime from decimal import Decimal from dateutil.relativedelta import relativedelta from functools import reduce class PYSON(object): def pyson(self): raise NotImplementedError def types(self): raise NotImplementedError @staticmethod def eval(dct, context): raise NotImplementedError def __invert__(self): if self.types() != {bool}: return Not(Bool(self)) else: return Not(self) def __and__(self, other): if (isinstance(other, PYSON) and other.types() != {bool}): other = Bool(other) if (isinstance(self, And) and not isinstance(self, Or)): self._statements.append(other) return self if self.types() != {bool}: return And(Bool(self), other) else: return And(self, other) __rand__ = __and__ def __or__(self, other): if (isinstance(other, PYSON) and other.types() != {bool}): other = Bool(other) if isinstance(self, Or): self._statements.append(other) return self if self.types() != {bool}: return Or(Bool(self), other) else: return Or(self, other) __ror__ = __or__ def __eq__(self, other): return Equal(self, other) def __ne__(self, other): return Not(Equal(self, other)) def __gt__(self, other): return Greater(self, other) def __ge__(self, other): return Greater(self, other, True) def __lt__(self, other): return Less(self, other) def __le__(self, other): return Less(self, other, True) def get(self, k, d=''): return Get(self, k, d) def in_(self, obj): return In(self, obj) def contains(self, k): return In(k, self) def __repr__(self): klass = self.__class__.__name__ return '%s(%s)' % (klass, ', '.join(map(repr, self.__repr_params__))) @property def __repr_params__(self): return NotImplementedError class PYSONEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, PYSON): return obj.pyson() elif isinstance(obj, datetime.date): if isinstance(obj, datetime.datetime): return DateTime(obj.year, obj.month, obj.day, obj.hour, obj.minute, obj.second, obj.microsecond ).pyson() else: return Date(obj.year, obj.month, obj.day).pyson() elif isinstance(obj, Decimal): return float(obj) return super(PYSONEncoder, self).default(obj) class PYSONDecoder(json.JSONDecoder): def __init__(self, context=None, noeval=False): self.__context = context or {} self.noeval = noeval super(PYSONDecoder, self).__init__(object_hook=self._object_hook) def _object_hook(self, dct): if '__class__' in dct: klass = CONTEXT.get(dct['__class__']) if klass: if not self.noeval: return klass.eval(dct, self.__context) else: dct = dct.copy() del dct['__class__'] return klass(**dct) return dct class Eval(PYSON): def __init__(self, v, d=''): super(Eval, self).__init__() self._value = v self._default = d @property def __repr_params__(self): return self._value, self._default def pyson(self): return { '__class__': 'Eval', 'v': self._value, 'd': self._default, } def types(self): if isinstance(self._default, PYSON): return self._default.types() else: return {type(self._default)} @staticmethod def eval(dct, context): if '.' in dct['v']: base, name = dct['v'].split('.', 1) return Eval.eval({ 'v': name, 'd': dct['d'], }, context.get(base) or {}) return context.get(dct['v'], dct['d']) class Not(PYSON): def __init__(self, v): super(Not, self).__init__() if isinstance(v, PYSON): if v.types() != {bool}: v = Bool(v) elif not isinstance(v, bool): v = bool(v) self._value = v @property def __repr_params__(self): return (self._value,) def pyson(self): return { '__class__': 'Not', 'v': self._value, } def types(self): return {bool} @staticmethod def eval(dct, context): return not dct['v'] class Bool(PYSON): def __init__(self, v): super(Bool, self).__init__() self._value = v @property def __repr_params__(self): return (self._value,) def pyson(self): return { '__class__': 'Bool', 'v': self._value, } def types(self): return {bool} @staticmethod def eval(dct, context): return bool(dct['v']) class And(PYSON): def __init__(self, *statements, **kwargs): super(And, self).__init__() statements = list(statements) + kwargs.get('s', []) for i, statement in enumerate(list(statements)): if isinstance(statement, PYSON): if statement.types() != {bool}: statements[i] = Bool(statement) elif not isinstance(statement, bool): statements[i] = bool(statement) assert len(statements) >= 2, 'must have at least 2 statements' self._statements = statements @property def __repr_params__(self): return tuple(self._statements) def pyson(self): return { '__class__': 'And', 's': self._statements, } def types(self): return {bool} @staticmethod def eval(dct, context): return bool(reduce(lambda x, y: x and y, dct['s'])) class Or(And): def pyson(self): res = super(Or, self).pyson() res['__class__'] = 'Or' return res @staticmethod def eval(dct, context): return bool(reduce(lambda x, y: x or y, dct['s'])) class Equal(PYSON): def __init__(self, s1, s2): statement1, statement2 = s1, s2 super(Equal, self).__init__() if isinstance(statement1, PYSON): types1 = statement1.types() else: types1 = {type(s1)} if isinstance(statement2, PYSON): types2 = statement2.types() else: types2 = {type(s2)} assert types1 == types2, 'statements must have the same type' self._statement1 = statement1 self._statement2 = statement2 @property def __repr_params__(self): return (self._statement1, self._statement2) def pyson(self): return { '__class__': 'Equal', 's1': self._statement1, 's2': self._statement2, } def types(self): return {bool} @staticmethod def eval(dct, context): return dct['s1'] == dct['s2'] class Greater(PYSON): def __init__(self, s1, s2, e=False): statement1, statement2, equal = s1, s2, e super(Greater, self).__init__() for i in (statement1, statement2): if isinstance(i, PYSON): assert i.types().issubset({ int, float, type(None), datetime.datetime, datetime.date}), \ 'statement must be an integer, float, date or datetime' else: assert isinstance(i, ( int, float, type(None), datetime.datetime, datetime.date)), \ 'statement must be an integer, float, date or datetime' if isinstance(equal, PYSON): if equal.types() != {bool}: equal = Bool(equal) elif not isinstance(equal, bool): equal = bool(equal) self._statement1 = statement1 self._statement2 = statement2 self._equal = equal @property def __repr_params__(self): return (self._statement1, self._statement2, self._equal) def pyson(self): return { '__class__': 'Greater', 's1': self._statement1, 's2': self._statement2, 'e': self._equal, } def types(self): return {bool} @staticmethod def _convert(dct): for i in ('s1', 's2'): if dct[i] is None: dct[i] = 0.0 if not isinstance(dct[i], (int, float)): dct = dct.copy() stmt = dct[i] if isinstance(stmt, datetime.datetime): stmt = stmt.timestamp() elif isinstance(stmt, datetime.date): time = datetime.time(0, 0) stmt = datetime.datetime.combine(stmt, time).timestamp() dct[i] = float(stmt) return dct @staticmethod def eval(dct, context): if dct['s1'] is None or dct['s2'] is None: return False dct = Greater._convert(dct) if dct['e']: return dct['s1'] >= dct['s2'] else: return dct['s1'] > dct['s2'] class Less(Greater): def pyson(self): res = super(Less, self).pyson() res['__class__'] = 'Less' return res @staticmethod def eval(dct, context): if dct['s1'] is None or dct['s2'] is None: return False dct = Less._convert(dct) if dct['e']: return dct['s1'] <= dct['s2'] else: return dct['s1'] < dct['s2'] class If(PYSON): def __init__(self, c, t, e=None): condition, then_statement, else_statement = c, t, e super(If, self).__init__() if isinstance(condition, PYSON): if condition.types() != {bool}: condition = Bool(condition) elif not isinstance(condition, bool): condition = bool(condition) if isinstance(then_statement, PYSON): then_types = then_statement.types() else: then_types = {type(then_statement)} if isinstance(else_statement, PYSON): else_types = else_statement.types() else: else_types = {type(else_statement)} assert then_types == else_types, \ 'then and else statements must be the same type' self._condition = condition self._then_statement = then_statement self._else_statement = else_statement @property def __repr_params__(self): return (self._condition, self._then_statement, self._else_statement) def pyson(self): return { '__class__': 'If', 'c': self._condition, 't': self._then_statement, 'e': self._else_statement, } def types(self): if isinstance(self._then_statement, PYSON): return self._then_statement.types() else: return {type(self._then_statement)} @staticmethod def eval(dct, context): if dct['c']: return dct['t'] else: return dct['e'] class Get(PYSON): def __init__(self, v, k, d=''): obj, key, default = v, k, d super(Get, self).__init__() if isinstance(obj, PYSON): assert obj.types() == {dict}, 'obj must be a dict' else: assert isinstance(obj, dict), 'obj must be a dict' self._obj = obj if isinstance(key, PYSON): assert key.types() == {str}, 'key must be a string' else: assert isinstance(key, str), 'key must be a string' self._key = key self._default = default @property def __repr_params__(self): return (self._obj, self._key, self._default) def pyson(self): return { '__class__': 'Get', 'v': self._obj, 'k': self._key, 'd': self._default, } def types(self): if isinstance(self._default, PYSON): return self._default.types() else: return {type(self._default)} @staticmethod def eval(dct, context): return dct['v'].get(dct['k'], dct['d']) class In(PYSON): def __init__(self, k, v): key, obj = k, v super(In, self).__init__() if isinstance(key, PYSON): assert key.types().issubset({str, int}), \ 'key must be a string or an integer or a long' else: assert isinstance(key, (str, int)), \ 'key must be a string or an integer or a long' if isinstance(obj, PYSON): assert obj.types().issubset({dict, list}), \ 'obj must be a dict or a list' if obj.types() == {dict}: assert isinstance(key, str), 'key must be a string' else: assert isinstance(obj, (dict, list)) if isinstance(obj, dict): assert isinstance(key, str), 'key must be a string' self._key = key self._obj = obj @property def __repr_params__(self): return (self._key, self._obj) def pyson(self): return { '__class__': 'In', 'k': self._key, 'v': self._obj, } def types(self): return {bool} @staticmethod def eval(dct, context): return dct['k'] in dct['v'] class Date(PYSON): def __init__(self, year=None, month=None, day=None, delta_years=0, delta_months=0, delta_days=0, start=None, **kwargs): year = kwargs.get('y', year) month = kwargs.get('M', month) day = kwargs.get('d', day) delta_years = kwargs.get('dy', delta_years) delta_months = kwargs.get('dM', delta_months) delta_days = kwargs.get('dd', delta_days) super(Date, self).__init__() for i in (year, month, day, delta_years, delta_months, delta_days): if isinstance(i, PYSON): assert i.types().issubset({int, type(None)}), \ '%s must be an integer or None' % (i,) else: assert isinstance(i, (int, type(None))), \ '%s must be an integer or None' % (i,) self._year = year self._month = month self._day = day self._delta_years = delta_years self._delta_months = delta_months self._delta_days = delta_days self._start = start @property def __repr_params__(self): return (self._year, self._month, self._day, self._delta_years, self._delta_months, self._delta_days, self._start) def pyson(self): return { '__class__': 'Date', 'y': self._year, 'M': self._month, 'd': self._day, 'dy': self._delta_years, 'dM': self._delta_months, 'dd': self._delta_days, 'start': self._start, } def types(self): return {datetime.date} @staticmethod def eval(dct, context): today = dct.get('start') if isinstance(today, datetime.datetime): today = today.date() if not isinstance(today, datetime.date): today = datetime.date.today() return today + relativedelta( year=dct['y'], month=dct['M'], day=dct['d'], years=dct['dy'], months=dct['dM'], days=dct['dd'], ) class DateTime(Date): def __init__(self, year=None, month=None, day=None, hour=None, minute=None, second=None, microsecond=None, delta_years=0, delta_months=0, delta_days=0, delta_hours=0, delta_minutes=0, delta_seconds=0, delta_microseconds=0, start=None, **kwargs): hour = kwargs.get('h', hour) minute = kwargs.get('m', minute) second = kwargs.get('s', second) microsecond = kwargs.get('ms', microsecond) delta_hours = kwargs.get('dh', delta_hours) delta_minutes = kwargs.get('dm', delta_minutes) delta_seconds = kwargs.get('ds', delta_seconds) delta_microseconds = kwargs.get('dms', delta_microseconds) super(DateTime, self).__init__(year=year, month=month, day=day, delta_years=delta_years, delta_months=delta_months, delta_days=delta_days, start=start, **kwargs) for i in (hour, minute, second, microsecond, delta_hours, delta_minutes, delta_seconds, delta_microseconds): if isinstance(i, PYSON): assert i.types() == {int, type(None)}, \ '%s must be an integer or None' % (i,) else: assert isinstance(i, (int, type(None))), \ '%s must be an integer or None' % (i,) self._hour = hour self._minute = minute self._second = second self._microsecond = microsecond self._delta_hours = delta_hours self._delta_minutes = delta_minutes self._delta_seconds = delta_seconds self._delta_microseconds = delta_microseconds @property def __repr_params__(self): date_params = super(DateTime, self).__repr_params__ return (date_params[:3] + (self._hour, self._minute, self._second, self._microsecond) + date_params[3:-1] + (self._delta_hours, self._delta_minutes, self._delta_seconds, self._delta_microseconds) + date_params[-1:]) def pyson(self): res = super(DateTime, self).pyson() res['__class__'] = 'DateTime' res['h'] = self._hour res['m'] = self._minute res['s'] = self._second res['ms'] = self._microsecond res['dh'] = self._delta_hours res['dm'] = self._delta_minutes res['ds'] = self._delta_seconds res['dms'] = self._delta_microseconds return res def types(self): return {datetime.datetime} @staticmethod def eval(dct, context): now = dct.get('start') if (isinstance(now, datetime.date) and not isinstance(now, datetime.datetime)): now = datetime.datetime.combine(now, datetime.time()) if not isinstance(now, datetime.datetime): now = datetime.datetime.utcnow() return now + relativedelta( year=dct['y'], month=dct['M'], day=dct['d'], hour=dct['h'], minute=dct['m'], second=dct['s'], microsecond=dct['ms'], years=dct['dy'], months=dct['dM'], days=dct['dd'], hours=dct['dh'], minutes=dct['dm'], seconds=dct['ds'], microseconds=dct['dms'], ) class TimeDelta(PYSON): def __init__(self, days=0, seconds=0, microseconds=0): for i in [days, seconds, microseconds]: if isinstance(i, PYSON): assert i.types().issubset({int, float}), \ '%s must be an integer' % (i,) else: assert isinstance(i, (int, float)), \ '%s must be an integer' % (i,) self._days = days self._seconds = seconds self._microseconds = microseconds @property def __repr_params__(self): return self._days, self._seconds, self._microseconds def pyson(self): return { '__class__': 'TimeDelta', 'd': self._days, 's': self._seconds, 'm': self._microseconds, } def types(self): return {datetime.timedelta} @staticmethod def eval(dct, context): return datetime.timedelta( days=dct['d'], seconds=dct['s'], microseconds=dct['m'], ) class Len(PYSON): def __init__(self, v): super(Len, self).__init__() if isinstance(v, PYSON): assert v.types().issubset({dict, list, str}), \ 'value must be a dict or a list or a string' else: assert isinstance(v, (dict, list, str)), \ 'value must be a dict or list or a string' self._value = v @property def __repr_params__(self): return (self._value,) def pyson(self): return { '__class__': 'Len', 'v': self._value, } def types(self): return {int} @staticmethod def eval(dct, context): return len(dct['v']) CONTEXT = { 'Eval': Eval, 'Not': Not, 'Bool': Bool, 'And': And, 'Or': Or, 'Equal': Equal, 'Greater': Greater, 'Less': Less, 'If': If, 'Get': Get, 'In': In, 'Date': Date, 'DateTime': DateTime, 'TimeDelta': TimeDelta, 'Len': Len, 'true': True, 'false': False, } ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1633127074.3626652 proteus-6.0.3/proteus/tests/0000755000175000017500000000000000000000000014135 5ustar00cedced././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1632778607.0 proteus-6.0.3/proteus/tests/__init__.py0000644000175000017500000000330200000000000016244 0ustar00cedced# 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 os import sys import unittest import doctest import proteus import proteus.config os.environ.setdefault('TRYTOND_DATABASE_URI', 'sqlite:///:memory:') os.environ.setdefault('DB_NAME', ':memory:') from trytond.tests.test_tryton import ( # noqa: E402 doctest_setup, doctest_teardown) here = os.path.dirname(__file__) readme = os.path.normpath(os.path.join(here, '..', '..', 'README.rst')) def test_suite(): suite = unittest.TestSuite() loader = unittest.TestLoader() for filename in os.listdir(os.path.dirname(__file__)): if filename.startswith("test") and filename.endswith(".py"): modname = "proteus.tests." + filename[:-3] __import__(modname) module = sys.modules[modname] suite.addTests(loader.loadTestsFromModule(module)) suite.addTests(additional_tests()) return suite def additional_tests(): suite = unittest.TestSuite() for mod in (proteus, proteus.config): suite.addTest(doctest.DocTestSuite(mod)) if os.path.isfile(readme): suite.addTest(doctest.DocFileSuite(readme, module_relative=False, setUp=doctest_setup, tearDown=doctest_teardown, encoding='utf-8', optionflags=doctest.REPORT_ONLY_FIRST_FAILURE)) return suite def main(): suite = test_suite() runner = unittest.TextTestRunner() return runner.run(suite) if __name__ == '__main__': sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname( os.path.abspath(__file__))))) sys.exit(not main().wasSuccessful()) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1620052473.0 proteus-6.0.3/proteus/tests/common.py0000644000175000017500000000070700000000000016003 0ustar00cedced# 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 unittest import TestCase from trytond.tests.test_tryton import db_exist, create_db from proteus import config class ProteusTestCase(TestCase): @classmethod def setUpClass(cls): if not db_exist(): create_db() def setUp(self): self.config = config.set_trytond() ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1620052473.0 proteus-6.0.3/proteus/tests/test_config.py0000644000175000017500000000271300000000000017016 0ustar00cedced# 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 proteus.config from .common import ProteusTestCase class TestConfig(ProteusTestCase): def test_proxy(self): config = proteus.config.get_config() user_proxy = config.get_proxy('res.user') user_id = user_proxy.search([('login', '=', 'admin')], 0, 1, None, config.context)[0] self.assertTrue(user_id == config.user) def test_proxy_keyword(self): config = proteus.config.get_config() user_proxy = config.get_proxy('res.user') user_id, = user_proxy.search( [('login', '=', 'admin')], limit=1, context=config.context) self.assertTrue(user_id == config.user) def test_proxy_methods(self): config = proteus.config.get_config() self.assertTrue('search' in config.get_proxy_methods('res.user')) def test_trytond_config_eq(self): config1 = proteus.config.get_config() proteus.config.set_trytond() config2 = proteus.config.get_config() self.assertEqual(config1, config2) self.assertRaises(NotImplementedError, config1.__eq__, None) def test_repr(self): config = proteus.config.TrytondConfig('sqlite:///:memory:') self.assertEqual(repr(config), "proteus.config.TrytondConfig(" "'sqlite:///:memory:', 'admin', config_file=None)") ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1620052473.0 proteus-6.0.3/proteus/tests/test_context.py0000644000175000017500000000106400000000000017233 0ustar00cedced# 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 .common import ProteusTestCase class TestContext(ProteusTestCase): def test_config(self): prev_ctx = self.config._context with self.config.set_context({'a': 1}): self.assertEqual(self.config.context['a'], 1) for key, value in prev_ctx.items(): self.assertEqual(self.config.context[key], value) self.assertEqual(self.config.context, prev_ctx) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1632778607.0 proteus-6.0.3/proteus/tests/test_model.py0000644000175000017500000002721500000000000016655 0ustar00cedced# 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 proteus import Model from .common import ProteusTestCase class TestModel(ProteusTestCase): def test_class_cache(self): User1 = Model.get('res.user') User2 = Model.get('res.user') self.assertEqual(id(User1), id(User2)) Model.reset() User3 = Model.get('res.user') self.assertNotEqual(id(User1), id(User3)) def test_class_method(self): User = Model.get('res.user') self.assertTrue(len(User.search([('login', '=', 'admin')], {}))) def test_int(self): User = Model.get('res.user') admin = User.find([('login', '=', 'admin')])[0] self.assertEqual(int(admin), admin.id) def test_id_zero(self): User = Model.get('res.user') root = User(0) self.assertEqual(root.login, 'root') def test_find(self): User = Model.get('res.user') admin = User.find([('login', '=', 'admin')])[0] self.assertEqual(admin.login, 'admin') def test_many2one(self): User = Model.get('res.user') admin = User.find([('login', '=', 'admin')])[0] self.assertTrue(isinstance(admin.create_uid, User)) try: admin.create_uid = 'test' self.fail() except AssertionError: pass admin.create_uid = admin admin.create_uid = None User(write_uid=None) def test_one2many(self): Group = Model.get('res.group') administration = Group.find([('name', '=', 'Administration')])[0] self.assertTrue(isinstance(administration.model_access, list)) self.assertTrue(isinstance(administration.model_access[0], Model.get('ir.model.access'))) try: administration.model_access = [] self.fail() except AttributeError: pass def test_many2many(self): User = Model.get('res.user') admin = User.find([('login', '=', 'admin')])[0] self.assertTrue(isinstance(admin.groups, list)) self.assertTrue(isinstance(admin.groups[0], Model.get('res.group'))) try: admin.groups = [] self.fail() except AttributeError: pass # TODO test date def test_reference(self): Attachment = Model.get('ir.attachment') User = Model.get('res.user') admin = User.find([('login', '=', 'admin')])[0] attachment = Attachment() attachment.name = 'Test' attachment.resource = admin attachment.save() self.assertEqual(attachment.resource, admin) def test_id_counter(self): User = Model.get('res.user') test1 = User() self.assertTrue(test1.id < 0) test2 = User() self.assertTrue(test2.id < 0) self.assertNotEqual(test1.id, test2.id) def test_init(self): User = Model.get('res.user') self.assertEqual(User(1).id, 1) self.assertEqual(User(name='Foo').name, 'Foo') Lang = Model.get('ir.lang') en, = Lang.find([('code', '=', 'en')]) self.assertEqual(User(language=en).language, en) self.assertEqual(User(language=en.id).language, en) Group = Model.get('res.group') groups = Group.find() self.assertEqual(len(User(groups=groups).groups), len(groups)) self.assertEqual(len(User(groups=[x.id for x in groups]).groups), len(groups)) def test_assign_unknown_field(self): "Test it is not allowed to assign unknown field" User = Model.get('res.user') user = User() with self.assertRaises(AttributeError): user.unknown_field = 'foo' def test_save(self): User = Model.get('res.user') test = User() test.name = 'Test' test.login = 'test' test.save() self.assertTrue(test.id > 0) test = User(test.id) self.assertEqual(test.name, 'Test') self.assertEqual(test.login, 'test') self.assertTrue(test.active) test.signature = 'Test signature' self.assertEqual(test.signature, 'Test signature') test.save() self.assertEqual(test.signature, 'Test signature') test = User(test.id) self.assertEqual(test.signature, 'Test signature') Group = Model.get('res.group') test2 = User(name='Test 2', login='test2', groups=[Group(name='Test 2')]) test2.save() self.assertTrue(test2.id > 0) self.assertEqual(test2.name, 'Test 2') self.assertEqual(test2.login, 'test2') test.signature = 'classmethod save' test2.name = 'Test 2 classmethod' test3 = User(name='Test 3', login='test3') User.save([test, test2, test3]) self.assertEqual(test.signature, 'classmethod save') self.assertEqual(test2.name, 'Test 2 classmethod') self.assertTrue(test3.id > 0) self.assertEqual(test3.name, 'Test 3') def test_save_many2one(self): User = Model.get('res.user') test = User() test.name = 'Test save many2one' test.login = 'test_save_many2one' test.save() Lang = Model.get('ir.lang') en, = Lang.find([('code', '=', 'en')]) test.language = en test.save() self.assertEqual(test.language, en) test.language = None test.save() self.assertFalse(test.language) def test_save_one2many(self): Group = Model.get('res.group') group = Group() group.name = 'Test save one2many' group.save() ModelAccess = Model.get('ir.model.access') Model_ = Model.get('ir.model') model_access = ModelAccess() model_access.model = Model_.find([('model', '=', 'res.group')])[0] model_access.perm_read = True model_access.perm_write = True model_access.perm_create = True model_access.perm_delete = True group.model_access.append(model_access) group.save() self.assertEqual(len(group.model_access), 1) model_access_id = group.model_access[0].id group.name = 'Test save one2many bis' group.model_access[0].description = 'Test save one2many' group.save() self.assertEqual(group.model_access[0].description, 'Test save one2many') group.model_access.pop() group.save() self.assertEqual(group.model_access, []) self.assertEqual(len(ModelAccess.find([('id', '=', model_access_id)])), 1) group.model_access.append(ModelAccess(model_access_id)) group.save() self.assertEqual(len(group.model_access), 1) group.model_access.remove(group.model_access[0]) group.save() self.assertEqual(group.model_access, []) self.assertEqual(len(ModelAccess.find([('id', '=', model_access_id)])), 0) def test_save_many2many(self): User = Model.get('res.user') test = User() test.name = 'Test save many2many' test.login = 'test_save_many2many' test.save() Group = Model.get('res.group') group = Group() group.name = 'Test save many2many' group.save() test.groups.append(group) test.save() self.assertEqual(len(test.groups), 1) group_id = test.groups[0].id test.name = 'Test save many2many bis' test.groups[0].name = 'Test save many2many bis' test.save() self.assertEqual(test.groups[0].name, 'Test save many2many bis') test.groups.pop() test.save() self.assertEqual(test.groups, []) self.assertEqual(len(Group.find([('id', '=', group_id)])), 1) test.groups.append(Group(group_id)) test.save() self.assertEqual(len(test.groups), 1) test.groups.remove(test.groups[0]) test.save() self.assertEqual(test.groups, []) self.assertEqual(len(Group.find([('id', '=', group_id)])), 0) def test_eq(self): User = Model.get('res.user') test = User() test.name = 'Test eq' test.login = 'test_eq' test.save() admin1 = User.find([('login', '=', 'admin')])[0] admin2 = User.find([('login', '=', 'admin')])[0] self.assertEqual(admin1, admin2) self.assertFalse(admin1 != admin2) self.assertNotEqual(admin1, test) self.assertFalse(admin1 == test) self.assertNotEqual(admin1, None) self.assertNotEqual(admin1, False) self.assertNotEqual(admin1, 1) def test_default_set(self): User = Model.get('res.user') Group = Model.get('res.group') group_ids = [x.id for x in Group.find()] test = User() test._default_set({ 'name': 'Test', 'groups': group_ids, }) self.assertEqual(test.name, 'Test') self.assertEqual([x.id for x in test.groups], group_ids) test = User() test._default_set({ 'name': 'Test', 'groups': [ { 'name': 'Group 1', }, { 'name': 'Group 2', }, ], }) self.assertEqual(test.name, 'Test') self.assertEqual([x.name for x in test.groups], ['Group 1', 'Group 2']) def test_delete(self): Group = Model.get('res.group') test = Group() test.name = 'Test delete' test.save() test.delete() def test_duplicate(self): User = Model.get('res.user') test = User() test.name = 'Test duplicate' test.login = 'test duplicate' test.save() copy, = User.duplicate([test], {'name': 'Test copy'}) self.assertEqual(copy.name, 'Test copy') self.assertEqual(copy.login, 'test duplicate (copy)') self.assertNotEqual(copy.id, test.id) def test_on_change(self): Trigger = Model.get('ir.trigger') trigger = Trigger() trigger.on_time = True self.assertEqual(trigger.on_create, False) trigger.on_create = True self.assertEqual(trigger.on_time, False) def test_on_change_with(self): Attachment = Model.get('ir.attachment') attachment = Attachment() attachment.description = 'Test' self.assertEqual(attachment.summary, 'Test') def test_on_change_set(self): User = Model.get('res.user') Group = Model.get('res.group') test = User() test._on_change_set('name', 'Test') self.assertEqual(test.name, 'Test') group_ids = [x.id for x in Group.find()] test._on_change_set('groups', group_ids) self.assertEqual([x.id for x in test.groups], group_ids) test._on_change_set('groups', {'remove': [group_ids[0]]}) self.assertEqual([x.id for x in test.groups], group_ids[1:]) test._on_change_set('groups', {'add': [(-1, { 'name': 'Bar', })]}) self.assertTrue([x for x in test.groups if x.name == 'Bar']) test.groups.extend(Group.find()) group = test.groups[0] test._on_change_set('groups', {'update': [{ 'id': group.id, 'name': 'Foo', }]}) self.assertTrue([x for x in test.groups if x.name == 'Foo']) def test_model_list_find(self): User = Model.get('res.user') Group = Model.get('res.group') test = User() groups = test.groups.find(order=[('id', 'ASC')]) all_groups = Group.find([], order=[('id', 'ASC')]) self.assertListEqual(groups, all_groups) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1620052473.0 proteus-6.0.3/proteus/tests/test_report.py0000644000175000017500000000142700000000000017065 0ustar00cedced# 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 unittest try: import pydot except ImportError: pydot = None from proteus import Report, Model from .common import ProteusTestCase class TestReport(ProteusTestCase): @unittest.skipIf(not pydot, 'requires pydot') def test_model_graph(self): IrModel = Model.get('ir.model') models = IrModel.find([]) data = { 'level': 1, 'filter': '', } report = Report('ir.model.graph') type_, data, print_, name = report.execute(models, data) self.assertEqual(type_, 'png') self.assertEqual(print_, False) self.assertEqual(name, 'Graph') ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1620052473.0 proteus-6.0.3/proteus/tests/test_wizard.py0000644000175000017500000000414500000000000017052 0ustar00cedced# 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 proteus import Wizard, Model from .common import ProteusTestCase class TestWizard(ProteusTestCase): def test_translation_clean(self): translation_clean = Wizard('ir.translation.clean') self.assertEqual(translation_clean.form.__class__.__name__, 'ir.translation.clean.start') translation_clean.execute('clean') self.assertEqual(translation_clean.form.__class__.__name__, 'ir.translation.clean.succeed') def test_translation_export(self): Lang = Model.get('ir.lang') Module = Model.get('ir.module') translation_export = Wizard('ir.translation.export') translation_export.form.language, = Lang.find([('code', '=', 'en')]) translation_export.form.module, = Module.find([('name', '=', 'ir')]) translation_export.execute('export') self.assertTrue(translation_export.form.file) translation_export.execute('end') def test_user_config(self): User = Model.get('res.user') user_config = Wizard('res.user.config') user_config.execute('user') user_config.form.name = 'Foo' user_config.form.login = 'foo' user_config.execute('add') self.assertEqual(user_config.form.name, None) self.assertEqual(user_config.form.login, None) user_config.form.name = 'Bar' user_config.form.login = 'bar' user_config.execute('end') self.assertTrue(User.find([('name', '=', 'Foo')])) self.assertFalse(User.find([('name', '=', 'Bar')])) def test_translation_update(self): print_model_graph = Wizard('ir.translation.update') self.assertEqual(len(print_model_graph.actions), 0) print_model_graph.execute('update') self.assertEqual(len(print_model_graph.actions), 1) def test_configuration_wizard(self): config_wizard = Wizard('ir.module.config_wizard') config_wizard.execute('action') self.assertTrue(config_wizard.actions) ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1633127074.3559985 proteus-6.0.3/proteus.egg-info/0000755000175000017500000000000000000000000014465 5ustar00cedced././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1633127073.0 proteus-6.0.3/proteus.egg-info/PKG-INFO0000644000175000017500000001265300000000000015571 0ustar00cedcedMetadata-Version: 2.1 Name: proteus Version: 6.0.3 Summary: Library to access Tryton server as a client Home-page: http://www.tryton.org/ Author: Tryton Author-email: bugs@tryton.org License: LGPL-3 Download-URL: http://downloads.tryton.org/6.0/ Project-URL: Bug Tracker, https://bugs.tryton.org/ Project-URL: Documentation, https://docs.tryton.org/ Project-URL: Forum, https://www.tryton.org/forum Project-URL: Source Code, https://hg.tryton.org/proteus Description: ======================= Tryton Scripting Client ======================= A library to access Tryton's models like a client. Example of usage ---------------- >>> from proteus import config, Model, Wizard, Report Configuration ~~~~~~~~~~~~~ Configuration to connect to a sqlite memory database using trytond as module. >>> config = config.set_trytond('sqlite:///:memory:') Activating a module ~~~~~~~~~~~~~~~~~~~ Find the module, call the activate button and run the upgrade wizard. >>> Module = Model.get('ir.module') >>> party_module, = Module.find([('name', '=', 'party')]) >>> party_module.click('activate') >>> Wizard('ir.module.activate_upgrade').execute('upgrade') Creating a party ~~~~~~~~~~~~~~~~ First instanciate a new Party: >>> Party = Model.get('party.party') >>> party = Party() >>> party.id < 0 True Fill the fields: >>> party.name = 'ham' Save the instance into the server: >>> party.save() >>> party.name 'ham' >>> party.id > 0 True Setting the language of the party ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The language on party is a `Many2One` relation field. So it requires to get a `Model` instance as value. >>> Lang = Model.get('ir.lang') >>> en, = Lang.find([('code', '=', 'en')]) >>> party.lang = en >>> party.save() >>> party.lang.code 'en' Creating an address for the party ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Addresses are store on party with a `One2Many` field. So the new address just needs to be appended to the list `addresses`. >>> address = party.addresses.new(postal_code='42') >>> party.save() >>> party.addresses #doctest: +ELLIPSIS [proteus.Model.get('party.address')(...)] Adding category to the party ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Categories are linked to party with a `Many2Many` field. So first create a category >>> Category = Model.get('party.category') >>> category = Category() >>> category.name = 'spam' >>> category.save() Append it to categories of the party >>> party.categories.append(category) >>> party.save() >>> party.categories #doctest: +ELLIPSIS [proteus.Model.get('party.category')(...)] Print party label ~~~~~~~~~~~~~~~~~ There is a label report on `Party`. >>> label = Report('party.label') The report is executed with a list of records and some extra data. >>> type_, data, print_, name = label.execute([party], {}) Sorting addresses and register order ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Addresses are ordered by sequence which means they can be stored following a specific order. The `set_sequence` method stores the current order. >>> address = party.addresses.new(postal_code='69') >>> party.save() >>> address = party.addresses.new(postal_code='23') >>> party.save() Now changing the order. >>> reversed_addresses = list(reversed(party.addresses)) >>> while party.addresses: ... _ = party.addresses.pop() >>> party.addresses.extend(reversed_addresses) >>> party.addresses.set_sequence() >>> party.save() >>> party.addresses == reversed_addresses True Keywords: tryton library cli Platform: any 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 Library or Lesser General Public License (LGPL) Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.6 Classifier: Programming Language :: Python :: 3.7 Classifier: Programming Language :: Python :: 3.8 Classifier: Programming Language :: Python :: 3.9 Classifier: Programming Language :: Python :: Implementation :: CPython Classifier: Programming Language :: Python :: Implementation :: PyPy Classifier: Topic :: Office/Business Requires-Python: >=3.6 Provides-Extra: trytond ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1633127074.0 proteus-6.0.3/proteus.egg-info/SOURCES.txt0000644000175000017500000000103200000000000016345 0ustar00cedced.drone.yml .flake8 .hgtags CHANGELOG COPYRIGHT LICENSE MANIFEST.in README.rst setup.py tox.ini doc/index.rst proteus/__init__.py proteus/config.py proteus/pyson.py proteus.egg-info/PKG-INFO proteus.egg-info/SOURCES.txt proteus.egg-info/dependency_links.txt proteus.egg-info/requires.txt proteus.egg-info/top_level.txt proteus.egg-info/zip-safe proteus/tests/__init__.py proteus/tests/common.py proteus/tests/test_config.py proteus/tests/test_context.py proteus/tests/test_model.py proteus/tests/test_report.py proteus/tests/test_wizard.py././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1633127073.0 proteus-6.0.3/proteus.egg-info/dependency_links.txt0000644000175000017500000000000100000000000020533 0ustar00cedced ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1633127073.0 proteus-6.0.3/proteus.egg-info/requires.txt0000644000175000017500000000005500000000000017065 0ustar00cedcedpython-dateutil [trytond] trytond<6.1,>=6.0 ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1633127073.0 proteus-6.0.3/proteus.egg-info/top_level.txt0000644000175000017500000000001000000000000017206 0ustar00cedcedproteus ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1620419713.0 proteus-6.0.3/proteus.egg-info/zip-safe0000644000175000017500000000000100000000000016115 0ustar00cedced ././@PaxHeader0000000000000000000000000000003400000000000010212 xustar0028 mtime=1633127074.3659985 proteus-6.0.3/setup.cfg0000644000175000017500000000004600000000000013113 0ustar00cedced[egg_info] tag_build = tag_date = 0 ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1632778607.0 proteus-6.0.3/setup.py0000755000175000017500000000702500000000000013013 0ustar00cedced#!/usr/bin/env python3 # 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 io import os import re from setuptools import setup, find_packages def read(fname): return io.open( os.path.join(os.path.dirname(__file__), fname), 'r', encoding='utf-8').read() def get_version(): init = read(os.path.join('proteus', '__init__.py')) return re.search('__version__ = "([0-9.]*)"', init).group(1) def get_require_version(name): if minor_version % 2: require = '%s >= %s.%s.dev0, < %s.%s' else: require = '%s >= %s.%s, < %s.%s' require %= (name, major_version, minor_version, major_version, minor_version + 1) return require name = 'proteus' version = get_version() major_version, minor_version, _ = version.split('.', 2) major_version = int(major_version) minor_version = int(minor_version) download_url = 'http://downloads.tryton.org/%s.%s/' % ( major_version, minor_version) if minor_version % 2: version = '%s.%s.dev0' % (major_version, minor_version) download_url = 'hg+http://hg.tryton.org/%s#egg=%s-%s' % ( name, name, version) local_version = [] if os.environ.get('CI_JOB_ID'): local_version.append(os.environ['CI_JOB_ID']) else: for build in ['CI_BUILD_NUMBER', 'CI_JOB_NUMBER']: if os.environ.get(build): local_version.append(os.environ[build]) else: local_version = [] break if local_version: version += '+' + '.'.join(local_version) dependency_links = [] if minor_version % 2: dependency_links.append( 'https://trydevpi.tryton.org/?local_version=' + '.'.join(local_version)) setup(name=name, version=version, description='Library to access Tryton server as a client', long_description=read('README.rst'), author='Tryton', author_email='bugs@tryton.org', url='http://www.tryton.org/', download_url=download_url, project_urls={ "Bug Tracker": 'https://bugs.tryton.org/', "Documentation": 'https://docs.tryton.org/', "Forum": 'https://www.tryton.org/forum', "Source Code": 'https://hg.tryton.org/proteus', }, keywords='tryton library cli', packages=find_packages(), classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Plugins', 'Framework :: Tryton', 'Intended Audience :: Developers', 'Intended Audience :: Financial and Insurance Industry', 'Intended Audience :: Legal Industry', 'License :: OSI Approved :: ' 'GNU Library or Lesser General Public License (LGPL)', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', 'Topic :: Office/Business', ], platforms='any', license='LGPL-3', python_requires='>=3.6', install_requires=[ "python-dateutil", ], extras_require={ 'trytond': [get_require_version('trytond')], }, dependency_links=dependency_links, zip_safe=True, test_suite='proteus.tests', tests_require=[get_require_version('trytond'), get_require_version('trytond_party')], ) ././@PaxHeader0000000000000000000000000000002600000000000010213 xustar0022 mtime=1632778607.0 proteus-6.0.3/tox.ini0000644000175000017500000000056200000000000012610 0ustar00cedced[tox] envlist = py36,py37,py38,py39,pypy3 [testenv] commands = {envpython} setup.py test deps = setenv = TRYTOND_DATABASE_URI={env:TRYTOND_DATBASE_URI:sqlite://} DB_NAME={env:DB_NAME::memory:} install_command = pip install --pre --find-links https://trydevpi.tryton.org/?local_version={env:CI_JOB_ID:{env:CI_BUILD_NUMBER}.{env:CI_JOB_NUMBER}} {opts} {packages}