pax_global_header00006660000000000000000000000064126520757230014523gustar00rootroot0000000000000052 comment=dac679a8ec1cd01924e7b2e80280c270f69b55ac core_engine-2.6.1-dac679a8ec1cd01924e7b2e80280c270f69b55ac/000077500000000000000000000000001265207572300215225ustar00rootroot00000000000000core_engine-2.6.1-dac679a8ec1cd01924e7b2e80280c270f69b55ac/.externalToolBuilders/000077500000000000000000000000001265207572300257525ustar00rootroot00000000000000core_engine-2.6.1-dac679a8ec1cd01924e7b2e80280c270f69b55ac/.externalToolBuilders/My_Builder.launch000077500000000000000000000012721265207572300312060ustar00rootroot00000000000000 core_engine-2.6.1-dac679a8ec1cd01924e7b2e80280c270f69b55ac/.hgignore000066400000000000000000000001041265207572300233200ustar00rootroot00000000000000# use glob syntax. syntax: glob .* *.pyc *~ *.lock *.cache data/* core_engine-2.6.1-dac679a8ec1cd01924e7b2e80280c270f69b55ac/.project000077500000000000000000000012541265207572300231760ustar00rootroot00000000000000 core_engine org.python.pydev.PyDevBuilder org.eclipse.ui.externaltools.ExternalToolBuilder full,incremental, LaunchConfigHandle <project>/.externalToolBuilders/My_Builder.launch org.python.pydev.pythonNature core_engine-2.6.1-dac679a8ec1cd01924e7b2e80280c270f69b55ac/.pydevproject000077500000000000000000000006601265207572300242460ustar00rootroot00000000000000 Default python 2.7 /core_engine/gnukhataserver core_engine-2.6.1-dac679a8ec1cd01924e7b2e80280c270f69b55ac/CHANGELOG000066400000000000000000000075721265207572300227470ustar00rootroot00000000000000[27-Jan-2016 Release 2.6.1] * Minor improvements and bug fixes. [3-Nov-2015 Release 2.6.0] * Added the core logic for transaction security. * System generated accounts will now also include Opening Stock and Stock at the Beginning. * Improved the functionality of closebooks and rollover to include management of stocks. * Minor improvements and bugs fixes. [28-Aug-2015 Release 2.5.0] * Implemented core functionality for advanced calculation of profit and loss as seperate account heads along with facility of transferring closing stock as opening stock entry after rollover. * Brought more stability to bank recon rpcs. * Now no duplicate organisation can be created. * Minor bug fixes. [24-July-2015 Release 2.4.0] * Corrected Bank Reconciliation Statement. * Fundamental changes which refines the way closebooks and rollover works. * Organizations with same names with different types can be safely created. [06-June-2015 Release 2.3.2] * Perfected CloseBooks and Rollover. [15-May-2015 Release 2.3.1] * Further refined Rollover and Closebooks. * Corrected names of a few default accounts like Income and Expenditure. [28-March-2015 Release 2.3] * Added the stored procedure for remove user. * Added the rpc for remove user. * Added the stored procedures for getting and setting the security question and answer in case the user forgets the login password. * Added the rpc for getting and setting the the security question and answer in case the user forgets the login password. * Added the procedure for closebooks. * Added the rpc for closebooks. [3-March-2015 Release 2.2.1] * Fixed a crutial bug where some times after deleting an account, we could not ad any more accounts. * Update of Install file and adduser script for Fedora Distro. * Added minor typo corrections in group heads. [8-Nov-2014 Release 2.2.0] * Major enhancement in the functionality of Bank Reconciliation, it also dispalys the reconciled transactions which are above the reconciliation period along with it's actual reconciliation date. * Added the functionality for getting Rollover status and also added the set and get rollover status. * Added the logic for setting the roflag and booksclosedflag during rolover and closing of books. [18-Oct-2014 Release 2.1.3] * Solved regression where software was crashing while saving or skiping on initialsetup form * Procedure syntax cahnged in rpc_main * Added stored procedure and functionality for getting organization * Bank reconciliation now also has opening balance [8-Oct-2014 Release 2.1.2] * Changed the hashbang to python2 * Altered update bank recon to have closing and grand total with total dr, cr. * Further improvements in bank reco now closing balance and cr dr can be seen and the particulars are properly seen. * Added Stability in cash flow and negative amount can be seen * finaly corrected the issue where payment with 0 would some tiems show as -0 [13-Sept-2014 Release 2.1.1] * Fixed a major bug in Bank reconciliation to make the viewclearedanduncleared transactions consistent. [19-Aug-2014 Release 2.1] *Added new api for getclearedunclearedtransactions *Added new rpc getreconciledtransactions in rpc_reports *Updated deletclearedrecon stored procedure [22-July-2014 Release 2.0.1] * Fixed database connection issue during rollover [7-Jul-2014 Release 2.0 ] * added a new rpc function for getting list of accounts * modified stored procedures to show all accounts on Dr and Cr side for Payment and reseapt respectively * performance enhancement by removing code for creating unnecessary tables * alteration to global attributes to find if projectwise accounting is available * made 3 level user access possible -1: admin 0: manager 1: user * added pid to a pidfile for start stop daemons * all settings are now taken from configuration file * major security enhancement where engine connects to postgres via unix sockets * added scripts to create user and grant privileges core_engine-2.6.1-dac679a8ec1cd01924e7b2e80280c270f69b55ac/COPYING000066400000000000000000001045131265207572300225610ustar00rootroot00000000000000 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 . core_engine-2.6.1-dac679a8ec1cd01924e7b2e80280c270f69b55ac/INSTALL000066400000000000000000000051451265207572300225600ustar00rootroot00000000000000Installation Instructions ************************* Copyright (C) 2007, 2008, 2009 Comet Media Foundation. This file is free documentation; Comet Media Foundation gives unlimited permission to copy, distribute and modify it. Under the terms of GNU General Public License published by the Free Software Foundation, either version 3 or any later version at your choice. *WARNING* Comet Media Foundation or the author of this document disclaims all warranties including but not limited the implied warrenty of merchantability and fitness for a particular purpose. FOLLOW THE INSTRUCTIONS AT YOUR OWN RISK! NOTE: These set of instructions are meant for those who download the source and run it directly. The actual setup script will perform all the given activities for an end user using GNUKhata for production. You can also install gnukhata from debian packages available from, http://people.debian.org/~praveen/gnukhata/ (follow instructions in the README file there) Basic Installation ================== Gnukhata depends on the following components and they should be installed for the software to be functional. For the Core engine: * postgresql for the database, version 9.x * sqlite3 needed for suplimentary data * python version 2.7 recommended for stability * python-psycopg2 for the database connectivity and interfacing between python and postgresql. * python-sqlalchemy 0.7.x for stored procedures execution * python-twisted for the xmlrpc service For checkout of source code: * git for getting (pulling) the code and committing changes. 1. Install dependencies: $ sudo apt-get install python-psycopg2 postgresql python-twisted python-dateutil You will need python-sqlalchemy 0.7.x version for stored procedures to work. We are working with sqlalchemy upstream to make gnukhata work with newer versions of sqlalchemy. You can see the status of this issue at, https://bitbucket.org/zzzeek/sqlalchemy/issue/3103/nosuchcolumnerror-could-not-locate-column You can install python-sqlalchemy7 from, http://people.debian.org/~praveen/gnukhata/ (follow instructions in the README file there) 2. Copy conf/gnukhata.conf to /etc, $ sudo cp conf/gnukhata.conf /etc 3. Use scripts/adduser.sh to create a separate user for core_engine service $ sudo ./scripts/adduser.sh 4. Create a directory for storing gnukhata.xml $ sudo mkdir -p /var/lib/gnukhata $ sudo chown gnukhata: /var/lib/gnukhata 5. Create a database user and grant required privileges $ sudo -u postgres createuser gnukhata $ sudo ./scripts/grantpriv.sh GNUKhata server is ready to be used. To start GNUKhata type sudo -u gnukhata ./gkstart from the core_engine directory. core_engine-2.6.1-dac679a8ec1cd01924e7b2e80280c270f69b55ac/README000066400000000000000000000060571265207572300224120ustar00rootroot00000000000000Installation Instructions ************************* Copyright (C) 2007, 2008, 2009 Comet Media Foundation. This file is free documentation; Comet Media Foundation gives unlimited permission to copy, distribute and modify it. Under the terms of GNU General Public License published by the Free Software Foundation, either version 3 or any later version at your choice. *WARNING* Comet Media Foundation or the author of this document disclaims all warranties including but not limited the implied warrenty of merchantability and fitness for a particular purpose. FOLLOW THE INSTRUCTIONS AT YOUR OWN RISK! NOTE: These set of instructions are meant for those who download the source and run it directly. The actual setup script will perform all the given activities for an end user using GNUKhata for production. You can also install gnukhata from debian packages available from, http://people.debian.org/~praveen/gnukhata/ (follow instructions in the README file there) Basic Installation ================== Gnukhata depends on the following components and they should be installed for the software to be functional. For the Core engine: * postgresql for the database, version 9.x * sqlite3 needed for suplimentary data * python version 2.7 recommended for stability * python-psycopg2 for the database connectivity and interfacing between python and postgresql. * python-sqlalchemy 0.7.x for stored procedures execution * python-twisted for the xmlrpc service For checkout of source code: * git for getting (pulling) the code and committing changes. 1. Install dependencies: $ sudo apt-get install python-psycopg2 postgresql python-twisted python-dateutil On Fedora # dnf install python-psycopg2 postgresql postgresql-server python-twisted python-dateutil You will need python-sqlalchemy 0.7.x version for stored procedures to work. We are working with sqlalchemy upstream to make gnukhata work with newer versions of sqlalchemy. You can see the status of this issue at, https://bitbucket.org/zzzeek/sqlalchemy/issue/3103/nosuchcolumnerror-could-not-locate-column You can install python-sqlalchemy7 from, http://people.debian.org/~praveen/gnukhata/ (follow instructions in the README file there) On Fedora You can download the 0.7.x rpm from the link http://rpmfind.net/linux/rpm2html/search.php?query=python-sqlalchemy will work for Fedora 18 to 21 (Tested to that only) 2. Copy conf/gnukhata.conf to /etc, $ sudo cp conf/gnukhata.conf /etc 3. Use scripts/adduser.sh to create a separate user for core_engine service $ sudo ./scripts/adduser.sh 4. Create a directory for storing gnukhata.xml $ sudo mkdir -p /var/lib/gnukhata $ sudo chown gnukhata: /var/lib/gnukhata 5. Create a database user and grant required privileges On Fedora Initialize the Database # su - postgres -c initdb Start Postgresql Service # systemctl start postgresql.service -- $ sudo -u postgres createuser gnukhata $ sudo ./scripts/grantpriv.sh GNUKhata server is ready to be used. To start GNUKhata type sudo -u gnukhata ./gkstart from the core_engine directory. To stop the Server run $ sudo killall -9 gkstartcore_engine-2.6.1-dac679a8ec1cd01924e7b2e80280c270f69b55ac/authors000066400000000000000000000017211265207572300231330ustar00rootroot00000000000000active contributers: Krishnakant mane (team leader) Ishan Masdekar Sadhana Bagal Snehal Nighut Pravin Domain expert: Mr Arun Kelkar former contributors: Sayali Yewale Girish Mane Amit Chaugule Radhika Wadegaonkar Parthavi Hora Shruti Surve priyanka Tawde Sushila Sharma Sonal Chaudhari Akshay Puradkar Ankita Shanbhag Ruchika Pai Anusha Kadambala Nutan Nivate Ujwala Pawade Aditi Patil Ashwini Shinde Sundeep Pulaskar core_engine-2.6.1-dac679a8ec1cd01924e7b2e80280c270f69b55ac/conf/000077500000000000000000000000001265207572300224475ustar00rootroot00000000000000core_engine-2.6.1-dac679a8ec1cd01924e7b2e80280c270f69b55ac/conf/gnukhata.conf000066400000000000000000000011061265207572300251160ustar00rootroot00000000000000[core_engine] # Location to store organizations list xmlpath = /var/lib/gnukhata/gnukhata.xml # System user which will run gnukhata-core-engine service user = gnukhata # Postgres database configuration dbuser = gnukhata dbpassword = '' database = gnukhata host = /var/run/postgresql authmethod = peer # Port for core_engine xmlrpc service port = 7081 # Location of places.db file containing city names placesdb_path = /usr/share/gnukhata/places.db #valid values can be yes or no startpostgres = yes # File to store core_engine process id pidfile = /var/run/gnukhata/pidfile core_engine-2.6.1-dac679a8ec1cd01924e7b2e80280c270f69b55ac/gkstart000077500000000000000000000033421265207572300231310ustar00rootroot00000000000000#!/usr/bin/python2 ''' This file is part of GNUKhata:A modular,robust and Free Accounting System. GNUKhata 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.and old.stockflag = 's' GNUKhata 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 GNUKhata (COPYING); if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA59 Temple Place, Suite 330, Contributor: "Krishnakant Mane" Krishnakant Mane ''' """ import the main rpc module that starts gnukhata the module is in gnukhataserver, the package for core engine. We will also need the os module for executing other shell level commans. This script will be plased in the user's /opt/gnukhata/bin directory. It will have a symlink in /usr/bin so as to facilitate easy execution. First the script will initialise the postgresql daemon from /opt/gnukhata/bin/postgres after the RDBMS the nginx web server will be started on port 80. after that the core engine will be started followed by the web application. """ import gnukhataserver.rpc_main import os if __name__ == "__main__": try: #os.system("sudo su -c '/usr/bin/postgres -D /var/data &' postgres") gnukhataserver.rpc_main.rungnukhata() except: print "can't start GNUKhata, some thing is wrong " core_engine-2.6.1-dac679a8ec1cd01924e7b2e80280c270f69b55ac/gnukhataserver/000077500000000000000000000000001265207572300245535ustar00rootroot00000000000000core_engine-2.6.1-dac679a8ec1cd01924e7b2e80280c270f69b55ac/gnukhataserver/__init__.py000077500000000000000000000000001265207572300266550ustar00rootroot00000000000000core_engine-2.6.1-dac679a8ec1cd01924e7b2e80280c270f69b55ac/gnukhataserver/dbconnect.py000077500000000000000000000743241265207572300271010ustar00rootroot00000000000000''' This file is part of GNUKhata:A modular,robust and Free Accounting System. GNUKhata 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.and old.stockflag = 's' GNUKhata 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 GNUKhata (COPYING); if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA59 Temple Place, Suite 330, Contributor: "Krishnakant Mane" "Anusha Kadambala" "Sonal Chaudhari" Ankita Shanbhag Ashwini Shinde Nutan Nivate Sayali Yewale Ujwala Pawade Ruchika Pai ''' from sqlalchemy import create_engine, func, select, literal_column from sqlalchemy.engine import create_engine from sqlalchemy import orm from sqlalchemy import Table, Column, Integer, String, MetaData, ForeignKey, select, Text, DECIMAL, Enum from sqlalchemy.ext.declarative import declarative_base #from sqlalchemy.types import String, SchemaType from sqlalchemy.orm import sessionmaker, scoped_session from sqlalchemy.types import Numeric, TIMESTAMP, Enum from xml.etree import ElementTree as et import os import datetime, time from time import strftime from sqlalchemy import * from types import * import psycopg2 import ConfigParser #from paste.util.PySourceColor import null #creating an empty list of engines. #engine in this analogy is a connection maintained as a session. #so every time a new client connects to the rpc server, #a new engine is appended to the list and the index returned as the id. engines = {} session = sessionmaker() userlist = {} user_roles= {} #the getConnection function will actually establish connection and return the id of the latest engine added to the list. #first check if the file exists in the given path. #if this is the first time we are running the server then we need to create the gnukhata.xml file. confFileData = {} confData = {} def getConf(): """ Purpose: This functions access the gnukhata.conf file from the path '/etc/gnukhata.conf' and returns the values stored in the [core_engine] section. """ config = ConfigParser.ConfigParser() config.read('/etc/gnukhata.conf') confFileData['xmlpath'] = config.get('core_engine', 'xmlpath') confFileData['user'] = config.get('core_engine', 'user') confFileData['dbuser'] = config.get('core_engine', 'dbuser') confFileData['dbpassword'] = config.get('core_engine', 'dbpassword') confFileData['database'] = config.get('core_engine', 'database') confFileData['host'] = config.get('core_engine', 'host') confFileData['authmethod'] = config.get('core_engine', 'authmethod') confFileData['port'] = config.get('core_engine', 'port') confFileData['placesdb_path'] = config.get('core_engine', 'placesdb_path') confFileData['pidfile'] = config.get('core_engine', 'pidfile') return confFileData def getOrgList(): """ Purpose: This function opens the configuration file gnukhata.xml and gets the list of all organisations registered on the server. Function takes no arguments. Returns a list of organisations. """ confData = getConf() print "calling getorglist " if os.path.exists(confData['xmlpath']) == False: print "file not found trying to create one." try: os.system("touch " + confData['xmlpath']) print "file created " os.system("chmod 722 " + confData['xmlpath']) print "permissions granted " except: print "the software is finding trouble creating file." return False try: gkconf = open(confData['xmlpath'], "a") gkconf.write("\n") gkconf.write("") gkconf.close() except: print "we can't write to the file, sorry!" return False try: conn = psycopg2.connect("dbname='template1' host='" + confData['host']) print "template1 connected" cur = conn.cursor() cur.execute("create user gnukhata with password 'gnukhata';") print "created role gnukhata" cur.execute("grant all privileges on database template1 to gnukhata;") print "permission granted" conn.commit() cur.close() conn.close() print "job done " except: print "role already exists" #opening the gnukhata.xml file by parsing it into a tree. gnukhataconf = et.parse(confData['xmlpath']) #now since the file is opened we will get the root element. gnukhataroot = gnukhataconf.getroot() #we know that the file contains list of organisations. #so we will now extract the list of children (organisations ) into a variable named orgs. orgs = gnukhataroot.getchildren() return orgs def execproc(procname, engine, queryParams=[]): """ Purpose: executes a named stored procedure and returns the result. Function takes 3 parameters, procname is a string containing the name of the stored procedure. engine is the sqlalchemy engine instance through which the query will be executed. queryParams contains the input parameters in a list form (if any). The function returns a resultset with columns pertaining to the output parameters of the called stored procedure and number of rows equal to those returned by the return query. description. This function takes in the name of the stored procedure to be executed and constructs a query using the bound parameter syntax. The parameters are provided in a list which is attached to the main query. We have used the func object from sqlalchemy for executing a stored procedure through this process. """ function = getattr(func, procname) function_with_params = function(*queryParams) return engine.execute(select([literal_column('*')]).select_from(function_with_params).execution_options(autocommit=True)) def getConnection(queryParams): """ Purpose: This function connects to the corresponding database for the selected Organisation and financial year. The function takes in one parameter which is a list containing Organisation Name at 0th position and from date at second position and to year at third. The function will open the gnukhata.xml from /var/lib/gnukhata and query the same for the database for the given organisation. """ #the dbname variable will hold the final database name for the given organisation. dbname = "" orgs = getOrgList() #we will use org as an iterator and go through the list of all the orgs. for org in orgs: orgname = org.find("orgname") orgtype = org.find("org_Type") financialyear_from = org.find("financial_year_from") financialyear_to = org.find("financial_year_to") #print queryParams if orgname.text == queryParams[0] and financialyear_from.text == queryParams[1] and financialyear_to.text == queryParams[2] and orgtype.text==queryParams[3]: #print "we r in if" dbname = org.find("dbname") database = dbname.text #the engine has to be a global variable so that it is accessed throughout the module. global engines stmt = 'postgresql+psycopg2:///' + database + '?host=/var/run/postgresql' #now we will create an engine instance to connect to the given database. engine = create_engine(stmt, echo=False) today = datetime.datetime.now() newtime = str(today.year ) + str(today.month) + str(today.day) + str(today.hour) + str(today.minute) + str(today.second) + str(today.microsecond) #add the newly created engine instance to the list of engines. engines[newtime] = engine #returning the connection number for this engine. return newtime ''' Purpose: To add logs of user activities. Description: The the parameter list should contain: 1. activity-code 2. description The activity-codes are in the following order. Any new activity should be apended in the activity enumeration in the log class. 1. Login 2. Create Account 3. Edit Account 4. Create Voucher 5. Edit Voucher 6. Delete Voucher 7. Create Project ''' #the function only accepts the activity. it gets the current user by itself. def setLog(queryParams, client_id): user = getUserByClientId(client_id) queryParams.insert(0,user) result = execproc("setLog", engines[client_id],queryParams) print result return True """ Purpose: To add user into the userlist[]. It also sets the long along with it. """ def addUser(client_id, username,user_role): print("adding user to list " + str(client_id) + "|" + username) userlist[client_id] = username user_roles[client_id]=user_role setLog([1, ''], client_id) def delUser(client_id): del userlist[client_id] def getUserByClientId(client_id): print(client_id) if(not(userlist.has_key(client_id))): print("has_key false!") addUser(client_id, 'admin',1) print("forced admin") print("getting user by client" + userlist[client_id]) return userlist[client_id] Base = declarative_base() class Users(Base): __tablename__ = 'users' userid = Column(Integer, primary_key=True) username = Column(Text) userpassword = Column(Text) userrole = Column(Integer) userquestion = Column(Text) useranswer = Column(Text) def __init__(self, username, userpassword, userrole,userquestion,useranswer): self.userid = None self.username = username self.userpassword = userpassword self.userrole = userrole self.userquestion = userquestion self.useranswer = useranswer users_table = Users.__table__ class Organisation(Base): __tablename__ = 'organisation' orgcode = Column(Integer, primary_key=True) orgtype = Column(Text, nullable=False) orgname = Column(Text, nullable=False) orgaddr = Column(Text) orgcity = Column(Text) orgpincode = Column(String(30)) orgstate = Column(Text) orgcountry = Column(Text) orgtelno = Column(Text) orgfax = Column(Text) orgwebsite = Column(Text) orgemail = Column(Text) orgpan = Column(Text) orgmvat = Column(Text) orgstax = Column(Text) orgregno = Column(Text) orgregdate = Column(Text) orgfcrano = Column(Text) orgfcradate = Column(Text) roflag = Column(Integer) booksclosedflag = Column(Integer) def __init__(self, orgtype, orgname, orgaddr, orgcity, orgpincode, orgstate, orgcountry, orgtelno, orgfax, orgwebsite, orgemail, orgpan, orgmvat, orgstax, orgregno, orgregdate, orgfcrano, orgfcradate, roflag,booksclosedflag): self.orgtype = orgtype self.orgname = orgname self.orgaddr = orgaddr self.orgcity = orgcity self.orgpincode = orgpincode self.orgstate = orgstate self.orgcountry = orgcountry self.orgtelno = orgtelno self.orgfax = orgfax self.orgwebsite = orgwebsite self.orgemail = orgemail self.orgpan = orgpan self.orgmvat = orgmvat self.orgstax = orgstax self.orgregno = orgregno self.orgregdate = orgregdate self.orgfcrano = orgfcrano self.orgfcradate = orgfcradate self.roflag = roflag self.booksclosedflag = booksclosedflag organisation_table = Organisation.__table__ class branches(Base): __tablename__ = 'branches' branchcode = Column(String(6), primary_key = True ) branchname = Column(Text, nullable = False) subbranchof = Column(String(6), ForeignKey("branches.branchcode"), nullable = True) def __init__(self, branchcode, branchname, subbranchof): self.branchcode = branchcode self.branchname = branchname self.subbranchof = subbranchof branches_table = branches.__tablename__ class Projects(Base): __tablename__ = 'projects' projectcode = Column(Integer, primary_key=True) projectname = Column(Text) sanctionedamount = Column(Numeric(13,2)) def __init__(self, projectcode, projectname,sanctionedamount): self.projectcode = projectcode self.projectname = projectname self.sanctionedamount = sanctionedamount projects_table = Projects.__table__ class Flags(Base): __tablename__ = 'flags' flagno = Column(Integer, primary_key=True) flagname = Column(Text) def __init__(self, flagno, flagname): self.flagno = flagno self.flagname = flagname flags_table = Flags.__table__ class PeopleMaster(Base): __tablename__ = 'peoplemaster' peoplemastercode = Column(Integer, primary_key=True) peoplemastername = Column(Text, nullable=False) peoplemastertype = Column(Text, nullable=False) def __init__(self, peoplemastername, peoplemastertype): self.peoplemastername = peoplemastername self.peoplemastertype = peoplemastertype peoplemaster_table = PeopleMaster.__table__ class PeopleDetails(Base): __tablename__ = 'peopledetails' peopletype = Column(String(20)) peoplecode = Column(Text, primary_key=True) peoplename = Column(Text, nullable=False) peopleaddr = Column(Text) peoplecountry = Column(Text) peoplestate = Column(Text) peoplecity = Column(Text) peoplepincode = Column(String(30)) peopletelno = Column(Text) peoplefax = Column(Text) peopleemail = Column(Text) peoplewebsite = Column(Text) peoplecrperiod = Column(Text) peoplebalancelimit = Column(Text) contactperson = Column(Text) def __init__(self, peopletype, peoplecode, peoplename, peopleaddr, peoplecountry, peoplestate, peoplecity, peoplepincode, peopletelno, peoplefax, peopleemail, peoplewebsite, peoplecrperiod, peopelbalancelimit, contactperson): self.peoplecode = peoplecode self.peoplename = peoplename self.peopletype = peopletype self.peopleaddr = peopleaddr self.peoplecity = peoplecity self.peoplepincode = peoplepincode self.peoplestate = peoplestate self.peoplecountry = peoplecountry self.peopletelno = peopletelno self.peoplefax = peoplefax self.peoplecrperiod = peoplecrperiod self.peopelbalancelimit = peopelbalancelimit self.peoplewebsite = peoplewebsite self.peopleemail = peopleemail self.contactperson = contactperson peopledetails_table = PeopleDetails.__table__ class Vendor(Base): __tablename__ = 'vendor' vendorcode = Column(Integer, primary_key=True) vendorname = Column(Text, nullable=False) vendoraddr = Column(Text) vendorcity = Column(Text) vendorpincode = Column(String(30)) vendorstate = Column(Text) vendorcountry = Column(Text) vendortelno = Column(Text) vendorfax = Column(Text) vendortaxno = Column(Text) vendorcrperiod = Column(Integer, nullable=False) vendorwebsite = Column(Text) vendoremail = Column(Text) contactperson = Column(Text) def __init__(self, vendorname, vendoraddr, vendorcity, vendorpincode, vendorstate, vendorcountry, vendortelno, vendorfax, vendortaxno, vendorcrperiod, vendorwebsite, vendoremail, contactperson): self.vendorname = vendorname self.vendoraddr = vendoraddr self.vendorcity = vendorcity self.vendorpincode = vendorpincode self.vendorstate = vendorstate self.vendorcountry = vendorcountry self.vendortelno = vendortelno self.vendorfax = vendorfax self.vendortaxno = vendortaxno self.vendorcrperiod = vendorcrperiod self.vendorwebsite = vendorwebsite self.vendoremail = vendoremail self.contactperson = contactperson vendor_table = Vendor.__table__ class CategoryMaster(Base): __tablename__ = "categorymaster" categorycode = Column(Integer, primary_key=True) categoryname = Column(Text, nullable=False) nooffields = Column(Integer, nullable=False) def __init__(self, categoryname, nooffields): self.categoryname = categoryname self.nooffields = nooffields categorymaster_table = CategoryMaster.__table__ class CategoryDetails(Base): __tablename__ = "categorydetails" ctdtcode = Column(Integer, primary_key=True) categorycode = Column(Integer, ForeignKey("categorymaster.categorycode")) fieldname = Column(Text, nullable=False) fieldtype = Column(Text, nullable=False) def __init__(self, categorycode, fieldname, fieldtype): self.categorycode = categorycode self.fieldname = fieldname self.fieldtype = fieldtype categorydetails_table = CategoryDetails.__table__ class Supplier(Base): __tablename__ = 'supplier' supplierid = Column(Integer, primary_key=True) suppliername = Column(Text, nullable=False) supplieraddr = Column(Text) suppliertelno = Column(Text) supplierfax = Column(Text) suppliertaxno = Column(Text) suppliercrperiod = Column(Integer, nullable=False) supplierwebsite = Column(Text) supplieremail = Column(Text) def __init__(self, suppliername, supplieraddr, suppliertelno, supplierfax, suppliertaxno, suppliercrperiod, supplierwebsite, supplieremail): self.supplierid = None self.suppliername = suppliername self.supplieraddr = supplieraddr self.suppliertelno = suppliertelno self.supplierfax = supplierfax self.suppliertaxno = suppliertaxno self.suppliercrperiod = suppliercrperiod self.supplierwebsite = supplierwebsite self.supplieremail = supplieremail supplier_table = Supplier.__table__ class Customer(Base): __tablename__ = "customer" customerid = Column(Integer, primary_key=True) customername = Column(Text, nullable=False) customeraddr = Column(Text) customertelno = Column(Text) customeremail = Column(Text) def __init__(self, customername, customeraddr, customertelno, customeremail): self.customerid = None self.customername = customername self.customeraddr = customeraddr self.customertelno = customertelno self.customeremail = customeremail customer_table = Customer.__table__ class ProductMaster(Base): __tablename__ = "productmaster" prodcode = Column(Text, nullable=False, primary_key=True) categorycode = Column(Integer, ForeignKey("categorymaster.categorycode"), nullable=False) def __init__(self, prodcode, categorycode): self.prodcode = prodcode self.categorycode = categorycode productmaster_table = ProductMaster.__table__ class GenericProduct(Base): __tablename__ = "genericproduct" genprodcode = Column(String(40), nullable=False, primary_key=True) prodname = Column(Text, nullable=False) vendorname = Column(Text) proddesc = Column(Text) saleprice = Column(Numeric(13, 2), nullable=False) openqty = Column(Integer, nullable=False) curqty = Column(Integer, nullable=False) uom = Column(Text) def __init__(self, genprodcode, prodname, vendorname, proddesc, saleprice, openqty, uom): self.genprodcode = genprodcode self.prodname = prodname self.vendorname = vendorname self.proddesc = proddesc self.saleprice = saleprice self.openqty = openqty self.curqty = openqty self.uom = uom genericproduct_table = GenericProduct.__table__ class PurchaseMaster(Base): __tablename__ = "purchasemaster" pbillid = Column(Integer, primary_key=True) pbillno = Column(Text, nullable=False) pbilldate = Column(TIMESTAMP, nullable=False) reffdate = Column(TIMESTAMP) suppliername = Column(Text) pckfwd = Column(Numeric(6, 2)) tax = Column(Numeric(8, 2)) def __init__(self, pbillid, pbillno, pbilldate, reffdate, suppliername, pckfwd, tax): self.pbillid = pbillid self.pbillno = pbillno self.pbilldate = pbilldate self.reffdate = reffdate self.suppliername = suppliername self.pckfwd = pckfwd self.tax = tax purchasemaster_table = PurchaseMaster.__table__ class PurchaseDetails(Base): __tablename__ = "purchasedetails" purchasedtid = Column(Integer, primary_key=True) pbillid = Column(Integer, ForeignKey("purchasemaster.pbillid"), nullable=False) prodcode = Column(Text, ForeignKey("productmaster.prodcode"), nullable=False) quantity = Column(Integer, nullable=False) def __init__(self, purchasedtid, pbillid, prodcode, quantity): self.purchasedtid = purchasedtid self.pbillid = pbillid self.prodcode = prodcode self.quantity = quantity purchasedetails_table = PurchaseDetails.__table__ class SalesMaster(Base): __tablename__ = "salesmaster" sbillid = Column(Integer, primary_key=True) sbillno = Column(Text, nullable=False) sbilldate = Column(TIMESTAMP, nullable=False) reffdate = Column(TIMESTAMP) customername = Column(Text) def __init__(self, sbillid, sbillno, sbilldate, reffdate, customername): self.sbillid = sbillid self.sbillno = sbillno self.sbilldate = sbilldate self.reffdate = reffdate self.customername = customername salesmaster_table = SalesMaster.__table__ class SalesDetails(Base): __tablename__ = "salesdetails" salesdtid = Column(Integer, primary_key=True) sbillid = Column(Integer, ForeignKey("salesmaster.sbillid"), nullable=False) prodcode = Column(Text, ForeignKey("productmaster.prodcode"), nullable=False) quantity = Column(Integer, nullable=False) def __init__(self, salesdtid, sbillid, prodcode, quantity): self.salesdtid = salesdtid self.sbillid = sbillid self.prodcode = prodcode self.quantity = quantity salesdetails_table = SalesDetails.__table__ class StockQty(Base): #stock qty is used to store stock details and status. #stock opening is done in the product table __tablename__ = "stockqty" stockcode = Column(Integer, primary_key=True) prodcode = Column(String(50), ForeignKey("genericproduct.genprodcode"), nullable=False) transactiondate = Column(TIMESTAMP, nullable=False) quantity = Column(Integer, nullable=False) billno = Column(Text) stockflag = Column(Integer, nullable=False) #stockflag 0 = stock down #stockflag 1 = stock up def __init__(self, prodcode, transactiondate, quantity, billno, stockflag): self.stockcode = None self.prodcode = prodcode self.transactiondate = transactiondate self.quantity = quantity self.billno = billno self.stockflag = stockflag stockqty_table = StockQty.__table__ class Groups(Base): __tablename__ = "groups" groupcode = Column(Integer, primary_key=True) groupname = Column(Text, nullable=False) groupdesc = Column(Text) def __init__(self, groupname, groupdesc): self.groupname = groupname self.groupdesc = groupdesc groups_table = Groups.__table__ class subGroups(Base): __tablename__ = "subgroups" subgroupcode = Column(Integer, primary_key=True) groupcode = Column(Integer, ForeignKey("groups.groupcode"), nullable=False) subgroupname = Column(Text) def __init__(self, groupcode, subgroupname): self.groupcode = groupcode self.subgroupname = subgroupname subgroups_table = subGroups.__table__ class Account(Base): __tablename__ = "account" accountcode = Column(Integer, primary_key=True) groupcode = Column(Integer, ForeignKey("groups.groupcode"), nullable=True) subgroupcode = Column(Integer, ForeignKey("subgroups.subgroupcode"), nullable=True) #branchcode = Column(String(6), ForeignKey("branches.branchcode"), nullable = True) accountname = Column(Text, nullable=False) openingbalance = Column(Numeric(13, 2)) openingdate = Column(TIMESTAMP) balance = Column(Numeric(13, 2)) def __init__(self, accountcode, groupcode, subgroupcode, accountname, openingbalance, openingdate, balance): self.accountcode = accountcode self.groupcode = groupcode self.subgroupcode = subgroupcode self.accountname = accountname self.openingbalance = openingbalance self.openingdate = openingdate self.balance = balance account_table = Account.__table__ class branchaccount(Base): __tablename__ = "branchaccount" bacode = Column(Integer, primary_key=True) branchcode = Column(String(6), ForeignKey("branches.branchcode"), nullable = False) accountcode = Column(Integer, ForeignKey("account.accountcode"), nullable = False) sanctionedamt = Column(Numeric(13,2)) def __init__(self, bacode, branchcode, accountcode, sanctionedamt): self.bacode = bacode self.branchcode = branchcode self.accountcode = accountcode self.sanctionedamt = sanctionedamt branchaccount_table = branchaccount.__table__ class CreditnoteMaster(Base): __tablename__ = "creditnotemaster" vouchercode = Column(String(40), primary_key=True) pbillno = Column(String(40)) voucherdate = Column(TIMESTAMP, nullable=False) reffdate = Column(TIMESTAMP) booktype = Column(Text) chequeno = Column(Text) bankname = Column(Text) creditnarration = Column(Text, nullable=False) def __init__(self, vouchercode, pbillno, voucherdate, reffdate, booktype, chequeno, bankname, creditnarration): self.vouchercode = vouchercode self.pbillno = pbillno self.voucherdate = voucherdate self.reffdate = reffdate self.booktype = booktype self.chequeno = chequeno self.bankname = bankname self.creditnarration = creditnarration creditnotemaster_table = CreditnoteMaster.__table__ class CreditnoteDetails(Base): __tablename__ = "creditnotedetails" cndtcode = Column(Integer, primary_key=True) vouchercode = Column(String(40), ForeignKey("creditnotemaster.vouchercode")) craccountcode = Column(Integer, ForeignKey("account.accountcode"), nullable=False) draccountcode = Column(Integer, ForeignKey("account.accountcode"), nullable=False) amount = Column(Numeric(13, 2), nullable=False) def __init__(self, vouchercode, craccountcode, draccountcode, amount): self.vouchercode = vouchercode self.craccountcode = craccountcode self.draccountcode = draccountcode self.amount = amount creditnotedetails_table = CreditnoteDetails.__table__ class DebitnoteMaster(Base): __tablename__ = "debitnotemaster" vouchercode = Column(String(40), primary_key=True) sbillno = Column(String(40)) voucherdate = Column(TIMESTAMP, nullable=False) reffdate = Column(TIMESTAMP) booktype = Column(Text) chequeno = Column(Text) bankname = Column(Text) debitnarration = Column(Text, nullable=False) def __init__(self, vouchercode, sbillno, voucherdate, reffdate, booktype, chequeno, bankname, debitnarration): self.vouchercode = vouchercode self.sbillno = sbillno self.voucherdate = voucherdate self.reffdate = reffdate self.booktype = booktype self.chequeno = chequeno self.bankname = bankname self.debitnarration = debitnarration debitnotemaster_table = DebitnoteMaster.__table__ class DebitnoteDetails(Base): __tablename__ = "debitnotedetails" dndtcode = Column(Integer, primary_key=True) vouchercode = Column(String(40), ForeignKey("debitnotemaster.vouchercode")) craccountcode = Column(Integer, ForeignKey("account.accountcode"), nullable=False) draccountcode = Column(Integer, ForeignKey("account.accountcode"), nullable=False) amount = Column(Numeric(13, 2), nullable=False) def __init__(self, vouchercode, craccountcode, draccountcode, amount): self.vouchercode = vouchercode self.craccountcode = craccountcode self.draccountcode = draccountcode self.amount = amount debitnotedetails_table = DebitnoteDetails.__table__ class VoucherMaster(Base): __tablename__ = "voucher_master" vouchercode = Column(Integer, primary_key=True) reference = Column(String(40), nullable=False) voucherdate = Column(TIMESTAMP, nullable=False) reffdate = Column(TIMESTAMP) vouchertype = Column(String(40)) flag = Column(Integer) projectcode = Column(Integer) #branchcode = Column(String(6), ForeignKey("branches.branchcode")) narration = Column(Text, nullable=False) pono = Column(Text) podate = Column(TIMESTAMP) poamt = Column(Numeric(13,2)) lockflag = Column(Integer) def __init__(self, vouchercode, reference, voucherdate, reffdate, vouchertype, flag, projectcode, narration,pono ,podate , poamt): self.vouchercode = vouchercode self.reference = reference self.voucherdate = voucherdate self.reffdate = reffdate self.vouchertype = vouchertype self.flag = flag self.projectcode = projectcode self.narration = narration self.pono = pono self.podate = podate self.poamt = poamt self.lockFlag = 0 vouchermaster_table = VoucherMaster.__table__ class VoucherDetails(Base): __tablename__ = "voucher_details" cbdtcode = Column(Integer, primary_key=True) vouchercode = Column(Integer, ForeignKey("voucher_master.vouchercode")) typeflag = Column(String(10), nullable=False) accountcode = Column(Integer, ForeignKey("account.accountcode"), nullable=False) amount = Column(Numeric(13, 2), nullable=False) def __init__(self, vouchercode, typeflag, accountcode, amount): self.vouchercode = vouchercode self.typeflag = typeflag self.accountcode = accountcode self.amount = amount voucherdetails_table = VoucherDetails.__table__ class Tax(Base): __tablename__ = "tax" taxid = Column(Integer, primary_key=True) taxname = Column(Text, nullable=False) taxpercent = Column(Numeric(13, 2), nullable=False) narration = Column(Text) def __init__(self, taxname, taxpercent, narration): self.taxname = taxname self.taxpercent = taxpercent self.narration = narration tax_table = Tax.__table__ class CustomizableMaster(Base): __tablename__ = "customize_master" customcode = Column(Integer, primary_key=True) customname = Column(Text, nullable=False) def __init__(self, customname): self.customname = customname customize_master_table = CustomizableMaster.__table__ class CustomizableDetails(Base): __tablename__ = "customize_details" custdtcode = Column(Integer, primary_key=True) customcode = Column(Integer, ForeignKey("customize_master.customcode")) typeflag = Column(String(10), nullable=False) accountcode = Column(Integer, ForeignKey("account.accountcode"), nullable=False) def __init__(self, customcode, typeflag, accountcode): self.customcode = customcode self.typeflag = typeflag self.accountcode = accountcode customize_details_table = CustomizableDetails.__table__ # #class activity(Enum): # __name__="activity" # # def __init__(self,act): # ''' 1. Login 2. Create Account 3. Edit Account 4. Create Voucher 5. Edit Voucher 6. Delete Voucher 7. Create Project ''' class log(Base): __tablename__ = "log" logid = Column(Integer, primary_key=True) username=Column(String,nullable=False) activity = Column(Enum('Login', 'Create_Account','Edit_Account','Create_Voucher', 'Edit_Voucher','Delete_Voucher','Create_Project',name='activity'), nullable=False) #activity = Column(Numeric(1), nullable=False) description = Column(Text, nullable=False) # ipaddress=Column(Text,nullable=False) logdatetime = Column(TIMESTAMP) def __init__(self, username, activity, description):#,ipaddress): self.logid = None self.username = username self.activity = activity self.description = description # self.ipaddress = None self.logdatetime = str(strftime("%Y-%m-%d %H:%M:%S")) log_table = log.__table__ class BankRecon(Base): __tablename__ = "bankrecon" reconcode = Column(Integer,primary_key = True) vouchercode = Column(Integer,ForeignKey("voucher_master.vouchercode")) reffdate = Column(TIMESTAMP) accountname = Column(String(40)) dramount = Column(Numeric(13,2)) cramount = Column(Numeric(13,2)) clearancedate = Column(TIMESTAMP) memo = Column(Text) def __init__(self,reconcode,vouchercode,reffdate,accountname,dramount,cramount,clearancedate,memo): self.reconcode = reconcode self.vouchercode = vouchercode self.reffdate = reffdate self.accountname = accountname self.dramount = dramount self.cramount = cramount self.clearancedate = clearancedate self.memo = memo bankrecon_table = BankRecon.__table__ orm.compile_mappers() core_engine-2.6.1-dac679a8ec1cd01924e7b2e80280c270f69b55ac/gnukhataserver/rpc_account.py000077500000000000000000000451471265207572300274430ustar00rootroot00000000000000''' This file is part of GNUKhata:A modular,robust and Free Accounting System. GNUKhata 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. GNUKhata 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 GNUKhata (COPYING); if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA59 Temple Place, Suite 330, Contributor: "Anusha Kadambala" "Sonal Chaudhari" "Shruti Surve" "Priyanka Tawde" Krishnakant Mane Ankita Shanbhag Ashwini Shinde Ruchika Pai Nutan Nivate ''' #from sqlalchemy.engine.base import ResultProxy #from beaker.ext.google import db '''import the database connector and functions for stored procedure.''' '''import the twisted modules for executing rpc calls and also to implement the server''' from twisted.web import xmlrpc, server '''reactor from the twisted library starts the server with a published object and listens on a given port.''' from twisted.internet import reactor from time import strftime import pydoc import datetime, time from time import strftime from sqlalchemy.orm.exc import NoResultFound from sqlalchemy import func from decimal import * from sqlalchemy import or_ import rpc_groups import dbconnect # -------------------------------------------- account generator class account(xmlrpc.XMLRPC): """class name is aacount which having different store procedures""" def T(self): xmlrpc.XMLRPC.__init__(self) '''note that all the functions to be accessed by the client must have the xmlrpc_ prefix.''' '''the client however will not use the prefix to call the functions. ''' def xmlrpc_setAccount(self, queryParams, client_id): """ Purpose: Adds an account in the account table, under a selected group and optionally a subgroup. Account code is either auto generated or entered by the user Depending on the preference choosen by the user. description: This function inserts a row in the account table. Function takes one parameter named queryParams which is a list containing, * groupname as string at position 0 * subgroupflag as string at position 1 * subgroupname (optionally) at position 2 * account name: string at position 3 * accountcodetype: string at position 4 * openingbalance: integer at position 5 * currentBalance: integer at position 6 * suggestedcode: string at position 7 Function makes a call to the stored procedure setAccount, which does the actual insertion of the row and also inserts a row in the subgroups table if user has entered a new subgroup name that does not exist. Refer class rpc_main -> rpc_deploy for the exact specification of setAccount. Returns true if successful and false otherwise. """ print queryParams sp_params = [queryParams[0], queryParams[3]] if queryParams[2] == "": if queryParams[1] == "No Sub-Group": print "we are not taking subgroup " sp_params.append("null") else: sp_params.append(queryParams[1]) if queryParams[1] == "Create New Sub-Group" : print "there is a new subgroup created" sp_params.append(queryParams[2]) print queryParams[1] if queryParams[0] == "Direct Income" or queryParams[0] == "Direct Expense" or queryParams[0] == "Indirect Income" or queryParams[0] == "Indirect Expense": sp_params.append(0) else: sp_params.append(queryParams[5]) account_creation_date = str(strftime("%Y-%m-%d %H:%M:%S")) sp_params.append(account_creation_date) sp_params.append(sp_params[3]) if queryParams[7] == "": sp_params.append(-1) else: sp_params.append(queryParams[7]) #execute here print "here is what we send to the execproc as a param list " print sp_params dbconnect.execproc("setAccount", dbconnect.engines[client_id], sp_params) return True def xmlrpc_editAccount(self, queryParams, client_id): """ purpose: modifies an account based on account code. alters account name and opening balance. function takes one parameter queryParams, which is a list containing accountname,accountcode, groupname and new opening balance. returns the newly updated current balance. description: this function will edit an account and change either account name, oepning balance or both. the account is fetched internally by the software on the basis of account code, even if it was searched by client using account name. If the function is successful,it will return the newly updated current balance. If the groupname sent in the queryParams is direct or indirect income, or direct or indirect expence, then the oepning balance is sent as 0. this function uses the editAccount stored procedure. Refer rpc_main -> rpc_deploy for the complete spec of the stored said stored procedure. """ spQueryParams = [queryParams[0], queryParams[1]] if queryParams[2] == "Direct Income" or queryParams[2] == "Indirect Income" or queryParams[2] == "Direct Expense" or queryParams[2] == "Indirect Expense": print "sending openingbalance as 0" spQueryParams.append(0) else: spQueryParams.append(queryParams[3]) print spQueryParams result = dbconnect.execproc("editAccount", dbconnect.engines[client_id], spQueryParams) row = result.fetchone() return row(0) def xmlrpc_getSuggestedCode(self, queryParams, client_id): """ purpose: decides the code to be suggested on the basis of provided 3 characters at list queryParams[0] 2 from group and 1 from the account name returns a string containing the suggested code. description: function takes the 2 characters of selected group and first character of account. The 2 characters of the selected group are determined in the front end. The first character of the entered account is then appended to the former. For example, an account SBI in group Current Assets will send CAS as the 3 characters as queryParams[0] The function then executes a stored procedure getSuggestedCode and checks if an account exists with a code starting with the given 3 characters. if an account did exist then the given 3 characters will be postfixed with total count of existing similar account codes + 100. If no such account is fQound then 100 will be concatinated to the first 3 chars. for example if no account exists with an account code starting with CAS, then the suggested code will be CAS100. Next time an account with 3 chars as CAS is entered, then it will be CAS101. to see the entire spec of stored procedure getSuggestedCode, refer rpc_main -> rpc_deploy. """ result = dbconnect.execproc("getSuggestedCode", dbconnect.engines[client_id], [queryParams[0]]) row = result.fetchone() SuggestedAccountCode = row[0] if SuggestedAccountCode == 0: return str(queryParams[0] + "100") else: SuggestedAccount = SuggestedAccountCode + 100 return str(queryParams[0]) + str(SuggestedAccount) def xmlrpc_getAccountNames(self, queryParams, client_id): ''' Purpose : Function for extracting accountnames from account table based on groupcode Parameters : Queryparams is the single element list consisting of groupcode(datatype:integer) Returns : res1(datatype:list) when successful, False when failed Description : Querys the account tables and it retrives the account names on basis of groupcode which is a foreign key from the group table. When successful it returns the list of lists in which each list consists of single element i.e accountname(datatype:text) else it returns False. ''' connection = dbconnect.engines[client_id].connect() Session = dbconnect.session(bind=connection) res = Session.query(dbconnect.Account.accountname).filter(dbconnect.Account.groupcode == queryParams[0]).all() Session.close() connection.connection.close() if res == []: return False else: res1 = [] for l in res: res1.extend(list(l)) return res1 def xmlrpc_getCrOpeningBalance(self, client_id): """ Purpose: calculates the total credit opening balance for all accounts with Cr opening balance. Functions takes no arguement and returns a float value. Description: when adding an account we tend to know what is the total of all debit and credit opening balances. This function calculates the total for all accounts with Cr as opening balance. function executes the getTotalCrOpeningBalance for the expected result as float. refer rpc_main -> rpc_deploy for the complet spec of the said procedure. """ result = dbconnect.execproc("getTotalCrOpeningBalance", dbconnect.engines[client_id]) row = result.fetchone() print result.rowcount #print row[0] if row[0] == None: return 0.00 else: return row[0] def xmlrpc_getDrOpeningBalance(self, client_id): """ Purpose: calculates the total debit opening balance for all accounts with Dr opening balance. Functions takes no arguement and returns a float value. Description: when adding an account we tend to know what is the total of all debit and credit opening balances. This function calculates the total for all accounts with Dr as opening balance. function executes the getTotalDrOpeningBalance for the expected result as float. refer rpc_main -> rpc_deploy for the complet spec of the said procedure. """ result = dbconnect.execproc("getTotalDrOpeningBalance", dbconnect.engines[client_id]) row = result.fetchone() if row[0] == None: return 0.00 else: return row[0] def xmlrpc_getAllAccounts(self, client_id): """ purpose: returns the list of all accountnames in the database. description: returns the list of name of all accounts. if there are no accounts to return then returns False. The function calls the getAllAccounts stored procedure. refer the class rpc_main -> rpc_deploy method for complete spec. """ result = dbconnect.execproc("getAllAccounts", dbconnect.engines[client_id]) res = result.fetchall() accountnames = [] if res == []: return accountnames for r in res: accountnames.append(r[0]) return accountnames def xmlrpc_getAccount(self, queryParams, client_id): """ purpose: Searches and returns account details. Search is based on either accountcode or account name. function takes one parameter queryParams of type list containing, *searchFlag as integer (1 means search by account code and 2 means account name ) * searchValue as text (value depends on the searchFlag) description: This function queries the group_subgroup_account view and fetches the following. *groupname * subgroupname (if any ) * accountcode * accountname * openingbalance The function makes a call to stored procedure named getAccount. Refer to rpc_main -> rpc_deploy function for the complete spec of the stored procedure. """ result = dbconnect.execproc("getAccount", dbconnect.engines[client_id], queryParams) row = result.fetchone() hasTransactionResult = dbconnect.execproc("hasTransactions", dbconnect.engines[client_id], [str(row[3])]) hasTransactionRow = hasTransactionResult.fetchone() hasTransactionFlag = hasTransactionRow["success"] hasOpeningBalanceResult = dbconnect.execproc("hasOpeningBalance", dbconnect.engines[client_id], [str(row[3])]) hasOpeningBalanceRow = hasOpeningBalanceResult.fetchone() hasOpeningBalanceFlag = hasOpeningBalanceRow["success"] if row[1] == None: return list([row[2], row[0], 0.00, row[3], row[4],hasTransactionFlag, hasOpeningBalanceFlag]) else: return list([row[2], row[0], row[1], row[3], row[4],hasTransactionFlag, hasOpeningBalanceFlag ]) def xmlrpc_getAccountByGroup(self, queryParams, client_id): ''' Purpose :function for extracting all rows of view_account based on groupname Parameters : QueryParams, list containing groupname(datatype:text) Returns : List when successful, False when failed Description : Querys the view_account which is created based on the account and groups table.It retrieves all rows of view_account based on groupname. When successful it returns the list of lists in which each list contain each row that are retrived from view otherwise it returns False. ''' stmt = "select * from view_account where groupname='" + queryParams[0] + "'" res = dbconnect.engines[client_id].execute(stmt).fetchall() if res == []: return False else: res1 = [] for l in range(0, len(res)): res1.append([res[l][0], res[l][1], res[l][2], res[l][3]]) return res1 def xmlrpc_getAccountBySubGroup(self, queryParams, client_id): ''' Purpose :function for extracting all rows of view_account based on subgroupcode Parameters : QueryParams, list containing subgroupcode(datatype:text) Returns : List when successful, False when failed Description : Querys the view_account which is created based on the account and groups table.It retrieves all rows of view_account based on subgroupcode. When successful it returns the list of lists in which each list contain each row that are retrived from view otherwise it returns False. ''' stmt = "select * from view_account where subgroupcode='" + queryParams[0] + "'" res = dbconnect.engines[client_id].execute(stmt).fetchall() if res == []: return False else: res1 = [] for l in range(0, len(res)): res1.append([res[l][0], res[l][1], res[l][2], res[l][3]]) return res1 def xmlrpc_getAllAccountBank(self, client_id): ''' Purpose :function for extracting accountnames which are grouped under 'Bank A/C' Parameters : None Returns : List when successful, False when failed Description : Querys the view_account which is created based on the account and groups table.It retrieves all account names from view_account whose groupname is 'Bank A/C' When successful it returns the list of lists in which each list contain accountname retrived from view otherwise it returns False. ''' stmt = "select accountname from view_account where groupname='Bank A/C' order by accountname;" res = dbconnect.engines[client_id].execute(stmt).fetchall() if res == []: return False else: res1 = [] for l in range(0, len(res)): res1.append(res[l][0]) return res1 def xmlrpc_accountExists(self, queryParams, client_id): ''' Purpose : Function for finding if an account already exists with the supplied name. Parameters : queryParams which is a list containing one element, accountname as string. Returns : 1 if account name exists and 0 if not. Description : Querys the account table and sees if an account name similar to one provided as a parameter exists. We can ensure that no duplicate account is ever entered because if a similar account exists like the one in queryparams[0[ then we won't allow another entry with same name. ''' result = dbconnect.execproc("accountExists", dbconnect.engines[client_id], [queryParams[0]]) row = result.fetchone() return str(row[0]) def xmlrpc_getSubGroupByAccount(self,queryParams,client_id): ''' Purpose :function for extracting all rows of view_account based on groupname Parameters : QueryParams, list containing groupname(datatype:text) Returns : List when successful, False when failed Description : Querys the view_account which is created based on the account ,subgroups and groups table.It retrieves all rows of view_account based on groupname order by subgroupname. When successful it returns the list of lists in which each list contain each row that are retrived from view otherwise it returns False. ''' res = dbconnect.execproc("getSubGroupByAccount",dbconnect.engines[client_id],[queryParams[0]]) if res == []: return False else: result = [] for row in res: result.append([row["subgroupname"]]) return result def xmlrpc_getAccountCodeListByCode(self,queryParams,client_id): ''' Purpose : Function for extracting accountcode list from account table I/O Parameters : queryparam which contain value of accountcode field Returns : accountcode(datatype:list) when successful, False when failed Description : Querys the account tables and it retrives the accountcode depending upon the initial characters from rows in account table. When successful it returns the list consists of elements who matches that character i.e accountcode(datatype:string) else it returns False. ''' print str(queryParams) result = dbconnect.execproc("getAccountCodeListByCode", dbconnect.engines[client_id],[str(queryParams[0])]) res = result.fetchall() print res if res == []: return False accountcode = [] for r in res: accountcode.append(r[0]) return accountcode def xmlrpc_deleteAccount(self,queryParams,client_id): ''' Purpose : Function for deleting accounts. For this we have used hasOpeningBalance, hasTransactions & deleteAccount stored procedures. With the help of hasTransactions we are able to find out whether the given account has any transactions or not. The stored procedure tells that if there is any voucher entry of that account name return true or else return false The second stored procedure hasOpeningBalance returns true if opening balance for that account exists or else returns false The third stored procedure deleteAccount deletes that particular accountname ''' hasOpeningBalance = dbconnect.execproc("hasOpeningBalance", dbconnect.engines[client_id], [str(queryParams[0])]) hasOpeningBalanceRow = hasOpeningBalance.fetchone() print hasOpeningBalanceRow["success"] hasTransactions = dbconnect.execproc("hasTransactions", dbconnect.engines[client_id], [str(queryParams[0])]) hasTransactionsRow = hasTransactions.fetchone() print hasTransactionsRow["success"] if hasOpeningBalanceRow["success"] == False and hasTransactionsRow["success"] == False: try: dbconnect.execproc("deleteAccount", dbconnect.engines[client_id],[str(queryParams[0])]) return True except: return False else: return False def xmlrpc_getAccountReport(self,client_id): """ takes no arguement and returns a grid of rows containing accountname, groupname and subgroupname in the respective order """ result = dbconnect.execproc("getAccountReport",dbconnect.engines[client_id] ,[] ) accountReport = result.fetchall() reportGrid = [] srno =1 for ar in accountReport: row = [] row.append(srno) row.append(str(ar[0])) row.append(str(ar[1])) row.append(str(ar[2])) srno = srno +1 reportGrid.append(row) if(len(reportGrid) == 0 ): return [] else: return reportGrid core_engine-2.6.1-dac679a8ec1cd01924e7b2e80280c270f69b55ac/gnukhataserver/rpc_category.py000077500000000000000000000075471265207572300276260ustar00rootroot00000000000000''' This file is part of GNUKhata:A modular,robust and Free Accounting System. GNUKhata 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. GNUKhata 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 GNUKhata (COPYING); if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA59 Temple Place, Suite 330, Contributor: "Anusha Kadambala" "Sonal Chaudhari" ''' from twisted.web import xmlrpc, server from twisted.internet import reactor import dbconnect class category(xmlrpc.XMLRPC): def __init__(self): xmlrpc.XMLRPC.__init__(self) def xmlrpc_setCategoryMaster(self,queryParams_Master, queryParams_Details,client_id): connection = dbconnect.engines[client_id].connect() Session = dbconnect.session(bind=connection) Session.add_all([dbconnect.CategoryMaster(queryParams_Master[0],queryParams_Master[1])]) Session.commit() lstCategoryName = [queryParams_Master[0]] res = Session.query(dbconnect.CategoryMaster.categorycode).filter(dbconnect.CategoryMaster.categoryname == lstCategoryName[0]).first() for row in queryParams_Details: insertRow = [res.categorycode] + row category = Session.query(dbconnect.CategoryDetails).all() for i in category: if i.attrname == insertRow[1]: Session.add_all([dbconnect.CategoryDetails(insertRow[0],insertRow[1],insertRow[2],insertRow[3])]) Session.commit() return True dbconnect.engines[client_id].execute("alter table productmaster add column "+insertRow[1]+" text") Session.add_all([dbconnect.CategoryDetails(insertRow[0],insertRow[1],insertRow[2],insertRow[3])]) Session.commit() Session.close() return "insert ok" def xmlrpc_getCategorySpecs(self,queryParams,client_id): connection = dbconnect.engines[client_id].connect() Session = dbconnect.session(bind=connection) res = Session.query(dbconnect.CategoryDetails.attrname,dbconnect.CategoryDetails.attrtype,dbconnect.CategoryDetails.attrisnull).filter(dbconnect.CategoryDetails.categorycode == queryParams[0]).all() Session.close() if res == []: return False else: res1 = [] i = 0 for i in range(0,len(res)): res1.append([res[i].attrname, res[i].attrtype, res[i].attrisnull]) return res1 def xmlrpc_getCategories(self,client_id): connection = dbconnect.engines[client_id].connect() Session = dbconnect.session(bind=connection) res = Session.query(dbconnect.CategoryMaster).all() Session.close() if res == []: return False else: res1 = [] i = 0 for i in range(0,len(res)): res1.append([res[i].categorycode, res[i].categoryname, res[i].hint]) return res1 def xmlrpc_getCategory(self,queryParams,client_id): connection = dbconnect.engines[client_id].connect() Session = dbconnect.session(bind=connection) if queryParams[0] == 'code': res = Session.query(dbconnect.ProductMaster.categorycode).filter(dbconnect.ProductMaster.prodcode == queryParams[1]).order_by(dbconnect.ProductMaster.prodcode).first() else: res = Session.query(dbconnect.ProductMaster.categorycode).filter(dbconnect.ProductMaster.prodname == queryParams[1]).order_by(dbconnect.ProductMaster.prodcode).first() result = Session.query(dbconnect.CategoryMaster.categoryname).filter(dbconnect.CategoryMaster.categorycode == res.categorycode).first() Session.close() if result != None: return [res.categorycode, result.categoryname] else: return False core_engine-2.6.1-dac679a8ec1cd01924e7b2e80280c270f69b55ac/gnukhataserver/rpc_customizable.py000077500000000000000000000067701265207572300305070ustar00rootroot00000000000000''' This file is part of GNUKhata:A modular,robust and Free Accounting System. GNUKhata 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. GNUKhata 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 GNUKhata (COPYING); if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA59 Temple Place, Suite 330, ''' #import the database connector and functions for stored procedure. import dbconnect #import the twisted modules for executing rpc calls and also to implement the server from twisted.web import xmlrpc, server #reactor from the twisted library starts the server with a published object and listens on a given port. from twisted.internet import reactor import xmlrpclib #inherit the class from XMLRPC to make it publishable as an rpc service. class customizable(xmlrpc.XMLRPC): def __init__(self): xmlrpc.XMLRPC.__init__(self) #note that all the functions to be accessed by the client must have the xmlrpc_ prefix. #the client however will not use the prefix to call the functions. def xmlrpc_setCustomizable(self,queryParams_master,queryParams_details,client_id): connection = dbconnect.engines[client_id].connect() Session = dbconnect.session(bind=connection) #try: Session.add_all([dbconnect.CustomizableMaster(queryParams_master[0])]) for r in queryParams_details: #print r[1] self.account = Session.query(dbconnect.Account).filter(dbconnect.Account.accountname == r[1]).first() self.code = Session.query(dbconnect.CustomizableMaster).filter(dbconnect.CustomizableMaster.customname == queryParams_master[0]).first() #print self.code #print r[0] #print self.account.accountcode Session.add_all([dbconnect.CustomizableDetails(self.code.customcode,r[0],self.account.accountcode)]) Session.commit() Session.close() connection.connection.close() #except: # return False return True def xmlrpc_getCustVoucherNames(self,client_id): connection = dbconnect.engines[client_id].connect() Session = dbconnect.session(bind=connection) res = Session.query(dbconnect.CustomizableMaster.customname).all() #print res Session.close() connection.connection.close() if res == []: return False else: res1 = [] for r in res: res1.append([r[0]]) #print res1 return res1 def xmlrpc_getCustVoucherDetails(self,queryParams,client_id): connection = dbconnect.engines[client_id].connect() Session = dbconnect.session(bind=connection) res = Session.query(dbconnect.CustomizableMaster).filter(dbconnect.CustomizableMaster.customname == queryParams[0]).first() details = Session.query(dbconnect.CustomizableDetails).filter(dbconnect.CustomizableDetails.customcode == res.customcode).all() if res == []: return False else: cust_details = [] for dt in details: #print dt.accountcode self.account = Session.query(dbconnect.Account).filter(dbconnect.Account.accountcode == dt.accountcode).first(); cust_details.append([dt.typeflag,self.account.accountname]) #print cust_details Session.close() connection.connection.close() return cust_details core_engine-2.6.1-dac679a8ec1cd01924e7b2e80280c270f69b55ac/gnukhataserver/rpc_data.py000077500000000000000000000044401265207572300267070ustar00rootroot00000000000000''' This file is part of GNUKhata:A modular,robust and Free Accounting System. GNUKhata 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. GNUKhata 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 GNUKhata (COPYING); if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA59 Temple Place, Suite 330, Contributor: "Sonal Chaudhari" ''' import sqlite3 #import the database connector #import the twisted modules for executing rpc calls and also to implement the server from twisted.web import xmlrpc, server #reactor from the twisted library starts the server with a published object and listens on a given port. from twisted.internet import reactor import dbconnect #import sqlite #inherit the class from XMLRPC to make it publishable as an rpc service. class data(xmlrpc.XMLRPC): def __init__(self): xmlrpc.XMLRPC.__init__(self) placesdb = dbconnect.getConf() #note that all the functions to be accessed by the client must have the xmlrpc_ prefix. #the client however will not use the prefix to call the functions. def xmlrpc_getStateNames(self): confData = dbconnect.getConf() try: conn = sqlite3.connect(confData['placesdb_path']) cur = conn.cursor() result = cur.execute("select distinct state from state_city") rows =result.fetchall() states = [] for row in rows: states.append(list(row)) conn.close() return states except: return [] def xmlrpc_getCityNames(self,queryParams): try: confData = dbconnect.getConf() conn = sqlite3.connect(confData['placesdb_path']) cur = conn.cursor() result = cur.execute("select city from state_city where state = '%s'"%str(queryParams[0])) rows = result.fetchall() cities = [] for row in rows: cities.append(row[0]) return cities except: return [] core_engine-2.6.1-dac679a8ec1cd01924e7b2e80280c270f69b55ac/gnukhataserver/rpc_getaccountsbyrule.py000077500000000000000000000254071265207572300315460ustar00rootroot00000000000000""" This file is part of GNUKhata:A modular,robust and Free Accounting System. GNUKhata 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. GNUKhata 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 GNUKhata (COPYING); if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA59 Temple Place, Suite 330, Contributor: "Anusha Kadambala" "Priyanka A Tawde" "Shruti A Surve" "Akshay P Puradkar" "Ashwini Shinde" "Ankita Shanbhag" """ #import the database connector and functions for stored procedure. import dbconnect #import the twisted modules for executing rpc calls and also to implement the server from twisted.web import xmlrpc, server #reactor from the twisted library starts the server with a published object and listens on a given port. from twisted.internet import reactor from sqlalchemy import or_ from sqlalchemy import not_ from sqlalchemy import and_ from sqlalchemy.orm import join #inherit the class from XMLRPC to make it publishable as an rpc service. class getaccountsbyrule(xmlrpc.XMLRPC): def __init__(self): xmlrpc.XMLRPC.__init__(self) #note that all the functions to be accessed by the client must have the xmlrpc_ prefix. #the client however will not use the prefix to call the functions. '''Purpose :function for extracting contents from Account table i/p parameters :subGroupcode o/p parameters : accountname except bank and cash ''' def xmlrpc_getContraAccounts(self,client_id): """ Purpose: fetches the list of all accounts which are used in a contra voucher. Takes no arguments and returns list of accounts. If no accounts are found for contra then returns false. description: This function is called for populating the account's list with all the accounts for contra. Note that contra voucher only involves cash and bank accounts. This function calls the getContra stored procedure for fetching the said list of account names. refer to class rpc_main -> rpc_deploy for complete spec of the said stored procedure. """ result = dbconnect.execproc("getContra", dbconnect.engines[client_id],[]) if result == []: return False else: contraAccounts = [] for row in result: contraAccounts.append(row[0]) return contraAccounts def xmlrpc_getReceivableAccounts(self,queryParams,client_id): result = dbconnect.execproc("getReceivables", dbconnect.engines[client_id], queryParams) if result == []: return False else: recievableAccounts = [] for row in result: recievableAccounts.append(row[0]) return recievableAccounts def xmlrpc_getPaymentAccounts(self,queryParams,client_id): result = dbconnect.execproc("getPayments",dbconnect.engines[client_id], queryParams) if result == []: return False else: paymentAccounts = [] for row in result: paymentAccounts.append(row[0]) return paymentAccounts def xmlrpc_getJournalAccounts(self,client_id): """ Purpose: fetches the list of all accounts which are used in a journal voucher. Takes no arguments and returns list of accounts. If no accounts are found for journal then returns false. description: This function is called for populating the account's list with all the accounts for journal. Note that journal voucher involves all accounts, except cash and bank accounts. This function calls the getJournal stored procedure for fetching the said list of account names. refer to class rpc_main -> rpc_deploy for complete spec of the said stored procedure. """ result = dbconnect.execproc("getJournal", dbconnect.engines[client_id],[]) if result == []: return False else: journalAccounts = [] for row in result: journalAccounts.append(row[0]) return journalAccounts def xmlrpc_getCustomizableAccounts(self,queryParams,client_id): connection = dbconnect.engines[client_id].connect() Session = dbconnect.session(bind=connection) res = Session.query(dbconnect.CustomizableMaster).filter(dbconnect.CustomizableMaster.customname == queryParams[1]).first(); #print res details = Session.query(dbconnect.CustomizableDetails).filter(and_(dbconnect.CustomizableDetails.customcode == res.customcode,dbconnect.CustomizableDetails.typeflag == queryParams[0])).all(); #print details if res == []: return False else: accounts = [] for dt in details: #print dt.accountcode self.account = Session.query(dbconnect.Account).filter(dbconnect.Account.accountcode == dt.accountcode).first(); accounts.append([self.account.accountname]) #print accounts Session.close() connection.connection.close() return accounts def xmlrpc_getDebitNoteAccounts(self,queryParams,client_id): """ Purpose: gets the list of accounts for debit note either for credit or debit side. Function takes one parameter queryParams which is a list containing only one element, cr_dr_flag. Returns list of accounts else false if not found. description: returns a list of accounts pertaining to debit note. If the input parameter in queryParams[0] is Cr then only the credit side of accounts is returned else debit side of accounts is returned in form of list. The function makes a call to the getDebitNote stored procedure. For detailed spec of the said procedure refer to the class xmlrpc_main -> xmlrpc_deploy method. """ result = dbconnect.execproc("getDebitNote",dbconnect.engines[client_id], queryParams) if result == []: return False else: debitnoteAccounts = [] for row in result: debitnoteAccounts.append(row[0]) return debitnoteAccounts def xmlrpc_getCreditNoteAccounts(self,queryParams,client_id): """ Purpose: gets the list of accounts for credit note either for credit or debit side. Function takes one parameter queryParams which is a list containing only one element, cr_dr_flag. Returns list of accounts else false if not found. description: returns a list of accounts pertaining to credit note. If the input parameter in queryParams[0] is Cr then only the credit side of accounts is returned else debit side of accounts is returned in form of list. The function makes a call to the getCreditNote stored procedure. For detailed spec of the said procedure refer to the class xmlrpc_main -> xmlrpc_deploy method. """ result = dbconnect.execproc("getCreditNote",dbconnect.engines[client_id], queryParams) if result == []: return False else: creditnoteAccounts = [] for row in result: creditnoteAccounts.append(row[0]) return creditnoteAccounts def xmlrpc_getSalesAccounts(self,queryParams,client_id): """ Purpose: gets the list of accounts for sales accounts either for credit or debit side. Function takes one parameter queryParams which is a list containing only one element, cr_dr_flag. Returns list of accounts else false if not found. description: returns a list of accounts pertaining to sales accounts. If the input parameter in queryParams[0] is Cr then only the credit side of accounts is returned else debit side of accounts is returned in form of list. The function makes a call to the getSales stored procedure. For detailed spec of the said procedure refer to the class xmlrpc_main -> xmlrpc_deploy method. """ result = dbconnect.execproc("getSales",dbconnect.engines[client_id], queryParams) if result == []: return False else: salesAccounts = [] for row in result: salesAccounts.append(row[0]) return salesAccounts def xmlrpc_getPurchaseAccounts(self,queryParams,client_id): """ Purpose: gets the list of accounts for purchase accounts either for credit or debit side. Function takes one parameter queryParams which is a list containing only one element, cr_dr_flag. Returns list of accounts else false if not found. description: returns a list of accounts pertaining to purchase accounts. If the input parameter in queryParams[0] is Cr then only the credit side of accounts is returned else debit side of accounts is returned in form of list. The function makes a call to the getPurchases stored procedure. For detailed spec of the said procedure refer to the class xmlrpc_main -> xmlrpc_deploy method. """ result = dbconnect.execproc("getPurchases",dbconnect.engines[client_id], queryParams) if result == []: return False else: purchaseAccounts = [] for row in result: purchaseAccounts.append(row[0]) return purchaseAccounts def xmlrpc_getSalesReturnAccounts(self,queryParams,client_id): """ Purpose: gets the list of accounts for salesreturn either for credit or debit side. Function takes one parameter queryParams which is a list containing only one element, cr_dr_flag. Returns list of accounts else false if not found. description: returns a list of accounts pertaining to sales return accounts. If the input parameter in queryParams[0] is Cr then only the credit side of accounts is returned else debit side of accounts is returned in form of list. The function makes a call to the getSalesReturn stored procedure. For detailed spec of the said procedure refer to the class xmlrpc_main -> xmlrpc_deploy method. """ result = dbconnect.execproc("getSalesReturn",dbconnect.engines[client_id], queryParams) if result == []: return False else: salesreturnAccounts = [] for row in result: salesreturnAccounts.append(row[0]) return salesreturnAccounts def xmlrpc_getPurchaseReturnAccounts(self,queryParams,client_id): """ Purpose: gets the list of accounts for purchases return either for credit or debit side. Function takes one parameter queryParams which is a list containing only one element, cr_dr_flag. Returns list of accounts else false if not found. description: returns a list of accounts pertaining to purchases return. If the input parameter in queryParams[0] is Cr then only the credit side of accounts is returned else debit side of accounts is returned in form of list. The function makes a call to the getPurchasesReturn stored procedure. For detailed spec of the said procedure refer to the class xmlrpc_main -> xmlrpc_deploy method. """ result = dbconnect.execproc("getPurchasesReturn",dbconnect.engines[client_id], queryParams) if result == []: return False else: purchasereturnAccounts = [] for row in result: purchasereturnAccounts.append(row[0]) return purchasereturnAccounts core_engine-2.6.1-dac679a8ec1cd01924e7b2e80280c270f69b55ac/gnukhataserver/rpc_groups.py000077500000000000000000000146261265207572300273240ustar00rootroot00000000000000''' This file is part of GNUKhata:A modular,robust and Free Accounting System. GNUKhata 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. GNUKhata 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 GNUKhata (COPYING); if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA59 Temple Place, Suite 330, Contributor: "Anusha Kadambala" "Sonal Chaudhari" Ashwini Shinde ''' #import the database connector and functions for stored procedure. import dbconnect #import the twisted modules for executing rpc calls and also to implement the server from twisted.web import xmlrpc, server #reactor from the twisted library starts the server with a published object and listens on a given port. from twisted.internet import reactor from sqlalchemy.orm import join from decimal import * from sqlalchemy import or_ #inherit the class from XMLRPC to make it publishable as an rpc service. class groups(xmlrpc.XMLRPC): def __init__(self): xmlrpc.XMLRPC.__init__(self) #note that all the functions to be accessed by the client must have the xmlrpc_ prefix. #the client however will not use the prefix to call the functions. def xmlrpc_getGroupByCode(self,queryParams,client_id): """ purpose: gets record for group given its code. description: returns a row containing details for a group given its code. the record contains groupcode and groupname. The function calls the getGroupByCode stored procedure which actually returns the said record. Refer rpc_class rpc_main -> rpc_deploy function for specifications of the stored procedure. """ result = dbconnect.execproc("getGroupByCode", dbconnect.engines[client_id],[queryParams[0]]) row = result.fetchone() return row def xmlrpc_getAllGroups(self,client_id): ''' purpose:gets the list of all standard groups. description: returns list containing group name. ''' res = dbconnect.execproc("getAllGroups",dbconnect.engines[client_id]) if res == []: return False else: result = [] for row in res: result.append([row["groupcode"],row["groupname"],row["groupdesc"]]) return result def xmlrpc_getGroupByName(self,queryParams,client_id): connection = dbconnect.engines[client_id].connect() Session = dbconnect.session(bind=connection) res = Session.query(dbconnect.Groups).filter(dbconnect.Groups.groupname == queryParams[0]).order_by(dbconnect.Groups.groupcode).first() Session.close() connection.connection.close() if res != None: return [res.groupcode, res.groupname, res.groupdesc] else: return False def xmlrpc_getGroupCodeByName(self,queryParams,client_id): connection = dbconnect.engines[client_id].connect() Session = dbconnect.session(bind=connection) res = Session.query(dbconnect.Groups.groupcode).filter(dbconnect.Groups.groupname == queryParams[0]).first() Session.close() connection.connection.close() if res != None: return res else: return False ''' purpose :function for extracting groupname from group table by account name i/p parameters : accountname o/p parameters : groupcode ''' def xmlrpc_getGroupNameByAccountName(self,queryParams,client_id): connection = dbconnect.engines[client_id].connect() Session = dbconnect.session(bind=connection) res = Session.query(dbconnect.Groups).select_from(join(dbconnect.Groups,dbconnect.Account)).filter(dbconnect.Account.accountname == queryParams[0]).first() Session.close() connection.connection.close() if res != None: return [res.groupname] else: return False def xmlrpc_getSubGroupByName(self,queryParams,client_id): ''' Purpose :function for extracting data from subgroup table by namewise i/p parameters : subgroupname o/p parameters :subgroupcode ''' connection = dbconnect.engines[client_id].connect() Session = dbconnect.session(bind=connection) res = Session.query(dbconnect.subGroups).filter(dbconnect.subGroups.subgroupname == queryParams[0]).order_by(dbconnect.subGroups.groupcode).first() Session.close() connection.connection.close() if res != None: return res.subgroupcode else: return False def xmlrpc_subgroupExists(self,queryParams,client_id): """ purpose: Checks if the new subgroup typed by the user already exists. This will validate and prevent any duplication. Description: The function takes queryParams as its parameter and contains one element, the subgroupname as string. Returns True if the subgroup exists and False otherwise """ result = dbconnect.execproc("subgroupExists", dbconnect.engines[client_id],[queryParams[0]] ) row = result.fetchone() return str(row[0]) def xmlrpc_getSubGroupsByGroup(self,queryParams,client_id): ''' Purpose :function for extracting all rows of view_account based on groupname Parameters : QueryParams, list containing groupname(datatype:text) Returns : List when successful, False when failed Description : Querys the view_account which is created based on the account ,subgroups and groups table.It retrieves all rows of view_account based on groupname order by subgroupname. When successful it returns the list of lists in which each list contain each row that are retrived from view otherwise it returns False. ''' res = dbconnect.execproc("getSubGroupsByGroup",dbconnect.engines[client_id],[queryParams[0]]) if res == []: return False else: result = [] for row in res: result.append([row["subgroupname"]]) return result def xmlrpc_setSubGroup(self,queryParams,client_id): ''' Purpose :function for adding new subgroups in table subgroups Parameters : groupname(datatype:text), subgroupname(datatype:text) Returns : returns 1 when successful, 0 when failed Description : Adds new subgroup to the database. When successful it returns 1 otherwise it returns 0. ''' res = dbconnect.execproc("setSubGroup",dbconnect.engines[client_id],[queryParams[0],queryParams[1]]) row = res.fetchone() return str(row[0]) core_engine-2.6.1-dac679a8ec1cd01924e7b2e80280c270f69b55ac/gnukhataserver/rpc_inventory.py000066400000000000000000000125211265207572300300270ustar00rootroot00000000000000#from sqlalchemy.engine.base import ResultProxy '''import the database connector and functions for stored procedure.''' '''import the twisted modules for executing rpc calls and also to implement the server''' from twisted.web import xmlrpc, server '''reactor from the twisted library starts the server with a published object and listens on a given port.''' from twisted.internet import reactor from time import strftime import pydoc import datetime, time from time import strftime from sqlalchemy.orm.exc import NoResultFound from sqlalchemy import func from decimal import * from sqlalchemy import or_ import rpc_groups import dbconnect # -------------------------------------------- account generator class inventory(xmlrpc.XMLRPC): """class name is aacount which having different store procedures""" def __init__(self): xmlrpc.XMLRPC.__init__(self) '''note that all the functions to be accessed by the client must have the xmlrpc_ prefix.''' '''the client however will not use the prefix to call the functions. ''' def xmlrpc_setGenericProduct(self,queryParams, client_id): ''' Purpose: Adds a product in the genericproduct table, Product code is entered by the user which is primary key itself Description: This function inserts a row in the genericproduct table. Function takes one parameter named queryParams which is a list containing, * productcode as string at position 0 * productname as text at position 1 * vendorname as text at position 2 * product description as text at position 3 * sale_price as numeric at position 4 * open_qty as integer at position 5 * unit of measurement as integer at position 6 Function makes a call to the stored procedure setGenericProduct, which does the actual insertion of the row. Refer class rpc_main -> rpc_deploy for the exact specification of setGenericProduct. Returns true if successful and false otherwise. ''' dbconnect.execproc("setGenericProduct", dbconnect.engines[client_id],queryParams) return True def xmlrpc_searchProductDetails(self,queryParams,client_id): ''' purpose: Searches and returns product details. Search is based on either productcode or product name. function takes one parameter queryParams of type list containing, *searchFlag as integer (1 means search by product code and 2 means product name ) * searchValue as text (value depends on the searchFlag) description: This function queries the genericproduct table and fetches the following * product_name * vendor_name * prod_desc * sale_price * open_qty * cur_qty * u_o_m The function makes a call to stored procedure named searchProductDetails. Refer to rpc_main -> rpc_deploy function for the complet spec of the stored procedure. ''' searchedDetails = dbconnect.execproc("searchProductDetails", dbconnect.engines[client_id], queryParams) products = searchedDetails.fetchall() productView = [] for productRow in products: productView.append([productRow["product_name"],productRow["vendor_name"],productRow["prod_desc"],float(productRow["sale_price"]),productRow["open_qty"],productRow["cur_qty"],productRow["u_o_m"]]) return list(productView) def xmlrpc_setStockQty(self, queryParams, client_id): ''' Purpose: Function to insert data into stock quantity table which keeps track of quantity of all products. I/O Parameters: queryParams which contain product key, transactiondate (yyyy-mm-dd format), quantity, bill number and stockflag Returns: True on successfull insertion of data into table Description : While setting stock to UP, we set stockflag to 1 and for stock down stockflag is 0 ''' dbconnect.execproc("setStockQty", dbconnect.engines[client_id],queryParams) return True def xmlrpc_curStockQty(self, queryParams, client_id): ''' Purpose: Function to get the current quantity of the given product I/O Parameters: queryParams which contains searchFlag and searchValue Returns: total number of stock Description: To serch product by code we pass searchFlag =1 and to search product by name we pass searchFlag = 0. searchValue will either be product code or product name. If searchFlag is 1 then we only search the stockqty table for all the rows matching given product code and count the quantiy by reading stocflag. If searchFlag is 0 then we first get product code by searching for givne product name in genericproduct table. Then same procedure as above. To the sql function curStockQty we pass spqueryParams which contains searchFlag, searchValue and primerykey ''' totalstock=0 spqueryParams=[queryParams[0],queryParams[0],queryParams[0]] connection = dbconnect.engines[client_id].connect() Session = dbconnect.session(bind=connection) res = Session.query(dbconnect.StockQty).all() Session.commit() for l in res: #spqueryParams for curStockQty(the sql function) are (searchFlag, searchValue, primarykey) spqueryParams=[queryParams[0],queryParams[1],l.stockcode] search=dbconnect.execproc("curStockQty",dbconnect.engines[client_id],spqueryParams) stock=search.fetchall() stqview=[] for stockrow in stock: stqview.extend([stockrow["stockcode"],stockrow["prodcode"],stockrow["quantity"],stockrow["stockflag"]]) if stqview==[None,None,None,None]: continue; else: if stqview[3]==1: totalstock = totalstock + stqview[2] else: totalstock = totalstock - stqview[2] return totalstock core_engine-2.6.1-dac679a8ec1cd01924e7b2e80280c270f69b55ac/gnukhataserver/rpc_main.py000066400000000000000000003127371265207572300267320ustar00rootroot00000000000000 ''' This file is part of GNUKhata:A modular,robust and Free Accounting System. GNUKhata 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.and old.stockflag = 's' GNUKhata 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 GNUKhata (COPYING); if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA59 Temple Place, Suite 330, Contributor: "Krishnakant Mane" "Anusha Kadambala" "Sonal Chaudhari" Ashwini Shinde ''' from dbconnect import getOrgList from dbconnect import getConf #from mx.DateTime import DateTime #from apport_python_hook import CONFIG #from paste.util.PySourceColor import ARGS import re from rpc_account import account """ RPC module for organisation. This module will handle entry and updates of organisation and also getting the data for a given organisation """ #import the database connector and functions for stored procedure. import dbconnect import ConfigParser #import the twisted modules for executing rpc calls and also to implement the server from twisted.web import xmlrpc, server #reactor from the twisted library starts the server with a published object and listens on a given port. from twisted.internet import reactor from time import strftime import rpc_organisation import rpc_groups import rpc_account import rpc_transaction import rpc_data import rpc_customizable import rpc_user import rpc_reports import dbconnect import rpc_getaccountsbyrule import rpc_inventory import datetime #from dateutil.relativedelta import relativedelta import os,sys #import rpc_schemagnukhata = gnukhata() import psycopg2 from sqlalchemy.orm import sessionmaker,scoped_session #import xml etree library from xml.etree import ElementTree as et import os import sys import getopt confData = {} confData = dbconnect.getConf() #inherit the class from XMLRPC to make it publishable as an rpc service. class gnukhata(xmlrpc.XMLRPC): #note that all the functions to be accessed by the client must have the xmlrpc_ prefix. def __init__(self): xmlrpc.XMLRPC.__init__(self) #the client however will not use the prefix to call the functions. #self.client_id = dbconnect.getConnection() def xmlrpc_getOrganisationNames(self): #this function is used to return the list of organsations found in gnukhata.xml located at /etc.Returns a list of organisations already present in the file #calling the function for getting list of organisation nodes. orgs = dbconnect.getOrgList() #initialising an empty list for organisation names orgnames = [] nameType = [] for org in orgs: orgname=org.find("orgname") orgtype=org.find("org_Type") nametype = orgname.text+orgtype.text #print type(orgname.text) #checking for unique names. #we will use the not in clause here. if nametype not in nameType : nameType.append(orgname.text+orgtype.text) orgnames.append([orgname.text,orgtype.text]) return orgnames def xmlrpc_getFinancialYear(self,arg_orgName,arg_orgtype): """ purpose: This function will return a list of financial years for the given organisation. Arguements, organisation name of type string. returns, list of financial years in the format yyyy-yy """ #get the list of organisations from the /var/lib/gnukhata/gnukhata.xml file. #we will call the getOrgList function to get the nodes. orgs = dbconnect.getOrgList() #Initialising an empty list to be filled with financial years financialyearlist = [] for org in orgs: orgname = org.find("orgname") orgtype = org.find("org_Type") if orgname.text== arg_orgName and orgtype.text == arg_orgtype: financialyear_from = org.find("financial_year_from") financialyear_to = org.find("financial_year_to") from_and_to = [financialyear_from.text, financialyear_to.text] financialyearlist.append(from_and_to) return financialyearlist def xmlrpc_getDatabase(self): confData = dbconnect.getConf() try: con = psycopg2.connect("dbname='" + confData['database']+ "' user='" + confData['host'] + "'") except: print "Error: Could not connect to postgresql" return False cur = con.cursor() cur.execute("select datname from pg_database where datname like 'gk%';") con.commit() res=cur.fetchall() if res != []: con = psycopg2.connect("dbname="+res[len(res)-1][0]+" host='confData['host']'"); return res else: return False def xmlrpc_getConnection(self,queryParams): self.client_id=dbconnect.getConnection(queryParams) print "yess" print self.client_id print "nooo" return self.client_id def xmlrpc_closeConnection(self,client_id): print('closing connection'+str(client_id)+" with user: "+dbconnect.getUserByClientId(client_id)) dbconnect.engines[client_id].dispose() del dbconnect.engines[client_id] return True def xmlrpc_getUBC(self,client_id): return dbconnect.getUserByClientId(client_id) def xmlrpc_getLogs(self,queryParams,client_id): connection = dbconnect.engines[client_id].connect() Session = dbconnect.session(bind=connection) # if(queryParams.__len__()==1): # print("meow!") logs=[] if(queryParams[0]==0): #user res = Session.query(dbconnect.log).filter(dbconnect.log.username==queryParams[1]).all() else: #activity res = Session.query(dbconnect.log).filter(dbconnect.log.activity==queryParams[1]).all() for i in res: log=[] log.append(i.username) log.append(i.description) log.append('%d'%i.activity) logs.append(log) #print(logs) Session.close() connection.close() return logs def xmlrpc_getActivities(self,client_id): acts=["Create Account","Edit Account","Create Voucher","Edit Voucher","Delete Voucher","Create Project"] return acts def xmlrpc_closeBooks(self,queryParams,client_id): """ Purpose: closes the existing (open) books and then moves on to transfer all amounts from direct/ indirect income and expenditures to Profit & Loss account. description: The function takes 1 argument apart from client_id, namely queryParams. The said queryParams is a list of: *financialStart *calculate_from *calculate_to *orgtype. The function will first get all the accounts from the 4 groups mentioned above. Then for each of those accounts, calculateBalance stored procedure will be called. Finally The closing balances will be transfered to Profit & Loss if it is a Profit Making org, or Income&exp if it is NGO. Depending on the balType the transfer will be either credit or debit. For example if the balType for an account in Direct Income is Cr, then the equall amount will be credited to Profit & Loss. Needless to say that this will be a JV with Dr on that account and Cr to Profit & Loss. Exactly the other way round if it is Dr. """ directIncomeAccounts = dbconnect.execproc("getAccountsByGroup", dbconnect.engines[client_id],["Direct Income"]) directIncomeAccountList = directIncomeAccounts.fetchall() indirectIncomeAccounts = dbconnect.execproc("getAccountsByGroup", dbconnect.engines[client_id],["Indirect Income"]) indirectIncomeAccountList = indirectIncomeAccounts.fetchall() directExpenseAccounts = dbconnect.execproc("getAccountsByGroup", dbconnect.engines[client_id],["Direct Expense"]) directExpenseAccountList = directExpenseAccounts.fetchall() indirectExpenseAccounts = dbconnect.execproc("getAccountsByGroup", dbconnect.engines[client_id],["Indirect Expense"]) indirectExpenseAccountList = indirectExpenseAccounts.fetchall() FinalAccount = "" if queryParams[3] == "Profit Making": FinalAccount= "Profit & Loss" else: FinalAccount= "Income & Expenditure" success = "" print "this is what we got from server" print queryParams if len(directIncomeAccountList) > 0: closingBalance = 0.00 for diAccount in directIncomeAccountList: if diAccount[0]==FinalAccount : continue closingBalanceResult = dbconnect.execproc("calculateBalance", dbconnect.engines[client_id],[diAccount[0],queryParams[0],queryParams[0],queryParams[1]]) closingBalanceRow = closingBalanceResult.fetchone() closingBalance= closingBalanceRow["curbal"] balType = closingBalanceRow["baltype"] if closingBalance > 0 and balType == "Cr": today = datetime.datetime.now() ms = str(today.microsecond) new_microsecond = ms[0:2] voucher_reference ="jv" + str(today.year) + str(today.month) + str(today.day) + str(today.hour) + str(today.minute) + str(today.second) + new_microsecond reffDate = str(queryParams[2]) voucherDate = str(strftime("%Y-%m-%d")) voucherType = "Journal" projectName = "No Project" narration = "Entry for closing %s "%(str(diAccount[0])) purchaseOrderNumber = "" purchaseOrderDate = "" purchaseOrderAmount = 0.00 queryParams_master = [voucher_reference,voucherDate,reffDate,voucherType,projectName,narration,purchaseOrderNumber,None,purchaseOrderAmount] queryParams_details = [] queryParams_details.append(["Cr",FinalAccount,closingBalance]) queryParams_details.append(["Dr",str(diAccount[0]),closingBalance]) print queryParams_details print "this is the reffffffffdateeeee" print queryParams_master[0] success = transaction.xmlrpc_setTransaction(queryParams_master, queryParams_details, client_id) if closingBalance > 0 and balType == "Dr": today = datetime.datetime.now() ms = str(today.microsecond) new_microsecond = ms[0:2] voucher_reference ="jv" + str(today.year) + str(today.month) + str(today.day) + str(today.hour) + str(today.minute) + str(today.second) + new_microsecond reffDate = str(queryParams[2]) voucherDate = str(strftime("%Y-%m-%d")) voucherType = "Journal" projectName = "No Project" narration = "Entry for closing %s "%(str(diAccount[0])) purchaseOrderNumber = "" purchaseOrderDate = "" purchaseOrderAmount = 0.00 queryParams_master = [voucher_reference,voucherDate,reffDate,voucherType,projectName,narration,purchaseOrderNumber,None,purchaseOrderAmount] queryParams_details = [] queryParams_details.append(["Dr",FinalAccount,closingBalance]) queryParams_details.append(["Cr",str(diAccount[0]),closingBalance]) print queryParams_details print "this is the reffffffffdateeeee" print queryParams_master[0] success = transaction.xmlrpc_setTransaction(queryParams_master, queryParams_details, client_id) if len(directExpenseAccountList) > 0: closingBalance = 0.00 for deAccount in directExpenseAccountList: closingBalanceResult = dbconnect.execproc("calculateBalance", dbconnect.engines[client_id],[deAccount[0],queryParams[0],queryParams[0],queryParams[1]]) closingBalanceRow = closingBalanceResult.fetchone() closingBalance= closingBalanceRow["curbal"] balType = closingBalanceRow["baltype"] if closingBalance > 0 and balType == "Cr": today = datetime.datetime.now() ms = str(today.microsecond) new_microsecond = ms[0:2] voucher_reference ="jv" + str(today.year) + str(today.month) + str(today.day) + str(today.hour) + str(today.minute) + str(today.second) + new_microsecond reffDate = str(queryParams[2]) voucherDate = str(strftime("%Y-%m-%d")) voucherType = "Journal" projectName = "No Project" narration = "Entry for closing %s "%(str(deAccount[0])) purchaseOrderNumber = "" purchaseOrderDate = "" purchaseOrderAmount = 0.00 queryParams_master = [voucher_reference,voucherDate,reffDate,voucherType,projectName,narration,purchaseOrderNumber,None,purchaseOrderAmount] queryParams_details = [] queryParams_details.append(["Cr",FinalAccount,closingBalance]) queryParams_details.append(["Dr",str(deAccount[0]),closingBalance]) print queryParams_details print "this is the reffffffffdateeeee" print queryParams_master[0] success = transaction.xmlrpc_setTransaction(queryParams_master, queryParams_details, client_id) if closingBalance > 0 and balType == "Dr": today = datetime.datetime.now() ms = str(today.microsecond) new_microsecond = ms[0:2] voucher_reference ="jv" + str(today.year) + str(today.month) + str(today.day) + str(today.hour) + str(today.minute) + str(today.second) + new_microsecond reffDate = str(queryParams[2]) voucherDate = str(strftime("%Y-%m-%d")) voucherType = "Journal" projectName = "No Project" narration = "Entry for closing %s "%(str(deAccount[0])) purchaseOrderNumber = "" purchaseOrderDate = "" purchaseOrderAmount = 0.00 queryParams_master = [voucher_reference,voucherDate,reffDate,voucherType,projectName,narration,purchaseOrderNumber,None,purchaseOrderAmount] queryParams_details = [] queryParams_details.append(["Dr",FinalAccount,closingBalance]) queryParams_details.append(["Cr",str(deAccount[0]),closingBalance]) print queryParams_details print "this is the reffffffffdateeeee" print queryParams_master[0] success = transaction.xmlrpc_setTransaction(queryParams_master, queryParams_details, client_id) if len(indirectExpenseAccountList) > 0: closingBalance = 0.00 for ideAccount in indirectExpenseAccountList: closingBalanceResult = dbconnect.execproc("calculateBalance", dbconnect.engines[client_id],[ideAccount[0],queryParams[0],queryParams[0],queryParams[1]]) closingBalanceRow = closingBalanceResult.fetchone() closingBalance= closingBalanceRow["curbal"] balType = closingBalanceRow["baltype"] if closingBalance > 0 and balType == "Cr": today = datetime.datetime.now() ms = str(today.microsecond) new_microsecond = ms[0:2] voucher_reference ="jv" + str(today.year) + str(today.month) + str(today.day) + str(today.hour) + str(today.minute) + str(today.second) + new_microsecond reffDate = str(queryParams[2]) voucherDate = str(strftime("%Y-%m-%d")) voucherType = "Journal" projectName = "No Project" narration = "Entry for closing %s "%(str(ideAccount[0])) purchaseOrderNumber = "" purchaseOrderDate = "" purchaseOrderAmount = 0.00 queryParams_master = [voucher_reference,voucherDate,reffDate,voucherType,projectName,narration,purchaseOrderNumber,None,purchaseOrderAmount] queryParams_details = [] queryParams_details.append(["Cr",FinalAccount,closingBalance]) queryParams_details.append(["Dr",str(ideAccount[0]),closingBalance]) print queryParams_details print "this is the reffffffffdateeeee" print queryParams_master[0] success = transaction.xmlrpc_setTransaction(queryParams_master, queryParams_details, client_id) if closingBalance > 0 and balType == "Dr": today = datetime.datetime.now() ms = str(today.microsecond) new_microsecond = ms[0:2] voucher_reference ="jv" + str(today.year) + str(today.month) + str(today.day) + str(today.hour) + str(today.minute) + str(today.second) + new_microsecond reffDate = str(queryParams[2]) voucherDate = str(strftime("%Y-%m-%d")) voucherType = "Journal" projectName = "No Project" narration = "Entry for closing %s "%(str(ideAccount[0])) purchaseOrderNumber = "" purchaseOrderDate = "" purchaseOrderAmount = 0.00 queryParams_master = [voucher_reference,voucherDate,reffDate,voucherType,projectName,narration,purchaseOrderNumber,None,purchaseOrderAmount] queryParams_details = [] queryParams_details.append(["Dr",FinalAccount,closingBalance]) queryParams_details.append(["Cr",str(ideAccount[0]),closingBalance]) print queryParams_details print "this is the reffffffffdateeeee" print queryParams_master[0] success = transaction.xmlrpc_setTransaction(queryParams_master, queryParams_details, client_id) if len(indirectIncomeAccountList) > 0: closingBalance = 0.00 for idiAccount in indirectIncomeAccountList: closingBalanceResult = dbconnect.execproc("calculateBalance", dbconnect.engines[client_id],[idiAccount[0],queryParams[0],queryParams[0],queryParams[1]]) closingBalanceRow = closingBalanceResult.fetchone() closingBalance= closingBalanceRow["curbal"] balType = closingBalanceRow["baltype"] if closingBalance > 0 and balType == "Cr": today = datetime.datetime.now() ms = str(today.microsecond) new_microsecond = ms[0:2] voucher_reference ="jv" + str(today.year) + str(today.month) + str(today.day) + str(today.hour) + str(today.minute) + str(today.second) + new_microsecond reffDate = str(queryParams[2]) voucherDate = str(strftime("%Y-%m-%d")) voucherType = "Journal" projectName = "No Project" narration = "Entry for closing %s "%(str(idiAccount[0])) purchaseOrderNumber = "" purchaseOrderDate = "" purchaseOrderAmount = 0.00 queryParams_master = [voucher_reference,voucherDate,reffDate,voucherType,projectName,narration,purchaseOrderNumber,None,purchaseOrderAmount] queryParams_details = [] queryParams_details.append(["Cr",FinalAccount,closingBalance]) queryParams_details.append(["Dr",str(idiAccount[0]),closingBalance]) print queryParams_details print "this is the reffffffffdateeeee" print queryParams_master[0] success = transaction.xmlrpc_setTransaction(queryParams_master, queryParams_details, client_id) if closingBalance > 0 and balType == "Dr": today = datetime.datetime.now() ms = str(today.microsecond) new_microsecond = ms[0:2] voucher_reference ="jv" + str(today.year) + str(today.month) + str(today.day) + str(today.hour) + str(today.minute) + str(today.second) + new_microsecond reffDate = str(queryParams[2]) voucherDate = str(strftime("%Y-%m-%d")) voucherType = "Journal" projectName = "No Project" narration = "Entry for closing %s "%(str(idiAccount[0])) purchaseOrderNumber = "" purchaseOrderDate = "" purchaseOrderAmount = 0.00 queryParams_master = [voucher_reference,voucherDate,reffDate,voucherType,projectName,narration,purchaseOrderNumber,None,purchaseOrderAmount] queryParams_details = [] queryParams_details.append(["Dr",FinalAccount,closingBalance]) queryParams_details.append(["Cr",str(idiAccount[0]),closingBalance]) print queryParams_details print "this is the reffffffffdateeeee" print queryParams_master[0] success = transaction.xmlrpc_setTransaction(queryParams_master, queryParams_details, client_id) closingBalanceResult = dbconnect.execproc("calculateBalance", dbconnect.engines[client_id],[FinalAccount,queryParams[0],queryParams[0],queryParams[1]]) closingBalanceRow = closingBalanceResult.fetchone() closingBalance= closingBalanceRow["curbal"] balType = closingBalanceRow["baltype"] FinalReserve = "" connection = dbconnect.engines[self.client_id].raw_connection() cur = connection.cursor() lstcompareacc = [] accounts1 = dbconnect.execproc("getAllAccounts", dbconnect.engines[client_id], []) reserve = "" for acc in accounts1: lstcompareacc.append(acc[0]) print lstcompareacc if "Profit b/f" in lstcompareacc: updateQuery = "update account set accountname = 'Profit c/f' where accountname = 'Profit b/f'" upd=cur.execute(updateQuery) reserve = "Profit c/f" print "profit carried forward ",upd elif "Loss b/f" in lstcompareacc: updateQuery = "update account set accountname = 'Loss c/f' where accountname = 'Loss b/f'" upd=cur.execute(updateQuery) reserve = "Loss c/f" print "loss carried forward ",upd elif "Surplus b/f" in lstcompareacc: updateQuery = "update account set accountname = 'Surplus c/f' where accountname = 'Surplus b/f'" upd=cur.execute(updateQuery) reserve = "Surplus c/f" print "surplus carried forward ",upd elif "Deficit b/f" in lstcompareacc: updateQuery = "update account set accountname = 'Deficit c/f' where accountname = 'Deficit b/f'" upd=cur.execute(updateQuery) reserve = "Deficit c/f" print "deficit carried forward ",upd else: if balType == "Cr": if FinalAccount=="Profit & Loss": reserve = "Profit c/f" else: reserve = "Surplus c/f" newqueryParams = ['Reserves', 'No Sub-Group', '', reserve, 'automatic', '0.00', '0.00', ''] account.xmlrpc_setAccount(newqueryParams, self.client_id) if balType == "Dr": if FinalAccount=="Profit & Loss": reserve = "Loss c/f" else: reserve = "Deficit c/f" newqueryParams = ['Reserves', 'No Sub-Group', '', reserve, 'automatic', '0.00', '0.00', ''] account.xmlrpc_setAccount(newqueryParams, self.client_id) connection.commit() if balType == "Cr": if FinalAccount=="Profit & Loss": curreserve = "Profit for the Year" else: curreserve = "Surplus for the Year" newqueryParams = ['Reserves', 'No Sub-Group', '', curreserve, 'automatic', '0.00', '0.00', ''] account.xmlrpc_setAccount(newqueryParams, self.client_id) if balType == "Dr": if FinalAccount=="Profit & Loss": curreserve = "Loss for the Year" else: curreserve = "Deficit for the Year" newqueryParams = ['Reserves', 'No Sub-Group', '', curreserve, 'automatic', '0.00', '0.00', ''] account.xmlrpc_setAccount(newqueryParams, self.client_id) connection.commit() if closingBalance > 0 and balType == "Cr": print "Printing the current reserve CR",curreserve today = datetime.datetime.now() ms = str(today.microsecond) new_microsecond = ms[0:2] voucher_reference ="jv" + str(today.year) + str(today.month) + str(today.day) + str(today.hour) + str(today.minute) + str(today.second) + new_microsecond reffDate = str(queryParams[2]) voucherDate = str(strftime("%Y-%m-%d")) voucherType = "Journal" projectName = "No Project" narration = "Entry for recording" +FinalAccount purchaseOrderNumber = "" purchaseOrderDate = "" purchaseOrderAmount = 0.00 queryParams_master = [voucher_reference,voucherDate,reffDate,voucherType,projectName,narration,purchaseOrderNumber,None,purchaseOrderAmount] queryParams_details = [] queryParams_details.append(["Cr",curreserve,closingBalance]) queryParams_details.append(["Dr",FinalAccount,closingBalance]) print queryParams_details print "this is the reffffffffdateeeee" print queryParams_master[0] success = transaction.xmlrpc_setTransaction(queryParams_master, queryParams_details, client_id) FinalReserve = reserve print "Printing the finaaaaaaaaaal reserve CR",FinalReserve today = datetime.datetime.now() ms = str(today.microsecond) new_microsecond = ms[0:2] voucher_reference ="jv" + str(today.year) + str(today.month) + str(today.day) + str(today.hour) + str(today.minute) + str(today.second) + new_microsecond reffDate = str(queryParams[2]) voucherDate = str(strftime("%Y-%m-%d")) voucherType = "Journal" projectName = "No Project" narration = "Entry for closing "+curreserve purchaseOrderNumber = "" purchaseOrderDate = "" purchaseOrderAmount = 0.00 queryParams_master = [voucher_reference,voucherDate,reffDate,voucherType,projectName,narration,purchaseOrderNumber,None,purchaseOrderAmount] queryParams_details = [] queryParams_details.append(["Cr",FinalReserve,closingBalance]) queryParams_details.append(["Dr",curreserve,closingBalance]) print queryParams_details print "this is the reffffffffdateeeee" print queryParams_master[0] success = transaction.xmlrpc_setTransaction(queryParams_master, queryParams_details, client_id) if closingBalance > 0 and balType == "Dr": print "Printing the current reserve Dr",curreserve today = datetime.datetime.now() ms = str(today.microsecond) new_microsecond = ms[0:2] voucher_reference ="jv" + str(today.year) + str(today.month) + str(today.day) + str(today.hour) + str(today.minute) + str(today.second) + new_microsecond reffDate = str(queryParams[2]) voucherDate = str(strftime("%Y-%m-%d")) voucherType = "Journal" projectName = "No Project" narration = "Entry for closing"+FinalAccount purchaseOrderNumber = "" purchaseOrderDate = "" purchaseOrderAmount = 0.00 queryParams_master = [voucher_reference,voucherDate,reffDate,voucherType,projectName,narration,purchaseOrderNumber,None,purchaseOrderAmount] queryParams_details = [] queryParams_details.append(["Dr",curreserve,closingBalance]) queryParams_details.append(["Cr",FinalAccount,closingBalance]) print queryParams_details print "this is the reffffffffdateeeee" print queryParams_master[0] success = transaction.xmlrpc_setTransaction(queryParams_master, queryParams_details, client_id) FinalReserve = reserve print "Printing the finaaaaaaaaaal reserve Dr",FinalReserve today = datetime.datetime.now() ms = str(today.microsecond) new_microsecond = ms[0:2] voucher_reference ="jv" + str(today.year) + str(today.month) + str(today.day) + str(today.hour) + str(today.minute) + str(today.second) + new_microsecond reffDate = str(queryParams[2]) voucherDate = str(strftime("%Y-%m-%d")) voucherType = "Journal" projectName = "No Project" narration = "Entry for recording"+ FinalAccount purchaseOrderNumber = "" purchaseOrderDate = "" purchaseOrderAmount = 0.00 queryParams_master = [voucher_reference,voucherDate,reffDate,voucherType,projectName,narration,purchaseOrderNumber,None,purchaseOrderAmount] queryParams_details = [] queryParams_details.append(["Dr",FinalReserve,closingBalance]) queryParams_details.append(["Cr",curreserve,closingBalance]) print queryParams_details print "this is the reffffffffdateeeee" print queryParams_master[0] success = transaction.xmlrpc_setTransaction(queryParams_master, queryParams_details, client_id) closingBalanceResult = dbconnect.execproc("calculateBalance", dbconnect.engines[client_id],[FinalReserve,queryParams[0],queryParams[0],queryParams[1]]) closingBalanceRow = closingBalanceResult.fetchone() balType = closingBalanceRow["baltype"] if FinalReserve == "Profit c/f" and balType == "Dr": updateQuery = "update account set accountname = 'Loss c/f' where accountname = 'Profit c/f'" upd=cur.execute(updateQuery) elif FinalReserve == "Loss c/f" and balType == "Cr": updateQuery = "update account set accountname = 'Profit c/f' where accountname = 'Loss c/f'" upd=cur.execute(updateQuery) elif FinalReserve == "Surplus c/f" and balType == "Dr": updateQuery = "update account set accountname = 'Deficit c/f' where accountname = 'Surplus c/f'" upd=cur.execute(updateQuery) elif FinalReserve == "Deficit c/f" and balType == "Cr": updateQuery = "update account set accountname = 'Surplus c/f' where accountname = 'Deficit c/f'" upd=cur.execute(updateQuery) connection.commit() print success return success def xmlrpc_rollover(self,queryParams,client_id): """ purpose: deploys new datTabase for and organisation for the next financial year. Takes one parameter, a list containing: Organisation Name, Financial start, financial end. Financial start should not be taken from user as it aught to be a day after the closing of current financial year. Similarly the Organisation type will be the same as the previous year. description: This function will be used for the rollover process where the organisation closes the books for the current financial year. In order to open a new set of books the user must provide the end date (start date is assumed to be the day after the close of current books). As soon as this function is called, it will first query the current database and get list of all accounts. After this, calculateBalance stored procedure will be called to get the balance Carried Forward (c/f) A dictionary will be maintained containing the accountname as the key and the corresponding balance as the value. Now a pg_dump will be called to get the data from subgroups and account table. The file thus generated will be kept in the /tmp folder. the data will be put into the new database, after which the connection to the current database will be closed. now a new connection for the newly created database will be procured. After getting all the details, the deploy function will be called to create a new database for the stated financial year. here too we need the name of the new database so that we can put the data in. now we will loop through the dictionary we had created earlier and enter the proper opening balances so that the books open proper. The function will make use of the getAllAccounts stored procedure and also editAccount stored procedure. For detailed specification of the said stored procedures, see the xmlrpc_deploy function in rpc_main.py """ #if the current user is admin or manager(ie.dbconnect.user_roles[client_id] == -1 or dbconnect.user_roles[client_id] == 0 ) then only this method will perform rollover function. if(dbconnect.user_roles[client_id] == 0 or dbconnect.user_roles[client_id] == -1) : #the empty dictionary which will be filled with accounts and their closing balances. rollOverAccounts = {} print client_id #get the list of accounts. accounts = dbconnect.execproc("getAllAccounts", dbconnect.engines[client_id], []) #accList = accounts.fetchall() for account in accounts: closingBalance = dbconnect.execproc("calculateBalance", dbconnect.engines[client_id],[str(account[0]),queryParams[1],queryParams[1],queryParams[2]]) closingRow = closingBalance.fetchone() actualClosing = 0.00 if str(closingRow["baltype"]) == "Cr" and (str(closingRow["group_name"])== "Current Assets" or str(closingRow["group_name"])== "Fixed Assets" or str(closingRow["group_name"])== "Investment" or str(closingRow["group_name"])== "Loans(Asset)" or str(closingRow["group_name"])== "Miscellaneous Expenses(Asset)"): actualClosing = -float(closingRow["curbal"]) rollOverAccounts[account[0]] = actualClosing if str(closingRow["baltype"]) == "Dr" and (str(closingRow["group_name"])== "Current Assets" or str(closingRow["group_name"])== "Fixed Assets" or str(closingRow["group_name"])== "Investment" or str(closingRow["group_name"])== "Loans(Asset)" or str(closingRow["group_name"])== "Miscellaneous Expenses(Asset)"): actualClosing = float(closingRow["curbal"]) rollOverAccounts[account[0]] = actualClosing if str(closingRow["baltype"]) == "Cr" and (str(closingRow["group_name"])== "Corpus" or str(closingRow["group_name"])== "Capital" or str(closingRow["group_name"])== "Current Liability" or str(closingRow["group_name"])== "Loans(Liability)" or str(closingRow["group_name"])== "Reserves"): actualClosing = float(closingRow["curbal"]) rollOverAccounts[account[0]] = actualClosing if str(closingRow["baltype"]) == "Dr" and (str(closingRow["group_name"])== "Corpus" or str(closingRow["group_name"])== "Capital" or str(closingRow["group_name"])== "Current Liability" or str(closingRow["group_name"])== "Loans(Liability)" or str(closingRow["group_name"])== "Reserves"): actualClosing = -float(closingRow["curbal"]) rollOverAccounts[account[0]] = actualClosing # now let's consider for the 4 Taklas. #we have to consider what we must do if the closing balance is 0. if int(closingRow["curbal"]) == 0: rollOverAccounts[account[0]] = 0 #all done with the old database. #now let's do the last rituals by dumping accounts and subgroups from the database before creating a new one. dbname = "" #the financial from declared below is in dd-mm-yyyy format, same is for financialto financialFrom = datetime.datetime.strptime(queryParams[1],"%Y-%m-%d %H:%M:%S").strftime("%d-%m-%Y") print financialFrom financialTo = datetime.datetime.strptime(queryParams[2],"%Y-%m-%d %H:%M:%S").strftime("%d-%m-%Y") print "this is the data before rollover `ment " print "the current financial from is " + financialFrom print "the current financial to is " + financialTo orgs = dbconnect.getOrgList() for org in orgs: orgname = org.find("orgname") financialyear_from = org.find("financial_year_from")#DD-MM-YYYY financialyear_to = org.find("financial_year_to") orgtype = org.find("org_Type") if orgname.text == queryParams[0] and financialyear_from.text == financialFrom and financialyear_to.text == queryParams[5] and orgtype.text == queryParams[4]: dbname = org.find("dbname") print dbname print financialyear_from.text print financialyear_to.text database = dbname.text print "the current database name is " + database os.system("pg_dump -U " + confData['dbuser'] + " -a -t organisation -t subgroups -t account -Fc " + database + " > /tmp/db.dump") #now on to the next financial year. #note that queryParams[2] contains the end date for the current year. #so the new financial year must start exactly one day after it. oneDay = datetime.timedelta(days=1) finalDate = datetime.date(int(financialTo[6:10]),int(financialTo[3:5]),int(financialTo[0:2])) newStartDate = finalDate + oneDay newYear = newStartDate.strftime("%d-%m-%Y") OpStockDate = newStartDate.strftime("%Y-%m-%d") dbconnect.engines[client_id].dispose() del dbconnect.engines[client_id] #the former database is closed. #now we will deploy a fresh one. #we will call xmlrpc_deploy print "about to create db for new financial year " print "the new year starts at " + newYear print "and the year ends at " + queryParams[3] self.client_id = self.xmlrpc_Deploy([queryParams[0],newYear,queryParams[3],queryParams[4]]) organisation.xmlrpc_setOrganisation(["","","","","","","","","","","","","","","","","","",""],self.client_id[1]) print "new client_id is " + str(self.client_id) #now lets query gnukhata.xml and get the fresh list of orgainzations #this will help us to get to the newly created database. dbname = "" newOrgs = dbconnect.getOrgList() for newOrg in newOrgs: orgname = newOrg.find("orgname") financialyear_from = newOrg.find("financial_year_from") financialyear_to = newOrg.find("financial_year_to") orgtype = newOrg.find("org_Type") print orgname.text print financialyear_from.text print financialyear_to.text if orgname.text == queryParams[0] and financialyear_from.text == newYear and financialyear_to.text == queryParams[3] and orgtype.text == queryParams[4]: print "the 4 of them tally with " print queryParams[0]+ " " + newYear + " " + queryParams[3]+" "+queryParams[4] dbname = newOrg.find("dbname") newDatabase = dbname.text print "deployment is done and the new dbname is " + newDatabase connection = dbconnect.engines[self.client_id[1]].raw_connection() cur = connection.cursor() print "about to delete closing stock acccccccccoooooouuunnnttt" cur.execute("delete from account where accountname = 'Closing Stock';") cur.execute("delete from account where accountname = 'Stock at the Beginning';") cur.execute("delete from subgroups;") cur.execute("delete from account;") connection.commit() os.system("pg_restore -U " + confData['dbuser'] + " -d " + newDatabase + " /tmp/db.dump") #we will now set the opening balances. #not that we already have a dictionary with accounts as keys and last year closing as values. cur.execute("delete from account where accountname in ('Profit for the Year','Loss for the Year','Surplus for the Year','Deficit for the Year' );") connection.commit() for acc in rollOverAccounts.keys(): acc1 = acc if acc == "Profit c/f": updateQuery = "update account set accountname = 'Profit b/f' where accountname = 'Profit c/f'" upd=cur.execute(updateQuery) acc = "Profit b/f" print "profit brought forward ",upd if acc == "Loss c/f": updateQuery = "update account set accountname = 'Loss b/f' where accountname = 'Loss c/f'" upd=cur.execute(updateQuery) print "loss brought forward ",upd acc = "Loss b/f" if acc == "Surplus c/f": updateQuery = "update account set accountname = 'Surplus b/f' where accountname = 'Surplus c/f'" upd=cur.execute(updateQuery) print "surplus brought forward ",upd acc = "Surplus b/f" if acc == "Deficit c/f": updateQuery = "update account set accountname = 'Deficit b/f' where accountname = 'Deficit c/f'" upd=cur.execute(updateQuery) print "deficit brought forward ",upd acc = "Deficit b/f" print "This is acccccccc",acc editQuery = "update account set openingbalance = " + str(rollOverAccounts[acc1]) + " where accountname = '" + acc.replace("'", "''") + "'" cur.execute(editQuery) connection.commit() if(rollOverAccounts["Closing Stock"]>0): params = [2,'Stock at the Beginning'] updateQuery = "update account set openingbalance ="+str(rollOverAccounts['Closing Stock'])+ "where accountname = 'Stock at the Beginning';" upd=cur.execute(updateQuery) updateQuery = "update account set openingbalance = 0.00 where accountname = 'Closing Stock';" upd=cur.execute(updateQuery) connection.commit() today = datetime.datetime.now() ms = str(today.microsecond) new_microsecond = ms[0:2] voucher_reference ="jv" + str(today.year) + str(today.month) + str(today.day) + str(today.hour) + str(today.minute) + str(today.second) + new_microsecond reffDate = str(OpStockDate) voucherDate = str(strftime("%Y-%m-%d")) voucherType = "Journal" projectName = "No Project" OrderNumber = "" OrderAmount = 0.00 narration = "Journal voucher for Opening Stock" queryParams_master = [voucher_reference,voucherDate,reffDate,voucherType,projectName,narration,OrderNumber,None,OrderAmount] queryParams_details = [] queryParams_details.append(["Dr","Opening Stock",float(rollOverAccounts["Closing Stock"])]) queryParams_details.append(["Cr","Stock at the Beginning",float(rollOverAccounts["Closing Stock"])]) success = transaction.xmlrpc_setTransaction(queryParams_master, queryParams_details, self.client_id[1]) return True,self.client_id[1] def xmlrpc_Deploy(self,queryParams): """ Purpose: This function deploys a database instance for an organisation for a given financial year. The expected parameters are: * organisation name * From date * to date * organisation type (NGO or Profit Making) The function will generate the database name based on the organisation name provided The name of the database is a combination of, First character of organisation name, * time stap as yyyy-mm-dd-hh-MM-ss-ms An entry will be made in the xml file for the currosponding organisation. Note, this function not just creates the database, but also implements all the tables through ORM (SQLAlchemy) and then executes queries for generating views and stored procedures. """ confData = dbconnect.getConf() gnukhataconf=et.parse(confData['xmlpath']) gnukhataroot = gnukhataconf.getroot() #creating an organisation tag org = et.SubElement(gnukhataroot,"organisation") org_name = et.SubElement(org,"orgname") #taking input i.e organisation name and financial year from front end name_of_org = queryParams[0] db_from_date = queryParams[1] db_to_date = queryParams[2] organisationType = queryParams[3] org_name.text = name_of_org #creating a new tag for financial year from-to financial_year_from = et.SubElement(org,"financial_year_from") financial_year_from.text = db_from_date financial_year_to = et.SubElement(org,"financial_year_to") financial_year_to.text = db_to_date org_Type = et.SubElement(org,"org_Type") org_Type.text = organisationType #creating database name for organisation dbname = et.SubElement(org,"dbname") org_db_name=name_of_org[0:1] time=datetime.datetime.now() str_time=str(time.microsecond) new_microsecond=str_time[0:2] result_dbname=org_db_name + str(time.year) + str(time.month) + str(time.day) + str(time.hour) + str(time.minute) + str(time.second) + new_microsecond dbname.text = result_dbname gnukhataconf.write(confData['xmlpath']) os.system("createdb -U " + confData['dbuser'] + " " + result_dbname) os.system("createlang plpgsql -U " + confData['dbuser'] +" " + result_dbname) # +os.system("createdb -U gnukhata "+result_dbname) # os.system("createlang plpgsql -U gnukhata "+result_dbname) #we may asume that the database is created so now let's try and connect again. #execute the table creation commands here. self.client_id = dbconnect.getConnection([name_of_org,db_from_date,db_to_date,organisationType]) metadata = dbconnect.Base.metadata metadata.create_all(dbconnect.engines[self.client_id]) Session = scoped_session(sessionmaker(bind=dbconnect.engines[self.client_id])) dbconnect.engines[self.client_id].execute("insert into users(username,userpassword,userrole) values('admin','admin',-1);") #dbconnect.engines[self.client_id].execute("create or replace view StockReport as select productmaster.prodcode, productmaster.prodname, stockqty.quantity,stockqty.transactiondate, stockqty.stockflag, stockqty.billno from productmaster,stockqty where productmaster.prodcode = stockqty.prodcode;") #dbconnect.engines[self.client_id].execute("create or replace view view_creditnote as select creditnotemaster.vouchercode,creditnotemaster.pbillno, creditnotemaster.voucherdate,creditnotemaster.reffdate,creditnotemaster.booktype,creditnotemaster.chequeno, creditnotemaster.bankname,cr_account.accountname as cr_accountname,dr_account.accountname as dr_accountname,creditnotedetails.amount,creditnotemaster.creditnarration from creditnotemaster,creditnotedetails,account as cr_account,account as dr_account where creditnotemaster.vouchercode = creditnotedetails.vouchercode and creditnotedetails.craccountcode = cr_account.accountcode and creditnotedetails.draccountcode = dr_account.accountcode;") #dbconnect.engines[self.client_id].execute("create or replace view view_debitnote as select debitnotemaster.vouchercode,debitnotemaster.sbillno, debitnotemaster.voucherdate,debitnotemaster.reffdate,debitnotemaster.booktype,debitnotemaster.chequeno, debitnotemaster.bankname,cr_account.accountname as cr_accountname,dr_account.accountname as dr_accountname,debitnotedetails.amount,debitnotemaster.debitnarration from debitnotemaster,debitnotedetails,account as cr_account,account as dr_account where debitnotemaster.vouchercode = debitnotedetails.vouchercode and debitnotedetails.craccountcode = cr_account.accountcode and debitnotedetails.draccountcode = dr_account.accountcode;") dbconnect.engines[self.client_id].execute("create or replace view view_account as select groups.groupname, account.accountcode, account.accountname, account.subgroupcode from groups, account where groups.groupcode = account.groupcode order by groupname;") dbconnect.engines[self.client_id].execute("create or replace view view_group_subgroup as select groups.groupcode, groups.groupname, subgroups.subgroupcode, subgroups.subgroupname from groups, subgroups where groups.groupcode = subgroups.groupcode order by groupname;") dbconnect.engines[self.client_id].execute("create or replace view view_voucherbook as select voucher_master.vouchercode,voucher_master.flag,voucher_master.reference, voucher_master.voucherdate,voucher_master.reffdate,voucher_master.vouchertype,account.accountname as account_name,voucher_details.typeflag,voucher_details.amount,voucher_master.narration,voucher_master.projectcode,voucher_master.lockflag from voucher_master,voucher_details,account as account where voucher_master.vouchercode = voucher_details.vouchercode and voucher_details.accountcode = account.accountcode;") dbconnect.engines[self.client_id].execute("create or replace view group_subgroup_account as select groups.groupname,subgroups.subgroupcode,subgroups.subgroupname,account.accountcode,account.accountname,account.openingbalance,account.balance from groups join account on (groups.groupcode = account.groupcode) left outer join subgroups on (account.subgroupcode = subgroups.subgroupcode) order by groupname;") # executing store procedures for GNUkhata tables. strsql = "create or replace function getGroupByCode(group_code groups.groupcode%type, out groupcode integer, out groupname text) returns record as $$ begin select g.groupcode, g.groupname into groupcode, groupname from groups as g where g.groupcode = group_code; end; $$ language plpgsql;" connection = dbconnect.engines[self.client_id].raw_connection() cur = connection.cursor() cur.execute(strsql) cur.execute("create or replace function addUser(user_name users.username%type, user_password users.userpassword%type, user_role users.userrole%type, user_question users.userquestion%type , user_answer users.useranswer%type, out success integer)returns integer as $$ begin insert into users (username, userpassword, userrole,userquestion,useranswer) values (user_name, user_password, user_role,user_question,user_answer); select max(userid) into success from users; end; $$ language plpgsql;") cur.execute("create or replace function getsecurityquestion(user_name users.username%type, out user_question text,out user_answer text) returns record as $$ begin select userquestion, useranswer into user_question,user_answer from users where username = user_name; end; $$ language plpgsql;") cur.execute("create or replace function forgotPassword(user_name users.username%type, new_password users.userpassword%type, out success boolean) returns boolean as $$ begin update users set userpassword = new_password where username = user_name; success := found; end; $$ language plpgsql;") cur.execute("create or replace function UserExists(user_name users.username%type) returns bit as $$ declare user_counter bit; begin select count(username) into user_counter from users where username = user_name; return user_counter; end; $$ language plpgsql;") cur.execute("create or replace function changePassword(user_name users.username%type, old_password text, new_password users.userpassword%type, out success boolean) returns boolean as $$ declare enter_old_password users.userpassword%type; begin select userpassword into enter_old_password from users where username = user_name; update users set userpassword = new_password where enter_old_password = old_password and username = user_name; success := found; end; $$ language plpgsql;") cur.execute("create or replace function getOrgDetails(out org_type text, out org_name text, out org_addr text, out org_city text, out org_pin char(30), out org_state text, out org_country text, out org_telno text, out org_fax text,out org_website text,out org_email text,out org_pan text,out org_mvat text,out org_stax text,out org_regno text,out org_regdate text,out org_fcrano text,out org_fcradate text) returns record as $$ begin select orgtype, orgname ,orgaddr,orgcity,bpchar(orgpincode),orgstate,orgcountry,orgtelno,orgfax,orgwebsite,orgemail,orgpan,orgmvat,orgstax,orgregno,orgregdate,orgfcrano,orgfcradate into org_type,org_name,org_addr,org_city,org_pin,org_state,org_country,org_telno,org_fax,org_website,org_email,org_pan,org_mvat,org_stax,org_regno,org_regdate,org_fcrano,org_fcradate from organisation; end;$$ language plpgsql;") cur.execute("create or replace function adminChangePassword(user_name users.username%type, password users.userpassword%type, out success boolean) returns boolean as $$ begin update users set userpassword = password where username = user_name; success := found; end; $$ language plpgsql;") cur.execute("create or replace function getActivity (id int) returns activity as $$ declare ac varchar; begin SELECT (ENUM_RANGE(NULL::activity))[s] into ac FROM generate_series(id,id) s; return ac; end; $$ language plpgsql;") cur.execute("create or replace function setLog (username log.username%type, acid int, description log.description%type) returns bit as $$ declare act activity; begin select getActivity(acid) into act; if act is null then return 0; end if; insert into log (username,activity,description,logdatetime) values (username,act,description,localtimestamp); return 1; end; $$ language plpgsql;") cur.execute("create or replace function getGroupByName(group_name groups.groupname%type, out groupcode integer) returns integer as $$ begin select g.groupcode into groupcode from groups as g where g.groupname = group_name; end; $$ language plpgsql;") cur.execute("create or replace function getAllGroups() returns setof groups as $$ declare res groups; begin for res in select * from groups order by groupname loop return next res; end loop; return; end; $$ language plpgsql;") cur.execute("create or replace function getGroupNames(out groupname text) returns setof text as $$ begin return query select g.groupname from groups as g order by g.groupname; end; $$ language plpgsql;") cur.execute("create or replace function getSubGroupsByGroup(group_name groups.groupname%type, out subgroupname text) returns setof text as $$ begin return query select v.subgroupname from view_group_subgroup as v where v.groupname = group_name order by v.subgroupname; end; $$ language plpgsql;") cur.execute("create or replace function getGroupNameByAccountName(account_name account.accountname%type, out groupname text) as $$ begin select t.groupname into groupname from groups as t, account where t.groupcode = account.groupcode and account.accountname = account_name; end; $$ language plpgsql;") cur.execute("create or replace function getSubGroupByName(subgroup_name subgroups.subgroupname%type, out subgroupcode integer) returns integer as $$ begin select s.subgroupcode into subgroupcode from subgroups as s where s.subgroupname = subgroup_name; end; $$ language plpgsql;") cur.execute("create or replace function setSubGroup(group_name groups.groupname%type, subgroup_name subgroups.subgroupname%type) returns bit as $$ declare group_code groups.groupcode%type; subgroup_code subgroups.subgroupcode%type; subgroups_counter integer; begin select groups.groupcode into group_code from groups where groupname = group_name; select subgroupcode into subgroup_code from subgroups where subgroupname = subgroup_name; select count(subgroupname) into subgroups_counter from subgroups where subgroupname = subgroup_name; if subgroups_counter = 0 then insert into subgroups (groupcode,subgroupname) values (group_code,subgroup_name); return 0; else return 1; end if; end; $$ language plpgsql;") cur.execute("create or replace function setAccount(group_name groups.groupname%type, account_name account.accountname%type, subgroup_name subgroups.subgroupname%type, opening_balance account.openingbalance%type, opening_date account.openingdate%type, cur_bal account.balance%type, suggested_code account.accountcode%type) returns bit as $$ declare group_code groups.groupcode%type; subgroup_code subgroups.subgroupcode%type; account_code account.accountcode%type; maxcode integer; begin group_code := getGroupByName(group_name); if suggested_code =-1 then maxcode := (select count(accountcode) from account); if maxcode= 0 then suggested_code := maxcode; else maxcode := (select max(accountcode) from account); end if; maxcode:= maxcode +1; suggested_code := maxcode; end if; if subgroup_name = 'null' then insert into account (accountcode,groupcode,subgroupcode,accountname,openingbalance,openingdate,balance) values (suggested_code,group_code,null,account_name,opening_balance,opening_date,cur_bal); else subgroup_code := getSubGroupByName(subgroup_name); if subgroup_code is null then perform setSubGroup(group_name,subgroup_name); subgroup_code := getSubGroupByName(subgroup_name); end if; insert into account (accountcode,groupcode,subgroupcode,accountname,openingbalance,openingdate,balance) values (suggested_code,group_code,subgroup_code,account_name,opening_balance,opening_date,cur_bal); end if; select accountcode into account_code from account where accountname = account_name; if account_code is null then return 0; else return 1; end if; end; $$ language plpgsql;") cur.execute("create or replace function getAccountsByGroupCode(group_code groups.groupcode%type, out accountname text) returns setof text as $$ begin return query select acc.accountname from account as acc where groupcode =group_code order by acc.accountname; end; $$ language plpgsql;") cur.execute("create or replace function getSubGroupByAccount(acc_name account.accountname%type, out subgroupname text) returns setof text as $$ begin return query select gs.subgroupname from group_subgroup_account as gs where gs.accountname = acc_name;end;$$ language plpgsql;") cur.execute("create or replace function getSuggestedCode(acc_code text, out suggested_code integer) returns integer as $$ begin select count(accountcode) into suggested_code from account where accountcode like acc_code||'%'; end; $$ language plpgsql;") cur.execute("create or replace function accountExists(account_name account.accountname%type) returns bit as $$ declare account_counter bit; begin select count(accountname) into account_counter from account where upper(accountname) = upper(account_name); return account_counter; end; $$ language plpgsql; ") cur.execute("create or replace function subgroupExists(subgroup_name subgroups.subgroupname%type) returns bit as $$ declare subgroups_counter bit; begin select count(subgroupname) into subgroups_counter from subgroups where subgroupname = subgroup_name; return subgroups_counter; end; $$ language plpgsql;") cur.execute("create or replace function getTotalDrOpeningBalance(out totaldrbal float) returns float as $$ begin select sum(openingbalance) into totaldrbal from group_subgroup_account where groupname in ('Current Assets','Fixed Assets','Investment','Loans(Asset)','Miscellaneous Expenses(Asset)'); end; $$ language plpgsql;") cur.execute("create or replace function getTotalCrOpeningBalance(out totalcrbal float) returns float as $$ begin select sum(openingbalance) into totalcrbal from group_subgroup_account where groupname in ('Corpus','Capital','Current Liability','Loans(Liability)','Reserves'); end; $$ language plpgsql;") cur.execute("create or replace function getAccount(searchFlag integer , searchValue text, out groupname text, out subgroupname text, out accountcode text, out accountname text,out openingBalance float) returns record as $$ begin if searchFlag = 1 then select gsa.groupname,gsa.subgroupname,gsa.accountcode, gsa.accountname,gsa.openingbalance into groupname,subgroupname,accountcode,accountname,openingBalance from group_subgroup_account as gsa where gsa.accountcode = searchValue; else select gsa.groupname,gsa.subgroupname,gsa.accountcode, gsa.accountname,gsa.openingbalance into groupname,subgroupname,accountcode,accountname,openingBalance from group_subgroup_account as gsa where gsa.accountname = searchValue; end if; end; $$ language plpgsql;") cur.execute("create or replace function editAccount(account_name account.accountname%type,account_code account.accountcode%type,new_opening_balance account.openingbalance%type, out currentBalance float) returns float as $$ declare old_opening_balance account.openingBalance%type; current_balance account.balance%type; final_balance account.balance%type; begin select openingbalance into old_opening_balance from account where accountcode = account_code; select balance into current_balance from account where accountcode = account_code; if old_opening_balance = new_opening_balance then update account set accountname = account_name where accountcode = account_code; else final_balance := (new_opening_balance - old_opening_balance) + current_balance; update account set accountname = account_name , openingbalance = new_opening_balance , balance = final_balance where accountcode = account_code; end if; select a.balance into currentBalance from account as a where a.accountcode = account_code; end; $$ language plpgsql;") #cur.execute("create or replace function getContra(out accountnames text) returns setof text as $$ begin return query select sga.accountname from group_subgroup_account as sga where subgroupname in ('Cash','Bank'); end; $$ language plpgsql;") #cur.execute("create or replace function getJournal(out accountnames text) returns setof text as $$ begin return query select sga.accountname from group_subgroup_account as sga where subgroupname not in ('Cash','Bank'); end; $$ language plpgsql;") cur.execute("create or replace function getContra(out accountnames text) returns setof text as $$ begin return query select gsa.accountname from group_subgroup_account as gsa where subgroupcode in (1,2) order by gsa.accountname; end; $$ language plpgsql;") cur.execute("create or replace function getJournal(out accountnames text) returns setof text as $$ begin return query select gsa.accountname from group_subgroup_account as gsa where subgroupname is null or subgroupcode not in (1,2) order by gsa.accountname; end; $$ language plpgsql;") #cur.execute("create or replace function getReceivables(dr_cr_flag text, out accountnames text) returns setof text as $$ begin if dr_cr_flag = 'Cr' then return query select gsa.accountname from group_subgroup_account as gsa where subgroupname not in ('Cash','Bank') or groupname in ('Loans(Asset)','Investment','Direct Income','Indirect Income') order by gsa.accountname; else return query select gsa.accountname from group_subgroup_account as gsa where subgroupname in ('Cash','Bank'); end if; end; $$ language plpgsql;") #cur.execute("create or replace function getPayments(dr_cr_flag text, out accountnames text) returns setof text as $$ begin if dr_cr_flag = 'Cr' then return query select gsa.accountname from group_subgroup_account as gsa where subgroupname in ('Cash','Bank'); else return query select gsa.accountname from group_subgroup_account as gsa where subgroupname not in ('Cash','Bank') or groupname in ('Direct Expense','Indirect Expense','Current Liability','Loans(Liability)'); end if; end; $$ language plpgsql;") cur.execute("create or replace function getReceivables(dr_cr_flag text, out accountnames text) returns setof text as $$ begin if dr_cr_flag = 'Cr' then return query select gsa.accountname from group_subgroup_account as gsa where subgroupcode not in (1,2) or subgroupname is null order by gsa.accountname; else return query select gsa.accountname from group_subgroup_account as gsa where subgroupcode in (1,2) order by gsa.accountname; end if; end; $$ language plpgsql;") cur.execute("create or replace function getPayments(dr_cr_flag text, out accountnames text) returns setof text as $$ begin if dr_cr_flag = 'Cr' then return query select gsa.accountname from group_subgroup_account as gsa where subgroupcode in (1,2) order by gsa.accountname; else return query select gsa.accountname from group_subgroup_account as gsa where subgroupcode not in (1,2) or subgroupname is null order by gsa.accountname; end if; end; $$ language plpgsql;") cur.execute("create or replace function getDebitNote(dr_cr_flag text, out accountnames text) returns setof text as $$ begin if dr_cr_flag = 'Cr' then return query select gsa.accountname from group_subgroup_account as gsa order by gsa.accountname; else return query select gsa.accountname from group_subgroup_account as gsa order by gsa.accountname; end if; end; $$ language plpgsql;") cur.execute("create or replace function getCreditNote(dr_cr_flag text, out accountnames text) returns setof text as $$ begin if dr_cr_flag = 'Cr' then return query select gsa.accountname from group_subgroup_account as gsa order by gsa.accountname; else return query select gsa.accountname from group_subgroup_account as gsa order by gsa.accountname; end if; end; $$ language plpgsql;") cur.execute("create or replace function getSales(dr_cr_flag text, out accountnames text) returns setof text as $$ begin if dr_cr_flag = 'Cr' then return query select gsa.accountname from group_subgroup_account as gsa order by gsa.accountname; else return query select gsa.accountname from group_subgroup_account as gsa order by gsa.accountname; end if; end; $$ language plpgsql;") cur.execute("create or replace function getPurchases(dr_cr_flag text, out accountnames text) returns setof text as $$ begin if dr_cr_flag = 'Cr' then return query select gsa.accountname from group_subgroup_account as gsa order by gsa.accountname; else return query select gsa.accountname from group_subgroup_account as gsa order by gsa.accountname; end if; end; $$ language plpgsql;") cur.execute("create or replace function getSalesReturn(dr_cr_flag text, out accountnames text) returns setof text as $$ begin if dr_cr_flag = 'Cr' then return query select gsa.accountname from group_subgroup_account as gsa order by gsa.accountname; else return query select gsa.accountname from group_subgroup_account as gsa order by gsa.accountname; end if; end; $$ language plpgsql;") cur.execute("create or replace function getPurchasesReturn(dr_cr_flag text, out accountnames text) returns setof text as $$ begin if dr_cr_flag = 'Cr' then return query select gsa.accountname from group_subgroup_account as gsa order by gsa.accountname; else return query select gsa.accountname from group_subgroup_account as gsa order by gsa.accountname; end if; end; $$ language plpgsql;") cur.execute("create or replace function calculateBalance(accname account.accountname%type, financial_start date, calculate_from date, calculate_to date, out bal_brought float, out curbal float, out total_CrBal float, out total_DrBal float, out baltype text, out opening_baltype text, out group_name text) returns record as $$ declare opening_balance float;total_dr_upto_from float;total_cr_upto_from float;begin select groupname into group_name from group_subgroup_account where accountname = accname; select openingbalance into opening_balance from group_subgroup_account where accountname = accname;if financial_start = calculate_from then if opening_balance = 0 then bal_brought := opening_balance; end if; if opening_balance < 0 and (group_name = 'Current Assets' or group_name = 'Fixed Assets'or group_name = 'Investment' or group_name = 'Loans(Asset)' or group_name = 'Miscellaneous Expenses(Asset)') then bal_brought := abs(opening_balance); opening_baltype := 'Cr'; baltype := 'Cr'; end if; if opening_balance > 0 and (group_name = 'Current Assets' or group_name = 'Fixed Assets'or group_name = 'Investment' or group_name = 'Loans(Asset)' or group_name = 'Miscellaneous Expenses(Asset)') then bal_brought := opening_balance; opening_baltype := 'Dr';baltype := 'Dr';end if;if opening_balance < 0 and (group_name = 'Corpus' or group_name = 'Capital' or group_name = 'Current Liability' or group_name = 'Loans(Liability)' or group_name = 'Reserves') then bal_brought := abs(opening_balance);opening_baltype := 'Dr';baltype := 'Dr';end if;if opening_balance > 0 and (group_name = 'Corpus' or group_name = 'Capital' or group_name = 'Current Liability' or group_name = 'Loans(Liability)' or group_name = 'Reserves') then bal_brought := opening_balance;opening_baltype := 'Cr';baltype := 'Cr';end if; else total_dr_upto_from := (select sum(amount) from view_voucherbook where account_name = accname and typeflag = 'Dr' and reffdate >= financial_start and reffdate < calculate_from and flag = 1); total_cr_upto_from := (select sum(amount) from view_voucherbook where account_name = accname and typeflag = 'Cr' and reffdate >= financial_start and reffdate < calculate_from and flag = 1); if total_dr_upto_from is null then total_dr_upto_from := 0;end if;if total_cr_upto_from is null then total_cr_upto_from := 0; end if; if opening_balance = 0 then bal_brought := opening_balance;end if;if opening_balance < 0 and (group_name = 'Current Assets' or group_name = 'Fixed Assets'or group_name = 'Investment' or group_name = 'Loans(Asset)' or group_name = 'Miscellaneous Expenses(Asset)') then total_cr_upto_from := total_cr_upto_from + abs(opening_balance);end if;if opening_balance > 0 and (group_name = 'Current Assets' or group_name = 'Fixed Assets'or group_name = 'Investment' or group_name = 'Loans(Asset)' or group_name = 'Miscellaneous Expenses(Asset)') then total_dr_upto_from := total_dr_upto_from + opening_balance;end if;if opening_balance < 0 and (group_name = 'Corpus' or group_name = 'Capital' or group_name = 'Current Liability' or group_name = 'Loans(Liability)' or group_name = 'Reserves') then total_dr_upto_from := total_dr_upto_from + abs(opening_balance);end if;if opening_balance > 0 and (group_name = 'Corpus' or group_name = 'Capital' or group_name = 'Current Liability' or group_name = 'Loans(Liability)' or group_name = 'Reserves') then total_cr_upto_from := total_cr_upto_from + opening_balance; end if; if total_dr_upto_from > total_cr_upto_from then bal_brought := total_dr_upto_from - total_cr_upto_from; baltype := 'Dr';opening_baltype := 'Dr';end if;if total_dr_upto_from < total_cr_upto_from then bal_brought := total_cr_upto_from - total_dr_upto_from; baltype := 'Cr';opening_baltype := 'Cr';end if; end if; total_DrBal := (select sum(amount) from view_voucherbook where typeflag = 'Dr' and account_name = accname and reffdate >= calculate_from and reffdate <= calculate_to and flag = 1); total_CrBal := (select sum(amount) from view_voucherbook where typeflag = 'Cr' and account_name = accname and reffdate >= calculate_from and reffdate <= calculate_to and flag = 1); if total_CrBal is null then total_CrBal := 0; end if; if total_DrBal is null then total_DrBal := 0; end if; if baltype = 'Dr' then total_DrBal := total_DrBal + bal_brought; end if; if baltype = 'Cr' then total_CrBal := total_CrBal + bal_brought; end if; if total_DrBal > total_CrBal then curbal := total_DrBal - total_CrBal; baltype := 'Dr';else curbal := total_CrBal - total_DrBal; baltype := 'Cr';end if;end;$$ language plpgsql;") cur.execute("create or replace function getAllAccounts(out accountname text) returns setof text as $$ begin return query select a.accountname from account as a order by a.accountname; end; $$ language plpgsql;") cur.execute("create or replace function getAccountNameListByName(acc_name account.accountname%type) returns setof account.accountname%type as $$ begin return query select acc.accountname from account as acc where accountname like acc_name||'%'; end; $$ language plpgsql;") cur.execute("create or replace function getAccountCodeListByCode(acc_code account.accountcode%type) returns setof account.accountcode%type as $$ begin return query select acc.accountcode from account as acc where accountcode like acc_code||'%'; end; $$ language plpgsql;") cur.execute("create or replace function getAccountReport(out account_name text, out group_name text, out subgroup_name text) returns setof record as $$ begin return query select gsa.accountname,gsa.groupname,gsa.subgroupname from group_subgroup_account as gsa order by gsa.accountname; end; $$ language plpgsql;") #cur.execute("create or replace function getTransactions(acc_name account.accountname%type, calculate_from date,calculate_to date, out voucher_code integer, out voucher_flag char(10), out reff_date date, out voucher_reference varchar(40), out transaction_amount numeric(13,2), out show_narration text) returns setof record as $$ begin return query select vouchercode, bpchar(typeflag), date(reffdate),reference, amount, narration from view_voucherbook where account_name = acc_name and reffdate >= calculate_from and reffdate < calculate_to order by reffdate; end; $$ language plpgsql;") cur.execute("create or replace function getTransactions(acc_name account.accountname%type, calculate_from date,calculate_to date,project_name projects.projectname%type, out voucher_code integer, out voucher_flag char(10), out reff_date date,out voucher_reference varchar(40), out transaction_amount numeric(13,2),out show_narration text) returns setof record as $$ declare project_code integer;begin if project_name = 'No Project' then return query select vouchercode, bpchar(typeflag), date(reffdate), reference, amount,narration from view_voucherbook where account_name = acc_name and reffdate >= calculate_from and reffdate <= calculate_to and flag = 1 order by reffdate ;else project_code := (select * from getProjectCodeByName(project_name));return query select vouchercode, bpchar(typeflag), date(reffdate), reference, amount,narration from view_voucherbook where account_name = acc_name and projectcode = project_code and reffdate >= calculate_from and reffdate <= calculate_to and flag = 1 order by reffdate ;end if;end; $$ language plpgsql;") cur.execute("create or replace function getParticulars(voucher_code voucher_master.vouchercode%type,type_flag text, out account_name text) returns setof text as $$ begin return query select vvb.account_name from view_voucherbook as vvb where vvb.vouchercode = voucher_code and vvb.typeflag = type_flag and flag = 1 order by vvb.account_name; end;$$ language plpgsql;") cur.execute("create or replace function setVoucherMaster(voucher_reference voucher_master.reference%type, voucher_date voucher_master.voucherdate%type, reff_date voucher_master.reffdate%type, voucher_type voucher_master.vouchertype%type, project_code voucher_master.projectcode%type, voucher_narration voucher_master.narration%type ,voucher_pono voucher_master.pono%type,voucher_podate voucher_master.podate%type, voucher_poamt voucher_master.poamt%type, out success integer)returns integer as $$ begin insert into voucher_master (reference,voucherdate,reffdate,vouchertype,flag,projectcode,narration,pono,podate,poamt,lockflag) values (voucher_reference,voucher_date,reff_date,voucher_type,1,project_code,voucher_narration,voucher_pono,voucher_podate,voucher_poamt,0);select max(vouchercode) into success from voucher_master;end;$$ language plpgsql;") cur.execute("create or replace function setVoucherDetails(voucher_code voucher_details.vouchercode%type,type_flag voucher_details.typeflag%type, account_code voucher_details.accountcode%type,account_amount voucher_details.amount%type, out success integer) returns integer as $$ begin insert into voucher_details (vouchercode,typeflag,accountcode,amount) values (voucher_code,type_flag,account_code,account_amount);success = 1;end;$$ language plpgsql;") cur.execute("create or replace function getAccountCode(account_name account.accountname%type ,out account_code text) returns text as $$ begin select a.accountcode into account_code from account as a where a.accountname = account_name;end;$$ language plpgsql;") cur.execute("create or replace function getClearedAccounts(acc_name view_voucherbook.account_name%type, voucher_code view_voucherbook.vouchercode%type, out success boolean) returns boolean as $$ declare acc_test account.accountname%type;begin select accountname into acc_test from bankrecon where accountname = acc_name and vouchercode = voucher_code;success := found;end;$$ language plpgsql;") cur.execute("create or replace function setBankRecon(voucher_code bankrecon.vouchercode%type,reff_date bankrecon.reffdate%type, acc_name bankrecon.accountname%type, dr_amount bankrecon.dramount%type, cr_amount bankrecon.cramount%type, clearance_date bankrecon.clearancedate%type, memo_recon bankrecon.memo%type, out success boolean) returns boolean as $$ declare acc_test account.accountname%type; v_code bankrecon.vouchercode%type; begin select accountname, vouchercode into acc_test, v_code from bankrecon where accountname = acc_name and vouchercode = voucher_code; if acc_test is null and v_code is null then if dr_amount = 0 then insert into bankrecon( vouchercode,reffdate, accountname,dramount,cramount,clearancedate,memo ) values (voucher_code,reff_date,acc_name,0,cr_amount,clearance_date,memo_recon); else insert into bankrecon( vouchercode,reffdate, accountname,dramount,cramount,clearancedate,memo ) values (voucher_code,reff_date,acc_name,dr_amount,0,clearance_date,memo_recon); end if; else delete from bankrecon where accountname = acc_name and vouchercode = voucher_code; if dr_amount = 0 then insert into bankrecon( vouchercode,reffdate, accountname,dramount,cramount,clearancedate,memo ) values (voucher_code,reff_date,acc_name,0,cr_amount,clearance_date,memo_recon); else insert into bankrecon( vouchercode,reffdate, accountname,dramount,cramount,clearancedate,memo ) values (voucher_code,reff_date,acc_name,dr_amount,0,clearance_date,memo_recon); end if; end if; success := found;end;$$ language plpgsql;") cur.execute("create or replace function getClearanceDate(acc_name bankrecon.accountname%type, voucher_code bankrecon.vouchercode%type, out c_date date, out memo_recon text) returns setof record as $$ begin return query select date(clearancedate), memo from bankrecon where accountname = acc_name and vouchercode = voucher_code;end;$$ language plpgsql;") cur.execute("create or replace function getAllTransactions(acc_name account.accountname%type, financial_start date, calculate_to date, out voucher_code integer, out voucher_flag char(10), out reff_date date,out voucher_reference varchar(40), out transaction_amount numeric(13,2)) returns setof record as $$ begin return query select vouchercode, bpchar(typeflag), date(reffdate), reference, amount from view_voucherbook where account_name = acc_name and reffdate >= financial_start and reffdate <= calculate_to order by reffdate;end;$$ language plpgsql;") cur.execute("create or replace function updateOrgDetails(org_name organisation.orgname%type,org_addr organisation.orgaddr%type,org_city organisation.orgcity%type,org_pin organisation.orgpincode%type,org_state organisation.orgstate%type,org_country organisation.orgcountry%type,org_telno organisation.orgtelno%type,org_fax organisation.orgfax%type,org_website organisation.orgwebsite%type,org_email organisation.orgemail%type,org_pan organisation.orgpan%type,org_mvat organisation.orgmvat%type,org_stax organisation.orgstax%type,org_regno organisation.orgregno%type,org_regdate organisation.orgregdate%type,org_fcrano organisation.orgfcrano%type, org_fcradate organisation.orgfcradate%type, out success integer) returns integer as $$ begin update organisation set orgname = org_name, orgaddr = org_addr, orgcity=org_city, orgpincode=org_pin,orgstate=org_state,orgcountry=org_country,orgtelno=org_telno,orgfax=org_fax,orgwebsite=org_website,orgemail=org_email,orgpan=org_pan,orgmvat=org_mvat,orgstax=org_stax,orgregno=org_regno,orgregdate=org_regdate,orgfcrano=org_fcrano,orgfcradate=org_fcradate; success := 1;end;$$ language plpgsql;") cur.execute("create or replace function getOnlyClearedTransactions(acc_name view_voucherbook.account_name%type,voucher_code view_voucherbook.vouchercode%type, financial_start date, calculate_to date, out success integer) returns integer as $$ declare acc_test account.accountname%type; begin success := 1; select accountname into acc_test from bankrecon where accountname = acc_name and vouchercode = voucher_code and (clearancedate >= financial_start and clearancedate <= calculate_to); if found then success := -1; end if; select accountname into acc_test from bankrecon where accountname = acc_name and vouchercode = voucher_code and clearancedate > calculate_to; if found then success := 0; end if; end; $$ language plpgsql;") cur.execute("create or replace function getAllBankAccounts(out accountnames text) returns setof text as $$ begin return query select gsa.accountname from group_subgroup_account as gsa where subgroupname ='Bank' order by gsa.accountname;end;$$ language plpgsql;") cur.execute("create or replace function searchVouchers(searchFlag integer,refno voucher_master.reference%type, fromdate voucher_master.reffdate%type, todate voucher_master.reffdate%type, v_narration voucher_master.narration%type, totalamount numeric(13,2),out voucher_code integer, out reference_number varchar(40), out reff_date date,out voucher_type char(10),out voucher_narration text,out total_amount numeric(13,2),out lock_flag integer) returns setof record as $$ begin if searchFlag = 1 then return query select vouchercode,reference,date(reffdate),bpchar(vouchertype), narration, sum(amount),lockflag from view_voucherbook where reference = refno and flag =1 and typeflag = 'Cr' group by vouchercode, reference,reffdate,vouchertype,narration,lockflag order by reffdate; end if; if searchFlag = 2 then return query select vouchercode,reference,date(reffdate),bpchar(vouchertype), narration, sum(amount),lockflag from view_voucherbook where reffdate >= fromdate and reffdate <= todate and flag = 1 and typeflag = 'Cr' group by vouchercode, reference,reffdate,vouchertype,narration,lockflag order by reffdate; end if; if searchFlag = 3 then return query select vouchercode,reference,date(reffdate),bpchar(vouchertype), narration, sum(amount),lockflag from view_voucherbook where flag = 1 and (narration like v_narration||'%' or narration like '%'||v_narration||'%' or narration like '%'||v_narration) and typeflag = 'Cr' group by vouchercode, reference,reffdate,vouchertype,narration,lockflag order by reffdate ; end if; if searchFlag = 4 then return query select vouchercode,reference,date(reffdate),bpchar(vouchertype), narration, sum(amount),lockflag from view_voucherbook where flag = 1 and typeflag = 'Cr' group by vouchercode, reference, reffdate, vouchertype, narration,lockflag having sum(amount) = totalamount order by reffdate; end if; end;$$ language plpgsql;") cur.execute("create or replace function getVoucherMaster(voucher_code voucher_master.vouchercode%type, out voucher_reference varchar(40), out reff_date date, out voucher_type varchar(40), out voucher_narration text, out po_no text, out po_date date, out po_amt numeric(13,2),out project_code integer,out lock_flag integer) returns setof record as $$begin return query select reference,date(reffdate),vouchertype, narration ,po_no ,po_date ,po_amt, projectcode, lockflag from voucher_master where vouchercode = voucher_code and flag = 1 order by reffdate;end;$$ language plpgsql;") cur.execute("create or replace function getVoucherDetails(voucher_code voucher_master.vouchercode%type ,out accountname text, out transactionFlag char(10), out transactionamount numeric(13,2)) returns setof record as $$ begin return query select account_name,bpchar(typeflag), amount from view_voucherbook where vouchercode = voucher_code and flag = 1 order by typeflag desc;end;$$ language plpgsql;") cur.execute("create or replace function editVoucherMaster(voucher_code voucher_master.vouchercode%type,reff_date voucher_master.reffdate%type,voucher_projectcode voucher_master.projectcode%type,voucher_narration voucher_master.narration%type, out success boolean) returns boolean as $$ begin update voucher_master set reffdate = reff_date ,projectcode = voucher_projectcode, narration = voucher_narration where vouchercode =voucher_code;success := found;end;$$ language plpgsql;") cur.execute("create or replace function editVoucherDetails(voucher_code voucher_master.vouchercode%type,account_name account.accountname%type, type_flag char(10), transaction_amount voucher_details.amount%type ,out success boolean) returns boolean as $$ declare account_code account.accountcode%type;begin account_code := (select accountcode from account where accountname = account_name);insert into voucher_details(vouchercode,accountcode,typeflag,amount) values (voucher_code,account_code,type_flag,transaction_amount);success := found;end;$$ language plpgsql;") cur.execute("create or replace function deleteVoucherDetails(voucher_code voucher_master.vouchercode%type ,out success boolean) returns boolean as $$ begin delete from voucher_details where vouchercode = voucher_code;success := found; end; $$ language plpgsql;") cur.execute("create or replace function getVoucherAmount(voucher_code voucher_master.vouchercode%type, out totalamount numeric(13,3)) returns numeric as $$ begin totalamount := (select sum(amount) as totalamount from view_voucherbook where vouchercode = voucher_code and typeflag = 'Cr'); end; $$ language plpgsql;") cur.execute("create or replace function deleteVoucher(voucher_code voucher_master.vouchercode%type, out success boolean) returns boolean as $$ begin update voucher_master set flag = 0 where vouchercode = voucher_code; success := found; end; $$ language plpgsql;") cur.execute("create or replace function setProject(project_name projects.projectname%type, project_amt projects.sanctionedamount%type , out success boolean) returns boolean as $$ begin insert into projects (projectname, sanctionedamount) values (project_name,project_amt); success := found; end; $$ language plpgsql;") cur.execute("create or replace function getAllProjects(out project_code integer, out project_name text) returns setof record as $$ begin return query select projectcode,projectname from projects order by projectname;end;$$ language plpgsql;") cur.execute("create or replace function getProjectCodeByName(project_name projects.projectname%type , out project_code integer) returns integer as $$ begin select p.projectcode into project_code from projects as p where p.projectname = project_name; end; $$ language plpgsql;") cur.execute("create or replace function getProjectAccounts(project_name projects.projectname%type, out accname text) returns setof text as $$ declare project_code projects.projectcode%type; begin project_code := (select projectcode from projects where projectname = project_name); return query select distinct(account_name) from view_voucherbook where projectcode = project_code and flag = 1 order by account_name;end; $$ language plpgsql;") cur.execute("create or replace function getProjectStatement(project_name projects.projectname%type, accname account.accountname%type,financial_start date, calculate_from date, calculate_to date , out totalDr float, out totalCr float ) returns record as $$ declare project_code projects.projectcode%type; begin project_code := (select projectcode from projects where projectname = project_name);totalDr := (select sum(amount) from view_voucherbook where projectcode = project_code and account_name = accname and typeflag = 'Dr' and flag = 1); totalCr := (select sum(amount) from view_voucherbook where projectcode = project_code and account_name = accname and typeflag = 'Cr' and flag = 1); if totalDr is null then totalDr := 0.00; end if; if totalCr is null then totalCr := 0.00;end if;end; $$ language plpgsql;") cur.execute("create or replace function getListOfProject(out projectname text, out sanctionedamount numeric(13,2)) returns setof record as $$ begin return query select prj.projectname,prj.sanctionedamount from projects as prj order by prj.projectname; end; $$ language plpgsql;") cur.execute("create or replace function DuplicateProject(project_name projects.projectname%type) returns bit as $$ declare project_counter bit; begin select count(projectname) into project_counter from projects where projectname = project_name; return project_counter; end; $$ language plpgsql;") cur.execute("create or replace function deleteclearedrecon(acc_name view_voucherbook.account_name%type, voucher_code view_voucherbook.vouchercode%type, Cdate bankrecon.clearancedate%type, out success boolean) returns boolean as $$ begin delete from bankrecon where accountname = acc_name and vouchercode = voucher_code and clearancedate = Cdate;success := found; end; $$ language plpgsql;") cur.execute("create or replace function getLastReffDate(financial_start date, voucher_type view_voucherbook.vouchertype%type, out reff_date date) returns date as $$ declare maxcode integer; begin maxcode := (select count(vouchercode) from view_voucherbook where vouchertype = voucher_type);if maxcode > 0 then select max(date(reffdate)) into reff_date from view_voucherbook where vouchertype = voucher_type;else reff_date := financial_start; end if; end; $$ language plpgsql;") cur.execute("create or replace function getLastReference(voucher_type view_voucherbook.vouchertype%type,out reffno varchar) returns varchar as $$ declare maxcode integer; reff varchar; begin maxcode := (select count(vouchercode) from view_voucherbook where vouchertype = voucher_type); reff := (select max(reference) from view_voucherbook where vouchertype = voucher_type); if maxcode > 0 then select max(reference) into reffno from view_voucherbook where reffdate = (select max(date(reffdate)) from view_voucherbook where vouchertype = voucher_type) and vouchertype = voucher_type; else reffno := reff; end if; end; $$ language plpgsql;") cur.execute("create or replace function setGenericProduct( genprod_code genericproduct.genprodcode%type,prod_name genericproduct.prodname%type, vendor_name genericproduct.vendorname%type, prod_desc genericproduct.proddesc%type, sale_price genericproduct.saleprice%type, open_qty genericproduct.openqty%type, u_o_m genericproduct.uom%type) returns bit as $$ begin insert into genericproduct ( genprodcode, prodname, vendorname, proddesc, saleprice, openqty, curqty, uom) values (genprod_code, prod_name, vendor_name, prod_desc, sale_price, open_qty, open_qty, u_o_m); return 1; end; $$ language plpgsql;") cur.execute("create or replace function searchProductDetails(searchFlag integer, prod_name genericproduct.prodname%type,prod_code genericproduct.genprodcode%type, out product_name text, out vendor_name text, out prod_desc text, out sale_price numeric(13,2) , out open_qty integer, out cur_qty integer, out u_o_m text ) returns setof record as $$ begin if searchFlag = 1 then return query select prodname, vendorname, proddesc, saleprice, openqty, curqty, uom from genericproduct where genprodcode = prod_code; end if; if searchFlag = 2 then return query select prodname,vendorname, proddesc, saleprice, openqty, curqty, uom from genericproduct where prodname = prod_name order by prodname; end if; end; $$ language plpgsql;") cur.execute("create or replace function setStockQty(prod_code stockqty.prodcode%type, transaction_date stockqty.transactiondate%type, stock_quantity stockqty.quantity%type, bill_no stockqty.billno%type, stock_flag stockqty.stockflag%type, out success integer) returns integer as $$ begin insert into stockqty(prodcode, transactiondate, quantity, billno, stockflag) values(prod_code, transaction_date, stock_quantity, bill_no, stock_flag); success = 1; end; $$ language plpgsql;") cur.execute("create or replace function curStockQty(searchFlag integer,searchValue text,stock_code stockqty.stockcode%type, out stockcode integer,out prodcode text, out quantity integer, out stockflag integer) returns record as $$ begin if searchFlag = 1 then select s.stockcode,s.prodcode,s.quantity,s.stockflag into stockcode,prodcode, quantity,stockflag from stockqty as s where s.prodcode = searchValue and s.stockcode=stock_code; else select s.stockcode,s.prodcode,s.quantity,s.stockflag into stockcode,prodcode, quantity, stockflag from stockqty as s where s.stockcode=stock_code and s.prodcode=(select genprodcode from genericproduct where prodname = searchValue); end if; end; $$ language plpgsql;") cur.execute("create or replace function getCashFlowOpening(out accountname text, out opening_balance numeric(13,2)) returns setof record as $$ begin return query select gsa.accountname, gsa.openingbalance from group_subgroup_account as gsa where gsa.subgroupname in ('Bank','Cash') order by gsa.accountname;end;$$ language plpgsql;") cur.execute("create or replace function getCashFlowReceivedAccounts(cfaccount account.accountname%type, cbaccount account.accountname%type, startdate date, enddate date, out cfamount numeric(13,2)) returns numeric as $$ begin select sum(vvb.amount) into cfamount from view_voucherbook as vvb where account_name = cfaccount and vouchercode in (select vouchercode from view_voucherbook where typeflag = 'Dr' and account_name = cbaccount and reffdate >= startdate and reffdate <= enddate and flag = 1) group by vvb.account_name; end; $$ language plpgsql;") cur.execute("create or replace function getCashFlowPaidAccounts(cfaccount account.accountname%type, cbaccount account.accountname%type, startdate date, enddate date, out cfamount numeric(13,2)) returns numeric as $$ begin select sum(vvb.amount) into cfamount from view_voucherbook as vvb where account_name = cfaccount and vouchercode in (select vouchercode from view_voucherbook where typeflag = 'Cr' and account_name = cbaccount and reffdate >= startdate and reffdate <= enddate and flag = 1) group by vvb.account_name; end; $$ language plpgsql;") cur.execute("create or replace function getProjectNameByCode(project_code projects.projectcode%type , out project_name varchar) returns varchar as $$ begin select p.projectname into project_name from projects as p where p.projectcode = project_code; end; $$ language plpgsql;") cur.execute("create or replace function hasTransactions(accname account.accountname%type, out success boolean) returns boolean as $$ declare voucherCounter integer; begin voucherCounter := (select count(vouchercode) from view_voucherbook where account_name = accname); if voucherCounter > 0 then success := TRUE; end if; if voucherCounter = 0 then success := FALSE; end if; end; $$ language plpgsql;") cur.execute("create or replace function hasOpeningBalance(account_name account.accountname%type, out success boolean ) returns boolean as $$ declare opening_balance account.openingbalance%type; begin select openingbalance into opening_balance from account where accountname = account_name; if opening_balance = 0 then success := FALSE; else success := TRUE; end if; end; $$ language plpgsql;") cur.execute("create or replace function deleteAccount(account_name account.accountname%type, out success boolean ) returns boolean as $$ begin delete from account where accountname = account_name; success := found; end; $$ language plpgsql;") cur.execute("create or replace function getAccountsByGroup(group_name groups.groupname%type, out account_name text) returns setof text as $$ begin return query select gsa.accountname from group_subgroup_account as gsa where groupname = group_name; end; $$ language plpgsql;") cur.execute("create or replace function getOrganizationType (out isngo boolean ) returns boolean as $$begin perform groupname from groups where groupname = 'Corpus';isngo:= found;end;$$ language plpgsql;") cur.execute("create or replace function getRoFlag (out ro_flag integer) returns integer as $$begin select roflag into ro_flag from organisation;end;$$ language plpgsql;") cur.execute("create or replace function setRoFlag(ro_flag organisation.roflag%type, out success boolean) returns boolean as $$begin update organisation set roflag = ro_flag;success := true;end;$$ language plpgsql;") cur.execute("create or replace function getBooksClosed(out book_closed integer) returns integer as $$begin select booksclosedflag into book_closed from organisation;end;$$language plpgsql;") cur.execute("create or replace function setBooksClosed(books_closed organisation.booksclosedflag%type, out success integer) returns integer as $$begin update organisation set booksclosedflag = books_closed;success := 1;end;$$language plpgsql;") cur.execute("create or replace function vouchersafterdate(reff_date voucher_master.reffdate%type, out vcount integer) returns integer as $$\ begin\ vcount :=( select count(vouchercode) from voucher_master where reffdate > reff_date);\ end;\ $$ language plpgsql;") cur.execute("create or replace function removeuser(user_name users.username%type, out success boolean) returns boolean as $$\ begin\ delete from users where username = user_name; \ success:=found; \ end;\ $$ language plpgsql;") cur.execute("create or replace function setLockFlag(voucher_code voucher_master.vouchercode%type,lock_flag voucher_master.lockflag%type, out success boolean) returns boolean as $$begin update voucher_master set lockflag = lock_flag where vouchercode = voucher_code;success := true;end;$$ language plpgsql;") cur.execute("create or replace function getLockFlag (voucher_code voucher_master.vouchercode%type,out lock_flag integer) returns integer as $$begin select lockflag into lock_flag from voucher_master where voucher_master.vouchercode = voucher_code;end;$$ language plpgsql;") connection.commit() if (organisationType == "Profit Making"): Session.add_all([dbconnect.Groups('Capital',''),dbconnect.Groups('Current Assets',''),dbconnect.Groups('Current Liability',''),dbconnect.Groups('Direct Income','Income refers to consumption opportunity gained by an entity within a specified time frame. Examples for Income are comision,discount received etc'),dbconnect.Groups('Direct Expense','This are the expenses to be incurred for operating the buisness.Examples of expensestrftime pygtks are administrative expense,selling expenses etc.'),dbconnect.Groups('Fixed Assets',''),dbconnect.Groups('Indirect Income','Income refers to consumption opportunity gained by an entity within a specified time frame. Examples for Income are comision,discount received etc'),dbconnect.Groups('Indirect Expense','This are the expenses to be incurred for operating the buisness.Examples of expensestrftime pygtks are administrative expense,selling expenses etc.'),dbconnect.Groups('Investment',''),dbconnect.Groups('Loans(Asset)',''),dbconnect.Groups('Loans(Liability)',''),dbconnect.Groups('Reserves',''),dbconnect.Groups('Miscellaneous Expenses(Asset)','')]) Session.commit() else: Session.add_all([dbconnect.Groups('Corpus',''),dbconnect.Groups('Current Assets',''),dbconnect.Groups('Current Liability',''),dbconnect.Groups('Direct Income','Income refers to consumption opportunity gained by an entity within a specified time frame. Examples for Income are comision,discount received etc'),dbconnect.Groups('Direct Expense','This are the expenses to be incurred for operating the buisness.Examples of expensestrftime pygtks are administrative expense,selling expenses etc.'),dbconnect.Groups('Fixed Assets',''),dbconnect.Groups('Indirect Income','Income refers to consumption opportunity gained by an entity within a specified time frame. Examples for Income are comision,discount received etc'),dbconnect.Groups('Indirect Expense','This are the expenses to be incurred for operating the buisness.Examples of expensestrftime pygtks are administrative expense,selling expenses etc.'),dbconnect.Groups('Investment',''),dbconnect.Groups('Loans(Asset)',''),dbconnect.Groups('Loans(Liability)',''),dbconnect.Groups('Reserves',''),dbconnect.Groups('Miscellaneous Expenses(Asset)','')]) Session.commit() Session.add_all([dbconnect.subGroups('2','Bank'),dbconnect.subGroups('2','Cash'),dbconnect.subGroups('2','Inventory'),dbconnect.subGroups('2','Loans & Advance'),dbconnect.subGroups('2','Sundry Debtors'),dbconnect.subGroups('3','Provisions'),dbconnect.subGroups('3','Sundry Creditors for Expense'),dbconnect.subGroups('3','Sundry Creditors for Purchase'),dbconnect.subGroups('6','Building'),dbconnect.subGroups('6','Furniture'),dbconnect.subGroups('6','Land'),dbconnect.subGroups('6','Plant & Machinery'),dbconnect.subGroups('9','Investment in Shares & Debentures'),dbconnect.subGroups('9','Investment in Bank Deposits'),dbconnect.subGroups('11','Secured'),dbconnect.subGroups('11','Unsecured')]) Session.commit() Session.add_all([dbconnect.Flags(None,'mandatory'),dbconnect.Flags(None,'automatic')]) Session.commit() Session.close() openStock = ['Direct Expense', 'No Sub-Group', '', 'Opening Stock', 'automatic', '0.00', '0.00', ''] closeStock = ['Current Assets', 'Inventory', '', 'Closing Stock', 'automatic', '0.00', '0.00', ''] BegStock = ['Current Assets', 'Inventory', '', 'Stock at the Beginning', 'automatic', '0.00', '0.00', ''] if (organisationType == "Profit Making"): newqueryParams2= ['Direct Income', 'No Sub-Group', '', 'Profit & Loss', 'automatic', '0.00', '0.00', ''] else: newqueryParams2= ['Direct Income', 'No Sub-Group', '', 'Income & Expenditure', 'automatic', '0.00', '0.00', ''] account.xmlrpc_setAccount(openStock, self.client_id) account.xmlrpc_setAccount(BegStock, self.client_id) account.xmlrpc_setAccount(closeStock, self.client_id) account.xmlrpc_setAccount(newqueryParams2, self.client_id) return True,self.client_id def xmlrpc_getRollOverStatus(self,client_id): """ purpose: gets the status of organization if it has already been rolled over. returns 1 if rollower has been done or 0 if rollower is pending. """ result = dbconnect.execproc("getRoFlag",dbconnect.engines[client_id] ,[] ) roRow = result.fetchone() roStatus = roRow['ro_flag'] return roStatus def xmlrpc_getClosedBooksStatus(self,client_id): """ purpose: gets the status of organization if it has already been rolled over. returns 1 if rollower has been done or 0 if rollower is pending. """ result = dbconnect.execproc("getBooksClosed",dbconnect.engines[client_id] ,[] ) roRow = result.fetchone() roStatus = roRow['book_closed'] return roStatus def xmlrpc_setRollOverStatus(self,queryParams,client_id): """ purpose: sets the status of organization if it has already been rolled over. returns 1 if rollower has been done or 0 if rollower is pending. """ try: result = dbconnect.execproc("setRoFlag", dbconnect.engines[client_id],queryParams) return True except: return False def xmlrpc_setClosedBooksStatus(self,queryParams,client_id): """ purpose: sets the status of organization if it has already been rolled over. returns 1 if rollower has been done or 0 if rollower is pending. """ try: result = dbconnect.execproc("setBooksClosed", dbconnect.engines[client_id],queryParams) return True except: return False def xmlrpc_deleteOrganisation(self,queryParams,client_id): """ purpose: deletes an existing organization from the database, based on the Organization name and it's financial year. description: The function will delete an existing organization from the server. it will first remove the entry for the said organization for the said financial year from the gnukhata.xml file. Next, it will delete the database from the postgres server. The function takes one arguement apart from the standard client_id The arguement queryParams is a list containing organization name at position0, financialStart at position 1 and financialEnd at position 2. First the function will open the gnukhata.xml file and get the list of all orgs (children). Then the function will traverse through all elements to find out one which matches organization name, financialStart and end (meaning all the values of the queryParams). When the match is found, that very organization (node) will be removed from the list of nodes. Finally the file will be saved. Meanwhile just before the deletion is done we store the name of the actual database in a variable. Following the deletion of the node from gnukhata.xml, we will also drop the respective database. Finally the function will return true if the entire process is successful. """ #if the current user is admin (ie. dbconnect.user_roles[client_id] == -1 ) then only this method will delete the organisation. if dbconnect.user_roles[client_id] == -1: confData = dbconnect.getConf() gkconf = et.parse(confData['xmlpath']) gkroot = gkconf.getroot() orgs = gkroot.getchildren() delIndex = 0 dbname = "" for org in orgs: orgname = org.find("orgname") financialyear_from = org.find("financial_year_from") financialyear_to = org.find("financial_year_to") if orgname.text == queryParams[0] and financialyear_from.text == queryParams[1] and financialyear_to.text == queryParams[2]: dbnode = org.find("dbname") dbname = dbnode.text break else: delIndex = delIndex +1 orgs.remove(orgs[delIndex]) #save the file with the fresh xml nodes. gkconf.write(confData['xmlpath']) #now drop the database os.system("dropdb " + dbname) return True #create aTn instance of the class to be published as the service. gnukhata = gnukhata() organisation = rpc_organisation.organisation() gnukhata.putSubHandler('organisation',organisation) groups=rpc_groups.groups() gnukhata.putSubHandler('groups',groups) account=rpc_account.account() gnukhata.putSubHandler('account',account) transaction=rpc_transaction.transaction() gnukhata.putSubHandler('transaction',transaction) data=rpc_data.data() gnukhata.putSubHandler('data',data) reports=rpc_reports.reports() gnukhata.putSubHandler('reports',reports) user=rpc_user.user() gnukhata.putSubHandler('user',user) customizable = rpc_customizable.customizable() gnukhata.putSubHandler('customizable',customizable) getaccountsbyrule=rpc_getaccountsbyrule.getaccountsbyrule() gnukhata.putSubHandler('getaccountsbyrule',getaccountsbyrule) inventory=rpc_inventory.inventory() gnukhata.putSubHandler('inventory',inventory) def rungnukhata(): confData = dbconnect.getConf() print "initialising application" #the code to daemonise published instance. print "starting server" # Daemonizing GNUKhata # Accept commandline arguments # A workaround for debugging def usage(): print "Usage: %s [-d|--debug] [-h|--help]\n" % (sys.argv[0]) print "\t-d (--debug)\tStart server in debug mode. Do not fork a daemon." print "\t-d (--help)\tShow this help" try: opts, args = getopt.getopt(sys.argv[1:], "hd", ["help","debug"]) except getopt.GetoptError: usage() os._exit(2) debug = 0 for opt, arg in opts: if opt in ("-h", "--help"): usage() os.exit(0) elif opt in ("-d", "--debug"): debug = 1 #print "debug value is " + str(debug) # Do not fork if we are debug mode if debug == 0: try: pid = os.fork() # print str(confData['pidfile']) try: pidfile = open(confData['pidfile'] , "w") pidfile.write(str(os.getpid())) pidfile.close() except: print str(confData['pidfile'])+" not writable or does not exist" except OSError, e: raise Exception, "Could not fork a daemon: %s" % (e.strerror) if pid != 0: os._exit(0) # Prevent it from being orphaned os.setsid() # Change working directory to root os.chdir("/") # Change umask os.umask(0) # All prints should be replaced with logging, preferrably into syslog # The standard I/O file descriptors are redirected to /dev/null by default. if (hasattr(os, "devnull")): REDIRECT_TO = os.devnull else: REDIRECT_TO = "/dev/null" # Redirect the standard I/O file descriptors to the specified file. Since # the daemon has no controlling terminal, most daemons redirect stdin, # stdout, and stderr to /dev/null. This is done to prevent side-effects # from reads and writes to the standard I/O file descriptors. # This call to open is guaranteed to return the lowest file descriptor, # which will be 0 (stdin), since it was closed above. os.open(REDIRECT_TO, os.O_RDWR) # standard input (0) # Duplicate standard input to standard output and standard error. os.dup2(0, 1) # standard output (1) os.dup2(0, 2) # standard error (2) #publish the object and make it to listen on the given port through reactor try: reactor.listenTCP(7081, server.Site(gnukhata)) #start the service by running the reactor. reactor.run() except: print "Cannot listen on 7081, please check if another gnukhata instance is running." core_engine-2.6.1-dac679a8ec1cd01924e7b2e80280c270f69b55ac/gnukhataserver/rpc_organisation.py000077500000000000000000000217021265207572300304730ustar00rootroot00000000000000''' This file is part of GNUKhata:A modular,robust and Free Accounting System. GNUKhata 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. GNUKhata 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 GNUKhata (COPYING); if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA59 Temple Place, Suite 330, Contributor: "Krishnakant Mane" "Anusha Kadambala" ''' from pydoc import cli #from mercurial.templater import if_ """ RPC module for organisation. This module will handle entry and updates of organisation and also getting the data for a given organisation """ #import the database connector and functions for stored procedure. import dbconnect #import the twisted modules for executing rpc calls and also to implement the server from twisted.web import xmlrpc, server #reactor from the twisted library starts the server with a published object and listens on a given port. from twisted.internet import reactor #inherit the class from XMLRPC to make it publishable as an rpc service. class organisation(xmlrpc.XMLRPC): def __init__(self): xmlrpc.XMLRPC.__init__(self) #note that all the functions to be accessed by the client must have the xmlrpc_ prefix. #the client however will not use the prefix to call the functions. ''' Purpose : function for saving contents in database i/p parameters : o/p parameter : true or false ''' def xmlrpc_setOrganisation(self,queryParams,client_id): connection = dbconnect.engines[client_id].connect() Session = dbconnect.session(bind=connection) res = Session.add_all([dbconnect.Organisation(queryParams[0],queryParams[1],queryParams[2],queryParams[3],queryParams[4],queryParams[5],queryParams[6],queryParams[7],queryParams[8],queryParams[9],queryParams[10],queryParams[11],queryParams[12],queryParams[13],queryParams[14],queryParams[15],queryParams[16],queryParams[17],0,0)]) #print res Session.commit() Session.close() connection.connection.close() return True def xmlrpc_getOrgDetails(self, client_id): """ This function returns details of the givern organization. Description: The function takes just the client_id which identifies the database which is connected. It then returns an list of all columns except flag and code. the function makes use of the getOrgDetails stored procedure. """ res = [] orgdetails = dbconnect.execproc("getOrgDetails",dbconnect.engines[client_id] , []) orgRow = orgdetails.fetchone() for r in orgRow: if r == None: res.append("") else: res.append(r) return res def xmlrpc_getDuplicateOrg(self,org_Name,financial_StartDate,financial_EndDate,org_type): orgs = dbconnect.getOrgList() found = False for org in orgs: orgname = org.find("orgname") if orgname.text == org_Name: financialyear_from = org.find("financial_year_from") financialyear_to = org.find("financial_year_to") orga_type=org.find("org_Type") if orgname.text == org_Name and financialyear_from.text == financial_StartDate and financialyear_to.text == financial_EndDate and orga_type.text == org_type : found=True return found def xmlrpc_getOrganisation(self,client_id): connection = dbconnect.engines[client_id].connect() Session = dbconnect.session(bind=connection) res = Session.query(dbconnect.Organisation).all() Session.commit() if res == []: return False else: res1 = [] for l in res: res1.append([l.orgcode,l.orgtype,l.orgname,l.orgaddr,l.orgcity,l.orgpincode,l.orgstate,l.orgcountry,l.orgtelno,l.orgfax,l.orgwebsite,l.orgemail,l.orgpan,l.orgmvat,l.orgstax,l.orgregno,l.orgregdate,l.orgfcrano,l.orgfcradate]) return res1 #print res1 Session.close() connection.connection.close() return True return True def xmlrpc_getOrganizationType(self,client_id): """ purpose: gets the organization type if it is NGO or Profit Making. description: The function checks if the organization is a Profit Making or an NGO. basically it checks if one of the groups is "Corpus". if it is not found then it means that the organization has "Capital" as it group and so it is a Profit Making organization. """ result = dbconnect.execproc("getOrganizationType", dbconnect.engines[client_id],[]) row = result.fetchone() return row["isngo"] """ Purpose: function for saving preferences for a particular organisation i/p parameters: orgname,project flag,reference flag and account code flag o/p parameter : true or false """ def xmlrpc_setPreferences(self,queryParams,client_id): connection = dbconnect.engines[client_id].connect() Session = dbconnect.session(bind=connection) #Session.add_all([dbconnect.Flags(None,queryParams[0])]) stmt = "update flags set flagname='"+queryParams[1]+"' where flagno='"+str(queryParams[0])+"'" dbconnect.engines[client_id].execute(stmt) Session.commit() Session.close() connection.connection.close() return True """ Purpose: finding the appropriate preferences i/p parameters: flagno o/p parameter : flagname """ def xmlrpc_getPreferences(self,queryParams,client_id): #print "get preferences called " connection = dbconnect.engines[client_id].connect() Session = dbconnect.session(bind=connection) #print "connection made" #print queryParams res = Session.query(dbconnect.Flags).filter(dbconnect.Flags.flagno ==int( queryParams[0])).first() #print res.flagname if res == []: return False else: #print res.flagname return res.flagname Session.commit() Session.close() connection.connection.close() def xmlrpc_setProjects(self,queryParams,client_id): """ Purpose: function for saving projects if any for a particular organisation i/p parameters: orgname, projectname o/p parameter : true or false """ print queryParams print client_id dbconnect.execproc("setProject", dbconnect.engines[client_id], queryParams) description='Created Project '+queryParams[0] #ipaddress='localhost' dbconnect.setLog([6,description],client_id) return True def xmlrpc_getAllProjects(self,client_id): result = dbconnect.execproc("getAllProjects",dbconnect.engines[client_id],[]) projectRecords = result.fetchall() projects = [] for row in projectRecords: projects.append([row["project_code"],row["project_name"]]) return projects def xmlrpc_DuplicateProject(self, queryParams, client_id): result = dbconnect.execproc("DuplicateProject", dbconnect.engines[client_id], [queryParams[0]]) row = result.fetchone() return str(row[0]) def xmlrpc_getListOfProject(self,client_id): result = dbconnect.execproc("getListOfProject",dbconnect.engines[client_id],[]) projectList = result.fetchall() projectGrid = [] srno = 1 for prj in projectList: row = [] row.append(srno) row.append(str(prj[0])) row.append(str(prj[1])) srno = srno + 1 projectGrid.append(row) if(len(projectGrid) == 0 ): return [] else: return projectGrid def xmlrpc_getProjectcodeByName(self,queryParams,client_id): result = dbconnect.execproc("getProjectCodeByName", dbconnect.engines[client_id], queryParams) row = result.fetchone() projectCode = row["project_code"] if projectCode == None: return 0 else: return projectCode def xmlrpc_updateOrg(self,queryParams_org,client_id): connection = dbconnect.engines[client_id].connect() Session = dbconnect.session(bind=connection) stmt = "update organisation set orgaddr='"+queryParams_org[1]+"',orgcountry='"+queryParams_org[2]+"',orgstate='"+queryParams_org[3]+"',orgcity='"+queryParams_org[4]+"',orgpincode='"+queryParams_org[5]+"',orgtelno='"+queryParams_org[6]+"',orgfax='"+queryParams_org[7]+"',orgemail='"+queryParams_org[8]+"',orgwebsite='"+queryParams_org[9]+"',orgmvat='"+queryParams_org[10]+"',orgstax='"+queryParams_org[11]+"',orgregno='"+queryParams_org[12]+"',orgregdate='"+queryParams_org[13]+"',orgfcrano='"+queryParams_org[14]+"',orgfcradate='"+queryParams_org[15]+"',orgpan='"+queryParams_org[16]+"' where orgcode='"+queryParams_org[0]+"'" dbconnect.engines[client_id].execute(stmt) #print "work done" winmsg = "Organisation Updated Successfully" #print winmsg Session.commit() Session.close() connection.connection.close() return winmsg def xmlrpc_updateOrgDetails(self, queryParams,client_id ): """ This function updates the existing organization details. The function will make use of the updateOrgDetails stored procedure. Returns true if successful or false otherwise. """ try: result = dbconnect.execproc("updateOrgDetails", dbconnect.engines[client_id], queryParams) return True except: return False core_engine-2.6.1-dac679a8ec1cd01924e7b2e80280c270f69b55ac/gnukhataserver/rpc_reports.py000077500000000000000000001611611265207572300275000ustar00rootroot00000000000000''' This file is part of GNUKhata:A modular,robust and Free Accounting System. GNUKhata 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. GNUKhata 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 GNUKhata (COPYING); if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA59 Temple Place, Suite 330, Contributor: "Krishnakant Mane" "Ankita Shanbhag" "Aditi Patil" ''' from multiprocessing.connection import Client from __builtin__ import str from operator import or_ '''import the database connector and functions for stored procedure.''' import dbconnect '''import the twisted modules for executing rpc calls and also to implement the server''' from twisted.web import xmlrpc, server '''reactor from the twisted library starts the server with a published object and listens on a given port.''' from twisted.internet import reactor import datetime,time from time import strftime class reports(xmlrpc.XMLRPC): """class name is aacount which having different store procedures""" def __init__(self): xmlrpc.XMLRPC.__init__(self) def xmlrpc_getLedger(self,queryParams,client_id): ''' Purpose : returns a complete ledger for given account. Information taken from view_voucherbook Parameters : It expects a list of queryParams which contains[accountname(datatype:text),fromdate(datatype:timestamp),todate(datatype:timestamp),financial year (datatype: timestamp] description: Returns a grid (2 dimentional list ) with columns as Date, Particulars, Reference number, Dr, Cr and vouchercode. Note that last 3 rows have the narration column blank. The 3rd last row contains just the total Dr and total Cr. the second last row contains the closing balance. If the closing balance (carried forward ) is Dr then it will be shown at Cr side. The C/F balance if Cr will be shown at Dr side. The last row will just contain the grand total which will be equal at credit and debit side. ''' #first let's get the details of the given account regarding the Balance and its Dr/Cr side. #note that we use the calculateBalance function which gives us the B/F balance, C/F balance group type and type of the balance. #we will not use this if a project is specified, as there is no point in displaying opening balance. #if all transactions are to be searched then project (queryparams[3]) will be "No Project". balance = dbconnect.execproc("calculateBalance",dbconnect.engines[client_id],[queryParams[0],queryParams[3],queryParams[1],queryParams[2]]) balanceRow = balance.fetchone() if queryParams[4] == "No Project": openingBalance = balanceRow["bal_brought"] else: openingBalance = 0.00 #declare the ledgerGrid as a blank list. #we will fill it up through a for loop where every iteration will append a row with 5 columns. ledgerGrid = [] #Let's start with 0 for Total Dr and total Cr amounts. totalDr = 0.00 totalCr = 0.00 if openingBalance != 0: #since we know that balance is not 0, we must decide if it is Cr or Dr balance. #This can be found out depending on the opening_baltype from the stored procedure calculateBalance. if balanceRow["opening_baltype"] == "Dr": #this makes the first row of the grid. #note that the total Dr is also set. Same will happen in the next condition for Cr. openingdate = datetime.datetime.strptime(str(queryParams[1]),"%Y-%m-%d").strftime("%d-%m-%Y") ledgerGrid.append([openingdate,["Opening Balance B/F"],"",'%.2f'%(openingBalance),"","",""]) if balanceRow["opening_baltype"] == "Cr": openingdate = datetime.datetime.strptime(str(queryParams[1]),"%Y-%m-%d").strftime("%d-%m-%Y") ledgerGrid.append([openingdate,["Opening Balance B/F"],"","",'%.2f'%(openingBalance),"",""]) #totalDr = openingBalance else: #its 0 so will be set to 0. totalDr= 0.00 totalCr = 0.00 #now lets get the core of the ledger, the transaction details for this account. transactions = dbconnect.execproc("getTransactions", dbconnect.engines[client_id],[queryParams[0],queryParams[1],queryParams[2],queryParams[4]]) #fill up the grid with the rows for transactions. for transactionRow in transactions: ledgerRow = [] transactionDate = transactionRow["reff_date"].strftime("%d-%m-%Y") ledgerRow.append(transactionDate) #if the transaction had the amount at Dr side then particulars must have the names of accounts involved in Cr. if transactionRow["voucher_flag"] == "Dr": particulars = dbconnect.execproc("getParticulars",dbconnect.engines[client_id],[int(transactionRow["voucher_code"]),"Cr"]) #may be more than one account was involved a tthe other side so loop through. particular = [] for particularRow in particulars: particular.append(particularRow["account_name"]) ledgerRow.append(particular) ledgerRow.append(transactionRow["voucher_reference"]) ledgerRow.append('%.2f'%(float(transactionRow["transaction_amount"]))) totalDr = totalDr + float(transactionRow["transaction_amount"]) ledgerRow.append("") ledgerRow.append(transactionRow["show_narration"]) if transactionRow["voucher_flag"] == "Cr": particulars = dbconnect.execproc("getParticulars",dbconnect.engines[client_id],[int(transactionRow["voucher_code"]),"Dr"]) particular = [] for particularRow in particulars: particular.append(particularRow["account_name"]) ledgerRow.append(particular) ledgerRow.append(transactionRow["voucher_reference"]) ledgerRow.append("") ledgerRow.append('%.2f'%(float(transactionRow["transaction_amount"]))) totalCr = totalCr + float(transactionRow["transaction_amount"]) ledgerRow.append(transactionRow["show_narration"]) ledgerRow.append(transactionRow["voucher_code"]) ledgerGrid.append(ledgerRow) #the transactions have been filled up duly. #now for the total dRs and Crs, we have added them up nicely during the grid loop. ledgerGrid.append(["",["Total of Transactions"],"",'%.2f'%(totalDr),'%.2f'%(totalCr),"",""]) if queryParams[4] == "No Project": ledgerGrid.append(["",[""],"","","","",""]) grandTotal = 0.00 closingdate = datetime.datetime.strptime(str(queryParams[2]),"%Y-%m-%d").strftime("%d-%m-%Y") if balanceRow["baltype"] == "Dr": #this is a Dr balance which will be shown at Cr side. #Difference will be also added to Cr for final balancing. ledgerGrid.append([closingdate,["Closing Balance C/F"],"","",'%.2f'%(balanceRow["curbal"]),"",""]) grandTotal =float(balanceRow["total_CrBal"]) + float(balanceRow["curbal"]) if balanceRow["baltype"] == "Cr": #now exactly the opposit, see the explanation in the if condition preceding this one. ledgerGrid.append([closingdate,["Closing Balance C/F"],"",'%.2f'%(balanceRow["curbal"]),"","",""]) grandTotal =float(balanceRow["total_DrBal"]) + float(balanceRow["curbal"]) ledgerGrid.append(["",["Grand Total"],"",'%.2f'%(grandTotal),'%.2f'%(grandTotal),"",""]) #we are ready with the complete ledger, so lets send it out! return ledgerGrid def xmlrpc_getReconLedger(self,queryParams,client_id): ''' Purpose : returns a complete ledger for given bank account. Information taken from view_voucherbook Parameters : For getting ledger it takes the result of rpc_getLedger. It expects a list of queryParams which contains[accountname(datatype:text),fromdate(datatype:timestamp),todate(datatype:timestamp)] description: Returns a grid (2 dimentional list ) with columns as Date, Particulars, Reference number, Dr amount, Cr amount, narration, Clearance Date and Memo. Note that It will display the value of clearance date and memo for only those transactions which are cleared. The last row will just contain the grand total which will be equal at credit and debit side. 2nd last row contains the closing balance. 3rd last row contains just the total Dr and total Cr. If the closing balance (carried forward ) is debit then it will be shown at credit side and if it is credit will be shown at debit side. ''' #first let's get the details of the given account regarding the Balance and its Dr/Cr side by calling getLedger function. #note that we use the getClearanceDate function which gives us the clearance date and memo for each account in the ledger. ledgerResult = self.xmlrpc_getLedger(queryParams,client_id) reconResult =[] #lets declare vouchercounter to zero voucherCounter = 0 transactions = dbconnect.execproc("getTransactions", dbconnect.engines[client_id],[queryParams[0],queryParams[1],queryParams[2],queryParams[4]]) # following delete operations are done for avoiding clearance date and memo in opening balance, totaldr, totalcr and grand total rows. openingRow = ledgerResult[0] vouchercode = openingRow[2] if vouchercode == "": del ledgerResult[0] #opening balance row del ledgerResult[len(ledgerResult)-1] #grand total row del ledgerResult[len(ledgerResult)-1] #closing balance row del ledgerResult[len(ledgerResult)-1] #total Dr and Cr row del ledgerResult[len(ledgerResult)-1] # empty row voucherCodes = [] vouchercodeRecords = transactions.fetchall() for vc in vouchercodeRecords: voucherCodes.append(int(vc[0])) #lets append required rows in new list. for ledgerRow in ledgerResult: reconRow = [] reconRow.append(ledgerRow[0]) #voucher date if (len(ledgerRow[1])==1): for acc in ledgerRow[1]: reconRow.append(acc) #particular reconRow.append(ledgerRow[2]) #ref no reconRow.append(voucherCodes[voucherCounter]) #voucher code reconRow.append(ledgerRow[3]) #Dr amount reconRow.append(ledgerRow[4]) #Cr amount reconRow.append(ledgerRow[5]) #narration clearanceDates = dbconnect.execproc("getClearanceDate",dbconnect.engines[client_id],[str(ledgerRow[1][0]),voucherCodes[voucherCounter]]) if clearanceDates.rowcount != 0: for datesRow in clearanceDates: clrDate = datesRow["c_date"].strftime("%d-%m-%Y") clrMemo = datesRow["memo_recon"] reconRow.append(clrDate) reconRow.append(clrMemo) else: reconRow.append("") reconRow.append("") voucherCounter = voucherCounter + 1 reconResult.append(reconRow) return reconResult def xmlrpc_getBankList(self,client_id): """ Purpose: returns list of all bank accounts. """ #let's get all the bank accounts where subgroup name is 'Bank'. getallbankaccounts = dbconnect.execproc("getAllBankAccounts", dbconnect.engines[client_id]) #if their is no bank account created in subgroup returns empty list. if getallbankaccounts == []: return False else: bankaccount = [] #this is to append bank accounts in list bankaccount. for row in getallbankaccounts: bankaccount.append(row[0]) #we are ready with list of all bank accounts. return bankaccount def xmlrpc_setBankRecon(self,queryParams,client_id): ''' Purpose : Sets the bankrecon table in database as saves transaction details of those transactions which are cleared with clearance date and memo in table bankrecon Also sets the reconcode(reconciliation code) for the respective transaction. Parameters : It expects a list of queryParams which contains[vouchercode(datatype:integer),reffdate(datatype:timestamp),accountname(datatype:varchar),dramount(datatype:numeric),cramount(datatype:numeric),clearancedate(datatype:timestamp),memo(datatype:text)] ''' # lets create a list containing vouchercode,reffdate,accountname. for clearRow in queryParams: sp_params = [clearRow[0],clearRow[1], clearRow[2]] #if dr_amount is blank, append 0 as dr_amount and respective cr_amount. if clearRow[3] == "": sp_params.append(0) sp_params.append(clearRow[4]) #if cr_amount is blank, append 0 as cr_amount and respective dr_amount. if clearRow[4] == "": sp_params.append(clearRow[3]) sp_params.append(0) #Now, lets append respective clearance date and memo sp_params.append(clearRow[5]) sp_params.append(clearRow[6]) print sp_params #Finally we are ready to set the bankrecon table. dbconnect.execproc("setBankRecon",dbconnect.engines[client_id],sp_params) return True def xmlrpc_updateBankRecon(self,queryParams,client_id): """ Purpose: Returns all uncleared transactions from the starting of financial year to the end date of given period with Bank Reconciliation Statement for the given period of time. Input Parameters: account name, financial start, Calculate_from and calculate_to Description: This function returns a grid of 7 columns and number of rows depending on number of uncleared transactions in the database. After appending uncleared transactions in grid, it appends Bank Reconciliation statement. A grid of 7 columns contains transaction date, accountname, vouchercode, reference number, dramount, cramount and narration. The function first makes a call to the previous function "getLedger" and passes the account as a parameter along with the financial start, Calculate_from and calculate_to. Note that balance is always calculated from the starting of the financial year. Then, on every iteration it calls following stored procedures: 1. getTransactions: to get trnsactions from starting date of financial year to the end date of given period 2. getParticulars: to get all particulars(account names) for that period 3. getOnlyClearedTransactions: to filter out all uncleared transactions and their details. """ ReconGrid = [] totalDbt = 0.00 totalCdt = 0.00 clearedDrTot=0.00; clearedCrTot=0.00; #now lets get te transaction details for this account. transactions = dbconnect.execproc("getTransactions", dbconnect.engines[client_id],[queryParams[0],queryParams[3],queryParams[2],queryParams[4]]) #fill up the grid with the rows for transactions. for transactionRow in transactions: transactionDate = transactionRow["reff_date"].strftime("%d-%m-%Y") #if the transaction had the amount at Dr side then particulars must have the names of accounts involved in Cr. if transactionRow["voucher_flag"] == "Dr": particulars = dbconnect.execproc("getParticulars",dbconnect.engines[client_id],[int(transactionRow["voucher_code"]),"Cr"]) ledgerRow = [] #may be more than one account was involved at the other side so loop through. for particularRow in particulars: getclearedacc = dbconnect.execproc("getOnlyClearedTransactions",dbconnect.engines[client_id],[str(particularRow["account_name"]),int(transactionRow["voucher_code"]),queryParams[3],queryParams[2]]) clearedAccRow = getclearedacc.fetchone() cleared = clearedAccRow["success"] if cleared == 0: ledgerRow.append(transactionDate) ledgerRow.append(particularRow["account_name"]) ledgerRow.append(transactionRow["voucher_reference"]) ledgerRow.append(transactionRow["voucher_code"]) ledgerRow.append('%.2f'%(float(transactionRow["transaction_amount"]))) totalDbt = totalDbt + float(transactionRow["transaction_amount"]) ledgerRow.append("") ledgerRow.append(transactionRow["show_narration"]) clearedDate_memo = dbconnect.execproc("getClearanceDate",dbconnect.engines[client_id],[str(particularRow["account_name"]),int(transactionRow["voucher_code"])]) cdmrecord = clearedDate_memo.fetchone() ledgerRow.append(cdmrecord["c_date"].strftime("%d-%m-%Y") ) ledgerRow.append(cdmrecord["memo_recon"]) ReconGrid.append(ledgerRow) if cleared == 1: ledgerRow.append(transactionDate) ledgerRow.append(particularRow["account_name"]) ledgerRow.append(transactionRow["voucher_reference"]) ledgerRow.append(transactionRow["voucher_code"]) ledgerRow.append('%.2f'%(float(transactionRow["transaction_amount"]))) totalDbt = totalDbt + float(transactionRow["transaction_amount"]) ledgerRow.append("") ledgerRow.append(transactionRow["show_narration"]) ledgerRow.append("") ledgerRow.append("") ReconGrid.append(ledgerRow) if cleared == -1: clearedDrTot = clearedDrTot + float(transactionRow["transaction_amount"]) if transactionRow["voucher_flag"] == "Cr": particulars = dbconnect.execproc("getParticulars",dbconnect.engines[client_id],[int(transactionRow["voucher_code"]),"Dr"]) ledgerRow = [] #may be more than one account was involved a tthe other side so loop through. for particularRow in particulars: getclearedacc = dbconnect.execproc("getOnlyClearedTransactions",dbconnect.engines[client_id],[str(particularRow["account_name"]),int(transactionRow["voucher_code"]),queryParams[3],queryParams[2]]) clearedAccRow = getclearedacc.fetchone() cleared = clearedAccRow["success"] if cleared == 0: ledgerRow.append(transactionDate) ledgerRow.append(particularRow["account_name"]) ledgerRow.append(transactionRow["voucher_reference"]) ledgerRow.append(transactionRow["voucher_code"]) ledgerRow.append("") ledgerRow.append('%.2f'%(float(transactionRow["transaction_amount"]))) ledgerRow.append(transactionRow["show_narration"]) totalCdt = totalCdt + float(transactionRow["transaction_amount"]) clearedDate_memo = dbconnect.execproc("getClearanceDate",dbconnect.engines[client_id],[str(particularRow["account_name"]),int(transactionRow["voucher_code"])]) cdmrecord = clearedDate_memo.fetchone() ledgerRow.append(cdmrecord["c_date"].strftime("%d-%m-%Y") ) ledgerRow.append(cdmrecord["memo_recon"]) ReconGrid.append(ledgerRow) if cleared == 1: ledgerRow.append(transactionDate) ledgerRow.append(particularRow["account_name"]) ledgerRow.append(transactionRow["voucher_reference"]) ledgerRow.append(transactionRow["voucher_code"]) ledgerRow.append("") ledgerRow.append('%.2f'%(float(transactionRow["transaction_amount"]))) ledgerRow.append(transactionRow["show_narration"]) totalCdt = totalCdt + float(transactionRow["transaction_amount"]) ledgerRow.append("") ledgerRow.append("") ReconGrid.append(ledgerRow) if cleared == -1: clearedCrTot = clearedCrTot + float(transactionRow["transaction_amount"]) legdate=datetime.datetime.strptime(str(queryParams[3]),"%d-%m-%Y").strftime("%Y-%m-%d") ledgerparams=[queryParams[0],legdate,queryParams[2],queryParams[3],queryParams[4]] #get the ledger Grid result, ledgerResult = self.xmlrpc_getLedger(ledgerparams,client_id) BankBal = 0.00 closingBal = 0.00 midTotal = 0.00 print "this issssssss itttttt"+str(clearedDrTot),str(clearedCrTot) #lets get the closing row for closing balance #also we will add the total Dr and Cr, closing balance and grand total to the grid. closingBalRow = ledgerResult[len(ledgerResult)-2] print closingBalRow """openingRow = ledgerResult[0] vouchercode = openingRow[2] if vouchercode == "": openingParticulars = openingRow[1] openingparticular = "" for p in openingParticulars: openingparticular= openingparticular + p del openingRow[1] openingRow.insert(1, openingparticular) print str(openingRow[4]) print str(openingRow[3])""" particularList = closingBalRow[1] particulars = "" for p in particularList: particulars = particulars + p print particulars del closingBalRow[1] closingBalRow.insert(1,particulars ) openDate= datetime.datetime.strptime(str(queryParams[1]),"%Y-%m-%d").strftime("%d-%m-%Y") """TotalDrCrRow = ledgerResult[len(ledgerResult)-4] openingBalRow = ledgerResult[0] if ledgerResult[0][1] =="": if openingBalRow[3] != "": openingBalRow[3]=float(openingBalRow[3])+clearedDrTot-clearedCrTot if openingBalRow[3]<0: openingBalRow[4] = abs(openingBalRow[3]) TotalDrCrRow[4] = float(totalCdt) + float(openingBalRow[4]) TotalDrCrRow[3] = float(totalDbt) ReconGrid.insert(0, [openDate,"Opening Balance B/F","","",'%.2f'%(openingBalRow[4]),""]) else: TotalDrCrRow[3] = float(totalDbt) + float(openingBalRow[3]) TotalDrCrRow[4]= float(totalCdt) ReconGrid.insert(0, [openDate,"Opening Balance B/F","",'%.2f'%(openingBalRow[3]),"",""]) else : openingBalRow[4]=float(openingBalRow[4])-clearedDrTot+clearedCrTot if openingBalRow[4]<0: openingBalRow[3] = abs(openingBalRow[4]) TotalDrCrRow[3] = float(totalDbt) + float(openingBalRow[3]) TotalDrCrRow[4]= float(totalCdt) ReconGrid.insert(0, [openDate,"Opening Balance B/F","",'%.2f'%(openingBalRow[3]),"",""]) else: TotalDrCrRow[4] = float(totalCdt) + float(openingBalRow[4]) TotalDrCrRow[3]=float(totalDbt) ReconGrid.insert(0, [openDate,"Opening Balance B/F","","",'%.2f'%(openingBalRow[4]),""]) ClosingBalance = float(TotalDrCrRow[3]) - float(TotalDrCrRow[4]) if(ClosingBalance>0): closingBalRow[4]= abs(ClosingBalance) else: closingBalRow[3]= abs(ClosingBalance) else: if clearedDrTot-clearedCrTot>0: openingBalRow[3]= abs(clearedDrTot-clearedCrTot) TotalDrCrRow[3] = float(totalDbt) + float(openingBalRow[3]) TotalDrCrRow[4]= float(totalCdt) ReconGrid.insert(0, [openDate,"Opening Balance B/F","",'%.2f'%(openingBalRow[3]),"",""]) elif clearedDrTot-clearedCrTot<0: openingBalRow[4]= abs(clearedDrTot-clearedCrTot) TotalDrCrRow[4] = float(totalCdt) + float(openingBalRow[4]) TotalDrCrRow[3]=float(totalDbt) ReconGrid.insert(0, [openDate,"Opening Balance B/F","","",'%.2f'%(openingBalRow[4]),""]) else: TotalDrCrRow[3]=float(totalDbt) TotalDrCrRow[4]= float(totalCdt) ClosingBalance = TotalDrCrRow[3]-TotalDrCrRow[4] if(ClosingBalance>0): closingBalRow[4]= abs(ClosingBalance) else: closingBalRow[3]= abs(ClosingBalance) ReconGrid.append(["","","Total","",'%.2f'%(TotalDrCrRow[3]),'%.2f'%(TotalDrCrRow[4])])""" #print "this is Total dr "+str(totalDbt)+" this is total cr"+str(totalCdt) #ReconGrid.append(closingBalRow) """grandTotal=ledgerResult[len(ledgerResult)-1] grandparticulars = grandTotal[1] grandparticular = "" for gp in grandparticulars: grandparticular = grandparticular+ gp del grandTotal[1] grandTotal.insert(1, grandparticular) if closingBalRow[3] !="": grandTotal[3]=TotalDrCrRow[3]+float(closingBalRow[3]) grandTotal[4]=TotalDrCrRow[4] if closingBalRow[4] !="": grandTotal[4]=TotalDrCrRow[4]+float(closingBalRow[4]) grandTotal[3]=TotalDrCrRow[3] ReconGrid.append(grandTotal) print str(grandTotal)""" ReconGrid.append(["","RECONCILIATION STATEMENT","","","","AMOUNT"]) #total of Dr and Cr # if opening balance is debit then add opening balance to total debit amount else to total credit amount balancedate = datetime.datetime.strptime(str(queryParams[2]),"%Y-%m-%d").strftime("%d-%m-%Y") if closingBalRow[3] != "": closingBal = float(closingBalRow[3]) if closingBal!=0: ReconGrid.append([balancedate,"Balance as per our book (Credit) on "+balancedate,"","","",closingBalRow[3]]) if closingBalRow[4] != "": ReconGrid.append([balancedate,"Balance as per our book (Debit) on "+balancedate,"","","",closingBalRow[4]]) closingBal = float(closingBalRow[4]) if closingBal == 0: ReconGrid.append([balancedate,"Balance as per our book (Debit) on "+balancedate,"","","",closingBalRow[3]]) closingBal = float(closingBalRow[3]) if closingBalRow[4] != "" or closingBalRow[3]=="0.00": if totalCdt != 0: ReconGrid.append(["","Add: Cheques issued but not presented","","","",'%.2f'%(totalCdt)]) else: ReconGrid.append(["","Add: Cheques issued but not presented","","","",'%.2f'%(totalCdt)]) midTotal = closingBal + totalCdt ReconGrid.append(["","","","","",""+'%.2f'%(abs(midTotal))]) if totalDbt != 0: ReconGrid.append(["","Less: Cheques deposited but not cleared","","","",'%.2f'%(totalDbt)]) else: ReconGrid.append(["","Less: Cheques deposited but not cleared","","","",'%.2f'%(totalDbt)]) BankBal = midTotal - totalDbt else: if totalCdt != 0: ReconGrid.append(["","Less: Cheques issued but not presented","","","",'%.2f'%(totalCdt)]) else: ReconGrid.append(["","Less: Cheques issued but not presented","","","",'%.2f'%(totalCdt)]) midTotal = closingBal - totalCdt if midTotal>=0: ReconGrid.append(["","","","","",""+'%.2f'%(abs(midTotal))]) if totalDbt != 0: ReconGrid.append(["","Add: Cheques deposited but not cleared","","","",'%.2f'%(totalDbt)]) else: ReconGrid.append(["","Add: Cheques deposited but not cleared","","","",'%.2f'%(totalDbt)]) BankBal = abs(midTotal) + totalDbt else: ReconGrid.append(["","","","","",""+'%.2f'%(abs(midTotal))]) if totalDbt != 0: ReconGrid.append(["","Less: Cheques deposited but not cleared","","","",'%.2f'%(totalDbt)]) else: ReconGrid.append(["","Less: Cheques deposited but not cleared","","","",'%.2f'%(totalDbt)]) BankBal = abs(midTotal) - totalDbt if BankBal < 0: ReconGrid.append(["","Balance as per Bank (Debit)","","","",'%.2f'%(abs(BankBal))]) if BankBal > 0: ReconGrid.append(["","Balance as per Bank (Credit)","","","",'%.2f'%(abs(BankBal))]) if BankBal == 0: ReconGrid.append(["","Balance as per Bank","","","",'%.2f'%(abs(BankBal))]) return ReconGrid def xmlrpc_getReconciledTransactions(self, queryParams,client_id): """ Purpose: returns the set of all reconciled transactions for a given bank account. Function will return grid of 7 columns. Description: Just like the update bank recon, this function will look at the reconciliation from the mutually opposite way. The function will be a replica of updateBankRecon except here we return the grid for cleared transactions, from the bankrecon table. The main stored procedure will be the same getOnlyClearedTransactions, except that this time we will look for success == true. """ ReconGrid = [] totalDbt = 0.00 totalCdt = 0.00 #now lets get te transaction details for this account. print str(queryParams[0] ) + str(queryParams[3]) + str(queryParams[2]) + str(queryParams[4]) transactions = dbconnect.execproc("getTransactions", dbconnect.engines[client_id],[queryParams[0],queryParams[3],queryParams[2],queryParams[4]]) transactionRecords = transactions.fetchall() print str(len(transactionRecords)) #fill up the grid with the rows for transactions. for transactionRow in transactionRecords: transactionDate = transactionRow["reff_date"].strftime("%d-%m-%Y") #if the transaction had the amount at Dr side then particulars must have the names of accounts involved in Cr. print " amount is at " + transactionRow["voucher_flag"] + " and voucher code is " + str(transactionRow["voucher_code"]) if transactionRow["voucher_flag"] == "Dr": particulars = dbconnect.execproc("getParticulars",dbconnect.engines[client_id],[int(transactionRow["voucher_code"]),"Cr"]) perows_dr = particulars.fetchall() ledgerRow = [] #may be more than one account was involved at the other side so loop through. for particularRow in perows_dr: getclearedacc = dbconnect.execproc("getOnlyClearedTransactions",dbconnect.engines[client_id],[str(particularRow["account_name"]),int(transactionRow["voucher_code"]),queryParams[3],queryParams[2]]) clearedAccRow = getclearedacc.fetchone() cleared = clearedAccRow["success"] if cleared == -1: ledgerRow.append(transactionDate) ledgerRow.append(particularRow["account_name"]) ledgerRow.append(transactionRow["voucher_reference"]) ledgerRow.append(transactionRow["voucher_code"]) ledgerRow.append('%.2f'%(float(transactionRow["transaction_amount"]))) totalDbt = totalDbt + float(transactionRow["transaction_amount"]) ledgerRow.append("") ledgerRow.append(transactionRow["show_narration"]) #we have to get clearancedate and memo seperately. clearedDate_memo = dbconnect.execproc("getClearanceDate",dbconnect.engines[client_id],[str(particularRow["account_name"]),int(transactionRow["voucher_code"])]) cdmrecord = clearedDate_memo.fetchone() ledgerRow.append(cdmrecord["c_date"].strftime("%d-%m-%Y") ) ledgerRow.append(cdmrecord["memo_recon"]) ReconGrid.append(ledgerRow) if transactionRow["voucher_flag"] == "Cr": particularsCr = dbconnect.execproc("getParticulars",dbconnect.engines[client_id],[int(transactionRow["voucher_code"]),"Dr"]) perows_cr = particularsCr.fetchall() #print str(len(particularsCr)) #print perows_cr[0]["account_name"] ledgerRow = [] #may be more than one account was involved a tthe other side so loop through. for particularRow in perows_cr: getclearedacc = dbconnect.execproc("getOnlyClearedTransactions",dbconnect.engines[client_id],[str(particularRow["account_name"]),int(transactionRow["voucher_code"]),queryParams[3],queryParams[2]]) clearedAccRow = getclearedacc.fetchone() cleared = clearedAccRow["success"] if cleared == -1: ledgerRow.append(transactionDate) ledgerRow.append(particularRow["account_name"]) ledgerRow.append(transactionRow["voucher_reference"]) ledgerRow.append(transactionRow["voucher_code"]) ledgerRow.append("") ledgerRow.append('%.2f'%(float(transactionRow["transaction_amount"]))) ledgerRow.append(transactionRow["show_narration"]) totalCdt = totalCdt + float(transactionRow["transaction_amount"]) clearedDate_memo = dbconnect.execproc("getClearanceDate",dbconnect.engines[client_id],[str(particularRow["account_name"]),int(transactionRow["voucher_code"])]) cdmrecord = clearedDate_memo.fetchone() ledgerRow.append(cdmrecord["c_date"].strftime("%d-%m-%Y")) ledgerRow.append(cdmrecord["memo_recon"]) ReconGrid.append(ledgerRow) return ReconGrid def xmlrpc_deleteClearedRecon(self,queryParams,client_id): print "this is delete query param" print queryParams result = dbconnect.execproc("deleteclearedrecon", dbconnect.engines[client_id],[queryParams[0],queryParams[1],queryParams[2] ]) if result == True: return True else: return False def xmlrpc_getTrialBalance(self,queryParams,client_id): """ Purpose: gets trial balance as on the given date. Returns a grid of 4 columns and number of rows depending on number of accounts. description: This function returns a grid of 4 columns contaning trial balance. Number of rows in this grid will depend on the number of accounts in the database. The function first makes a call to the stored procedure getAllAccounts and stors the list. then a loop runs through the list of accounts. on every iteration it calls the calculateBalance and passes the account as a parameter along with the financial start, Calculate_from and calculate_to. Note that trial balance is always calculated from the starting of the financial year. Also in the for loop we see if the typeflag for the balance for given account is Dr or Cr. if the balance is Dr then we put the procured amount in the 4th column, with the 5th column blank. If the typeflag is credit then we put the amount in the 5th row, leaving the 4th as blank. """ print queryParams if (dbconnect.user_roles[client_id]== 0) or (dbconnect.user_roles[client_id] ==-1) : accounts = dbconnect.execproc("getAllAccounts", dbconnect.engines[client_id],[]) trialBalance = [] srno =1 total_dr = 0.00 total_cr = 0.00 for account in accounts: closingBalance = dbconnect.execproc("calculateBalance", dbconnect.engines[client_id], [str(account[0]),queryParams[0],queryParams[1],queryParams[2]]) closingRow = closingBalance.fetchone() if float(closingRow["curbal"]) != 0: trialRow = [] trialRow.append(srno) trialRow.append(account["accountname"]) trialRow.append(closingRow["group_name"]) if closingRow["baltype"] == "Cr": total_cr = total_cr + float(closingRow["curbal"]) trialRow.append("") trialRow.append('%.2f'%float(closingRow["curbal"])) if closingRow["baltype"] == "Dr": total_dr = total_dr + float(closingRow["curbal"]) trialRow.append('%.2f'%float(closingRow["curbal"])) trialRow.append("") srno = srno +1 trialBalance.append(trialRow) total_balances = ['%.2f'%total_dr,'%.2f'%total_cr] trialBalance.append(total_balances) return trialBalance def xmlrpc_getGrossTrialBalance(self,queryParams,client_id): ''' purpose: just like the getTrialBalance, this function too returns list of balances of all accounts. However it has a difference in that it provides the total Dr and total Cr for all accounts, instead of the difference. description: Similar to the getTrial balance function this one returns a grid, but instead of current balance, it returns total Dr and total Cr in the grid. This function too uses the calculateBalance stored procedure after getting list of accounts. ''' if (dbconnect.user_roles[client_id]== 0) or (dbconnect.user_roles[client_id] ==-1) : accounts = dbconnect.execproc("getAllAccounts", dbconnect.engines[client_id],[]) trialBalance = [] srno =1 total_dr = 0.00 total_cr = 0.00 for account in accounts: closingBalance = dbconnect.execproc("calculateBalance", dbconnect.engines[client_id], [str(account[0]),queryParams[0],queryParams[1],queryParams[2]]) closingRow = closingBalance.fetchone() if float(closingRow["total_DrBal"]) != 0 or float(closingRow["total_CrBal"]) != 0: trialRow = [] trialRow.append(srno) trialRow.append(account["accountname"]) trialRow.append(closingRow["group_name"]) trialRow.append('%.2f'%float(closingRow["total_DrBal"])) trialRow.append('%.2f'%float(closingRow["total_CrBal"])) total_dr = total_dr + float(closingRow["total_DrBal"]) total_cr = total_cr + float(closingRow["total_CrBal"]) srno = srno +1 trialBalance.append(trialRow) total_balances = ['%.2f'%total_dr,'%.2f'%total_cr] trialBalance.append(total_balances) return trialBalance def xmlrpc_getExtendedTrialBalance(self,queryParams,client_id): """ Purpose: gets trial balance as on the given date. Returns a grid of 7 columns and number of rows depending on number of accounts. description: This function returns a grid of 7 columns contaning trial balance. Number of rows in this grid will depend on the number of accounts in the database. The function first makes a call to the stored procedure getAllAccounts and stors the list. then a loop runs through the list of accounts. on every iteration it calls the calculateBalance and passes the account as a parameter along with the financial start, Calculate_from and calculate_to. Note that trial balance is always calculated from the starting of the financial year. Also in the for loop we see if the typeflag for the balance for given account is Dr or Cr. if the balance is Dr then we put the procured amount in the 4th column, with the 5th column blank. If the typeflag is credit then we put the amount in the 5th row, leaving the 4th as blank. """ if (dbconnect.user_roles[client_id]== 0) or (dbconnect.user_roles[client_id] ==-1) : accounts = dbconnect.execproc("getAllAccounts", dbconnect.engines[client_id],[]) trialBalance = [] srno =1 total_dr = 0.00 total_cr = 0.00 total_ExtendedCr = 0.00 total_ExtendedDr = 0.00 for account in accounts: closingBalance = dbconnect.execproc("calculateBalance", dbconnect.engines[client_id], [str(account[0]),queryParams[0],queryParams[1],queryParams[2]]) closingRow = closingBalance.fetchone() print closingRow if float(closingRow["bal_brought"]) != 0 or float(closingRow["total_DrBal"]) != 0 or float(closingRow["total_CrBal"]) != 0: trialRow = [] trialRow.append(srno) trialRow.append(account["accountname"]) trialRow.append(closingRow["group_name"]) if float(closingRow["bal_brought"]) != 0 and closingRow["opening_baltype"] == "Dr": trialRow.append('%.2f'%float(closingRow["bal_brought"])+"(Dr)") trialRow.append('%.2f'%(float(closingRow["total_DrBal"])- float(closingRow["bal_brought"]))) total_dr = total_dr + (float(closingRow["total_DrBal"]) - float(closingRow["bal_brought"])) trialRow.append('%.2f'%float(closingRow["total_CrBal"])) total_cr = total_cr +float(closingRow["total_CrBal"]) if float(closingRow["bal_brought"]) != 0 and closingRow["opening_baltype"] == "Cr": trialRow.append('%.2f'%float(closingRow["bal_brought"])+"(Cr)") trialRow.append('%.2f'%float(closingRow["total_DrBal"])) total_dr = total_dr + float(closingRow["total_DrBal"]) trialRow.append('%.2f'%(float(closingRow["total_CrBal"])- float(closingRow["bal_brought"]))) total_cr = total_cr + (float(closingRow["total_CrBal"]) - float(closingRow["bal_brought"])) if float(closingRow["bal_brought"]) == 0: trialRow.append("") trialRow.append('%.2f'%float(closingRow["total_DrBal"])) total_dr = total_dr + float(closingRow["total_DrBal"]) trialRow.append('%.2f'%float(closingRow["total_CrBal"])) total_cr = total_cr + float(closingRow["total_CrBal"]) if closingRow["baltype"] == "Dr": trialRow.append('%.2f'%float(closingRow["curbal"])) trialRow.append("") total_ExtendedDr = total_ExtendedDr + float(closingRow["curbal"]) if closingRow["baltype"] == "Cr": trialRow.append("") trialRow.append('%.2f'%float(closingRow["curbal"])) total_ExtendedCr = total_ExtendedCr + float(closingRow["curbal"]) srno = srno +1 trialBalance.append(trialRow) total_balances = ['%.2f'%total_ExtendedDr,'%.2f'%total_ExtendedCr,'%.2f'%total_dr,'%.2f'%total_cr] trialBalance.append(total_balances) return trialBalance def xmlrpc_getCashFlow(self,queryParams,client_id): """ Purpose: Returns the data for CashFlow in a grid format description: the function takes one arguement queryParams which is a list containing, * startdate and * end date The function will return a grid with 4 columns. First 2 columns will have the account name and its sum of received amount, while next 2 columns will have the same for amount paid. First we make a call to get CashFlowAccounts stored procedure for the list of accounts falling under Bank or Cash subgroups. Then a loop will run through the list and get the list of payment and receipts as mentioned above. Every row will contain a pair of account:amount for payment and receipt each. """ #declare the cashFlowGrid, rlist, plist as a blank list. #we will fill up cashFlowGrid by appending rlist and plist. #rlist will contain the cashflow of received accounts. #plist will contain the cashflow of paid accounts. cashFlowGrid = [] rlist = [] plist = [] rlist.append(["Opening Balance","",""]) #Let's start with 0 for totalreceivedamount and totalpaid amounts. totalreceivedamount = 0.00 totalpaidamount = 0.00 #first let's get the list of all accounts coming under cash or bank subgroup and their respective opening balance. cashBankAccounts = dbconnect.execproc("getCashFlowOpening",dbconnect.engines[client_id]) #fill up the rlist with the rows for cashFlowAccounts. #also maintaining a list of cash and bank accounts will facilitate the loop for getting actual cash flow. cbAccounts = [] for account in cashBankAccounts: openingRow = [] openingRow.append("ob") openingRow.append(account["accountname"]) cbAccounts.append(account["accountname"]) balbroughtRow = dbconnect.execproc("calculateBalance",dbconnect.engines[client_id],[str(account[0]),queryParams[2],queryParams[0],queryParams[1]]) openinglist = balbroughtRow.fetchone() openingBalType = openinglist["opening_baltype"] crBal_Brought = 0.00 if openingBalType== "Cr": crBal_Brought = - float(openinglist['bal_brought'] ) openingRow.append('%.2f'%float(crBal_Brought)) else: crBal_Brought = float(openinglist['bal_brought'] ) openingRow.append('%.2f'%float(openinglist["bal_brought"])) totalreceivedamount = totalreceivedamount + float(crBal_Brought) print totalreceivedamount rlist.append(openingRow) cashBankAccounts.close() cfAccounts = dbconnect.execproc("getJournal",dbconnect.engines[client_id]) cfAccountsRows = cfAccounts.fetchall() #now we will run a nested loop for getting cash flow for all non-cash/bank accounts # the outer loop will run through the list of all the cfAccounts and check for any transactions on them involving bank or cash based accounts for which we have a list of cbAccounts #needless to say this process will happen once for recieved and one for paid transactions. for account in cfAccountsRows: receivedAmount = 0.00 for cb in cbAccounts: #print "checking with account " + str(account[0]) + " against " + cb received = dbconnect.execproc("getCashFlowReceivedAccounts",dbconnect.engines[client_id],[str(account[0]),str(cb),queryParams[0],queryParams[1]]) receivedRow = received.fetchone() #print"the amount for given combination is " + str(receivedRow["cfamount"]) if receivedRow["cfamount"] != None: receivedAmount = receivedAmount + float(str(receivedRow["cfamount"])) if receivedAmount != 0: rlist.append([account["accountnames"],'%.2f'% receivedAmount,""]) totalreceivedamount = totalreceivedamount + float(receivedAmount) #print rlist #print "received samapt hue" #print "finally the total of received with opening is " + str(totalreceivedamount) #print "now into the payed loop " for account in cfAccountsRows: paidAmount = 0.00 for cb in cbAccounts: #print "checking with account " + str(account[0]) + " against " + cb paid = dbconnect.execproc("getCashFlowPaidAccounts",dbconnect.engines[client_id],[str(account[0]),str(cb),queryParams[0],queryParams[1]]) paidRow = paid.fetchone() if paidRow["cfamount"] != None: paidAmount = paidAmount + float(str(paidRow["cfamount"])) if paidAmount != 0: plist.append([account["accountnames"],'%.2f'% paidAmount,""]) totalpaidamount = totalpaidamount + float(paidAmount) plist.append(["Closing Balance","",""]) #print plist #fill up the rlist with the rows for cashFlowAccounts only if receivedRow is not none. #now sum up the totalreceived amounts. for closingcb in cbAccounts: closingCbRow = [] closingRow = dbconnect.execproc("calculateBalance",dbconnect.engines[client_id],[str(closingcb),queryParams[2],queryParams[0],queryParams[1]]) closinglist = closingRow.fetchone() closingBalType = closinglist["baltype"] closingCbRow.append("cb") closingCbRow.append(closingcb) DrBal_Cf = 0.00 if closingBalType== "Cr" and float(closinglist['curbal'] )> 0: DrBal_Cf = - float(closinglist['curbal'] ) closingCbRow.append('%.2f'%float(DrBal_Cf)) else: DrBal_Cf = float(closinglist['curbal'] ) closingCbRow.append('%.2f'%float(closinglist["curbal"])) totalpaidamount = totalpaidamount + float(DrBal_Cf) plist.append(closingCbRow) #fill up the plist with the rows for cashFlowAccounts only if paidRow is not none. #now sum up the totalpaid amounts. #Now lets equate the row of rlist and plist. rlength = len(rlist) plength = len(plist) #if length of rlist is greater than plist then append the blank lists times of difference in rlist and plist into the plist or vice versa. if rlength > plength: diflength = rlength - plength for d in range(0,diflength): plist.append(["","",""]) if rlength < plength: diflength = plength - rlength for d in range(0,diflength): rlist.append(["","",""]) #now append the total receivedamount and total paidamount in respective lists i.e. rlist and plist rlist.append(["Total",'%.2f'% totalreceivedamount,""]) plist.append(["Total",'%.2f'% totalpaidamount,""]) #now append rlist and plist to cashFlowGrid cashFlowGrid.append(rlist) cashFlowGrid.append(plist) return cashFlowGrid def xmlrpc_getProjectStatement(self,queryParams,client_id): """ Purpose, gets the project statement for a given project. The function takes 1 arguement a list of query params. The list contains one string, project name. returns the total incoming and out going for a given project. Description: The function takes one arguement named queryParams which is a single element list. The element contains projectname. On the basis of this projectname, a list of accounts is produced. this list of accounts contains those accounts which are involved in transactions corresponding to the given project. However this list will be further filtered in a final list of accounts with only those names which are not in the subgroup bank or cash. after this filteration the call to the stored procedure for getting sum of total Crs and Drs is made. This function makes use of getProjectAccounts,getGroupNameByAccountName,getProjectStatement,getSubGroupByAccount """ projectAccountResult = dbconnect.execproc("getProjectAccounts",dbconnect.engines[client_id],[str(queryParams[0])]) projectAccounts = projectAccountResult.fetchall() totalDr = 0.00 totalCr = 0.00 srno = 1 projectStatement = [] for accountRow in projectAccounts: group = dbconnect.execproc("getGroupNameByAccountName",dbconnect.engines[client_id],[str(accountRow["accname"])]) groupRow = group.fetchone() groupForAccount = groupRow["groupname"] if groupForAccount == "Direct Income" or groupForAccount == "Direct Expense" or groupForAccount == "Indirect Income" or groupForAccount == "Indirect Expense": groupResult = dbconnect.execproc("getGroupNameByAccountName",dbconnect.engines[client_id],[str(accountRow["accname"])]) groupRow = groupResult.fetchone() accountGroup = groupRow["groupname"] result = dbconnect.execproc("getProjectStatement", dbconnect.engines[client_id],[queryParams[0],str(accountRow["accname"]),queryParams[1],queryParams[2],queryParams[3]]) resultRow = result.fetchone() statementRow = [srno,accountRow["accname"],accountGroup,'%.2f'%float(resultRow["totalDr"]),'%.2f'%float(resultRow["totalCr"])] totalDr = totalDr + resultRow["totalDr"] totalCr = totalCr + resultRow["totalCr"] srno = srno +1 projectStatement.append(statementRow) projectStatement.append(["","","",'%.2f'%float(totalDr),'%.2f'%float(totalCr)]) return projectStatement def xmlrpc_getProfitLoss(self,queryParams,client_id): """ Purpose: gets trial balance as on the given date. Returns a grid of 4 columns and number of rows depending on number of accounts. description: This function returns a grid of 4 columns contaning profit and loss details. Number of rows in this grid will depend on the number of accounts in the database. For profit and loss the accounts from group direct and indirect ecome and expence are invoke. The function first makes a call to the stored procedure getAccountsByGroupCode and stors the list. then a loop runs through the list of accounts. on every iteration it calls the calculateBalance and passes the account as a parameter along with the financial start, Calculate_from and calculate_to. Note that profit and loss is always calculated from the starting of the financial year. the total of each group of accounts is calculated separately for calculation purpose. """ if (dbconnect.user_roles[client_id]== 0) or (dbconnect.user_roles[client_id] ==-1) : grpCodes = [4,5,7,8] profitloss = [] closingStock = [] srno = 1 total_dirInc_balances = 0.00; total_dirExp_balances =0.00 total_indirInc_balances =0.00; total_indirExp_balances = 0.00 grossProfit = 0.00 ; grossLoss = 0.00 netProfit = 0.00 ; netLoss = 0.00 pnlbal1=0.00 for grpCode in grpCodes: accounts = dbconnect.execproc("getAccountsByGroupCode", dbconnect.engines[client_id],[grpCode]) for account in accounts.fetchall(): profitlossrow = [] closingBalance = dbconnect.execproc("calculateBalance", dbconnect.engines[client_id],[str(account['accountname']),queryParams[0],queryParams[1],queryParams[2]]) closingRow = closingBalance.fetchone() print closingRow pnlbal=0.00 if account['accountname'] in ("Profit & Loss","Income & Expenditure") : pnlbal = (float(closingRow['curbal'])) print "aaaaaaaaaaaaaaaaaaaaaaa",'%.2f'%pnlbal if pnlbal !=0.00: closingStock.append(grpCode) closingBalance = dbconnect.execproc("calculateBalance", dbconnect.engines[client_id],["Closing Stock",queryParams[0],queryParams[1],queryParams[2]]) closingRow = closingBalance.fetchone() closingStock.append("Closing Stock") closingStock.append('%.2f'%(float(closingRow['curbal']))) closingStock.append("Cr") bal = "Cr" pnlbal1 = pnlbal else: profitlossrow.append(srno) profitlossrow.append(grpCode) profitlossrow.append(str(account['accountname'])) profitlossrow.append('%.2f'%(float(closingRow['curbal']))) profitlossrow.append(str(closingRow['baltype'])) srno = srno + 1 bal = closingRow['baltype'] profitloss.append(profitlossrow) if grpCode == 5: if str(bal) == "Dr": total_dirExp_balances = total_dirExp_balances + float(closingRow['curbal']) else: total_dirInc_balances = total_dirInc_balances + float(closingRow['curbal']) if grpCode == 8: if str(bal) == "Dr": total_indirExp_balances = total_indirExp_balances + float(closingRow['curbal']) else: total_indirInc_balances = total_indirInc_balances + float(closingRow['curbal']) if grpCode == 4: if str(bal) == "Cr": total_dirInc_balances = total_dirInc_balances + float(closingRow['curbal']) else: total_dirExp_balances = total_dirExp_balances + float(closingRow['curbal']) if grpCode == 7: if str(bal) == "Cr": total_indirInc_balances = total_indirInc_balances + float(closingRow['curbal']) else: total_indirExp_balances = total_indirExp_balances + float(closingRow['curbal']) print "thissss isss theee balance of pnnnlll",'%.2f'%(pnlbal1) if pnlbal1!=0 : if closingStock[2] >0 : closingStock.insert(0, srno) profitloss.append(closingStock) profitloss.append('%.2f'%(float(total_dirInc_balances))) profitloss.append('%.2f'%(float(total_dirExp_balances))) profitloss.append('%.2f'%(float(total_indirInc_balances))) profitloss.append('%.2f'%(float(total_indirExp_balances))) print "we are in profit and loss" print total_dirInc_balances print total_dirExp_balances print total_indirInc_balances print total_indirExp_balances if (total_dirInc_balances > total_dirExp_balances): grossProfit = total_dirInc_balances - total_dirExp_balances print "gross proftt" print grossProfit profitloss.append("grossProfit") profitloss.append('%.2f'%(float(grossProfit))) totalnetprofit = total_indirInc_balances + grossProfit if(totalnetprofit > total_indirExp_balances): netProfit = totalnetprofit - total_indirExp_balances grandTotal = netProfit+total_indirExp_balances profitloss.append("netProfit") profitloss.append('%.2f'%(float(netProfit))) profitloss.append('%.2f'%(float(totalnetprofit))) profitloss.append('%.2f'%(float(grandTotal))) else: netLoss = total_indirExp_balances - totalnetprofit grandTotal = netLoss+totalnetprofit profitloss.append("netLoss") profitloss.append('%.2f'%(float(netLoss))) profitloss.append('%.2f'%(float(totalnetprofit))) profitloss.append('%.2f'%(float(grandTotal))) else: grossLoss = total_dirExp_balances - total_dirInc_balances profitloss.append("grossLoss") profitloss.append('%.2f'%(float(grossLoss))) totalnetloss = total_indirExp_balances + grossLoss print "totalnetloss" print totalnetloss if(totalnetloss > total_indirInc_balances): netLoss = totalnetloss - total_indirInc_balances grandTotal = netLoss+total_indirInc_balances profitloss.append("netLoss") profitloss.append('%.2f'%(float(netLoss))) profitloss.append('%.2f'%(float(totalnetloss))) profitloss.append('%.2f'%(float(grandTotal))) else: netProfit = total_indirInc_balances - totalnetloss grandTotal = netProfit+total_indirInc_balances profitloss.append("netProfit") profitloss.append('%.2f'%(float(netProfit))) profitloss.append('%.2f'%(float(totalnetloss))) profitloss.append('%.2f'%(float(grandTotal))) print profitloss return profitloss def xmlrpc_getBalancesheet(self,queryParams,client_id): """ Purpose: gets trial balance as on the given date. Returns a grid of 4 columns and number of rows depending on number of accounts. description: This function returns a grid of 4 columns contaning balancesheet. Number of rows in this grid will depend on the number of accounts in the database. For balancesheet asset and liabilities side accounts are invoke. The function first makes a call to the stored procedure getAccountsByGroupCode and stors the list. then a loop runs through the list of accounts. on every iteration it calls the calculateBalance and passes the account as a parameter along with the financial start, Calculate_from and calculate_to. Note that profit and loss is always calculated from the starting of the financial year. the total of assets ans liabilities is calculated separately for calculation purpose. """ if (dbconnect.user_roles[client_id]== 0) or (dbconnect.user_roles[client_id] ==-1) : assetGrpCodes = [6,2,10,9,13] liabilitiesGrpCodes = [1,3,11,12] balancesheet = [] assetSrno = 1; liabilitiesSrno = 1 total_asset_balances = 0.00; total_liabilities_balances = 0.00 tot_capital = 0.00; tot_currliabilities = 0.00; tot_loansliabilities = 0.00; tot_reserves = 0.00 tot_fixedasset = 0.00; tot_currentasset = 0.00; tot_loansasset = 0.00; tot_investment = 0.00; tot_miscExpense = 0.00 for grpCode in liabilitiesGrpCodes: accounts = dbconnect.execproc("getAccountsByGroupCode", dbconnect.engines[client_id],[grpCode]) for account in accounts.fetchall(): assetrow = []; liabilitiesrow = [] closingBalance = dbconnect.execproc("calculateBalance", dbconnect.engines[client_id],[str(account['accountname']),queryParams[0],queryParams[1],queryParams[2]]) closingRow = closingBalance.fetchone() if closingRow["baltype"] == "Cr": closingBalanceAmount = float(closingRow['curbal']) else: closingBalanceAmount = - float(closingRow['curbal']) if closingBalanceAmount != 0: liabilitiesrow.append(liabilitiesSrno) liabilitiesrow.append(grpCode) liabilitiesrow.append(str(account['accountname'])) liabilitiesrow.append('%.2f'%(closingBalanceAmount)) if (grpCode == 1): tot_capital += closingBalanceAmount if (grpCode == 3): tot_currliabilities += closingBalanceAmount if (grpCode == 11): tot_loansliabilities += closingBalanceAmount if (grpCode == 12): tot_reserves += closingBalanceAmount total_liabilities_balances += closingBalanceAmount balancesheet.append(liabilitiesrow) liabilitiesSrno += 1 for grpCode in assetGrpCodes: accounts = dbconnect.execproc("getAccountsByGroupCode", dbconnect.engines[client_id],[grpCode]) for account in accounts.fetchall(): assetrow = []; liabilitiesrow = [] closingBalance = dbconnect.execproc("calculateBalance", dbconnect.engines[client_id],[str(account['accountname']),queryParams[0],queryParams[1],queryParams[2]]) closingRow = closingBalance.fetchone() if closingRow["baltype"] == "Dr": closingBalanceAmount = float(closingRow['curbal']) else: closingBalanceAmount = - float(closingRow['curbal']) if closingBalanceAmount != 0: assetrow.append(assetSrno) assetrow.append(grpCode) assetrow.append(str(account['accountname'])) assetrow.append('%.2f'%(closingBalanceAmount)) if (grpCode == 6): tot_fixedasset += closingBalanceAmount if (grpCode == 2): tot_currentasset += closingBalanceAmount if (grpCode == 10): tot_loansasset += closingBalanceAmount if (grpCode == 9): tot_investment += closingBalanceAmount if (grpCode == 13): tot_miscExpense += closingBalanceAmount total_asset_balances += closingBalanceAmount balancesheet.append(assetrow) assetSrno += 1 balancesheet.append(assetSrno - int(1)) balancesheet.append(liabilitiesSrno - int(2)) balancesheet.append('%.2f'%(float(tot_investment))) balancesheet.append('%.2f'%(float(tot_loansasset))) balancesheet.append('%.2f'%(float(tot_currentasset))) balancesheet.append('%.2f'%(float(tot_fixedasset))) balancesheet.append('%.2f'%(float(tot_miscExpense))) balancesheet.append('%.2f'%(float(tot_currliabilities))) balancesheet.append('%.2f'%(float(tot_loansliabilities))) balancesheet.append('%.2f'%(float(tot_capital))) balancesheet.append('%.2f'%(float(tot_reserves))) balancesheet.append('%.2f'%(float(total_liabilities_balances))) balancesheet.append('%.2f'%(float(total_asset_balances))) return balancesheet core_engine-2.6.1-dac679a8ec1cd01924e7b2e80280c270f69b55ac/gnukhataserver/rpc_transaction.py000077500000000000000000000323341265207572300303260ustar00rootroot00000000000000''' This file is part of GNUKhata:A modular,robust and Free Accounting System. GNUKhata 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. GNUKhata 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 GNUKhata (COPYING); if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA59 Temple Place, Suite 330, Contributor: "Anusha Kadambala" "Sonal Chaudhari" "priyanka Tawde" "Shruti Surve" ''' #import the database connector and functions for stored procedure. import dbconnect #import the twisted modules for executing rpc calls and also to implement the server from twisted.web import xmlrpc, server #reactor from the twisted library starts the server with a published object and listens on a given port. from twisted.internet import reactor import xmlrpclib import rpc_account import time,datetime #from sqlalchemy import func from multiprocessing.connection import Client from rpc_organisation import organisation #inherit the class from XMLRPC to make it publishable as an rpc service. class transaction(xmlrpc.XMLRPC): def __init__(self): xmlrpc.XMLRPC.__init__(self) #note that all the functions to be accessed by the client must have the xmlrpc_ prefix. #the client however will not use the prefix to call the functions. def xmlrpc_setTransaction(self,queryParams_master,queryParams_details,client_id): """ Purpose: adds a new voucher in the database given its reference number and transaction details (dr and cr), along with narration and the date. Purpose: This function is used to create a new voucher. A voucher code is generated automatically while the user gives optional reference number. The entire transaction is recorded in terms of Dr and Cr and the respected amounts. The function utilises 2 stored procedures. setVoucherMaster and setVoucherDetails. For voucher master the function takes queryParams_master containing, * reference Number *system Date (on which the voucher was entered ) * the actual transaction date *Voucher type, *project name, * Narration, *purchase order number, *purchase order date and *purchase order amount The setVoucherDetails takes a 2 dimensional list containing, rows with columns, * DrCr flag, AccountName (from which account code will be procured by the said stored procedure) * the amount for the respective account. The function returns true if successful or false otherwise. """ print queryParams_details; print queryParams_master prj = self.xmlrpc_getProjectcodeByName([str(queryParams_master[4])],client_id) del queryParams_master[4] queryParams_master.insert(4,prj) print queryParams_master success = dbconnect.execproc("setVoucherMaster", dbconnect.engines[client_id],queryParams_master) successRow = success.fetchone() voucherCode = successRow[0] print "query for masters is successful and voucher code is " + str(voucherCode) print queryParams_details for detailRow in queryParams_details: accountCodeResult = dbconnect.execproc("getAccountCode",dbconnect.engines[client_id],[detailRow[1]]) accountCodeRow = accountCodeResult.fetchone() accountCode = accountCodeRow["account_code"] dbconnect.execproc("setVoucherDetails",dbconnect.engines[client_id],[voucherCode,str(detailRow[0]),str(accountCode),float(detailRow[2])]) return 1 def xmlrpc_getProjectcodeByName(self,queryParams,client_id): result = dbconnect.execproc("getProjectCodeByName", dbconnect.engines[client_id], queryParams) row = result.fetchone() projectCode = row["project_code"] if projectCode == None: return 0 else: return projectCode def xmlrpc_getLastReffDate(self,queryParams,client_id): date = dbconnect.execproc("getLastReffDate", dbconnect.engines[client_id],queryParams) lastDate = date.fetchone() dateRow = lastDate["reff_date"].strftime("%Y-%m-%d") return dateRow def xmlrpc_getLastReference(self,queryParams,client_id): reference = dbconnect.execproc("getLastReference", dbconnect.engines[client_id],queryParams) lastReff = reference.fetchone() if lastReff["reffno"] == None: return '' else: return lastReff["reffno"] def xmlrpc_searchVoucher(self,queryParams,client_id): """ Returns one or more vouchers given the reference number, date range, narration or amount (which ever specified) takes one parameter queryParams as list. List contains searchFlag integer (1 implies serch by reference, 2 as search by date range, 3 as search by narration and 4 as amount at position 0 reference number text at position 1, start range date at 2, end range date at 3, narration phrase at position 4 and amount at position 5. returns a 2 dimensional list containing one or more records from voucher_master description: The function is used to get the list of vouchers on the basis of either reference number (which can be duplicate), or date range, or some words from narration or amount. This means one or more vouchers could be by the same reference number or within a given date range, narration or amount. The list thus returned contains all details of a given voucher except its exact transactions, i.e the records from voucher_master. The function makes use of the searchVouchers store procedure, following the getVoucherDetails stored procedures. """ searchedVouchers = dbconnect.execproc("searchVouchers", dbconnect.engines[client_id], queryParams) vouchers = searchedVouchers.fetchall() voucherView = [] for voucherRow in vouchers: resultAccounts = dbconnect.execproc("getVoucherDetails",dbconnect.engines[client_id],[voucherRow[0]]) voucherAccounts = resultAccounts.fetchall() drAccount = "" crAccount = "" drCounter = 1 crCounter = 1 for va in voucherAccounts: if va["transactionflag"] == "Dr" and drCounter == 2: drAccount = va["accountname"] + "+" if va["transactionflag"] == "Dr" and drCounter == 1: drAccount = va["accountname"] drCounter = drCounter +1 if va["transactionflag"] == "Cr" and crCounter == 2: crAccount = va["accountname"] + "+" if va["transactionflag"] == "Cr" and crCounter == 1: crAccount = va["accountname"] crCounter = crCounter +1 totalAmount = str(voucherRow["total_amount"]) if queryParams[0]== 3 and queryParams[4]=="": if voucherRow["voucher_narration"]=="": voucherView.append([voucherRow["voucher_code"],voucherRow["reference_number"],voucherRow["reff_date"].strftime("%d-%m-%Y"),voucherRow["voucher_type"],drAccount,crAccount,(totalAmount),voucherRow["voucher_narration"],voucherRow["lock_flag"]]) else: voucherView.append([voucherRow["voucher_code"],voucherRow["reference_number"],voucherRow["reff_date"].strftime("%d-%m-%Y"),voucherRow["voucher_type"],drAccount,crAccount,(totalAmount),voucherRow["voucher_narration"],voucherRow["lock_flag"]]) print queryParams return voucherView def xmlrpc_getVoucherMaster(self, queryParams,client_id): """ purpose: returns a record from the voucher master containing single row data for a given transaction. Returns list containing data from voucher_master. description: This function is used along with rpc_ getVoucherDetails to search a complete voucher. Useful while editing or cloning. The function takes one parameter which is a list containing vouchercode. The function makes use of the getvoucherMaster stored procedure and returns a list containing, * referencenumber *reffdate * vouchertype * project name * and voucherNarration. """ voucherMasterResult = dbconnect.execproc("getVoucherMaster", dbconnect.engines[client_id],queryParams) voucherRow = voucherMasterResult.fetchone() project = dbconnect.execproc("getProjectNameByCode",dbconnect.engines[client_id],[int(voucherRow["project_code"])]) projectRow = project.fetchone() projectName = projectRow["project_name"] if projectName == None: projectName = "No Project" voucherMaster = [voucherRow["voucher_reference"],voucherRow["reff_date"].strftime("%d-%m-%Y"),voucherRow["voucher_type"],voucherRow["voucher_narration"],projectName] print queryParams return voucherMaster def xmlrpc_getVoucherDetails(self,queryParams,client_id): """ purpose: gets the transaction related details given a vouchercode. returns a 2 dymentional list containing rows with 3 columns.takes one parameter QueryParams, which is list containing vouchercode description: The function used to get the detailed view of a voucher given its vouchercode. returns a 2 dymentional list containing rows for a transaction. the 3 columns are, accountname, typeflag (Cr/Dr) and amount. The function uses the getVoucherDetails stored procedure. """ transactions = dbconnect.execproc("getVoucherDetails",dbconnect.engines[client_id],queryParams) transactionRecords = transactions.fetchall() voucherDetails = [] for transactionRow in transactionRecords: voucherDetails.append([transactionRow["accountname"],transactionRow["transactionFlag"],'%.2f'%float(transactionRow["transactionamount"])]) print queryParams return voucherDetails def xmlrpc_editVoucher(self,queryParams_master,queryParams_details,client_id): proj_code = dbconnect.execproc("getProjectCodeByName", dbconnect.engines[client_id], [queryParams_master[2]]) projectRow = proj_code.fetchone() projectCode = projectRow[0] if projectCode == None: projectCode = 0 del queryParams_master[2] queryParams_master.insert(2,projectCode) successResult = dbconnect.execproc("editVoucherMaster", dbconnect.engines[client_id], queryParams_master) successRow = successResult.fetchone() print "here is what is in query params details" print queryParams_details if successRow["success"] == True: dbconnect.execproc("deleteVoucherDetails",dbconnect.engines[client_id],[queryParams_master[0]]) for detailRow in queryParams_details: sp_details = [] sp_details.append(queryParams_master[0]) sp_details.append(detailRow[0]) if float(detailRow[2]) == 0: print "CR has no value" sp_details.append("Dr") sp_details.append(float(detailRow[1])) if float(detailRow[1]) == 0: print "Dr has no value" sp_details.append("Cr") sp_details.append((detailRow[2])) dbconnect.execproc("editVoucherDetails",dbconnect.engines[client_id],sp_details) return True def xmlrpc_accountsCurrentBalance(self,queryParams,client_id): print queryParams if (dbconnect.user_roles[client_id]== 0) or (dbconnect.user_roles[client_id] ==-1) : CurrentBalance = [] closingBalance = dbconnect.execproc("calculateBalance", dbconnect.engines[client_id], [str(queryParams[0]),queryParams[1],queryParams[2],queryParams[3]]) closingRow = closingBalance.fetchone() print closingRow if float(closingRow["curbal"]) != 0: currbalRow = [] if closingRow["baltype"] == "Cr": currbalRow.append('%.2f'%float(closingRow["curbal"])) if closingRow["baltype"] == "Dr": currbalRow.append('%.2f'%float(closingRow["curbal"])) CurrentBalance.append(currbalRow) return CurrentBalance def xmlrpc_deleteVoucher(self,queryParams,client_id): try: dbconnect.execproc("deleteVoucher", dbconnect.engines[client_id],queryParams) return True except: return False print queryParams def xmlrpc_vouchersAfterDate(self,queryParams,client_id): """ purpose: checks if there are more vouchers after the specified date. Generally used during closing books and roll over. Description: The function takes in input parameter as a date in yyyy-mm-dd inside a list (queryParams). Returns boolean (true if there are vouchers after the date or false otherwise). This function makes use of the vouchersafterdate stored procedure. """ voucherResult = dbconnect.execproc('vouchersafterdate', dbconnect.engines[client_id], queryParams) vouchersrow = voucherResult.fetchone() if int(vouchersrow['vcount']) == 0: return False if int(vouchersrow['vcount']) > 0: return True def xmlrpc_voucherLock(self,queryParams,client_id): """ purpose: sets the lock flag for a particular voucher. Description: The function accepts list in which first parameter is voucher code and second parameter is integer value 0 or 1(0 for unlock and 1 for lock). Returns boolean(true if successful) """ voucherLockflag = dbconnect.execproc('setLockFlag', dbconnect.engines[client_id], queryParams) voucherflagRow = voucherLockflag.fetchone() return voucherflagRow[0] def xmlrpc_getvoucherLockFlag(self,queryParams,client_id): """ purpose: returns the lock flag for a particular voucher. Description: The function accepts list in which first parameter is voucher code Returns the lockflag from voucher_master table """ voucherLockflag = dbconnect.execproc('getLockFlag', dbconnect.engines[client_id], queryParams) voucherflagRow = voucherLockflag.fetchone() print "this is the lock flag",voucherflagRow return voucherflagRow[0] core_engine-2.6.1-dac679a8ec1cd01924e7b2e80280c270f69b55ac/gnukhataserver/rpc_user.py000077500000000000000000000201021265207572300267450ustar00rootroot00000000000000''' This file is part of GNUKhata:A modular,robust and Free Accounting System. GNUKhata 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. GNUKhata 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 GNUKhata (COPYING); if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA59 Temple Place, Suite 330, Contributor: "Anusha Kadambala" "Sonal Chaudhari" "Akshay Puradkar" "Ujwala Pawade" "Girish Joshi" "Sadhana Bagal " ''' #import the database connector and functions for stored procedure. import dbconnect #import the twisted modules for executing rpc calls and also to implement the server from twisted.web import xmlrpc, server #reactor from the twisted library starts the server with a published object and listens on a given port. from twisted.internet import reactor from sqlalchemy.orm.exc import NoResultFound #from mercurial.templater import if_ #inherit the class from XMLRPC to make it publishable as an rpc service. class user(xmlrpc.XMLRPC): def getUserRoleByName(self,queryParams,client_id): #this module returns the user role for the perticular user by it's name. connection = dbconnect.engines[client_id].connect() Session = dbconnect.session(bind=connection) res = Session.query(dbconnect.Users).filter(dbconnect.Users.username == queryParams[0]).first() Session.close() connection.connection.close() if res != None: print res.userrole return res.userrole else: print "no user found" return False def __init__(self): xmlrpc.XMLRPC.__init__(self) #note that all the functions to be accessed by the client must have the xmlrpc_ prefix. #the client however will not use the prefix to call the functions. def xmlrpc_setUser(self,queryParams,client_id): #admin can create the user for manager and operator and manager can create user for operator only. #another admin user cannot be created and manager cannot create user for manager. #the codes for user_roles are as follows #-1 : admin # 0 : manager # 1 : operator if ( ((dbconnect.user_roles[client_id]== -1) and ( queryParams[2] == 0 or queryParams[2] == 1)) or ((dbconnect.user_roles[client_id] == 0) and ( queryParams[2] == 1)) ) : dbconnect.execproc("addUser",dbconnect.engines[client_id],[queryParams[0],queryParams[1],queryParams[2],queryParams[3],queryParams[4]]) return 1 else: return -1 '''def xmlrpc_setPrivilege(self,queryParams): print queryParams res = dbconnect.executeProcedure("setPrivilege",False,queryParams) return True''' def xmlrpc_delUser(self, queryParams,client_id): """ purpose: deletes a user record from the userss table. description: This function takes one arguement queryParams which contains one element, the name of user to be deleted. Returns true if successful or false otherwise. """ success = dbconnect.execproc("removeuser", dbconnect.engines[client_id], queryParams) result = success.fetchone() return result['success'] def xmlrpc_getUser(self,queryParams,client_id): connection = dbconnect.engines[client_id].connect() Session = dbconnect.session(bind=connection) res = Session.query(dbconnect.Users).filter(dbconnect.Users.username == queryParams[0]).filter(dbconnect.Users.userpassword == queryParams[1]).first() Session.close() connection.connection.close() if res != None: dbconnect.addUser(client_id,queryParams[0],res.userrole) lst=[res.username, res.userrole] print lst print dbconnect.userlist return lst else: return False #multi return '''def xmlrpc_checkUser(self,queryParams,client_id): connection = dbconnect.engines[client_id].connect() Session = dbconnect.session(bind=connection) res = Session.query(dbconnect.Users).filter(dbconnect.Users.username == queryParams[0]).all() print res if res == []: return False else: return res''' def xmlrpc_changePassword(self,queryParams,client_id): #getting the role of the user whose password is to be changed. targate_user_role = self.getUserRoleByName([queryParams[0]],client_id) #if ((dbconnect.user_roles[client_id] == -1) and (targate_user_role == 0 or targate_user_role == 1 )) means admin is changing the password for the manager or operator then old password is not required. #if ((dbconnect.user_roles[client_id] == 0) and (targate_user_role == 1)) means manager is changing the password of the operator so the old password is not required. if ( ((dbconnect.user_roles[client_id] == -1) and (targate_user_role == 0 or targate_user_role == 1 )) or ((dbconnect.user_roles[client_id] == 0) and (targate_user_role == 1)) ) : result = dbconnect.execproc("adminChangePassword", dbconnect.engines[client_id], queryParams) row = result.fetchone() return row[0] elif ( (dbconnect.user_roles[client_id] == targate_user_role) and (dbconnect.userlist[client_id] == queryParams[0])) : #this condition is true when user is changing his own password, so the old password is required here. result = dbconnect.execproc("changePassword", dbconnect.engines[client_id], queryParams) row = result.fetchone() return row[0] else : #this condition occurs when the user tries to change the password of the other user having same user role or higher authority. return False def xmlrpc_isUserUnique(self,queryParams,client_id): connection = dbconnect.engines[client_id].connect() Session = dbconnect.session(bind=connection) res = Session.query(dbconnect.Users).filter(dbconnect.Users.username == queryParams[0]).all() Session.close() connection.close() if res == []: return True else: return False #this module will be accessed by the controller so this method is required. def xmlrpc_getUserRole(self,queryParams,client_id): return self.getUserRoleByName(queryParams,client_id) def xmlrpc_getUserByClientId(self,client_id): return dbconnect.getUserByClientId(client_id) #admin/user[True/False],password-yes,password-no[True/False] def xmlrpc_getUsers(self,queryParams,client_id): connection = dbconnect.engines[client_id].connect() Session = dbconnect.session(bind=connection) if queryParams[0]==True: role=0 else: role=1 res = Session.query(dbconnect.Users).filter(dbconnect.Users.userrole==role).all() users=[] for i in res: users.append(i.username) # user=[] # user.append(i.username) # user.append(i.userpassword) # users.append(user) return users def xmlrpc_getAllUsers(self,client_id): if (dbconnect.user_roles[client_id] == -1): stmt = "select username, userrole from users where userrole = '0' or userrole ='1';" res= dbconnect.engines[client_id].execute(stmt).fetchall() if res == []: return False else: res1 = [] for l in res: res1.append(l[0]) return res1 elif (dbconnect.user_roles[client_id] == 0): stmt = "select username, userrole from users where userrole='1';" res = dbconnect.engines[client_id].execute(stmt).fetchall() if res == []: return False else: res1 = [] for l in res: res1.append(l[0]) return res1 else: return False def xmlrpc_getQuestion(self,queryParams,client_id): ''' purpose: Gets the question and answer for forget password ''' res = dbconnect.execproc("getsecurityquestion", dbconnect.engines[client_id],queryParams) #suc = res.fetchone(); row = res.fetchone() qa = [row["user_question"],row["user_answer"]] return qa def xmlrpc_forgotPassword(self,queryparams,client_id): res = dbconnect.execproc("forgotPassword", dbconnect.engines[client_id],queryparams) row = res.fetchone() qa = row["success"] return qa core_engine-2.6.1-dac679a8ec1cd01924e7b2e80280c270f69b55ac/scripts/000077500000000000000000000000001265207572300232115ustar00rootroot00000000000000core_engine-2.6.1-dac679a8ec1cd01924e7b2e80280c270f69b55ac/scripts/adduser.sh000077500000000000000000000020171265207572300251770ustar00rootroot00000000000000#!/bin/bash # Read configuration . `dirname $0`/init.sh # add gnukhata system user (requires adduser >= 3.34) # don't muck around with this unless you KNOW what you're doing if [ -f ${CONFIG} ] then user=$(awk '/^user/{print $3}' "${CONFIG}") else echo "${CONFIG} not found" exit 1 fi function userexistmessage { if [ `getent passwd $user|awk -F ':' '{print $3}'` -gt 999 ] >/dev/null ; then echo "Non-system user $user found. I will not overwrite a non-system" >&2 echo "user. Remove the user and reinstall gnukhata." >&2 exit 1 fi # unknown adduser error, simply exit } echo "Creating/updating $user user account..." if [ -f /etc/redhat-release ] then adduser --system --home /var/run/$user \ --shell /bin/false $user || { # adduser failed. Why? userexistmessage exit 1 } else adduser --system --home /var/run/$user \ --gecos "$user system user" --shell /bin/false \ --quiet --disabled-password $user || { # adduser failed. Why? userexistmessage exit 1 } fi core_engine-2.6.1-dac679a8ec1cd01924e7b2e80280c270f69b55ac/scripts/gnukhata-core-engine.init000077500000000000000000000063521265207572300301020ustar00rootroot00000000000000#!/bin/sh # Copyright 2014 Praveen Arimbrathodityil # Copyright 1998-2002, 2004, 2005 Branden Robinson . # Copyright 2006 Eugene Konev # # This is free software; you may redistribute it and/or modify # it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2, # or (at your option) any later version. # # This 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 with # the Debian operating system, in /usr/share/common-licenses/GPL; if # not, write to the Free Software Foundation, Inc., 59 Temple Place, # Suite 330, Boston, MA 02111-1307 USA ### BEGIN INIT INFO # Provides: gnukhata-core-engine # Description: Free Accounting Software # Required-Start: $local_fs $remote_fs postgresql # Required-Stop: $local_fs $remote_fs # Should-Start: # Should-Stop: # Default-Start: 2 3 4 5 # Default-Stop: 0 1 6 # Short-Description: Free Accounting Software ### END INIT INFO set -e PATH=/bin:/usr/bin:/sbin:/usr/sbin DAEMON=/usr/bin/gkstart . /usr/lib/gnukhata/scripts/init.sh if [ -f ${CONFIG} ] then USER=$(awk '/^user/{print $3}' "${CONFIG}") PIDFILE=$(awk '/^pidfile/{print $3}' "${CONFIG}") if [ "x${PIDFILE}" = "x" ] then echo "Cannot find pidfile in ${CONFIG}" exit 1 fi else echo "${CONFIG} not found" exit 1 fi test -x $DAEMON || exit 0 . /lib/lsb/init-functions SSD_START_ARGS="--pidfile $PIDFILE --chuid $USER --exec $DAEMON --startas $DAEMON" SSD_STOP_ARGS="--pidfile $PIDFILE --chuid $USER --retry TERM/5/TERM/5" case "$1" in start) # create run directory if ! [ -d /var/run/gnukhata ]; then install -d -m 2775 -o gnukhata /var/run/gnukhata [ -x /sbin/restorecon ] && restorecon -R /var/run/gnukhata || true fi # start gnukhata if not running already if ! status_of_proc -p $PIDFILE $DAEMON gnukhata-core-engine >/dev/null then log_daemon_msg "Starting GNUKhata core engine" start-stop-daemon --start --quiet $SSD_START_ARGS else log_daemon_msg "GNUKhata core engine is already running" fi log_end_msg 0 ;; restart) /etc/init.d/gnukhata-core-engine stop /etc/init.d/gnukhata-core-engine start ;; force-reload) rm -rf $PIDFILE if [ `ps ax |grep gkstart |wc -l` -eq 2 ] then killall -9 gkstart fi [ -f $PIDFILE ] && exit 1 /etc/init.d/gnukhata-core-engine start ;; stop) # stop gnukhata if running if status_of_proc -p $PIDFILE $DAEMON gnukhata-core-engine >/dev/null then log_daemon_msg "Stopping GNUKhata core engine" start-stop-daemon --stop --quiet $SSD_STOP_ARGS rm -rf $PIDFILE else log_daemon_msg "GNUKhata core engine is not running" fi log_end_msg 0 ;; status) status_of_proc -p $PIDFILE $DAEMON gnukhata-core-engine && exit 0 || exit $? ;; *) echo "Usage: /etc/init.d/gnukhata-core-engine {start|stop|restart|force-reload|status}" exit 1 ;; esac exit 0 # vim:set ai et sts=2 sw=2 tw=80: core_engine-2.6.1-dac679a8ec1cd01924e7b2e80280c270f69b55ac/scripts/grantpriv.sh000077500000000000000000000005531265207572300255670ustar00rootroot00000000000000#!/bin/sh # Read configuration . `dirname $0`/init.sh user=$(awk '/^user/{print $3}' "${CONFIG}") echo "Allow $user user to create databases..." sudo -u postgres psql -c "ALTER USER $user CREATEDB;" || { exit 1 } echo "Grant all privileges to $user user..." sudo -u postgres psql -c "GRANT ALL PRIVILEGES ON DATABASE template1 to $user;" || { exit 1 }core_engine-2.6.1-dac679a8ec1cd01924e7b2e80280c270f69b55ac/scripts/init.sh000077500000000000000000000002431265207572300245120ustar00rootroot00000000000000#!/bin/sh # Check if CONFIG environment variable is defined if [ "x${CONFIG}" = "x" ] then # Use /etc/gnukhata.conf as config file CONFIG=/etc/gnukhata.conf fi core_engine-2.6.1-dac679a8ec1cd01924e7b2e80280c270f69b55ac/setup.py000077500000000000000000000022121265207572300232340ustar00rootroot00000000000000from distutils.core import setup setup(name = "gnukhataserver", version = "1.0", description = "A free and open source accounting and book keeping software.", author = "Krishnakant Mane, Ankita Shanbhag", author_email = "krmane@gmail.com, ankitargs@gmail.com", url = "www.gnukhata.org", #Name the folder where your packages live: #(If you have other packages (dirs) or modules (py files) then #put them into the package directory - they will be found #recursively.) packages = ['gnukhataserver'], #'package' package must contain files (see list above) #I called the package 'package' thus cleverly confusing the whole issue... #This dict maps the package name =to=> directories #It says, package *needs* these files. #package_data = {'package' : files }, #'runner' is in the root. scripts = ["gkstart"], long_description = """GNUKhata is a foss based accounting and inventory software that helps book keeping for small scale enterprises as well as big organisations.""" # #This next part it for the Cheese Shop, look a little down the page. #classifiers = [] ) core_engine-2.6.1-dac679a8ec1cd01924e7b2e80280c270f69b55ac/stdeb.cfg000077500000000000000000000001401265207572300233020ustar00rootroot00000000000000[DEFAULT] Depends: postgresql-8.4, python-twisted, python-psycopg2, python-sqlalchemy, sqlite3 core_engine-2.6.1-dac679a8ec1cd01924e7b2e80280c270f69b55ac/tests/000077500000000000000000000000001265207572300226645ustar00rootroot00000000000000core_engine-2.6.1-dac679a8ec1cd01924e7b2e80280c270f69b55ac/tests/__init__.py000077500000000000000000000000001265207572300247660ustar00rootroot00000000000000core_engine-2.6.1-dac679a8ec1cd01924e7b2e80280c270f69b55ac/tests/test_account.py000077500000000000000000000074301265207572300257400ustar00rootroot00000000000000''' This file is part of GNUKhata:A modular,robust and Free Accounting System. GNUKhata 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. GNUKhata 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 GNUKhata (COPYING); if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA59 Temple Place, Suite 330, Contributor: "Anusha Kadambala" ''' import xmlrpclib class test_people: def setUp(self): self.server = xmlrpclib.Server("http://localhost:7081") self.dbname = ["testdatabase","1950-51"] self.client_id = self.server.getConnection(self.dbname) def test_setAccount(self): result = self.server.account.setAccount([1,'Anusha','Sundry Creditors','vendor',1234,'2010-03-03',0],self.client_id) assert result def test_editAccount(self): result = self.server.account.editAccount([16,1,'Anusha','Sundry Creditors','vendor edited',12344,'2010-03-03',0],self.client_id) assert result def test_getAccountNames(self): result = self.server.account.getAccountNames([1],self.client_id) assert result def test_getAccountWithOpeningBalance_ass(self): result = self.server.account.getAccountWithOpeningBalance_ass(self.client_id) assert result def test_getAccountWithOpeningBalance_Lia(self): result = self.server.account.getAccountWithOpeningBalance_Lia(self.client_id) assert result def test_getAccountWithOpeningBalance_IExp(self): result = self.server.account.getAccountWithOpeningBalance_IExp(self.client_id) assert result def test_getAccountWithOpeningBalance_DExp(self): result = self.server.account.getAccountWithOpeningBalance_DExp(self.client_id) assert result def test_getAccountWithOpeningBalance_Inc(self): result = self.server.account.getAccountWithOpeningBalance_Inc(self.client_id) assert result def test_getAccountWithOpeningBalance_DInc(self): result = self.server.account.getAccountWithOpeningBalance_DInc(self.client_id) assert result def test_getAllAccountNamesByLedger(self): result = self.server.account.getAllAccountNamesByLedger(self.client_id) assert result def test_getAllAccounts(self): result = self.server.account.getAllAccounts(self.client_id) assert result def testbycode_getAccount(self): result = self.server.account.getAccount(['code',1],self.client_id) assert result def testbyname_getAccount(self): result = self.server.account.getAccount(['name','Sales Return A/C'],self.client_id) assert result def test_getAccountByGroup(self): result = self.server.account.getAccountByGroup(['Asset'],self.client_id) assert result def test_getAllAccountBank(self): result = self.server.account.getAllAccountBank(self.client_id) assert result def test_getAccount_basedon(self): result = self.server.account.getAccount_basedon(['Sales Return A/C'],self.client_id) assert result def testcraccount_updateAccountBalance(self): result = self.server.account.updateAccountBalance(['Sales Return A/C',1000,'craccount'],self.client_id) assert result def testdraccount_updateAccountBalance(self): result = self.server.account.updateAccountBalance(['Sales Return A/C',1000,'draccount'],self.client_id) assert result def test_getFinalAccounts(self): result = self.server.account.getFinalAccounts([1],self.client_id) assert result def TearDown(self): self.server.closeConnection(self.client_id) core_engine-2.6.1-dac679a8ec1cd01924e7b2e80280c270f69b55ac/tests/test_cashbook.py000077500000000000000000000034751265207572300261020ustar00rootroot00000000000000''' This file is part of GNUKhata:A modular,robust and Free Accounting System. GNUKhata 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. GNUKhata 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 GNUKhata (COPYING); if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA59 Temple Place, Suite 330, Contributor: "Anusha Kadambala" ''' import xmlrpclib,datetime class test_cashbook: def setUp(self): self.server = xmlrpclib.Server("http://localhost:7081") self.dbname = ["testdatabase","1950-51"] self.client_id = self.server.getConnection(self.dbname) self.today_date = datetime.date.today().strftime('%Y-%m-%d') def test_setCashbook(self): res = self.server.voucher.getVoucherCode(self.client_id) if res: result = self.server.cashbook.setCashBook([res,self.today_date,self.today_date,'paid 1000 towards book'],[[res,'dr','Anusha',1000],[res,'cr','Cash',1000]],self.client_id) assert result def test_getVoucher(self): result = self.server.cashbook.getVoucher([1],self.client_id) assert result def test_editVoucher(self): result = self.server.cashbook.editVoucher([1,self.today_date,self.today_date,'paid 3000 towards book'],[[1,'dr','Anusha',3000],[1,'cr','Cash',3000]],self.client_id) assert result def TearDown(self): self.server.closeConnection(self.client_id) core_engine-2.6.1-dac679a8ec1cd01924e7b2e80280c270f69b55ac/tests/test_category.py000077500000000000000000000033171265207572300261210ustar00rootroot00000000000000''' This file is part of GNUKhata:A modular,robust and Free Accounting System. GNUKhata 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. GNUKhata 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 GNUKhata (COPYING); if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA59 Temple Place, Suite 330, Contributor: "Anusha Kadambala" ''' import xmlrpclib,datetime class test_category: def setUp(self): self.server = xmlrpclib.Server("http://localhost:7081") self.dbname = ["testdatabase","1950-51"] self.client_id = self.server.getConnection(self.dbname) self.count=str(len(self.server.category.getCategories(self.client_id))) def test_setCategoryMaster(self): result = self.server.category.setCategoryMaster(['books'+self.count,'reading materials for all age-groups'+self.count],[['language'+self.count,'text','y'],['agegroup'+self.count,'text','n']],self.client_id) assert result def test_getCategorySpecs(self): result = self.server.category.getCategorySpecs([1],self.client_id) assert result def test_getCategories(self): result = self.server.category.getCategories(self.client_id) assert result def TearDown(self): self.server.closeConnection(self.client_id) core_engine-2.6.1-dac679a8ec1cd01924e7b2e80280c270f69b55ac/tests/test_contravoucher.py000077500000000000000000000024311265207572300271620ustar00rootroot00000000000000''' This file is part of GNUKhata:A modular,robust and Free Accounting System. GNUKhata 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. GNUKhata 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 GNUKhata (COPYING); if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA59 Temple Place, Suite 330, Contributor: "Anusha Kadambala" ''' import xmlrpclib,datetime class test_contravoucher: def setUp(self): self.server = xmlrpclib.Server("http://localhost:7081") self.dbname = ["testdatabase","1950-51"] self.client_id = self.server.getConnection(self.dbname) def test_getContraAccounts(self): result = self.server.contravoucher.getContraAccounts(self.client_id) assert result def TearDown(self): self.server.closeConnection(self.client_id) core_engine-2.6.1-dac679a8ec1cd01924e7b2e80280c270f69b55ac/tests/test_data.py000077500000000000000000000025721265207572300252170ustar00rootroot00000000000000''' This file is part of GNUKhata:A modular,robust and Free Accounting System. GNUKhata 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. GNUKhata 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 GNUKhata (COPYING); if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA59 Temple Place, Suite 330, Contributor: "Anusha Kadambala" ''' import xmlrpclib,datetime class test_data: def setUp(self): self.server = xmlrpclib.Server("http://localhost:7081") self.dbname = ["testdatabase","1950-51"] self.client_id = self.server.getConnection(self.dbname) def test_getStateNames(self): result = self.server.data.getStateNames(self.client_id) assert result def test_getCityNames(self): result = self.server.data.getCityNames(['Andhra Pradesh'],self.client_id) assert result def TearDown(self): self.server.closeConnection(self.client_id) core_engine-2.6.1-dac679a8ec1cd01924e7b2e80280c270f69b55ac/tests/test_deploy.py000077500000000000000000000033761265207572300256050ustar00rootroot00000000000000''' This file is part of GNUKhata:A modular,robust and Free Accounting System. GNUKhata 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. GNUKhata 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 GNUKhata (COPYING); if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA59 Temple Place, Suite 330, Contributor: "Anusha Kadambala" ''' import xmlrpclib class test_deploy: def setUp(self): self.server = xmlrpclib.Server("http://localhost:7081"); self.queryParams = ["testdatabase","1950-51"] def test_deploy(self): if self.queryParams[1] not in self.server.getFinancialYear(self.queryParams[0]): result = self.server.Deploy(self.queryParams) assert result def test_getConnection(self): self.client_id = self.server.getConnection(self.queryParams) assert type(self.client_id)==int,"Int output expected" def test_getOrganisationNames(self): result = self.server.getOrganisationNames() assert result def test_getFinancialYear(self): res = self.server.getOrganisationNames() if res: result = self.server.getFinancialYear(res[0]) assert result def test_getDatabase(self): result = self.server.getDatabase() assert result def TearDown(self): self.server.closeConnection(self.client_id) core_engine-2.6.1-dac679a8ec1cd01924e7b2e80280c270f69b55ac/tests/test_groups.py000077500000000000000000000044171265207572300256250ustar00rootroot00000000000000''' This file is part of GNUKhata:A modular,robust and Free Accounting System. GNUKhata 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. GNUKhata 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 GNUKhata (COPYING); if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA59 Temple Place, Suite 330, Contributor: "Anusha Kadambala" ''' import xmlrpclib class test_groups: def setUp(self): self.server = xmlrpclib.Server("http://localhost:7081") self.dbname = ["testdatabase","1950-51"] self.client_id = self.server.getConnection(self.dbname) def test_setGroups(self): result = self.server.groups.setGroups(['Petty Cash','','Accounts involving petty cash',0.00],self.client_id) assert result def test_getGroupByCode(self): result = self.server.groups.getGroupByCode([1],self.client_id) assert result def test_getAllGroups(self): result = self.server.groups.getAllGroups(self.client_id) assert result def test_drupdateGroupBalance(self): result = self.server.groups.updateGroupBalance([1,1000,'draccount'],self.client_id) assert result def test_crupdateGroupBalance(self): result = self.server.groups.updateGroupBalance([1,1000,'craccount'],self.client_id) assert result def test_getGroupByName(self): result = self.server.groups.getGroupByName(['Cash'],self.client_id) assert result def test_editGroups(self): result = self.server.groups.editGroups([1,'Asset','','',0.00],self.client_id) assert result def test_getGroupNames(self): result = self.server.groups.getGroupNames(self.client_id) assert result def test_getGroupNameByAccountName(self): result = self.server.groups.getGroupNameByAccountName(['Cash'],self.client_id) assert result def TearDown(self): self.server.closeConnection(self.client_id) core_engine-2.6.1-dac679a8ec1cd01924e7b2e80280c270f69b55ac/tests/test_organisation.py000077500000000000000000000043531265207572300270020ustar00rootroot00000000000000''' This file is part of GNUKhata:A modular,robust and Free Accounting System. GNUKhata 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. GNUKhata 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 GNUKhata (COPYING); if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA59 Temple Place, Suite 330, Contributor: "Anusha Kadambala" ''' import xmlrpclib class test_organisation: def setUp(self): self.server = xmlrpclib.Server("http://localhost:7081") self.dbname = ["testdatabase","1950-51"] self.client_id = self.server.getConnection(self.dbname) self.count=str(self.server.people.getCountMaster(self.client_id)) def test_setOrganisation(self): result = self.server.organisation.setOrganisation(['AD LTD','NGO','P10122','Anusha','Dream land home,Powai','Mumbai','400 102','Maharastra','India','23234242,323232','3123213213','www.website.com','email@email.com'],self.client_id) assert result def testbycode_getOrganisation(self): result = self.server.organisation.getOrganisation(['code',1],self.client_id) assert result def testbyname_getOrganisation(self): result = self.server.organisation.getOrganisation(['name','AD LTD'],self.client_id) assert result def test_editOrganisation(self): result = self.server.organisation.editOrganisation([1,'AD LTD','NPO','P10122','Anusha D','Sweet home, Dream land,Powai','Mumbai','400 102','Maharastra','India','23234242,323232','3123213213','www.website.com','email@email.com'],self.client_id) assert result def test_getOrganisationNames(self): result = self.server.organisation.getOrganisationNames(self.client_id) assert result def test_getAllOrganisation(self): result = self.server.organisation.getAllOrganisation(self.client_id) assert result core_engine-2.6.1-dac679a8ec1cd01924e7b2e80280c270f69b55ac/tests/test_people.py000077500000000000000000000052211265207572300255640ustar00rootroot00000000000000''' This file is part of GNUKhata:A modular,robust and Free Accounting System. GNUKhata 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. GNUKhata 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 GNUKhata (COPYING); if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA59 Temple Place, Suite 330, Contributor: "Anusha Kadambala" ''' import xmlrpclib class test_people: def setUp(self): self.server = xmlrpclib.Server("http://localhost:7081") self.dbname = ["testdatabase","1950-51"] self.client_id = self.server.getConnection(self.dbname) self.count=str(self.server.people.getCountMaster(self.client_id)) self.queryParams_master = [['Title'+self.count,'Text'],['Rate per day'+self.count,'Float']] self.queryParams_details =['v'+self.count,'anusha'+self.count,'vendor','angel palace,happy lane'+self.count,'mumbai','400103','mah','india',324343324,2432432,'','','www.anusha.com','anu@anusha.com','Anusha'+self.count] def test_setPeopleMaster(self): result = self.server.people.setPeopleMaster(self.queryParams_master,self.client_id) assert result def test_setPeopleDetails(self): result = self.server.people.getPeopleMaster(self.client_id) if result: for r in result: if r[2] == 'Float': self.queryParams_details.append(float(self.count)) else: self.queryParams_details.append(r[1]+self.count) res = self.server.people.setPeopleDetails(self.queryParams_details,self.client_id) assert res else: assert result,"Get Master Method Failed" def test_getAllPeople(self): people = self.server.people.getAllPeople(self.client_id) assert people,"People details are not there" def testbycode_getPeopleDetails(self): res = self.server.people.getPeopleDetails(['code','v2'],self.client_id) assert res," Get People details By code failed" def testbyname_getPeopleDetails(self): res = self.server.people.getPeopleDetails(['name','anusha2'],self.client_id) assert res," Get People details By name failed" def test_getPeopleMasterById(self): res = self.server.people.getPeopleMasterById([1],self.client_id) assert res def TearDown(self): self.server.closeConnection(self.client_id) core_engine-2.6.1-dac679a8ec1cd01924e7b2e80280c270f69b55ac/tests_readme000077500000000000000000000002511265207572300241250ustar00rootroot00000000000000this is a file for instructions on tests. The tests could be run using nosetest or trial. nosetest and trial are 2 test suitsout of which trial is for twisted library.