From 53c1aced4aee50ae22cab2f064f4a670998713e5 Mon Sep 17 00:00:00 2001 From: jdolkowski Date: Wed, 17 May 2023 16:48:17 +0200 Subject: [PATCH 01/50] CM-25: initial module structure --- .github/workflows/openmis-module-test.yml | 100 ++++ .github/workflows/python-publish.yml | 38 ++ .gitignore | 10 + LICENSE | 661 ---------------------- LICENSE.md | 14 + MANIFEST.md | 2 + README.md | 1 + setup.py | 38 ++ social_protection/__init__.py | 0 social_protection/admin.py | 3 + social_protection/apps.py | 6 + social_protection/migrations/__init__.py | 0 social_protection/models.py | 3 + social_protection/tests.py | 3 + social_protection/urls.py | 1 + social_protection/views.py | 3 + 16 files changed, 222 insertions(+), 661 deletions(-) create mode 100644 .github/workflows/openmis-module-test.yml create mode 100644 .github/workflows/python-publish.yml create mode 100644 .gitignore delete mode 100644 LICENSE create mode 100644 LICENSE.md create mode 100644 MANIFEST.md create mode 100644 README.md create mode 100644 setup.py create mode 100644 social_protection/__init__.py create mode 100644 social_protection/admin.py create mode 100644 social_protection/apps.py create mode 100644 social_protection/migrations/__init__.py create mode 100644 social_protection/models.py create mode 100644 social_protection/tests.py create mode 100644 social_protection/urls.py create mode 100644 social_protection/views.py diff --git a/.github/workflows/openmis-module-test.yml b/.github/workflows/openmis-module-test.yml new file mode 100644 index 0000000..6e6b63b --- /dev/null +++ b/.github/workflows/openmis-module-test.yml @@ -0,0 +1,100 @@ +name: Automated CI testing +# This workflow run automatically for every commit on github it checks the syntax and launch the tests. +# | grep . | uniq -c filters out empty lines and then groups consecutive lines together with the number of occurrences +on: + pull_request: + workflow_dispatch: + inputs: + comment: + description: Just a simple comment to know the purpose of the manual build + required: false + +jobs: + run_test: + runs-on: ubuntu-latest + services: + mssql: + image: mcr.microsoft.com/mssql/server:2017-latest + env: + ACCEPT_EULA: Y + SA_PASSWORD: GitHub999 + ports: + - 1433:1433 + # needed because the mssql container does not provide a health check + options: --health-interval=10s --health-timeout=3s --health-start-period=10s --health-retries=10 --health-cmd="/opt/mssql-tools/bin/sqlcmd -S localhost -U sa -P ${SA_PASSWORD} -Q 'SELECT 1' || exit 1" + + steps: + - name: Set up Python 3.8 + uses: actions/setup-python@v2 + with: + python-version: 3.8 + - name: install linux packages + run: | + wget https://raw.githubusercontent.com/openimis/database_ms_sqlserver/main/Empty%20databases/openIMIS_ONLINE.sql -O openIMIS_ONLINE.sql + wget https://raw.githubusercontent.com/openimis/database_ms_sqlserver/main/Demo%20database/openIMIS_demo_ONLINE.sql -O openIMIS_demo_ONLINE.sql + curl https://packages.microsoft.com/keys/microsoft.asc | sudo apt-key add - + curl https://packages.microsoft.com/config/ubuntu/20.04/prod.list | sudo tee /etc/apt/sources.list.d/msprod.list + sudo apt-get update + sudo ACCEPT_EULA=Y apt-get install -y mssql-tools build-essential dialog apt-utils unixodbc-dev -y + python -m pip install --upgrade pip + - name: pull openimis backend + run: | + rm ./openimis -rf + git clone --depth 1 --branch develop https://github.com/openimis/openimis-be_py.git ./openimis + - name: copy current branch + uses: actions/checkout@v2 + with: + path: './current-module' + - name: Update the configuration + working-directory: ./openimis + run: | + export MODULE_NAME="$(echo $GITHUB_REPOSITORY | sed 's#^openimis/openimis-be-\(.*\)_py$#\1#')" + echo "the local module called $MODULE_NAME will be injected in openIMIS .json" + jq --arg name "$MODULE_NAME" 'if [.modules[].name == ($name)]| max then (.modules[] | select(.name == ($name)) | .pip)|="../current-module" else .modules |= .+ [{name:($name), pip:"../current-module"}] end' openimis.json + echo $(jq --arg name "$MODULE_NAME" 'if [.modules[].name == ($name)]| max then (.modules[] | select(.name == ($name)) | .pip)|="../current-module" else .modules |= .+ [{name:($name), pip:"../current-module"}] end' openimis.json) > openimis.json + - name: Install openIMIS Python dependencies + working-directory: ./openimis + run: | + pip install -r requirements.txt + python modules-requirements.py openimis.json > modules-requirements.txt + cat modules-requirements.txt + pip install -r modules-requirements.txt + - name: Environment info + working-directory: ./openimis + run: | + pip list + - name: Initialize DB + run: | + /opt/mssql-tools/bin/sqlcmd -S localhost,1433 -U SA -P $SA_PASSWORD -Q 'DROP DATABASE IF EXISTS imis' + /opt/mssql-tools/bin/sqlcmd -S localhost,1433 -U SA -P $SA_PASSWORD -Q 'CREATE DATABASE imis' + /opt/mssql-tools/bin/sqlcmd -S localhost,1433 -U SA -P $SA_PASSWORD -d imis -i openIMIS_ONLINE.sql | grep . | uniq -c + /opt/mssql-tools/bin/sqlcmd -S localhost,1433 -U SA -P $SA_PASSWORD -d imis -i openIMIS_demo_ONLINE.sql | grep . | uniq -c + env: + SA_PASSWORD: GitHub999 + ACCEPT_EULA: Y + +# - name: Check formatting with black +# run: | +# black --check . + + - name: Django tests + working-directory: ./openimis/openIMIS + run: | + export MODULE_NAME="$(echo $GITHUB_REPOSITORY | sed 's#^openimis/openimis-be-\(.*\)_py$#\1#')" + python -V + ls -l + python manage.py migrate + python init_test_db.py | grep . | uniq -c + python manage.py test --keepdb $MODULE_NAME + env: + SECRET_KEY: secret + DEBUG: true + #DJANGO_SETTINGS_MODULE: hat.settings + DB_HOST: localhost + DB_PORT: 1433 + DB_NAME: imis + DB_USER: sa + DB_PASSWORD: GitHub999 + #DEV_SERVER: true + SITE_ROOT: api + REMOTE_USER_AUTHENTICATION: True diff --git a/.github/workflows/python-publish.yml b/.github/workflows/python-publish.yml new file mode 100644 index 0000000..f591ca8 --- /dev/null +++ b/.github/workflows/python-publish.yml @@ -0,0 +1,38 @@ +# This workflows will upload a Python Package using Twine when a release is created +# For more information see: https://help.github.com/en/actions/language-and-framework-guides/using-python-with-github-actions#publishing-to-package-registries + +name: Upload Python Package + +on: + release: + types: [created] + +jobs: + deploy: + + runs-on: ubuntu-latest + + steps: + - uses: olegtarasov/get-tag@v2.1 + id: tagName + - uses: actions/checkout@v2 + - name: Set up Python + uses: actions/setup-python@v2 + with: + python-version: '3.x' + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install setuptools wheel twine jq + + - name: update setup.py + run: | + echo "tag to use $GIT_TAG_NAME" + sed -i "s/version='.*'/version='$GIT_TAG_NAME'/g" setup.py + - name: Build and publish + env: + TWINE_USERNAME: __token__ + TWINE_PASSWORD: ${{secrets.PYPI_TOKEN}} + run: | + python setup.py sdist bdist_wheel + twine upload dist/* diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9311e1c --- /dev/null +++ b/.gitignore @@ -0,0 +1,10 @@ +**/venv +**/.env +**/.idea +**/__pycache__ +build +dist +*.egg-info +**/.vscode +**/*.mo +locale/__init__.py diff --git a/LICENSE b/LICENSE deleted file mode 100644 index 0ad25db..0000000 --- a/LICENSE +++ /dev/null @@ -1,661 +0,0 @@ - GNU AFFERO GENERAL PUBLIC LICENSE - Version 3, 19 November 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 Affero General Public License is a free, copyleft license for -software and other kinds of works, specifically designed to ensure -cooperation with the community in the case of network server software. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -our General Public Licenses are 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. - - 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. - - Developers that use our General Public Licenses protect your rights -with two steps: (1) assert copyright on the software, and (2) offer -you this License which gives you legal permission to copy, distribute -and/or modify the software. - - A secondary benefit of defending all users' freedom is that -improvements made in alternate versions of the program, if they -receive widespread use, become available for other developers to -incorporate. Many developers of free software are heartened and -encouraged by the resulting cooperation. However, in the case of -software used on network servers, this result may fail to come about. -The GNU General Public License permits making a modified version and -letting the public access it on a server without ever releasing its -source code to the public. - - The GNU Affero General Public License is designed specifically to -ensure that, in such cases, the modified source code becomes available -to the community. It requires the operator of a network server to -provide the source code of the modified version running there to the -users of that server. Therefore, public use of a modified version, on -a publicly accessible server, gives the public access to the source -code of the modified version. - - An older license, called the Affero General Public License and -published by Affero, was designed to accomplish similar goals. This is -a different license, not a version of the Affero GPL, but Affero has -released a new version of the Affero GPL which permits relicensing under -this license. - - 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 Affero 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. Remote Network Interaction; Use with the GNU General Public License. - - Notwithstanding any other provision of this License, if you modify the -Program, your modified version must prominently offer all users -interacting with it remotely through a computer network (if your version -supports such interaction) an opportunity to receive the Corresponding -Source of your version by providing access to the Corresponding Source -from a network server at no charge, through some standard or customary -means of facilitating copying of software. This Corresponding Source -shall include the Corresponding Source for any work covered by version 3 -of the GNU General Public License that is incorporated pursuant to the -following paragraph. - - 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 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 work with which it is combined will remain governed by version -3 of the GNU General Public License. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU Affero 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 Affero 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 Affero 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 Affero 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 Affero 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 Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If your software can interact with users remotely through a computer -network, you should also make sure that it provides a way for users to -get its source. For example, if your program is a web application, its -interface could display a "Source" link that leads users to an archive -of the code. There are many ways you could offer source, and different -solutions will be better for different programs; see section 13 for the -specific requirements. - - 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 AGPL, see -. diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..1afba5f --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,14 @@ + +The program users must agree to the following terms: + +License notices +This program is free software: you can redistribute it and/or modify it under the terms of the GNU AGPL v3 License as published by the Free Software Foundation, version 3 of the License. +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 AGPL v3 License for more details www.gnu.org. + +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. + +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. + +In case of dispute arising out or in relation to the use of the program, it is subject to the public law of Switzerland. The place of jurisdiction is Berne. diff --git a/MANIFEST.md b/MANIFEST.md new file mode 100644 index 0000000..7425f8e --- /dev/null +++ b/MANIFEST.md @@ -0,0 +1,2 @@ +include LICENSE.md +include README.md diff --git a/README.md b/README.md new file mode 100644 index 0000000..aaa9c2c --- /dev/null +++ b/README.md @@ -0,0 +1 @@ +# openIMIS Backend social_protection reference module diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..1566170 --- /dev/null +++ b/setup.py @@ -0,0 +1,38 @@ +import os +from setuptools import find_packages, setup + +with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme: + README = readme.read() + +# allow setup.py to be run from any path +os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) + +setup( + name='openimis-be-social_protection', + version='1.0.0', + packages=find_packages(), + include_package_data=True, + license='GNU AGPL v3', + description='The openIMIS Backend social_protection reference module.', + long_description=README, + long_description_content_type='text/markdown', + url='https://openimis.org/', + author='Jan Dolkowski', + author_email='jdolkowski@soldevelo.com', + install_requires=[ + 'django', + 'django-db-signals', + 'djangorestframework', + 'openimis-be-core' + ], + classifiers=[ + 'Environment :: Web Environment', + 'Framework :: Django', + 'Framework :: Django :: 3.0', + 'Intended Audience :: Developers', + 'License :: OSI Approved :: GNU Affero General Public License v3', + 'Operating System :: OS Independent', + 'Programming Language :: Python', + 'Programming Language :: Python :: 3.8', + ], +) diff --git a/social_protection/__init__.py b/social_protection/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/social_protection/admin.py b/social_protection/admin.py new file mode 100644 index 0000000..8c38f3f --- /dev/null +++ b/social_protection/admin.py @@ -0,0 +1,3 @@ +from django.contrib import admin + +# Register your models here. diff --git a/social_protection/apps.py b/social_protection/apps.py new file mode 100644 index 0000000..c208612 --- /dev/null +++ b/social_protection/apps.py @@ -0,0 +1,6 @@ +from django.apps import AppConfig + + +class SocialProtectionConfig(AppConfig): + default_auto_field = 'django.db.models.BigAutoField' + name = 'social_protection' diff --git a/social_protection/migrations/__init__.py b/social_protection/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/social_protection/models.py b/social_protection/models.py new file mode 100644 index 0000000..71a8362 --- /dev/null +++ b/social_protection/models.py @@ -0,0 +1,3 @@ +from django.db import models + +# Create your models here. diff --git a/social_protection/tests.py b/social_protection/tests.py new file mode 100644 index 0000000..7ce503c --- /dev/null +++ b/social_protection/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/social_protection/urls.py b/social_protection/urls.py new file mode 100644 index 0000000..637600f --- /dev/null +++ b/social_protection/urls.py @@ -0,0 +1 @@ +urlpatterns = [] diff --git a/social_protection/views.py b/social_protection/views.py new file mode 100644 index 0000000..91ea44a --- /dev/null +++ b/social_protection/views.py @@ -0,0 +1,3 @@ +from django.shortcuts import render + +# Create your views here. From 830f5297b33e5ab17ee382b69bf1eb18c234b293 Mon Sep 17 00:00:00 2001 From: jdolkowski Date: Thu, 18 May 2023 12:14:34 +0200 Subject: [PATCH 02/50] CM-25: add social_protection app config --- social_protection/apps.py | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/social_protection/apps.py b/social_protection/apps.py index c208612..018b223 100644 --- a/social_protection/apps.py +++ b/social_protection/apps.py @@ -1,6 +1,33 @@ from django.apps import AppConfig +DEFAULT_CONFIG = { + "gql_benefit_plan_search_perms": ["160001"], + "gql_benefit_plan_create_perms": ["160002"], + "gql_benefit_plan_update_perms": ["160003"], + "gql_benefit_plan_delete_perms": ["160004"], +} + class SocialProtectionConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'social_protection' + + gql_benefit_plan_search_perms = None + gql_benefit_plan_create_perms = None + gql_benefit_plan_update_perms = None + gql_benefit_plan_delete_perms = None + + def ready(self): + from core.models import ModuleConfiguration + + cfg = ModuleConfiguration.get_or_default(self.name, DEFAULT_CONFIG) + self.__load_config(cfg) + + @classmethod + def __load_config(cls, cfg): + """ + Load all config fields that match current AppConfig class fields, all custom fields have to be loaded separately + """ + for field in cfg: + if hasattr(SocialProtectionConfig, field): + setattr(SocialProtectionConfig, field, cfg[field]) From c62cb26a51518cc2e80a906c6d9faf855a401eb7 Mon Sep 17 00:00:00 2001 From: jdolkowski Date: Thu, 18 May 2023 12:38:04 +0200 Subject: [PATCH 03/50] CM-25: create BenefitPlan model --- social_protection/models.py | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/social_protection/models.py b/social_protection/models.py index 71a8362..1d03d07 100644 --- a/social_protection/models.py +++ b/social_protection/models.py @@ -1,3 +1,23 @@ from django.db import models +from core import models as core_models +from policyholder.models import PolicyHolder -# Create your models here. + +class BenefitPlan(core_models.HistoryBusinessModel): + code = models.CharField(db_column='Code', max_length=50, null=False) + name = models.CharField(db_column='NameBF', max_length=255, null=False) + date_from = models.DateTimeField(db_column="DateFrom") + date_to = models.DateTimeField(db_column="DateTo") + max_beneficiaries = models.SmallIntegerField(db_column="MaxNoBeneficiaries") + ceiling_per_beneficiary = models.DecimalField(db_column="BeneficiaryCeiling", + max_digits=18, + decimal_places=2, + blank=True, + null=True, + ) + organization = models.ForeignKey(PolicyHolder, models.DO_NOTHING, db_column='Organization', blank=True, null=True) + schema = models.TextField(db_column="Schema", null=True, blank=True) + + class Meta: + managed = True + db_table = 'tblBenefitPlan' From 8e423c66c11bfcf68f6e930801e471bb20b13491 Mon Sep 17 00:00:00 2001 From: jdolkowski Date: Thu, 18 May 2023 12:58:22 +0200 Subject: [PATCH 04/50] CM-25: add gql_mutations --- social_protection/gql_mutations.py | 68 ++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 social_protection/gql_mutations.py diff --git a/social_protection/gql_mutations.py b/social_protection/gql_mutations.py new file mode 100644 index 0000000..8570e94 --- /dev/null +++ b/social_protection/gql_mutations.py @@ -0,0 +1,68 @@ +import graphene as graphene +from django.contrib.auth.models import AnonymousUser +from pydantic.error_wrappers import ValidationError + +from core.gql.gql_mutations.base_mutation import BaseHistoryModelCreateMutationMixin, BaseMutation, \ + BaseHistoryModelUpdateMutationMixin, BaseHistoryModelDeleteMutationMixin +from core.schema import OpenIMISMutation +from social_protection.apps import SocialProtectionConfig +from social_protection.models import BenefitPlan + + +class CreateBenefitPlanInputType(OpenIMISMutation.Input): + name = graphene.String(required=True, max_length=255) + date_from = graphene.Date(required=True) + date_to = graphene.Date(required=True) + max_beneficiaries = graphene.Int(default_value=0) + ceiling_per_beneficiary = graphene.Decimal(max_digits=18, decimal_places=2, required=False) + organization_id = graphene.Int(required=False) + schema = graphene.String() + + +class UpdateBenefitPlanInputType(CreateBenefitPlanInputType): + id = graphene.UUID(required=True) + + +class CreateBenefitPlanMutation(BaseHistoryModelCreateMutationMixin, BaseMutation): + _mutation_class = "CreateBenefitPlanMutation" + _mutation_module = "social_protection" + _model = BenefitPlan + + @classmethod + def _validate_mutation(cls, user, **data): + if type(user) is AnonymousUser or not user.has_perms( + SocialProtectionConfig.gql_benefit_plan_create_perms): + raise ValidationError("mutation.authentication_required") + + class Input(CreateBenefitPlanInputType): + pass + + +class UpdateBenefitPlanMutation(BaseHistoryModelUpdateMutationMixin, BaseMutation): + _mutation_class = "UpdateBenefitPlanMutation" + _mutation_module = "social_protection" + _model = BenefitPlan + + @classmethod + def _validate_mutation(cls, user, **data): + if type(user) is AnonymousUser or not user.has_perms( + SocialProtectionConfig.gql_benefit_plan_update_perms): + raise ValidationError("mutation.authentication_required") + + class Input(UpdateBenefitPlanInputType): + pass + + +class DeleteBenefitPlanMutation(BaseHistoryModelDeleteMutationMixin, BaseMutation): + _mutation_class = "DeleteBenefitPlanMutation" + _mutation_module = "social_protection" + _model = BenefitPlan + + @classmethod + def _validate_mutation(cls, user, **data): + if type(user) is AnonymousUser or not user.id or not user.has_perms( + SocialProtectionConfig.gql_benefit_plan_delete_perms): + raise ValidationError("mutation.authentication_required") + + class Input(OpenIMISMutation.Input): + uuids = graphene.List(graphene.UUID) From 11b188f051dd0dfbdc9f5e7acc88f2b866034604 Mon Sep 17 00:00:00 2001 From: jdolkowski Date: Thu, 18 May 2023 13:18:44 +0200 Subject: [PATCH 05/50] CM-25: add mising fields to CreateBenefitPlanInputType --- social_protection/gql_mutations.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/social_protection/gql_mutations.py b/social_protection/gql_mutations.py index 8570e94..fea7c5e 100644 --- a/social_protection/gql_mutations.py +++ b/social_protection/gql_mutations.py @@ -10,6 +10,7 @@ class CreateBenefitPlanInputType(OpenIMISMutation.Input): + code = graphene.String(required=True) name = graphene.String(required=True, max_length=255) date_from = graphene.Date(required=True) date_to = graphene.Date(required=True) @@ -18,6 +19,10 @@ class CreateBenefitPlanInputType(OpenIMISMutation.Input): organization_id = graphene.Int(required=False) schema = graphene.String() + date_valid_from = graphene.Date(required=False) + date_valid_to = graphene.Date(required=False) + json_ext = graphene.types.json.JSONString(required=False) + class UpdateBenefitPlanInputType(CreateBenefitPlanInputType): id = graphene.UUID(required=True) From bcf03de6cf867d59b993fe4c2a62daf7d8828de6 Mon Sep 17 00:00:00 2001 From: jdolkowski Date: Thu, 18 May 2023 13:19:05 +0200 Subject: [PATCH 06/50] CM-25: change code length --- social_protection/models.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/social_protection/models.py b/social_protection/models.py index 1d03d07..9c8440a 100644 --- a/social_protection/models.py +++ b/social_protection/models.py @@ -4,7 +4,7 @@ class BenefitPlan(core_models.HistoryBusinessModel): - code = models.CharField(db_column='Code', max_length=50, null=False) + code = models.CharField(db_column='Code', max_length=8, null=False) name = models.CharField(db_column='NameBF', max_length=255, null=False) date_from = models.DateTimeField(db_column="DateFrom") date_to = models.DateTimeField(db_column="DateTo") From b1332941cbbf9f380af7ff7299a77418d9042c27 Mon Sep 17 00:00:00 2001 From: jdolkowski Date: Thu, 18 May 2023 13:26:20 +0200 Subject: [PATCH 07/50] CM-25: create BenefitPlanGQLType --- social_protection/gql_queries.py | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 social_protection/gql_queries.py diff --git a/social_protection/gql_queries.py b/social_protection/gql_queries.py new file mode 100644 index 0000000..96f8b8f --- /dev/null +++ b/social_protection/gql_queries.py @@ -0,0 +1,30 @@ +import graphene +from graphene_django import DjangoObjectType + +from core import prefix_filterset, ExtendedConnection +from policyholder.gql import PolicyHolderGQLType +from social_protection.models import BenefitPlan + + +class BenefitPlanGQLType(DjangoObjectType): + uuid = graphene.String(source='uuid') + + class Meta: + model = BenefitPlan + interfaces = (graphene.relay.Node,) + filtered_fields = { + "id": ["exact"], + "code": ["exact", "iexact", "startswith", "istartswith", "contains", "icontains"], + "name": ["exact", "iexact", "startswith", "istartswith", "contains", "icontains"], + "date_from": ["exact", "lt", "lte", "gt", "gte"], + "date_to": ["exact", "lt", "lte", "gt", "gte"], + "max_beneficiaries": ["exact", "lt", "lte", "gt", "gte"], + "schema": ["exact", "iexact", "startswith", "istartswith", "contains", "icontains"], + **prefix_filterset("policyholder__", PolicyHolderGQLType._meta.filter_fields), + + "date_created": ["exact", "lt", "lte", "gt", "gte"], + "date_updated": ["exact", "lt", "lte", "gt", "gte"], + "is_deleted": ["exact"], + "version": ["exact"], + } + connection_class = ExtendedConnection From 7c74c05e0d62d5a684cb3437ef5a624ffefded25 Mon Sep 17 00:00:00 2001 From: jdolkowski Date: Thu, 18 May 2023 13:50:45 +0200 Subject: [PATCH 08/50] CM-25: add Query and Mutation in schema.py --- social_protection/schema.py | 45 +++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 social_protection/schema.py diff --git a/social_protection/schema.py b/social_protection/schema.py new file mode 100644 index 0000000..f662ba7 --- /dev/null +++ b/social_protection/schema.py @@ -0,0 +1,45 @@ +import graphene +from django.contrib.auth.models import AnonymousUser +from django.db.models import Q + +from core.schema import OrderedDjangoFilterConnectionField +from core.utils import append_validity_filter +from social_protection.apps import SocialProtectionConfig +from social_protection.gql_mutations import CreateBenefitPlanMutation +from social_protection.gql_queries import BenefitPlanGQLType +from social_protection.models import BenefitPlan +import graphene_django_optimizer as gql_optimizer + + +class Query: + benefit_plan = OrderedDjangoFilterConnectionField( + BenefitPlanGQLType, + orderBy=graphene.List(of_type=graphene.String), + dateValidFrom__Gte=graphene.DateTime(), + dateValidTo__Lte=graphene.DateTime(), + applyDefaultValidityFilter=graphene.Boolean(), + client_mutation_id=graphene.String() + ) + + def resolve_benefit_plan(self, info, **kwargs): + filters = [] + filters += append_validity_filter(**kwargs) + + client_mutation_id = kwargs.get("client_mutation_id", None) + if client_mutation_id: + filters.append(Q(mutations__mutation__client_mutation_id=client_mutation_id)) + + Query._check_permissions(info.context.user) + query = BenefitPlan.objects.filter(*filters) + return gql_optimizer.query(query, info) + + @staticmethod + def _check_permissions(user): + if type(user) is AnonymousUser or not user.id or not user.has_perms( + SocialProtectionConfig.gql_benefit_plan_search_perms): + raise PermissionError("Unauthorized") + +class Mutation(graphene.ObjectType): + create_benefit_plan = CreateBenefitPlanMutation.field() + update_benefit_plan = CreateBenefitPlanMutation.field() + delete_benefit_plan = CreateBenefitPlanMutation.field() From aeeedb74b4fc542a0a27580989bc80fcfd133bd7 Mon Sep 17 00:00:00 2001 From: jdolkowski Date: Thu, 18 May 2023 13:51:31 +0200 Subject: [PATCH 09/50] CM-25: refactor schema.py --- social_protection/schema.py | 1 + 1 file changed, 1 insertion(+) diff --git a/social_protection/schema.py b/social_protection/schema.py index f662ba7..57f3c7f 100644 --- a/social_protection/schema.py +++ b/social_protection/schema.py @@ -39,6 +39,7 @@ def _check_permissions(user): SocialProtectionConfig.gql_benefit_plan_search_perms): raise PermissionError("Unauthorized") + class Mutation(graphene.ObjectType): create_benefit_plan = CreateBenefitPlanMutation.field() update_benefit_plan = CreateBenefitPlanMutation.field() From 70cca873aa5c9e676167abe8bbb0a6e7b616840d Mon Sep 17 00:00:00 2001 From: jdolkowski Date: Thu, 18 May 2023 13:55:12 +0200 Subject: [PATCH 10/50] CM-25: add benefit plan validations --- social_protection/validation.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 social_protection/validation.py diff --git a/social_protection/validation.py b/social_protection/validation.py new file mode 100644 index 0000000..e054581 --- /dev/null +++ b/social_protection/validation.py @@ -0,0 +1,18 @@ +from core.validation import BaseModelValidation +from social_protection.models import BenefitPlan + + +class BenefitPlanValidation(BaseModelValidation): + OBJECT_TYPE = BenefitPlan + + @classmethod + def validate_create(cls, user, **data): + super().validate_create(user, **data) + + @classmethod + def validate_update(cls, user, **data): + super().validate_update(user, **data) + + @classmethod + def validate_delete(cls, user, **data): + super().validate_delete(user, **data) From 5f20a6c779efc4426b44f65c508e36aa0e05f71b Mon Sep 17 00:00:00 2001 From: jdolkowski Date: Thu, 18 May 2023 13:55:45 +0200 Subject: [PATCH 11/50] CM-25: add services.py --- social_protection/services.py | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 social_protection/services.py diff --git a/social_protection/services.py b/social_protection/services.py new file mode 100644 index 0000000..905327c --- /dev/null +++ b/social_protection/services.py @@ -0,0 +1,10 @@ +from core.services import BaseService +from social_protection.models import BenefitPlan +from social_protection.validation import BenefitPlanValidation + + +class BenefitPlanService(BaseService): + OBJECT_TYPE = BenefitPlan + + def __init__(self, user, validation_class=BenefitPlanValidation): + super().__init__(user, validation_class) From 0ef3f073cb8be1639fae51722a6d18792303e78e Mon Sep 17 00:00:00 2001 From: jdolkowski Date: Thu, 18 May 2023 13:59:07 +0200 Subject: [PATCH 12/50] CM-25: create initial test --- social_protection/tests.py | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/social_protection/tests.py b/social_protection/tests.py index 7ce503c..f95eecb 100644 --- a/social_protection/tests.py +++ b/social_protection/tests.py @@ -1,3 +1,10 @@ from django.test import TestCase -# Create your tests here. + +class BenefitPlanTest(TestCase): + @classmethod + def setUpClass(cls): + super().setUpClass() + + def test_example_module_loaded_correctly(self): + self.assertTrue(True) From fb72ce977f918530295271c1a8c80a8dddc2d67d Mon Sep 17 00:00:00 2001 From: jdolkowski Date: Thu, 18 May 2023 14:03:26 +0200 Subject: [PATCH 13/50] CM-25: fix typo --- social_protection/schema.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/social_protection/schema.py b/social_protection/schema.py index 57f3c7f..78cbbc7 100644 --- a/social_protection/schema.py +++ b/social_protection/schema.py @@ -41,6 +41,6 @@ def _check_permissions(user): class Mutation(graphene.ObjectType): - create_benefit_plan = CreateBenefitPlanMutation.field() - update_benefit_plan = CreateBenefitPlanMutation.field() - delete_benefit_plan = CreateBenefitPlanMutation.field() + create_benefit_plan = CreateBenefitPlanMutation.Field() + update_benefit_plan = CreateBenefitPlanMutation.Field() + delete_benefit_plan = CreateBenefitPlanMutation.Field() From 5a48b3ce291d9dffa01ad481ca305fd4c89c875f Mon Sep 17 00:00:00 2001 From: jdolkowski Date: Thu, 18 May 2023 14:07:26 +0200 Subject: [PATCH 14/50] CM-25: fix filter_fileds --- social_protection/gql_queries.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/social_protection/gql_queries.py b/social_protection/gql_queries.py index 96f8b8f..963bd0b 100644 --- a/social_protection/gql_queries.py +++ b/social_protection/gql_queries.py @@ -12,7 +12,7 @@ class BenefitPlanGQLType(DjangoObjectType): class Meta: model = BenefitPlan interfaces = (graphene.relay.Node,) - filtered_fields = { + filter_fields = { "id": ["exact"], "code": ["exact", "iexact", "startswith", "istartswith", "contains", "icontains"], "name": ["exact", "iexact", "startswith", "istartswith", "contains", "icontains"], @@ -20,7 +20,7 @@ class Meta: "date_to": ["exact", "lt", "lte", "gt", "gte"], "max_beneficiaries": ["exact", "lt", "lte", "gt", "gte"], "schema": ["exact", "iexact", "startswith", "istartswith", "contains", "icontains"], - **prefix_filterset("policyholder__", PolicyHolderGQLType._meta.filter_fields), + **prefix_filterset("organization__", PolicyHolderGQLType._meta.filter_fields), "date_created": ["exact", "lt", "lte", "gt", "gte"], "date_updated": ["exact", "lt", "lte", "gt", "gte"], From 63a923529fc51d641aa7273312f381153316ff80 Mon Sep 17 00:00:00 2001 From: jdolkowski Date: Thu, 18 May 2023 15:50:46 +0200 Subject: [PATCH 15/50] CM-25: add missing mutations --- social_protection/schema.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/social_protection/schema.py b/social_protection/schema.py index 78cbbc7..c626bd7 100644 --- a/social_protection/schema.py +++ b/social_protection/schema.py @@ -5,7 +5,8 @@ from core.schema import OrderedDjangoFilterConnectionField from core.utils import append_validity_filter from social_protection.apps import SocialProtectionConfig -from social_protection.gql_mutations import CreateBenefitPlanMutation +from social_protection.gql_mutations import CreateBenefitPlanMutation, UpdateBenefitPlanMutation, \ + DeleteBenefitPlanMutation from social_protection.gql_queries import BenefitPlanGQLType from social_protection.models import BenefitPlan import graphene_django_optimizer as gql_optimizer @@ -42,5 +43,5 @@ def _check_permissions(user): class Mutation(graphene.ObjectType): create_benefit_plan = CreateBenefitPlanMutation.Field() - update_benefit_plan = CreateBenefitPlanMutation.Field() - delete_benefit_plan = CreateBenefitPlanMutation.Field() + update_benefit_plan = UpdateBenefitPlanMutation.Field() + delete_benefit_plan = DeleteBenefitPlanMutation.Field() From 59ebb5949dff0c6be04466599d4ecfdd8104ec19 Mon Sep 17 00:00:00 2001 From: jdolkowski Date: Thu, 18 May 2023 16:03:47 +0200 Subject: [PATCH 16/50] CM-25 add migrations --- social_protection/migrations/0001_initial.py | 87 +++++++++++++++++++ .../0002_add_benefit_plan_rights_to_admin.py | 27 ++++++ 2 files changed, 114 insertions(+) create mode 100644 social_protection/migrations/0001_initial.py create mode 100644 social_protection/migrations/0002_add_benefit_plan_rights_to_admin.py diff --git a/social_protection/migrations/0001_initial.py b/social_protection/migrations/0001_initial.py new file mode 100644 index 0000000..96ae69f --- /dev/null +++ b/social_protection/migrations/0001_initial.py @@ -0,0 +1,87 @@ +# Generated by Django 3.2.19 on 2023-05-18 12:01 + +import core.fields +import datetime +import dirtyfields.dirtyfields +from django.conf import settings +from django.db import migrations, models +import django.db.models.deletion +import simple_history.models + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ('policyholder', '0017_auto_20230126_0903'), + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ] + + operations = [ + migrations.CreateModel( + name='HistoricalBenefitPlan', + fields=[ + ('id', models.UUIDField(db_column='UUID', db_index=True, default=None, editable=False)), + ('is_deleted', models.BooleanField(db_column='isDeleted', default=False)), + ('json_ext', models.JSONField(blank=True, db_column='Json_ext', null=True)), + ('date_created', core.fields.DateTimeField(db_column='DateCreated', null=True)), + ('date_updated', core.fields.DateTimeField(db_column='DateUpdated', null=True)), + ('version', models.IntegerField(default=1)), + ('date_valid_from', core.fields.DateTimeField(db_column='DateValidFrom', default=datetime.datetime.now)), + ('date_valid_to', core.fields.DateTimeField(blank=True, db_column='DateValidTo', null=True)), + ('replacement_uuid', models.UUIDField(db_column='ReplacementUUID', null=True)), + ('code', models.CharField(db_column='Code', max_length=8)), + ('name', models.CharField(db_column='NameBF', max_length=255)), + ('date_from', models.DateTimeField(db_column='DateFrom')), + ('date_to', models.DateTimeField(db_column='DateTo')), + ('max_beneficiaries', models.SmallIntegerField(db_column='MaxNoBeneficiaries')), + ('ceiling_per_beneficiary', models.DecimalField(blank=True, db_column='BeneficiaryCeiling', decimal_places=2, max_digits=18, null=True)), + ('schema', models.TextField(blank=True, db_column='Schema', null=True)), + ('history_id', models.AutoField(primary_key=True, serialize=False)), + ('history_date', models.DateTimeField(db_index=True)), + ('history_change_reason', models.CharField(max_length=100, null=True)), + ('history_type', models.CharField(choices=[('+', 'Created'), ('~', 'Changed'), ('-', 'Deleted')], max_length=1)), + ('history_user', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to=settings.AUTH_USER_MODEL)), + ('organization', models.ForeignKey(blank=True, db_column='Organization', db_constraint=False, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='+', to='policyholder.policyholder')), + ('user_created', models.ForeignKey(blank=True, db_column='UserCreatedUUID', db_constraint=False, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='+', to=settings.AUTH_USER_MODEL)), + ('user_updated', models.ForeignKey(blank=True, db_column='UserUpdatedUUID', db_constraint=False, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='+', to=settings.AUTH_USER_MODEL)), + ], + options={ + 'verbose_name': 'historical benefit plan', + 'verbose_name_plural': 'historical benefit plans', + 'ordering': ('-history_date', '-history_id'), + 'get_latest_by': ('history_date', 'history_id'), + }, + bases=(simple_history.models.HistoricalChanges, models.Model), + ), + migrations.CreateModel( + name='BenefitPlan', + fields=[ + ('id', models.UUIDField(db_column='UUID', default=None, editable=False, primary_key=True, serialize=False)), + ('is_deleted', models.BooleanField(db_column='isDeleted', default=False)), + ('json_ext', models.JSONField(blank=True, db_column='Json_ext', null=True)), + ('date_created', core.fields.DateTimeField(db_column='DateCreated', null=True)), + ('date_updated', core.fields.DateTimeField(db_column='DateUpdated', null=True)), + ('version', models.IntegerField(default=1)), + ('date_valid_from', core.fields.DateTimeField(db_column='DateValidFrom', default=datetime.datetime.now)), + ('date_valid_to', core.fields.DateTimeField(blank=True, db_column='DateValidTo', null=True)), + ('replacement_uuid', models.UUIDField(db_column='ReplacementUUID', null=True)), + ('code', models.CharField(db_column='Code', max_length=8)), + ('name', models.CharField(db_column='NameBF', max_length=255)), + ('date_from', models.DateTimeField(db_column='DateFrom')), + ('date_to', models.DateTimeField(db_column='DateTo')), + ('max_beneficiaries', models.SmallIntegerField(db_column='MaxNoBeneficiaries')), + ('ceiling_per_beneficiary', models.DecimalField(blank=True, db_column='BeneficiaryCeiling', decimal_places=2, max_digits=18, null=True)), + ('schema', models.TextField(blank=True, db_column='Schema', null=True)), + ('organization', models.ForeignKey(blank=True, db_column='Organization', null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='policyholder.policyholder')), + ('user_created', models.ForeignKey(db_column='UserCreatedUUID', on_delete=django.db.models.deletion.DO_NOTHING, related_name='benefitplan_user_created', to=settings.AUTH_USER_MODEL)), + ('user_updated', models.ForeignKey(db_column='UserUpdatedUUID', on_delete=django.db.models.deletion.DO_NOTHING, related_name='benefitplan_user_updated', to=settings.AUTH_USER_MODEL)), + ], + options={ + 'db_table': 'tblBenefitPlan', + 'managed': True, + }, + bases=(dirtyfields.dirtyfields.DirtyFieldsMixin, models.Model), + ), + ] diff --git a/social_protection/migrations/0002_add_benefit_plan_rights_to_admin.py b/social_protection/migrations/0002_add_benefit_plan_rights_to_admin.py new file mode 100644 index 0000000..9915e9a --- /dev/null +++ b/social_protection/migrations/0002_add_benefit_plan_rights_to_admin.py @@ -0,0 +1,27 @@ +from django.db import migrations + +from core.models import Role, RoleRight + +benefit_plan_rights = [160001, 160002, 160003, 160004] +imis_administrator_system = 64 + + +def add_rights(apps, schema_editor): + role = Role.objects.get(is_system=imis_administrator_system) + for right_id in benefit_plan_rights: + if not RoleRight.objects.filter(validity_to__isnull=True, role=role, right_id=right_id).exists(): + _add_right_for_role(role, right_id) + + +def _add_right_for_role(role, right_id): + RoleRight.objects.create(role=role, right_id=right_id, audit_user_id=1) + + +class Migration(migrations.Migration): + dependencies = [ + ('social_protection', '0001_initial') + ] + + operations = [ + migrations.RunPython(add_rights), + ] From 0c2921a244881a49d3a54f2e8fe5650420f586b6 Mon Sep 17 00:00:00 2001 From: jdolkowski Date: Thu, 18 May 2023 16:25:03 +0200 Subject: [PATCH 17/50] CM-25: setup tests --- .github/workflows/openmis-module-test.yml | 9 ++- .github/workflows/python-publish.yml | 2 +- social_protection/tests.py | 10 --- social_protection/tests/__init__.py | 0 .../tests/benefit_plan_service_test.py | 62 +++++++++++++++++++ social_protection/tests/data.py | 37 +++++++++++ social_protection/tests/helpers.py | 30 +++++++++ 7 files changed, 134 insertions(+), 16 deletions(-) delete mode 100644 social_protection/tests.py create mode 100644 social_protection/tests/__init__.py create mode 100644 social_protection/tests/benefit_plan_service_test.py create mode 100644 social_protection/tests/data.py create mode 100644 social_protection/tests/helpers.py diff --git a/.github/workflows/openmis-module-test.yml b/.github/workflows/openmis-module-test.yml index 6e6b63b..434a72d 100644 --- a/.github/workflows/openmis-module-test.yml +++ b/.github/workflows/openmis-module-test.yml @@ -11,7 +11,7 @@ on: jobs: run_test: - runs-on: ubuntu-latest + runs-on: ubuntu-20.04 services: mssql: image: mcr.microsoft.com/mssql/server:2017-latest @@ -30,8 +30,8 @@ jobs: python-version: 3.8 - name: install linux packages run: | - wget https://raw.githubusercontent.com/openimis/database_ms_sqlserver/main/Empty%20databases/openIMIS_ONLINE.sql -O openIMIS_ONLINE.sql - wget https://raw.githubusercontent.com/openimis/database_ms_sqlserver/main/Demo%20database/openIMIS_demo_ONLINE.sql -O openIMIS_demo_ONLINE.sql + git clone --depth 1 --branch develop https://github.com/openimis/database_ms_sqlserver.git ./sql + cd sql/ && bash concatenate_files.sh && cd .. curl https://packages.microsoft.com/keys/microsoft.asc | sudo apt-key add - curl https://packages.microsoft.com/config/ubuntu/20.04/prod.list | sudo tee /etc/apt/sources.list.d/msprod.list sudo apt-get update @@ -67,8 +67,7 @@ jobs: run: | /opt/mssql-tools/bin/sqlcmd -S localhost,1433 -U SA -P $SA_PASSWORD -Q 'DROP DATABASE IF EXISTS imis' /opt/mssql-tools/bin/sqlcmd -S localhost,1433 -U SA -P $SA_PASSWORD -Q 'CREATE DATABASE imis' - /opt/mssql-tools/bin/sqlcmd -S localhost,1433 -U SA -P $SA_PASSWORD -d imis -i openIMIS_ONLINE.sql | grep . | uniq -c - /opt/mssql-tools/bin/sqlcmd -S localhost,1433 -U SA -P $SA_PASSWORD -d imis -i openIMIS_demo_ONLINE.sql | grep . | uniq -c + /opt/mssql-tools/bin/sqlcmd -S localhost,1433 -U SA -P $SA_PASSWORD -d imis -i sql/output/fullDemoDatabase.sql | grep . | uniq -c env: SA_PASSWORD: GitHub999 ACCEPT_EULA: Y diff --git a/.github/workflows/python-publish.yml b/.github/workflows/python-publish.yml index f591ca8..6ff810f 100644 --- a/.github/workflows/python-publish.yml +++ b/.github/workflows/python-publish.yml @@ -10,7 +10,7 @@ on: jobs: deploy: - runs-on: ubuntu-latest + runs-on: ubuntu-20.04 steps: - uses: olegtarasov/get-tag@v2.1 diff --git a/social_protection/tests.py b/social_protection/tests.py deleted file mode 100644 index f95eecb..0000000 --- a/social_protection/tests.py +++ /dev/null @@ -1,10 +0,0 @@ -from django.test import TestCase - - -class BenefitPlanTest(TestCase): - @classmethod - def setUpClass(cls): - super().setUpClass() - - def test_example_module_loaded_correctly(self): - self.assertTrue(True) diff --git a/social_protection/tests/__init__.py b/social_protection/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/social_protection/tests/benefit_plan_service_test.py b/social_protection/tests/benefit_plan_service_test.py new file mode 100644 index 0000000..c84704a --- /dev/null +++ b/social_protection/tests/benefit_plan_service_test.py @@ -0,0 +1,62 @@ +import copy + +from django.test import TestCase + +from social_protection.models import BenefitPlan +from social_protection.services import BenefitPlanService +from social_protection.tests.data import ( + service_add_payload, + service_add_payload_no_ext, + service_update_payload +) +from social_protection.tests.helpers import LogInHelper + + +class BenefitPlanServiceTest(TestCase): + user = None + service = None + query_all = None + + @classmethod + def setUpClass(cls): + super().setUpClass() + + cls.user = LogInHelper().get_or_create_user_api() + cls.service = BenefitPlanService(cls.user) + cls.query_all = BenefitPlan.objects.filter(is_deleted=False) + + def test_add_benefit_plan(self): + result = self.service.create(service_add_payload) + self.assertTrue(result.get('success', False), result.get('detail', "No details provided")) + uuid = result.get('data', {}).get('uuid', None) + query = self.query_all.filter(uuid=uuid) + self.assertEqual(query.count(), 1) + + def test_add_benefit_plan_no_ext(self): + result = self.service.create(service_add_payload_no_ext) + self.assertTrue(result.get('success', False), result.get('detail', "No details provided")) + uuid = result.get('data', {}).get('uuid') + query = self.query_all.filter(uuid=uuid) + self.assertEqual(query.count(), 1) + + def test_update_individual(self): + result = self.service.create(service_add_payload) + self.assertTrue(result.get('success', False), result.get('detail', "No details provided")) + uuid = result.get('data', {}).get('uuid') + update_payload = copy.deepcopy(service_update_payload) + update_payload['id'] = uuid + result = self.service.update(update_payload) + self.assertTrue(result.get('success', False), result.get('detail', "No details provided")) + query = self.query_all.filter(uuid=uuid) + self.assertEqual(query.count(), 1) + self.assertEqual(query.first().first_name, update_payload.get('first_name')) + + def test_delete_individual(self): + result = self.service.create(service_add_payload) + self.assertTrue(result.get('success', False), result.get('detail', "No details provided")) + uuid = result.get('data', {}).get('uuid') + delete_payload = {'id': uuid} + result = self.service.delete(delete_payload) + self.assertTrue(result.get('success', False), result.get('detail', "No details provided")) + query = self.query_all.filter(uuid=uuid) + self.assertEqual(query.count(), 0) diff --git a/social_protection/tests/data.py b/social_protection/tests/data.py new file mode 100644 index 0000000..6de075b --- /dev/null +++ b/social_protection/tests/data.py @@ -0,0 +1,37 @@ +service_add_payload = { + "code": "example", + "name": "example_name", + "dateFrom": "2023-01-01", + "dateTo": "2023-12-31", + "maxBeneficiaries": 0, + "ceilingPerBeneficiary": "0.00", + "schema": "example_schema", + "dateValidFrom": "2023-01-01", + "dateValidTo": "2023-12-31", + "jsonExt": "{\"key\":\"value\"}" +} + +service_add_payload_no_ext = { + "code": "example", + "name": "example_name", + "dateFrom": "2023-01-01", + "dateTo": "2023-12-31", + "maxBeneficiaries": 0, + "ceilingPerBeneficiary": "0.00", + "schema": "example_schema", + "dateValidFrom": "2023-01-01", + "dateValidTo": "2023-12-31", +} + +service_update_payload = { + "code": "update", + "name": "example_update", + "dateFrom": "2023-01-01", + "dateTo": "2023-12-31", + "maxBeneficiaries": 0, + "ceilingPerBeneficiary": "0.00", + "schema": "example_schema_updated", + "dateValidFrom": "2023-01-01", + "dateValidTo": "2023-12-31", + "jsonExt": "{\"key\":\"updated_value\"}" +} diff --git a/social_protection/tests/helpers.py b/social_protection/tests/helpers.py new file mode 100644 index 0000000..670b2c1 --- /dev/null +++ b/social_protection/tests/helpers.py @@ -0,0 +1,30 @@ +from api_fhir_r4.utils import DbManagerUtils +from core.forms import User +from core.services import create_or_update_interactive_user, create_or_update_core_user + + +class LogInHelper: + _TEST_USER_NAME = "TestUserTest2" + _TEST_USER_PASSWORD = "TestPasswordTest2" + _TEST_DATA_USER = { + "username": _TEST_USER_NAME, + "last_name": _TEST_USER_NAME, + "password": _TEST_USER_PASSWORD, + "other_names": _TEST_USER_NAME, + "user_types": "INTERACTIVE", + "language": "en", + "roles": [1, 3, 5, 9], + } + + def get_or_create_user_api(self): + user = User.objects.filter(username=self._TEST_USER_NAME).first() + if user is None: + user = self.__create_user_interactive_core() + return user + + def __create_user_interactive_core(self): + i_user, i_user_created = create_or_update_interactive_user( + user_id=None, data=self._TEST_DATA_USER, audit_user_id=999, connected=False) + create_or_update_core_user( + user_uuid=None, username=self._TEST_DATA_USER["username"], i_user=i_user) + return DbManagerUtils.get_object_or_none(User, username=self._TEST_USER_NAME) From 74262c53e550bae7894b226e840802b99b8d6ef7 Mon Sep 17 00:00:00 2001 From: jdolkowski Date: Thu, 18 May 2023 16:40:44 +0200 Subject: [PATCH 18/50] CM-25: update module modules dependencies --- setup.py | 3 ++- social_protection/migrations/0001_initial.py | 3 ++- .../0002_add_benefit_plan_rights_to_admin.py | 10 +++++++++- 3 files changed, 13 insertions(+), 3 deletions(-) diff --git a/setup.py b/setup.py index 1566170..e09c94a 100644 --- a/setup.py +++ b/setup.py @@ -23,7 +23,8 @@ 'django', 'django-db-signals', 'djangorestframework', - 'openimis-be-core' + 'openimis-be-core', + 'openimis-be-policyholder', ], classifiers=[ 'Environment :: Web Environment', diff --git a/social_protection/migrations/0001_initial.py b/social_protection/migrations/0001_initial.py index 96ae69f..c8e842b 100644 --- a/social_protection/migrations/0001_initial.py +++ b/social_protection/migrations/0001_initial.py @@ -15,7 +15,8 @@ class Migration(migrations.Migration): dependencies = [ ('policyholder', '0017_auto_20230126_0903'), - migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ('core', '0018_auto_20230318_1551'), + migrations.swappable_dependency(settings.AUTH_USER_MODEL) ] operations = [ diff --git a/social_protection/migrations/0002_add_benefit_plan_rights_to_admin.py b/social_protection/migrations/0002_add_benefit_plan_rights_to_admin.py index 9915e9a..d60e723 100644 --- a/social_protection/migrations/0002_add_benefit_plan_rights_to_admin.py +++ b/social_protection/migrations/0002_add_benefit_plan_rights_to_admin.py @@ -17,11 +17,19 @@ def _add_right_for_role(role, right_id): RoleRight.objects.create(role=role, right_id=right_id, audit_user_id=1) +def remove_rights(apps, schema_editor): + RoleRight.objects.filter( + role__is_system=imis_administrator_system, + right_id__in=benefit_plan_rights, + validity_to__isnull=True + ).delete() + + class Migration(migrations.Migration): dependencies = [ ('social_protection', '0001_initial') ] operations = [ - migrations.RunPython(add_rights), + migrations.RunPython(add_rights, remove_rights), ] From ea40dae70c4ecd6db54ee7be2076354ebf232be2 Mon Sep 17 00:00:00 2001 From: jdolkowski Date: Thu, 18 May 2023 16:40:59 +0200 Subject: [PATCH 19/50] CM-25 update readme --- README.md | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/README.md b/README.md index aaa9c2c..e96e0f5 100644 --- a/README.md +++ b/README.md @@ -1 +1,31 @@ # openIMIS Backend social_protection reference module +This repository holds the files of the openIMIS Backend social_protection reference module. +It is dedicated to be deployed as a module of [openimis-be_py](https://github.com/openimis/openimis-be_py). + +## ORM mapping: +* tblBenefitPlan > BenefitPlan + +## GraphQl Queries +* benefitPlan + +## GraphQL Mutations - each mutation emits default signals and return standard error lists (cfr. openimis-be-core_py) +* createBenefitPlan +* updateBenefitPlan +* deleteBenefitPlan + +## Services +- BenefitPlan + - create + - update + - delete + +## Configuration options (can be changed via core.ModuleConfiguration) +* gql_benefit_plan_search_perms: required rights to call individual GraphQL Query (default: ["160001"]) +* gql_benefit_plan_create_perms: required rights to call createIndividual GraphQL Mutation (default: ["160002"]) +* gql_benefit_plan_update_perms: required rights to call updateIndividual GraphQL Mutation (default: ["160003"]) +* gql_benefit_plan_delete_perms: required rights to call deleteIndividual GraphQL Mutation (default: ["160004"]) + + +## openIMIS Modules Dependencies +- core +- policyholder \ No newline at end of file From cd1cdd7b80697711845f68004aa81fb126c61d4e Mon Sep 17 00:00:00 2001 From: jdolkowski Date: Thu, 18 May 2023 16:44:58 +0200 Subject: [PATCH 20/50] CM-25: add benfit plan services --- social_protection/services.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/social_protection/services.py b/social_protection/services.py index 905327c..06b904f 100644 --- a/social_protection/services.py +++ b/social_protection/services.py @@ -1,9 +1,26 @@ +import logging + from core.services import BaseService +from core.signals import register_service_signal from social_protection.models import BenefitPlan from social_protection.validation import BenefitPlanValidation +logger = logging.getLogger(__name__) + class BenefitPlanService(BaseService): + @register_service_signal('benefit_plan_service.create') + def create(self, obj_data): + return super().create(obj_data) + + @register_service_signal('benefit_plan_service.update') + def update(self, obj_data): + return super().update(obj_data) + + @register_service_signal('benefit_plan_service.delete') + def delete(self, obj_data): + return super().delete(obj_data) + OBJECT_TYPE = BenefitPlan def __init__(self, user, validation_class=BenefitPlanValidation): From 33f0283bc64d077cc769f89ad37aa5ce1109fe59 Mon Sep 17 00:00:00 2001 From: jdolkowski Date: Thu, 18 May 2023 16:50:27 +0200 Subject: [PATCH 21/50] CM-25: route gql mutations through service --- social_protection/gql_mutations.py | 43 ++++++++++++++++++++++++++++-- 1 file changed, 41 insertions(+), 2 deletions(-) diff --git a/social_protection/gql_mutations.py b/social_protection/gql_mutations.py index fea7c5e..d020e7c 100644 --- a/social_protection/gql_mutations.py +++ b/social_protection/gql_mutations.py @@ -1,12 +1,14 @@ import graphene as graphene from django.contrib.auth.models import AnonymousUser from pydantic.error_wrappers import ValidationError +from django.db import transaction from core.gql.gql_mutations.base_mutation import BaseHistoryModelCreateMutationMixin, BaseMutation, \ BaseHistoryModelUpdateMutationMixin, BaseHistoryModelDeleteMutationMixin from core.schema import OpenIMISMutation from social_protection.apps import SocialProtectionConfig from social_protection.models import BenefitPlan +from social_protection.services import BenefitPlanService class CreateBenefitPlanInputType(OpenIMISMutation.Input): @@ -16,7 +18,7 @@ class CreateBenefitPlanInputType(OpenIMISMutation.Input): date_to = graphene.Date(required=True) max_beneficiaries = graphene.Int(default_value=0) ceiling_per_beneficiary = graphene.Decimal(max_digits=18, decimal_places=2, required=False) - organization_id = graphene.Int(required=False) + organization_id = graphene.UUID(required=False) schema = graphene.String() date_valid_from = graphene.Date(required=False) @@ -39,6 +41,16 @@ def _validate_mutation(cls, user, **data): SocialProtectionConfig.gql_benefit_plan_create_perms): raise ValidationError("mutation.authentication_required") + @classmethod + def _mutate(cls, user, **data): + if "client_mutation_id" in data: + data.pop('client_mutation_id') + if "client_mutation_label" in data: + data.pop('client_mutation_label') + + service = BenefitPlanService(user) + service.create(data) + class Input(CreateBenefitPlanInputType): pass @@ -54,6 +66,18 @@ def _validate_mutation(cls, user, **data): SocialProtectionConfig.gql_benefit_plan_update_perms): raise ValidationError("mutation.authentication_required") + @classmethod + def _mutate(cls, user, **data): + if "date_valid_to" not in data: + data['date_valid_to'] = None + if "client_mutation_id" in data: + data.pop('client_mutation_id') + if "client_mutation_label" in data: + data.pop('client_mutation_label') + + service = BenefitPlanService(user) + service.update(data) + class Input(UpdateBenefitPlanInputType): pass @@ -69,5 +93,20 @@ def _validate_mutation(cls, user, **data): SocialProtectionConfig.gql_benefit_plan_delete_perms): raise ValidationError("mutation.authentication_required") + @classmethod + def _mutate(cls, user, **data): + if "client_mutation_id" in data: + data.pop('client_mutation_id') + if "client_mutation_label" in data: + data.pop('client_mutation_label') + + service = BenefitPlanService(user) + + ids = data.get('ids') + if ids: + with transaction.atomic(): + for id in ids: + service.delete({'id': id}) + class Input(OpenIMISMutation.Input): - uuids = graphene.List(graphene.UUID) + ids = graphene.List(graphene.UUID) From 8fcf4cc2dc7a6e70389d1e08b1e914978a2f4dfd Mon Sep 17 00:00:00 2001 From: jdolkowski Date: Thu, 18 May 2023 17:23:08 +0200 Subject: [PATCH 22/50] CM-25: validate uniqueness of code and name --- social_protection/gql_mutations.py | 2 ++ social_protection/services.py | 29 +++++++++++++++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/social_protection/gql_mutations.py b/social_protection/gql_mutations.py index d020e7c..0e77b0f 100644 --- a/social_protection/gql_mutations.py +++ b/social_protection/gql_mutations.py @@ -62,10 +62,12 @@ class UpdateBenefitPlanMutation(BaseHistoryModelUpdateMutationMixin, BaseMutatio @classmethod def _validate_mutation(cls, user, **data): + super()._validate_mutation(user, **data) if type(user) is AnonymousUser or not user.has_perms( SocialProtectionConfig.gql_benefit_plan_update_perms): raise ValidationError("mutation.authentication_required") + @classmethod def _mutate(cls, user, **data): if "date_valid_to" not in data: diff --git a/social_protection/services.py b/social_protection/services.py index 06b904f..b266680 100644 --- a/social_protection/services.py +++ b/social_protection/services.py @@ -1,5 +1,7 @@ import logging +from django.core.exceptions import ValidationError + from core.services import BaseService from core.signals import register_service_signal from social_protection.models import BenefitPlan @@ -11,10 +13,23 @@ class BenefitPlanService(BaseService): @register_service_signal('benefit_plan_service.create') def create(self, obj_data): + incoming_code = obj_data.get('code') + if check_unique_code(incoming_code): + raise ValidationError(("Benefit code %s already exists" % incoming_code)) + incoming_name = obj_data.get('name') + if check_unique_name(incoming_name): + raise ValidationError(("Benefit name %s already exists" % incoming_name)) return super().create(obj_data) @register_service_signal('benefit_plan_service.update') def update(self, obj_data): + uuid = obj_data.get('id') + incoming_code = obj_data.get('code') + if check_unique_code(incoming_code, uuid): + raise ValidationError(("Benefit code %s already exists" % incoming_code)) + incoming_name = obj_data.get('name') + if check_unique_name(incoming_name, uuid): + raise ValidationError(("Benefit name %s already exists" % incoming_name)) return super().update(obj_data) @register_service_signal('benefit_plan_service.delete') @@ -25,3 +40,17 @@ def delete(self, obj_data): def __init__(self, user, validation_class=BenefitPlanValidation): super().__init__(user, validation_class) + + +def check_unique_code(code, uuid=None): + instance = BenefitPlan.objects.get(code=code, is_deleted=False) + if instance and instance.uuid != uuid: + return [{"message": "BenefitPlan code %s already exists" % code}] + return [] + + +def check_unique_name(name, uuid=None): + instance = BenefitPlan.objects.get(name=name, is_deleted=False) + if instance and instance.uuid != uuid: + return [{"message": "BenefitPlan name %s already exists" % name}] + return [] From 76e86c91e48b8330b05cbe967c7ab6999d3d87eb Mon Sep 17 00:00:00 2001 From: jdolkowski Date: Thu, 18 May 2023 17:25:05 +0200 Subject: [PATCH 23/50] CM-25: update readme --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index e96e0f5..4a3d351 100644 --- a/README.md +++ b/README.md @@ -20,10 +20,10 @@ It is dedicated to be deployed as a module of [openimis-be_py](https://github.co - delete ## Configuration options (can be changed via core.ModuleConfiguration) -* gql_benefit_plan_search_perms: required rights to call individual GraphQL Query (default: ["160001"]) -* gql_benefit_plan_create_perms: required rights to call createIndividual GraphQL Mutation (default: ["160002"]) -* gql_benefit_plan_update_perms: required rights to call updateIndividual GraphQL Mutation (default: ["160003"]) -* gql_benefit_plan_delete_perms: required rights to call deleteIndividual GraphQL Mutation (default: ["160004"]) +* gql_benefit_plan_search_perms: required rights to call benefitPlan GraphQL Query (default: ["160001"]) +* gql_benefit_plan_create_perms: required rights to call createBenefitPlan GraphQL Mutation (default: ["160002"]) +* gql_benefit_plan_update_perms: required rights to call updateBenefitPlan GraphQL Mutation (default: ["160003"]) +* gql_benefit_plan_delete_perms: required rights to call deleteBenefitPlan GraphQL Mutation (default: ["160004"]) ## openIMIS Modules Dependencies From f7b8b48dfe1edaddd56ee5d631ae2d9308b6774c Mon Sep 17 00:00:00 2001 From: jdolkowski Date: Thu, 18 May 2023 17:31:51 +0200 Subject: [PATCH 24/50] CM-25: change get to filter --- social_protection/services.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/social_protection/services.py b/social_protection/services.py index b266680..5281a74 100644 --- a/social_protection/services.py +++ b/social_protection/services.py @@ -43,14 +43,14 @@ def __init__(self, user, validation_class=BenefitPlanValidation): def check_unique_code(code, uuid=None): - instance = BenefitPlan.objects.get(code=code, is_deleted=False) + instance = BenefitPlan.objects.filter(code=code, is_deleted=False).first() if instance and instance.uuid != uuid: return [{"message": "BenefitPlan code %s already exists" % code}] return [] def check_unique_name(name, uuid=None): - instance = BenefitPlan.objects.get(name=name, is_deleted=False) + instance = BenefitPlan.objects.filter(name=name, is_deleted=False).first() if instance and instance.uuid != uuid: return [{"message": "BenefitPlan name %s already exists" % name}] return [] From 04862c80c1de9e7043acf58fdb07a182ecb6f0b8 Mon Sep 17 00:00:00 2001 From: jdolkowski Date: Fri, 19 May 2023 12:35:54 +0200 Subject: [PATCH 25/50] CM-25: remove model meta --- social_protection/migrations/0001_initial.py | 4 ---- social_protection/models.py | 4 ---- 2 files changed, 8 deletions(-) diff --git a/social_protection/migrations/0001_initial.py b/social_protection/migrations/0001_initial.py index c8e842b..4171ef4 100644 --- a/social_protection/migrations/0001_initial.py +++ b/social_protection/migrations/0001_initial.py @@ -79,10 +79,6 @@ class Migration(migrations.Migration): ('user_created', models.ForeignKey(db_column='UserCreatedUUID', on_delete=django.db.models.deletion.DO_NOTHING, related_name='benefitplan_user_created', to=settings.AUTH_USER_MODEL)), ('user_updated', models.ForeignKey(db_column='UserUpdatedUUID', on_delete=django.db.models.deletion.DO_NOTHING, related_name='benefitplan_user_updated', to=settings.AUTH_USER_MODEL)), ], - options={ - 'db_table': 'tblBenefitPlan', - 'managed': True, - }, bases=(dirtyfields.dirtyfields.DirtyFieldsMixin, models.Model), ), ] diff --git a/social_protection/models.py b/social_protection/models.py index 9c8440a..19308e1 100644 --- a/social_protection/models.py +++ b/social_protection/models.py @@ -17,7 +17,3 @@ class BenefitPlan(core_models.HistoryBusinessModel): ) organization = models.ForeignKey(PolicyHolder, models.DO_NOTHING, db_column='Organization', blank=True, null=True) schema = models.TextField(db_column="Schema", null=True, blank=True) - - class Meta: - managed = True - db_table = 'tblBenefitPlan' From d515128b077cbf7b25b483ac91ef5b8a1ebed3b5 Mon Sep 17 00:00:00 2001 From: jdolkowski Date: Fri, 19 May 2023 12:39:36 +0200 Subject: [PATCH 26/50] CM-25: change organization to holder --- social_protection/gql_mutations.py | 2 +- social_protection/gql_queries.py | 2 +- social_protection/migrations/0001_initial.py | 4 ++-- social_protection/models.py | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/social_protection/gql_mutations.py b/social_protection/gql_mutations.py index 0e77b0f..4eb175c 100644 --- a/social_protection/gql_mutations.py +++ b/social_protection/gql_mutations.py @@ -18,7 +18,7 @@ class CreateBenefitPlanInputType(OpenIMISMutation.Input): date_to = graphene.Date(required=True) max_beneficiaries = graphene.Int(default_value=0) ceiling_per_beneficiary = graphene.Decimal(max_digits=18, decimal_places=2, required=False) - organization_id = graphene.UUID(required=False) + holder_id = graphene.UUID(required=False) schema = graphene.String() date_valid_from = graphene.Date(required=False) diff --git a/social_protection/gql_queries.py b/social_protection/gql_queries.py index 963bd0b..7ff59db 100644 --- a/social_protection/gql_queries.py +++ b/social_protection/gql_queries.py @@ -20,7 +20,7 @@ class Meta: "date_to": ["exact", "lt", "lte", "gt", "gte"], "max_beneficiaries": ["exact", "lt", "lte", "gt", "gte"], "schema": ["exact", "iexact", "startswith", "istartswith", "contains", "icontains"], - **prefix_filterset("organization__", PolicyHolderGQLType._meta.filter_fields), + **prefix_filterset("holder__", PolicyHolderGQLType._meta.filter_fields), "date_created": ["exact", "lt", "lte", "gt", "gte"], "date_updated": ["exact", "lt", "lte", "gt", "gte"], diff --git a/social_protection/migrations/0001_initial.py b/social_protection/migrations/0001_initial.py index 4171ef4..279b8fe 100644 --- a/social_protection/migrations/0001_initial.py +++ b/social_protection/migrations/0001_initial.py @@ -44,7 +44,7 @@ class Migration(migrations.Migration): ('history_change_reason', models.CharField(max_length=100, null=True)), ('history_type', models.CharField(choices=[('+', 'Created'), ('~', 'Changed'), ('-', 'Deleted')], max_length=1)), ('history_user', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to=settings.AUTH_USER_MODEL)), - ('organization', models.ForeignKey(blank=True, db_column='Organization', db_constraint=False, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='+', to='policyholder.policyholder')), + ('holder', models.ForeignKey(blank=True, db_column='Holder', db_constraint=False, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='+', to='policyholder.policyholder')), ('user_created', models.ForeignKey(blank=True, db_column='UserCreatedUUID', db_constraint=False, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='+', to=settings.AUTH_USER_MODEL)), ('user_updated', models.ForeignKey(blank=True, db_column='UserUpdatedUUID', db_constraint=False, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='+', to=settings.AUTH_USER_MODEL)), ], @@ -75,7 +75,7 @@ class Migration(migrations.Migration): ('max_beneficiaries', models.SmallIntegerField(db_column='MaxNoBeneficiaries')), ('ceiling_per_beneficiary', models.DecimalField(blank=True, db_column='BeneficiaryCeiling', decimal_places=2, max_digits=18, null=True)), ('schema', models.TextField(blank=True, db_column='Schema', null=True)), - ('organization', models.ForeignKey(blank=True, db_column='Organization', null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='policyholder.policyholder')), + ('holder', models.ForeignKey(blank=True, db_column='Holder', null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='policyholder.policyholder')), ('user_created', models.ForeignKey(db_column='UserCreatedUUID', on_delete=django.db.models.deletion.DO_NOTHING, related_name='benefitplan_user_created', to=settings.AUTH_USER_MODEL)), ('user_updated', models.ForeignKey(db_column='UserUpdatedUUID', on_delete=django.db.models.deletion.DO_NOTHING, related_name='benefitplan_user_updated', to=settings.AUTH_USER_MODEL)), ], diff --git a/social_protection/models.py b/social_protection/models.py index 19308e1..1a5944f 100644 --- a/social_protection/models.py +++ b/social_protection/models.py @@ -15,5 +15,5 @@ class BenefitPlan(core_models.HistoryBusinessModel): blank=True, null=True, ) - organization = models.ForeignKey(PolicyHolder, models.DO_NOTHING, db_column='Organization', blank=True, null=True) + holder = models.ForeignKey(PolicyHolder, models.DO_NOTHING, db_column='Holder', blank=True, null=True) schema = models.TextField(db_column="Schema", null=True, blank=True) From afdb4643abcae894f634b3fc8d55e312d44f007a Mon Sep 17 00:00:00 2001 From: jdolkowski Date: Fri, 19 May 2023 12:40:53 +0200 Subject: [PATCH 27/50] CM-25: refactor filters in resolve_benefit_plan --- social_protection/schema.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/social_protection/schema.py b/social_protection/schema.py index c626bd7..7110c5f 100644 --- a/social_protection/schema.py +++ b/social_protection/schema.py @@ -23,8 +23,7 @@ class Query: ) def resolve_benefit_plan(self, info, **kwargs): - filters = [] - filters += append_validity_filter(**kwargs) + filters = append_validity_filter(**kwargs) client_mutation_id = kwargs.get("client_mutation_id", None) if client_mutation_id: From aab421b18cc1a15f03004b933969d8cedd737c3b Mon Sep 17 00:00:00 2001 From: jdolkowski Date: Fri, 19 May 2023 12:48:59 +0200 Subject: [PATCH 28/50] CM-25: move code and name validation to validation classes --- social_protection/services.py | 29 ----------------------------- social_protection/validation.py | 29 +++++++++++++++++++++++++++++ 2 files changed, 29 insertions(+), 29 deletions(-) diff --git a/social_protection/services.py b/social_protection/services.py index 5281a74..06b904f 100644 --- a/social_protection/services.py +++ b/social_protection/services.py @@ -1,7 +1,5 @@ import logging -from django.core.exceptions import ValidationError - from core.services import BaseService from core.signals import register_service_signal from social_protection.models import BenefitPlan @@ -13,23 +11,10 @@ class BenefitPlanService(BaseService): @register_service_signal('benefit_plan_service.create') def create(self, obj_data): - incoming_code = obj_data.get('code') - if check_unique_code(incoming_code): - raise ValidationError(("Benefit code %s already exists" % incoming_code)) - incoming_name = obj_data.get('name') - if check_unique_name(incoming_name): - raise ValidationError(("Benefit name %s already exists" % incoming_name)) return super().create(obj_data) @register_service_signal('benefit_plan_service.update') def update(self, obj_data): - uuid = obj_data.get('id') - incoming_code = obj_data.get('code') - if check_unique_code(incoming_code, uuid): - raise ValidationError(("Benefit code %s already exists" % incoming_code)) - incoming_name = obj_data.get('name') - if check_unique_name(incoming_name, uuid): - raise ValidationError(("Benefit name %s already exists" % incoming_name)) return super().update(obj_data) @register_service_signal('benefit_plan_service.delete') @@ -40,17 +25,3 @@ def delete(self, obj_data): def __init__(self, user, validation_class=BenefitPlanValidation): super().__init__(user, validation_class) - - -def check_unique_code(code, uuid=None): - instance = BenefitPlan.objects.filter(code=code, is_deleted=False).first() - if instance and instance.uuid != uuid: - return [{"message": "BenefitPlan code %s already exists" % code}] - return [] - - -def check_unique_name(name, uuid=None): - instance = BenefitPlan.objects.filter(name=name, is_deleted=False).first() - if instance and instance.uuid != uuid: - return [{"message": "BenefitPlan name %s already exists" % name}] - return [] diff --git a/social_protection/validation.py b/social_protection/validation.py index e054581..fce542e 100644 --- a/social_protection/validation.py +++ b/social_protection/validation.py @@ -1,3 +1,5 @@ +from django.core.exceptions import ValidationError + from core.validation import BaseModelValidation from social_protection.models import BenefitPlan @@ -7,12 +9,39 @@ class BenefitPlanValidation(BaseModelValidation): @classmethod def validate_create(cls, user, **data): + incoming_code = data.get('code') + if check_unique_code(incoming_code): + raise ValidationError(("Benefit code %s already exists" % incoming_code)) + incoming_name = data.get('name') + if check_unique_name(incoming_name): + raise ValidationError(("Benefit name %s already exists" % incoming_name)) super().validate_create(user, **data) @classmethod def validate_update(cls, user, **data): + uuid = data.get('id') + incoming_code = data.get('code') + if check_unique_code(incoming_code, uuid): + raise ValidationError(("Benefit code %s already exists" % incoming_code)) + incoming_name = data.get('name') + if check_unique_name(incoming_name, uuid): + raise ValidationError(("Benefit name %s already exists" % incoming_name)) super().validate_update(user, **data) @classmethod def validate_delete(cls, user, **data): super().validate_delete(user, **data) + + +def check_unique_code(code, uuid=None): + instance = BenefitPlan.objects.filter(code=code, is_deleted=False).first() + if instance and instance.uuid != uuid: + return [{"message": "BenefitPlan code %s already exists" % code}] + return [] + + +def check_unique_name(name, uuid=None): + instance = BenefitPlan.objects.filter(name=name, is_deleted=False).first() + if instance and instance.uuid != uuid: + return [{"message": "BenefitPlan name %s already exists" % name}] + return [] From f1a1b88d38ab2d65d0175d2face103da2f18d433 Mon Sep 17 00:00:00 2001 From: jdolkowski Date: Fri, 19 May 2023 13:08:18 +0200 Subject: [PATCH 29/50] CM-25: create gql query to validate uniqueness of BF name and code --- social_protection/schema.py | 32 ++++++++++++++++++++++++++++++++ social_protection/validation.py | 12 ++++++------ 2 files changed, 38 insertions(+), 6 deletions(-) diff --git a/social_protection/schema.py b/social_protection/schema.py index 7110c5f..394f59f 100644 --- a/social_protection/schema.py +++ b/social_protection/schema.py @@ -1,7 +1,10 @@ import graphene from django.contrib.auth.models import AnonymousUser from django.db.models import Q +from django.core.exceptions import PermissionDenied +from django.utils.translation import gettext as _ +from core.gql_queries import ValidationMessageGQLType from core.schema import OrderedDjangoFilterConnectionField from core.utils import append_validity_filter from social_protection.apps import SocialProtectionConfig @@ -9,6 +12,7 @@ DeleteBenefitPlanMutation from social_protection.gql_queries import BenefitPlanGQLType from social_protection.models import BenefitPlan +from social_protection.validation import check_bf_unique_code, check_bf_unique_name import graphene_django_optimizer as gql_optimizer @@ -21,6 +25,34 @@ class Query: applyDefaultValidityFilter=graphene.Boolean(), client_mutation_id=graphene.String() ) + bf_code_validity = graphene.Field( + ValidationMessageGQLType, + bf_code=graphene.String(required=True), + description="Checks that the specified Benefit Plan code is valid" + ) + bf_name_validity = graphene.Field( + ValidationMessageGQLType, + bf_name=graphene.String(required=True), + description="Checks that the specified Benefit Plan name is valid" + ) + + def resolve_bf_code_validity(self, info, **kwargs): + if not info.context.user.has_perms(SocialProtectionConfig.gql_benefit_plan_search_perms): + raise PermissionDenied(_("unauthorized")) + errors = check_bf_unique_code(kwargs['bf_code']) + if errors: + return ValidationMessageGQLType(False, error_message=errors[0]['message']) + else: + return ValidationMessageGQLType(True) + + def resolve_bf_name_validity(self, info, **kwargs): + if not info.context.user.has_perms(SocialProtectionConfig.gql_benefit_plan_search_perms): + raise PermissionDenied(_("unauthorized")) + errors = check_bf_unique_name(kwargs['bf_code']) + if errors: + return ValidationMessageGQLType(False, error_message=errors[0]['message']) + else: + return ValidationMessageGQLType(True) def resolve_benefit_plan(self, info, **kwargs): filters = append_validity_filter(**kwargs) diff --git a/social_protection/validation.py b/social_protection/validation.py index fce542e..d6e00d5 100644 --- a/social_protection/validation.py +++ b/social_protection/validation.py @@ -10,10 +10,10 @@ class BenefitPlanValidation(BaseModelValidation): @classmethod def validate_create(cls, user, **data): incoming_code = data.get('code') - if check_unique_code(incoming_code): + if check_bf_unique_code(incoming_code): raise ValidationError(("Benefit code %s already exists" % incoming_code)) incoming_name = data.get('name') - if check_unique_name(incoming_name): + if check_bf_unique_name(incoming_name): raise ValidationError(("Benefit name %s already exists" % incoming_name)) super().validate_create(user, **data) @@ -21,10 +21,10 @@ def validate_create(cls, user, **data): def validate_update(cls, user, **data): uuid = data.get('id') incoming_code = data.get('code') - if check_unique_code(incoming_code, uuid): + if check_bf_unique_code(incoming_code, uuid): raise ValidationError(("Benefit code %s already exists" % incoming_code)) incoming_name = data.get('name') - if check_unique_name(incoming_name, uuid): + if check_bf_unique_name(incoming_name, uuid): raise ValidationError(("Benefit name %s already exists" % incoming_name)) super().validate_update(user, **data) @@ -33,14 +33,14 @@ def validate_delete(cls, user, **data): super().validate_delete(user, **data) -def check_unique_code(code, uuid=None): +def check_bf_unique_code(code, uuid=None): instance = BenefitPlan.objects.filter(code=code, is_deleted=False).first() if instance and instance.uuid != uuid: return [{"message": "BenefitPlan code %s already exists" % code}] return [] -def check_unique_name(name, uuid=None): +def check_bf_unique_name(name, uuid=None): instance = BenefitPlan.objects.filter(name=name, is_deleted=False).first() if instance and instance.uuid != uuid: return [{"message": "BenefitPlan name %s already exists" % name}] From ad608fe6de8e40e1ff3946ee8e7692f9f2dd5106 Mon Sep 17 00:00:00 2001 From: jdolkowski Date: Fri, 19 May 2023 13:09:47 +0200 Subject: [PATCH 30/50] CM-25: class refactor --- social_protection/services.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/social_protection/services.py b/social_protection/services.py index 06b904f..311e2dd 100644 --- a/social_protection/services.py +++ b/social_protection/services.py @@ -9,6 +9,11 @@ class BenefitPlanService(BaseService): + OBJECT_TYPE = BenefitPlan + + def __init__(self, user, validation_class=BenefitPlanValidation): + super().__init__(user, validation_class) + @register_service_signal('benefit_plan_service.create') def create(self, obj_data): return super().create(obj_data) @@ -20,8 +25,3 @@ def update(self, obj_data): @register_service_signal('benefit_plan_service.delete') def delete(self, obj_data): return super().delete(obj_data) - - OBJECT_TYPE = BenefitPlan - - def __init__(self, user, validation_class=BenefitPlanValidation): - super().__init__(user, validation_class) From 3328a8c271a98c161bb62d0d3667ec533d37c3e7 Mon Sep 17 00:00:00 2001 From: jdolkowski Date: Fri, 19 May 2023 13:10:10 +0200 Subject: [PATCH 31/50] CM-25: qgl_mutations refactor --- social_protection/gql_mutations.py | 1 - 1 file changed, 1 deletion(-) diff --git a/social_protection/gql_mutations.py b/social_protection/gql_mutations.py index 4eb175c..eccfbf1 100644 --- a/social_protection/gql_mutations.py +++ b/social_protection/gql_mutations.py @@ -67,7 +67,6 @@ def _validate_mutation(cls, user, **data): SocialProtectionConfig.gql_benefit_plan_update_perms): raise ValidationError("mutation.authentication_required") - @classmethod def _mutate(cls, user, **data): if "date_valid_to" not in data: From 7663f15320f08b679f54453d24d6eeec12be1270 Mon Sep 17 00:00:00 2001 From: jdolkowski Date: Fri, 19 May 2023 13:41:05 +0200 Subject: [PATCH 32/50] CM-25: remove date_from and date_to from BenefitPlan --- social_protection/gql_mutations.py | 6 ++---- social_protection/gql_queries.py | 4 ++-- social_protection/migrations/0001_initial.py | 4 ---- social_protection/models.py | 2 -- social_protection/tests/data.py | 6 ------ 5 files changed, 4 insertions(+), 18 deletions(-) diff --git a/social_protection/gql_mutations.py b/social_protection/gql_mutations.py index eccfbf1..acaaaef 100644 --- a/social_protection/gql_mutations.py +++ b/social_protection/gql_mutations.py @@ -14,15 +14,13 @@ class CreateBenefitPlanInputType(OpenIMISMutation.Input): code = graphene.String(required=True) name = graphene.String(required=True, max_length=255) - date_from = graphene.Date(required=True) - date_to = graphene.Date(required=True) max_beneficiaries = graphene.Int(default_value=0) ceiling_per_beneficiary = graphene.Decimal(max_digits=18, decimal_places=2, required=False) holder_id = graphene.UUID(required=False) schema = graphene.String() - date_valid_from = graphene.Date(required=False) - date_valid_to = graphene.Date(required=False) + date_valid_from = graphene.Date(required=True) + date_valid_to = graphene.Date(required=True) json_ext = graphene.types.json.JSONString(required=False) diff --git a/social_protection/gql_queries.py b/social_protection/gql_queries.py index 7ff59db..85513c8 100644 --- a/social_protection/gql_queries.py +++ b/social_protection/gql_queries.py @@ -16,8 +16,8 @@ class Meta: "id": ["exact"], "code": ["exact", "iexact", "startswith", "istartswith", "contains", "icontains"], "name": ["exact", "iexact", "startswith", "istartswith", "contains", "icontains"], - "date_from": ["exact", "lt", "lte", "gt", "gte"], - "date_to": ["exact", "lt", "lte", "gt", "gte"], + "date_valid_from": ["exact", "lt", "lte", "gt", "gte"], + "date_valid_to": ["exact", "lt", "lte", "gt", "gte"], "max_beneficiaries": ["exact", "lt", "lte", "gt", "gte"], "schema": ["exact", "iexact", "startswith", "istartswith", "contains", "icontains"], **prefix_filterset("holder__", PolicyHolderGQLType._meta.filter_fields), diff --git a/social_protection/migrations/0001_initial.py b/social_protection/migrations/0001_initial.py index 279b8fe..b9f3812 100644 --- a/social_protection/migrations/0001_initial.py +++ b/social_protection/migrations/0001_initial.py @@ -34,8 +34,6 @@ class Migration(migrations.Migration): ('replacement_uuid', models.UUIDField(db_column='ReplacementUUID', null=True)), ('code', models.CharField(db_column='Code', max_length=8)), ('name', models.CharField(db_column='NameBF', max_length=255)), - ('date_from', models.DateTimeField(db_column='DateFrom')), - ('date_to', models.DateTimeField(db_column='DateTo')), ('max_beneficiaries', models.SmallIntegerField(db_column='MaxNoBeneficiaries')), ('ceiling_per_beneficiary', models.DecimalField(blank=True, db_column='BeneficiaryCeiling', decimal_places=2, max_digits=18, null=True)), ('schema', models.TextField(blank=True, db_column='Schema', null=True)), @@ -70,8 +68,6 @@ class Migration(migrations.Migration): ('replacement_uuid', models.UUIDField(db_column='ReplacementUUID', null=True)), ('code', models.CharField(db_column='Code', max_length=8)), ('name', models.CharField(db_column='NameBF', max_length=255)), - ('date_from', models.DateTimeField(db_column='DateFrom')), - ('date_to', models.DateTimeField(db_column='DateTo')), ('max_beneficiaries', models.SmallIntegerField(db_column='MaxNoBeneficiaries')), ('ceiling_per_beneficiary', models.DecimalField(blank=True, db_column='BeneficiaryCeiling', decimal_places=2, max_digits=18, null=True)), ('schema', models.TextField(blank=True, db_column='Schema', null=True)), diff --git a/social_protection/models.py b/social_protection/models.py index 1a5944f..0b10448 100644 --- a/social_protection/models.py +++ b/social_protection/models.py @@ -6,8 +6,6 @@ class BenefitPlan(core_models.HistoryBusinessModel): code = models.CharField(db_column='Code', max_length=8, null=False) name = models.CharField(db_column='NameBF', max_length=255, null=False) - date_from = models.DateTimeField(db_column="DateFrom") - date_to = models.DateTimeField(db_column="DateTo") max_beneficiaries = models.SmallIntegerField(db_column="MaxNoBeneficiaries") ceiling_per_beneficiary = models.DecimalField(db_column="BeneficiaryCeiling", max_digits=18, diff --git a/social_protection/tests/data.py b/social_protection/tests/data.py index 6de075b..ca7d8b0 100644 --- a/social_protection/tests/data.py +++ b/social_protection/tests/data.py @@ -1,8 +1,6 @@ service_add_payload = { "code": "example", "name": "example_name", - "dateFrom": "2023-01-01", - "dateTo": "2023-12-31", "maxBeneficiaries": 0, "ceilingPerBeneficiary": "0.00", "schema": "example_schema", @@ -14,8 +12,6 @@ service_add_payload_no_ext = { "code": "example", "name": "example_name", - "dateFrom": "2023-01-01", - "dateTo": "2023-12-31", "maxBeneficiaries": 0, "ceilingPerBeneficiary": "0.00", "schema": "example_schema", @@ -26,8 +22,6 @@ service_update_payload = { "code": "update", "name": "example_update", - "dateFrom": "2023-01-01", - "dateTo": "2023-12-31", "maxBeneficiaries": 0, "ceilingPerBeneficiary": "0.00", "schema": "example_schema_updated", From d9f23b11cddd98a28cb800245c1afa23d08fb669 Mon Sep 17 00:00:00 2001 From: jdolkowski Date: Fri, 19 May 2023 14:03:09 +0200 Subject: [PATCH 33/50] CM-25: add unique name and code test cases --- .../tests/benefit_plan_service_test.py | 30 +++++++++++++++++-- social_protection/tests/data.py | 22 ++++++++++++++ 2 files changed, 49 insertions(+), 3 deletions(-) diff --git a/social_protection/tests/benefit_plan_service_test.py b/social_protection/tests/benefit_plan_service_test.py index c84704a..f099faa 100644 --- a/social_protection/tests/benefit_plan_service_test.py +++ b/social_protection/tests/benefit_plan_service_test.py @@ -7,7 +7,7 @@ from social_protection.tests.data import ( service_add_payload, service_add_payload_no_ext, - service_update_payload + service_update_payload, service_add_payload_same_code, service_add_payload_same_name ) from social_protection.tests.helpers import LogInHelper @@ -39,7 +39,7 @@ def test_add_benefit_plan_no_ext(self): query = self.query_all.filter(uuid=uuid) self.assertEqual(query.count(), 1) - def test_update_individual(self): + def test_update_benefit_plan(self): result = self.service.create(service_add_payload) self.assertTrue(result.get('success', False), result.get('detail', "No details provided")) uuid = result.get('data', {}).get('uuid') @@ -51,7 +51,7 @@ def test_update_individual(self): self.assertEqual(query.count(), 1) self.assertEqual(query.first().first_name, update_payload.get('first_name')) - def test_delete_individual(self): + def test_delete_benefit_plan(self): result = self.service.create(service_add_payload) self.assertTrue(result.get('success', False), result.get('detail', "No details provided")) uuid = result.get('data', {}).get('uuid') @@ -60,3 +60,27 @@ def test_delete_individual(self): self.assertTrue(result.get('success', False), result.get('detail', "No details provided")) query = self.query_all.filter(uuid=uuid) self.assertEqual(query.count(), 0) + + def test_add_not_unique_code_benefit_plan(self): + first_bf = self.service.create(service_add_payload) + self.assertTrue(first_bf.get('success', False), first_bf.get('detail', "No details provided")) + uuid = first_bf.get('data', {}).get('uuid', None) + query = self.query_all.filter(uuid=uuid) + self.assertEqual(query.count(), 1) + second_bf = self.service.create(service_add_payload_same_code) + self.assertFalse(second_bf.get('success', True)) + code = first_bf['code'] + code_query = self.query_all.filter(code=code) + self.assertEqual(code_query.count(), 1) + + def test_add_not_unique_name_benefit_plan(self): + first_bf = self.service.create(service_add_payload) + self.assertTrue(first_bf.get('success', False), first_bf.get('detail', "No details provided")) + uuid = first_bf.get('data', {}).get('uuid', None) + query = self.query_all.filter(uuid=uuid) + self.assertEqual(query.count(), 1) + second_bf = self.service.create(service_add_payload_same_name) + self.assertFalse(second_bf.get('success', True)) + name = first_bf['name'] + name_query = self.query_all.filter(name=name) + self.assertEqual(name.count(), 1) diff --git a/social_protection/tests/data.py b/social_protection/tests/data.py index ca7d8b0..612e18d 100644 --- a/social_protection/tests/data.py +++ b/social_protection/tests/data.py @@ -9,6 +9,28 @@ "jsonExt": "{\"key\":\"value\"}" } +service_add_payload_same_code = { + "code": "example", + "name": "random", + "maxBeneficiaries": 0, + "ceilingPerBeneficiary": "0.00", + "schema": "example_schema", + "dateValidFrom": "2023-01-01", + "dateValidTo": "2023-12-31", + "jsonExt": "{\"key\":\"value\"}" +} + +service_add_payload_same_name = { + "code": "random", + "name": "example_name", + "maxBeneficiaries": 0, + "ceilingPerBeneficiary": "0.00", + "schema": "example_schema", + "dateValidFrom": "2023-01-01", + "dateValidTo": "2023-12-31", + "jsonExt": "{\"key\":\"value\"}" +} + service_add_payload_no_ext = { "code": "example", "name": "example_name", From 9af73724fd9336069b022226fd462a009e62fcc5 Mon Sep 17 00:00:00 2001 From: jdolkowski Date: Fri, 19 May 2023 14:15:54 +0200 Subject: [PATCH 34/50] CM-25: change filed naming convetion to autogenerated in BenefitPlan --- social_protection/migrations/0001_initial.py | 24 ++++++++++---------- social_protection/models.py | 13 +++++------ 2 files changed, 18 insertions(+), 19 deletions(-) diff --git a/social_protection/migrations/0001_initial.py b/social_protection/migrations/0001_initial.py index b9f3812..2fdbb1b 100644 --- a/social_protection/migrations/0001_initial.py +++ b/social_protection/migrations/0001_initial.py @@ -32,17 +32,17 @@ class Migration(migrations.Migration): ('date_valid_from', core.fields.DateTimeField(db_column='DateValidFrom', default=datetime.datetime.now)), ('date_valid_to', core.fields.DateTimeField(blank=True, db_column='DateValidTo', null=True)), ('replacement_uuid', models.UUIDField(db_column='ReplacementUUID', null=True)), - ('code', models.CharField(db_column='Code', max_length=8)), - ('name', models.CharField(db_column='NameBF', max_length=255)), - ('max_beneficiaries', models.SmallIntegerField(db_column='MaxNoBeneficiaries')), - ('ceiling_per_beneficiary', models.DecimalField(blank=True, db_column='BeneficiaryCeiling', decimal_places=2, max_digits=18, null=True)), - ('schema', models.TextField(blank=True, db_column='Schema', null=True)), + ('code', models.CharField(max_length=8)), + ('name', models.CharField(max_length=255)), + ('max_beneficiaries', models.SmallIntegerField()), + ('ceiling_per_beneficiary', models.DecimalField(blank=True, decimal_places=2, max_digits=18, null=True)), + ('beneficiary_data_schema', models.TextField(blank=True, null=True)), ('history_id', models.AutoField(primary_key=True, serialize=False)), ('history_date', models.DateTimeField(db_index=True)), ('history_change_reason', models.CharField(max_length=100, null=True)), ('history_type', models.CharField(choices=[('+', 'Created'), ('~', 'Changed'), ('-', 'Deleted')], max_length=1)), ('history_user', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to=settings.AUTH_USER_MODEL)), - ('holder', models.ForeignKey(blank=True, db_column='Holder', db_constraint=False, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='+', to='policyholder.policyholder')), + ('holder', models.ForeignKey(blank=True, db_constraint=False, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='+', to='policyholder.policyholder')), ('user_created', models.ForeignKey(blank=True, db_column='UserCreatedUUID', db_constraint=False, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='+', to=settings.AUTH_USER_MODEL)), ('user_updated', models.ForeignKey(blank=True, db_column='UserUpdatedUUID', db_constraint=False, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='+', to=settings.AUTH_USER_MODEL)), ], @@ -66,12 +66,12 @@ class Migration(migrations.Migration): ('date_valid_from', core.fields.DateTimeField(db_column='DateValidFrom', default=datetime.datetime.now)), ('date_valid_to', core.fields.DateTimeField(blank=True, db_column='DateValidTo', null=True)), ('replacement_uuid', models.UUIDField(db_column='ReplacementUUID', null=True)), - ('code', models.CharField(db_column='Code', max_length=8)), - ('name', models.CharField(db_column='NameBF', max_length=255)), - ('max_beneficiaries', models.SmallIntegerField(db_column='MaxNoBeneficiaries')), - ('ceiling_per_beneficiary', models.DecimalField(blank=True, db_column='BeneficiaryCeiling', decimal_places=2, max_digits=18, null=True)), - ('schema', models.TextField(blank=True, db_column='Schema', null=True)), - ('holder', models.ForeignKey(blank=True, db_column='Holder', null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='policyholder.policyholder')), + ('code', models.CharField(max_length=8)), + ('name', models.CharField(max_length=255)), + ('max_beneficiaries', models.SmallIntegerField()), + ('ceiling_per_beneficiary', models.DecimalField(blank=True, decimal_places=2, max_digits=18, null=True)), + ('beneficiary_data_schema', models.TextField(blank=True, null=True)), + ('holder', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='policyholder.policyholder')), ('user_created', models.ForeignKey(db_column='UserCreatedUUID', on_delete=django.db.models.deletion.DO_NOTHING, related_name='benefitplan_user_created', to=settings.AUTH_USER_MODEL)), ('user_updated', models.ForeignKey(db_column='UserUpdatedUUID', on_delete=django.db.models.deletion.DO_NOTHING, related_name='benefitplan_user_updated', to=settings.AUTH_USER_MODEL)), ], diff --git a/social_protection/models.py b/social_protection/models.py index 0b10448..e527dc3 100644 --- a/social_protection/models.py +++ b/social_protection/models.py @@ -4,14 +4,13 @@ class BenefitPlan(core_models.HistoryBusinessModel): - code = models.CharField(db_column='Code', max_length=8, null=False) - name = models.CharField(db_column='NameBF', max_length=255, null=False) - max_beneficiaries = models.SmallIntegerField(db_column="MaxNoBeneficiaries") - ceiling_per_beneficiary = models.DecimalField(db_column="BeneficiaryCeiling", - max_digits=18, + code = models.CharField(max_length=8, null=False) + name = models.CharField(max_length=255, null=False) + max_beneficiaries = models.SmallIntegerField() + ceiling_per_beneficiary = models.DecimalField(max_digits=18, decimal_places=2, blank=True, null=True, ) - holder = models.ForeignKey(PolicyHolder, models.DO_NOTHING, db_column='Holder', blank=True, null=True) - schema = models.TextField(db_column="Schema", null=True, blank=True) + holder = models.ForeignKey(PolicyHolder, models.DO_NOTHING, blank=True, null=True) + beneficiary_data_schema = models.TextField(null=True, blank=True) From cb0a3c068b5b001877d0947208c8eabd931a8522 Mon Sep 17 00:00:00 2001 From: jdolkowski Date: Mon, 22 May 2023 11:23:19 +0200 Subject: [PATCH 35/50] CM-25: validate beneficiary_data_schema --- setup.py | 1 + social_protection/gql_mutations.py | 2 +- social_protection/gql_queries.py | 2 +- social_protection/migrations/0001_initial.py | 4 +- social_protection/models.py | 2 +- .../tests/benefit_plan_service_test.py | 7 +++- social_protection/tests/data.py | 40 ++++++++++++++++--- social_protection/validation.py | 38 ++++++++++++++---- 8 files changed, 77 insertions(+), 19 deletions(-) diff --git a/setup.py b/setup.py index e09c94a..c23af6a 100644 --- a/setup.py +++ b/setup.py @@ -25,6 +25,7 @@ 'djangorestframework', 'openimis-be-core', 'openimis-be-policyholder', + 'jsonschema', ], classifiers=[ 'Environment :: Web Environment', diff --git a/social_protection/gql_mutations.py b/social_protection/gql_mutations.py index acaaaef..9ffd21d 100644 --- a/social_protection/gql_mutations.py +++ b/social_protection/gql_mutations.py @@ -17,7 +17,7 @@ class CreateBenefitPlanInputType(OpenIMISMutation.Input): max_beneficiaries = graphene.Int(default_value=0) ceiling_per_beneficiary = graphene.Decimal(max_digits=18, decimal_places=2, required=False) holder_id = graphene.UUID(required=False) - schema = graphene.String() + beneficiary_data_schema = graphene.types.json.JSONString(required=False) date_valid_from = graphene.Date(required=True) date_valid_to = graphene.Date(required=True) diff --git a/social_protection/gql_queries.py b/social_protection/gql_queries.py index 85513c8..eb46e5f 100644 --- a/social_protection/gql_queries.py +++ b/social_protection/gql_queries.py @@ -19,7 +19,7 @@ class Meta: "date_valid_from": ["exact", "lt", "lte", "gt", "gte"], "date_valid_to": ["exact", "lt", "lte", "gt", "gte"], "max_beneficiaries": ["exact", "lt", "lte", "gt", "gte"], - "schema": ["exact", "iexact", "startswith", "istartswith", "contains", "icontains"], + "beneficiary_data_schema": ["exact", "iexact", "startswith", "istartswith", "contains", "icontains"], **prefix_filterset("holder__", PolicyHolderGQLType._meta.filter_fields), "date_created": ["exact", "lt", "lte", "gt", "gte"], diff --git a/social_protection/migrations/0001_initial.py b/social_protection/migrations/0001_initial.py index 2fdbb1b..36fd2c9 100644 --- a/social_protection/migrations/0001_initial.py +++ b/social_protection/migrations/0001_initial.py @@ -36,7 +36,7 @@ class Migration(migrations.Migration): ('name', models.CharField(max_length=255)), ('max_beneficiaries', models.SmallIntegerField()), ('ceiling_per_beneficiary', models.DecimalField(blank=True, decimal_places=2, max_digits=18, null=True)), - ('beneficiary_data_schema', models.TextField(blank=True, null=True)), + ('beneficiary_data_schema', models.JSONField(blank=True, null=True)), ('history_id', models.AutoField(primary_key=True, serialize=False)), ('history_date', models.DateTimeField(db_index=True)), ('history_change_reason', models.CharField(max_length=100, null=True)), @@ -70,7 +70,7 @@ class Migration(migrations.Migration): ('name', models.CharField(max_length=255)), ('max_beneficiaries', models.SmallIntegerField()), ('ceiling_per_beneficiary', models.DecimalField(blank=True, decimal_places=2, max_digits=18, null=True)), - ('beneficiary_data_schema', models.TextField(blank=True, null=True)), + ('beneficiary_data_schema', models.JSONField(blank=True, null=True)), ('holder', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to='policyholder.policyholder')), ('user_created', models.ForeignKey(db_column='UserCreatedUUID', on_delete=django.db.models.deletion.DO_NOTHING, related_name='benefitplan_user_created', to=settings.AUTH_USER_MODEL)), ('user_updated', models.ForeignKey(db_column='UserUpdatedUUID', on_delete=django.db.models.deletion.DO_NOTHING, related_name='benefitplan_user_updated', to=settings.AUTH_USER_MODEL)), diff --git a/social_protection/models.py b/social_protection/models.py index e527dc3..b3eb306 100644 --- a/social_protection/models.py +++ b/social_protection/models.py @@ -13,4 +13,4 @@ class BenefitPlan(core_models.HistoryBusinessModel): null=True, ) holder = models.ForeignKey(PolicyHolder, models.DO_NOTHING, blank=True, null=True) - beneficiary_data_schema = models.TextField(null=True, blank=True) + beneficiary_data_schema = models.JSONField(null=True, blank=True) diff --git a/social_protection/tests/benefit_plan_service_test.py b/social_protection/tests/benefit_plan_service_test.py index f099faa..01180bb 100644 --- a/social_protection/tests/benefit_plan_service_test.py +++ b/social_protection/tests/benefit_plan_service_test.py @@ -7,7 +7,8 @@ from social_protection.tests.data import ( service_add_payload, service_add_payload_no_ext, - service_update_payload, service_add_payload_same_code, service_add_payload_same_name + service_update_payload, service_add_payload_same_code, service_add_payload_same_name, + service_add_payload_invalid_schema ) from social_protection.tests.helpers import LogInHelper @@ -84,3 +85,7 @@ def test_add_not_unique_name_benefit_plan(self): name = first_bf['name'] name_query = self.query_all.filter(name=name) self.assertEqual(name.count(), 1) + + def test_add_invalid_schema_benefit_plan(self): + result = self.service.create(service_add_payload_invalid_schema) + self.assertFalse(result.get('success', True)) diff --git a/social_protection/tests/data.py b/social_protection/tests/data.py index 612e18d..052fdbb 100644 --- a/social_protection/tests/data.py +++ b/social_protection/tests/data.py @@ -3,7 +3,9 @@ "name": "example_name", "maxBeneficiaries": 0, "ceilingPerBeneficiary": "0.00", - "schema": "example_schema", + "beneficiary_data_schema": { + "$schema": "https://json-schema.org/draft/2019-09/schema" + }, "dateValidFrom": "2023-01-01", "dateValidTo": "2023-12-31", "jsonExt": "{\"key\":\"value\"}" @@ -14,7 +16,9 @@ "name": "random", "maxBeneficiaries": 0, "ceilingPerBeneficiary": "0.00", - "schema": "example_schema", + "beneficiary_data_schema": { + "$schema": "https://json-schema.org/draft/2019-09/schema" + }, "dateValidFrom": "2023-01-01", "dateValidTo": "2023-12-31", "jsonExt": "{\"key\":\"value\"}" @@ -25,7 +29,29 @@ "name": "example_name", "maxBeneficiaries": 0, "ceilingPerBeneficiary": "0.00", - "schema": "example_schema", + "beneficiary_data_schema": { + "$schema": "https://json-schema.org/draft/2019-09/schema" + }, + "dateValidFrom": "2023-01-01", + "dateValidTo": "2023-12-31", + "jsonExt": "{\"key\":\"value\"}" +} + +service_add_payload_invalid_schema = { + "code": "random", + "name": "example_name", + "maxBeneficiaries": 0, + "ceilingPerBeneficiary": "0.00", + "beneficiary_data_schema": { + "$schema": "https://json-schema.org/draft/2019-09/schema", + "type": "object", + "properties": { + "invalid_property": { + "type": "string" + } + }, + "required": ["invalid_property"] + }, "dateValidFrom": "2023-01-01", "dateValidTo": "2023-12-31", "jsonExt": "{\"key\":\"value\"}" @@ -36,7 +62,9 @@ "name": "example_name", "maxBeneficiaries": 0, "ceilingPerBeneficiary": "0.00", - "schema": "example_schema", + "beneficiary_data_schema": { + "$schema": "https://json-schema.org/draft/2019-09/schema" + }, "dateValidFrom": "2023-01-01", "dateValidTo": "2023-12-31", } @@ -46,7 +74,9 @@ "name": "example_update", "maxBeneficiaries": 0, "ceilingPerBeneficiary": "0.00", - "schema": "example_schema_updated", + "beneficiary_data_schema": { + "$schema": "https://json-schema.org/draft/2019-09/schema" + }, "dateValidFrom": "2023-01-01", "dateValidTo": "2023-12-31", "jsonExt": "{\"key\":\"updated_value\"}" diff --git a/social_protection/validation.py b/social_protection/validation.py index d6e00d5..ad3bfb3 100644 --- a/social_protection/validation.py +++ b/social_protection/validation.py @@ -1,3 +1,5 @@ +import jsonschema + from django.core.exceptions import ValidationError from core.validation import BaseModelValidation @@ -10,22 +12,34 @@ class BenefitPlanValidation(BaseModelValidation): @classmethod def validate_create(cls, user, **data): incoming_code = data.get('code') - if check_bf_unique_code(incoming_code): - raise ValidationError(("Benefit code %s already exists" % incoming_code)) + code_error = check_bf_unique_code(incoming_code) + if code_error: + raise ValidationError(code_error[0]['message']) incoming_name = data.get('name') - if check_bf_unique_name(incoming_name): - raise ValidationError(("Benefit name %s already exists" % incoming_name)) + name_error = check_bf_unique_name(incoming_name) + if name_error: + raise ValidationError(name_error[0]['message']) + incoming_schema = data.get('beneficiary_data_schema') + schema_error = is_valid_json_schema(incoming_schema) + if schema_error: + raise ValidationError(schema_error[0]['message']) super().validate_create(user, **data) @classmethod def validate_update(cls, user, **data): uuid = data.get('id') incoming_code = data.get('code') - if check_bf_unique_code(incoming_code, uuid): - raise ValidationError(("Benefit code %s already exists" % incoming_code)) + code_error = check_bf_unique_code(incoming_code, uuid) + if code_error: + raise ValidationError(code_error[0]['message']) incoming_name = data.get('name') - if check_bf_unique_name(incoming_name, uuid): - raise ValidationError(("Benefit name %s already exists" % incoming_name)) + name_error = check_bf_unique_name(incoming_name, uuid) + if name_error: + raise ValidationError(name_error[0]['message']) + incoming_schema = data.get('beneficiary_data_schema') + schema_error = is_valid_json_schema(incoming_schema) + if schema_error: + raise ValidationError(schema_error[0]['message']) super().validate_update(user, **data) @classmethod @@ -45,3 +59,11 @@ def check_bf_unique_name(name, uuid=None): if instance and instance.uuid != uuid: return [{"message": "BenefitPlan name %s already exists" % name}] return [] + + +def is_valid_json_schema(schema): + try: + jsonschema.Draft7Validator.check_schema(schema) + return [] + except jsonschema.exceptions.SchemaError: + return [{"message": "BenefitPlan schema is not valid"}] From 9ac4357f4d247338543c40d934c5779957b7b0d7 Mon Sep 17 00:00:00 2001 From: jdolkowski Date: Mon, 22 May 2023 12:26:14 +0200 Subject: [PATCH 36/50] CM-25: remove beneficiary_data_schema from filtered fields --- social_protection/gql_queries.py | 1 - 1 file changed, 1 deletion(-) diff --git a/social_protection/gql_queries.py b/social_protection/gql_queries.py index eb46e5f..6a10002 100644 --- a/social_protection/gql_queries.py +++ b/social_protection/gql_queries.py @@ -19,7 +19,6 @@ class Meta: "date_valid_from": ["exact", "lt", "lte", "gt", "gte"], "date_valid_to": ["exact", "lt", "lte", "gt", "gte"], "max_beneficiaries": ["exact", "lt", "lte", "gt", "gte"], - "beneficiary_data_schema": ["exact", "iexact", "startswith", "istartswith", "contains", "icontains"], **prefix_filterset("holder__", PolicyHolderGQLType._meta.filter_fields), "date_created": ["exact", "lt", "lte", "gt", "gte"], From 232564ec670dd0d9486e368d80e1c22a637fed01 Mon Sep 17 00:00:00 2001 From: sniedzielski Date: Mon, 22 May 2023 15:05:54 +0200 Subject: [PATCH 37/50] CM-27: added GQL query for Beneficiary --- social_protection/apps.py | 8 ++ social_protection/gql_mutations.py | 14 ++++ social_protection/gql_queries.py | 24 +++++- .../0003_beneficiary_historicalbeneficiary.py | 75 +++++++++++++++++++ social_protection/models.py | 7 ++ social_protection/schema.py | 42 +++++++++-- social_protection/services.py | 24 +++++- 7 files changed, 186 insertions(+), 8 deletions(-) create mode 100644 social_protection/migrations/0003_beneficiary_historicalbeneficiary.py diff --git a/social_protection/apps.py b/social_protection/apps.py index 018b223..e03d09f 100644 --- a/social_protection/apps.py +++ b/social_protection/apps.py @@ -5,6 +5,10 @@ "gql_benefit_plan_create_perms": ["160002"], "gql_benefit_plan_update_perms": ["160003"], "gql_benefit_plan_delete_perms": ["160004"], + "gql_beneficiary_search_perms": ["170001"], + "gql_beneficiary_create_perms": ["170002"], + "gql_beneficiary_update_perms": ["170003"], + "gql_beneficiary_delete_perms": ["170004"], } @@ -16,6 +20,10 @@ class SocialProtectionConfig(AppConfig): gql_benefit_plan_create_perms = None gql_benefit_plan_update_perms = None gql_benefit_plan_delete_perms = None + gql_beneficiary_search_perms = None + gql_beneficiary_create_perms = None + gql_beneficiary_update_perms = None + gql_beneficiary_delete_perms = None def ready(self): from core.models import ModuleConfiguration diff --git a/social_protection/gql_mutations.py b/social_protection/gql_mutations.py index 9ffd21d..6134cca 100644 --- a/social_protection/gql_mutations.py +++ b/social_protection/gql_mutations.py @@ -28,6 +28,20 @@ class UpdateBenefitPlanInputType(CreateBenefitPlanInputType): id = graphene.UUID(required=True) +class CreateBeneficiaryInputType(OpenIMISMutation.Input): + status = graphene.String(required=True) + individual_id = graphene.UUID(required=False) + benefit_plan_id = graphene.UUID(required=False) + + date_valid_from = graphene.Date(required=True) + date_valid_to = graphene.Date(required=True) + json_ext = graphene.types.json.JSONString(required=False) + + +class UpdateBeneficiaryInputType(CreateBeneficiaryInputType): + id = graphene.UUID(required=True) + + class CreateBenefitPlanMutation(BaseHistoryModelCreateMutationMixin, BaseMutation): _mutation_class = "CreateBenefitPlanMutation" _mutation_module = "social_protection" diff --git a/social_protection/gql_queries.py b/social_protection/gql_queries.py index 6a10002..b0cee78 100644 --- a/social_protection/gql_queries.py +++ b/social_protection/gql_queries.py @@ -3,7 +3,8 @@ from core import prefix_filterset, ExtendedConnection from policyholder.gql import PolicyHolderGQLType -from social_protection.models import BenefitPlan +from individual.gql_queries import IndividualGQLType +from social_protection.models import Beneficiary, BenefitPlan class BenefitPlanGQLType(DjangoObjectType): @@ -27,3 +28,24 @@ class Meta: "version": ["exact"], } connection_class = ExtendedConnection + + +class BeneficiaryGQLType(DjangoObjectType): + uuid = graphene.String(source='uuid') + + class Meta: + model = Beneficiary + interfaces = (graphene.relay.Node,) + filter_fields = { + "id": ["exact"], + "status": ["exact", "iexact", "startswith", "istartswith", "contains", "icontains"], + "date_valid_from": ["exact", "lt", "lte", "gt", "gte"], + "date_valid_to": ["exact", "lt", "lte", "gt", "gte"], + **prefix_filterset("individual__", IndividualGQLType._meta.filter_fields), + **prefix_filterset("benefit_plan__", BenefitPlanGQLType._meta.filter_fields), + "date_created": ["exact", "lt", "lte", "gt", "gte"], + "date_updated": ["exact", "lt", "lte", "gt", "gte"], + "is_deleted": ["exact"], + "version": ["exact"], + } + connection_class = ExtendedConnection diff --git a/social_protection/migrations/0003_beneficiary_historicalbeneficiary.py b/social_protection/migrations/0003_beneficiary_historicalbeneficiary.py new file mode 100644 index 0000000..b4798fe --- /dev/null +++ b/social_protection/migrations/0003_beneficiary_historicalbeneficiary.py @@ -0,0 +1,75 @@ +# Generated by Django 3.2.19 on 2023-05-22 12:44 + +import core.fields +import datetime +import dirtyfields.dirtyfields +from django.conf import settings +from django.db import migrations, models +import django.db.models.deletion +import simple_history.models + + +class Migration(migrations.Migration): + + dependencies = [ + ('individual', '0002_add_individual_rigts_for_admin'), + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ('social_protection', '0002_add_benefit_plan_rights_to_admin'), + ] + + operations = [ + migrations.CreateModel( + name='HistoricalBeneficiary', + fields=[ + ('id', models.UUIDField(db_column='UUID', db_index=True, default=None, editable=False)), + ('is_deleted', models.BooleanField(db_column='isDeleted', default=False)), + ('json_ext', models.JSONField(blank=True, db_column='Json_ext', null=True)), + ('date_created', core.fields.DateTimeField(db_column='DateCreated', null=True)), + ('date_updated', core.fields.DateTimeField(db_column='DateUpdated', null=True)), + ('version', models.IntegerField(default=1)), + ('date_valid_from', core.fields.DateTimeField(db_column='DateValidFrom', default=datetime.datetime.now)), + ('date_valid_to', core.fields.DateTimeField(blank=True, db_column='DateValidTo', null=True)), + ('replacement_uuid', models.UUIDField(db_column='ReplacementUUID', null=True)), + ('status', models.CharField(max_length=100)), + ('history_id', models.AutoField(primary_key=True, serialize=False)), + ('history_date', models.DateTimeField(db_index=True)), + ('history_change_reason', models.CharField(max_length=100, null=True)), + ('history_type', models.CharField(choices=[('+', 'Created'), ('~', 'Changed'), ('-', 'Deleted')], max_length=1)), + ('benefit_plan', models.ForeignKey(blank=True, db_constraint=False, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='+', to='social_protection.benefitplan')), + ('history_user', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to=settings.AUTH_USER_MODEL)), + ('individual', models.ForeignKey(blank=True, db_constraint=False, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='+', to='individual.individual')), + ('user_created', models.ForeignKey(blank=True, db_column='UserCreatedUUID', db_constraint=False, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='+', to=settings.AUTH_USER_MODEL)), + ('user_updated', models.ForeignKey(blank=True, db_column='UserUpdatedUUID', db_constraint=False, null=True, on_delete=django.db.models.deletion.DO_NOTHING, related_name='+', to=settings.AUTH_USER_MODEL)), + ], + options={ + 'verbose_name': 'historical beneficiary', + 'verbose_name_plural': 'historical beneficiarys', + 'ordering': ('-history_date', '-history_id'), + 'get_latest_by': ('history_date', 'history_id'), + }, + bases=(simple_history.models.HistoricalChanges, models.Model), + ), + migrations.CreateModel( + name='Beneficiary', + fields=[ + ('id', models.UUIDField(db_column='UUID', default=None, editable=False, primary_key=True, serialize=False)), + ('is_deleted', models.BooleanField(db_column='isDeleted', default=False)), + ('json_ext', models.JSONField(blank=True, db_column='Json_ext', null=True)), + ('date_created', core.fields.DateTimeField(db_column='DateCreated', null=True)), + ('date_updated', core.fields.DateTimeField(db_column='DateUpdated', null=True)), + ('version', models.IntegerField(default=1)), + ('date_valid_from', core.fields.DateTimeField(db_column='DateValidFrom', default=datetime.datetime.now)), + ('date_valid_to', core.fields.DateTimeField(blank=True, db_column='DateValidTo', null=True)), + ('replacement_uuid', models.UUIDField(db_column='ReplacementUUID', null=True)), + ('status', models.CharField(max_length=100)), + ('benefit_plan', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to='social_protection.benefitplan')), + ('individual', models.ForeignKey(on_delete=django.db.models.deletion.DO_NOTHING, to='individual.individual')), + ('user_created', models.ForeignKey(db_column='UserCreatedUUID', on_delete=django.db.models.deletion.DO_NOTHING, related_name='beneficiary_user_created', to=settings.AUTH_USER_MODEL)), + ('user_updated', models.ForeignKey(db_column='UserUpdatedUUID', on_delete=django.db.models.deletion.DO_NOTHING, related_name='beneficiary_user_updated', to=settings.AUTH_USER_MODEL)), + ], + options={ + 'abstract': False, + }, + bases=(dirtyfields.dirtyfields.DirtyFieldsMixin, models.Model), + ), + ] diff --git a/social_protection/models.py b/social_protection/models.py index b3eb306..dd96a1f 100644 --- a/social_protection/models.py +++ b/social_protection/models.py @@ -1,5 +1,6 @@ from django.db import models from core import models as core_models +from individual.models import Individual from policyholder.models import PolicyHolder @@ -14,3 +15,9 @@ class BenefitPlan(core_models.HistoryBusinessModel): ) holder = models.ForeignKey(PolicyHolder, models.DO_NOTHING, blank=True, null=True) beneficiary_data_schema = models.JSONField(null=True, blank=True) + + +class Beneficiary(core_models.HistoryBusinessModel): + individual = models.ForeignKey(Individual, models.DO_NOTHING, null=False) + benefit_plan = models.ForeignKey(BenefitPlan, models.DO_NOTHING, null=False) + status = models.CharField(max_length=100, null=False) diff --git a/social_protection/schema.py b/social_protection/schema.py index 394f59f..3c83d33 100644 --- a/social_protection/schema.py +++ b/social_protection/schema.py @@ -10,8 +10,14 @@ from social_protection.apps import SocialProtectionConfig from social_protection.gql_mutations import CreateBenefitPlanMutation, UpdateBenefitPlanMutation, \ DeleteBenefitPlanMutation -from social_protection.gql_queries import BenefitPlanGQLType -from social_protection.models import BenefitPlan +from social_protection.gql_queries import ( + BenefitPlanGQLType, + BeneficiaryGQLType +) +from social_protection.models import ( + BenefitPlan, + Beneficiary +) from social_protection.validation import check_bf_unique_code, check_bf_unique_name import graphene_django_optimizer as gql_optimizer @@ -25,6 +31,14 @@ class Query: applyDefaultValidityFilter=graphene.Boolean(), client_mutation_id=graphene.String() ) + beneficiary = OrderedDjangoFilterConnectionField( + BeneficiaryGQLType, + orderBy=graphene.List(of_type=graphene.String), + dateValidFrom__Gte=graphene.DateTime(), + dateValidTo__Lte=graphene.DateTime(), + applyDefaultValidityFilter=graphene.Boolean(), + client_mutation_id=graphene.String() + ) bf_code_validity = graphene.Field( ValidationMessageGQLType, bf_code=graphene.String(required=True), @@ -61,14 +75,30 @@ def resolve_benefit_plan(self, info, **kwargs): if client_mutation_id: filters.append(Q(mutations__mutation__client_mutation_id=client_mutation_id)) - Query._check_permissions(info.context.user) + Query._check_permissions( + info.context.user, + SocialProtectionConfig.gql_benefit_plan_search_perms + ) query = BenefitPlan.objects.filter(*filters) return gql_optimizer.query(query, info) + def resolve_beneficiary(self, info, **kwargs): + filters = append_validity_filter(**kwargs) + + client_mutation_id = kwargs.get("client_mutation_id", None) + if client_mutation_id: + filters.append(Q(mutations__mutation__client_mutation_id=client_mutation_id)) + + Query._check_permissions( + info.context.user, + SocialProtectionConfig.gql_beneficiary_search_perms + ) + query = Beneficiary.objects.filter(*filters) + return gql_optimizer.query(query, info) + @staticmethod - def _check_permissions(user): - if type(user) is AnonymousUser or not user.id or not user.has_perms( - SocialProtectionConfig.gql_benefit_plan_search_perms): + def _check_permissions(user, permission): + if type(user) is AnonymousUser or not user.id or not user.has_perms(permission): raise PermissionError("Unauthorized") diff --git a/social_protection/services.py b/social_protection/services.py index 311e2dd..c9d9157 100644 --- a/social_protection/services.py +++ b/social_protection/services.py @@ -2,7 +2,10 @@ from core.services import BaseService from core.signals import register_service_signal -from social_protection.models import BenefitPlan +from social_protection.models import ( + BenefitPlan, + Beneficiary +) from social_protection.validation import BenefitPlanValidation logger = logging.getLogger(__name__) @@ -25,3 +28,22 @@ def update(self, obj_data): @register_service_signal('benefit_plan_service.delete') def delete(self, obj_data): return super().delete(obj_data) + + +class BeneficiaryService(BaseService): + OBJECT_TYPE = Beneficiary + + def __init__(self, user, validation_class=None): + super().__init__(user, validation_class) + + @register_service_signal('beneficiary_service.create') + def create(self, obj_data): + return super().create(obj_data) + + @register_service_signal('beneficiary_service.update') + def update(self, obj_data): + return super().update(obj_data) + + @register_service_signal('beneficiary_service.delete') + def delete(self, obj_data): + return super().delete(obj_data) From f36c02c5f4f0170e600661d285ecb31f93c0dcaf Mon Sep 17 00:00:00 2001 From: sniedzielski Date: Mon, 22 May 2023 15:41:03 +0200 Subject: [PATCH 38/50] CM-27: added GQL mutations --- social_protection/gql_mutations.py | 99 ++++++++++++++++++++++++++++-- social_protection/schema.py | 14 ++++- social_protection/services.py | 7 ++- social_protection/validation.py | 6 +- 4 files changed, 117 insertions(+), 9 deletions(-) diff --git a/social_protection/gql_mutations.py b/social_protection/gql_mutations.py index 6134cca..a86ad3a 100644 --- a/social_protection/gql_mutations.py +++ b/social_protection/gql_mutations.py @@ -7,8 +7,14 @@ BaseHistoryModelUpdateMutationMixin, BaseHistoryModelDeleteMutationMixin from core.schema import OpenIMISMutation from social_protection.apps import SocialProtectionConfig -from social_protection.models import BenefitPlan -from social_protection.services import BenefitPlanService +from social_protection.models import ( + BenefitPlan, + Beneficiary +) +from social_protection.services import ( + BenefitPlanService, + BeneficiaryService +) class CreateBenefitPlanInputType(OpenIMISMutation.Input): @@ -33,8 +39,8 @@ class CreateBeneficiaryInputType(OpenIMISMutation.Input): individual_id = graphene.UUID(required=False) benefit_plan_id = graphene.UUID(required=False) - date_valid_from = graphene.Date(required=True) - date_valid_to = graphene.Date(required=True) + date_valid_from = graphene.Date(required=False) + date_valid_to = graphene.Date(required=False) json_ext = graphene.types.json.JSONString(required=False) @@ -123,3 +129,88 @@ def _mutate(cls, user, **data): class Input(OpenIMISMutation.Input): ids = graphene.List(graphene.UUID) + + +class CreateBeneficiaryMutation(BaseHistoryModelCreateMutationMixin, BaseMutation): + _mutation_class = "CreateBeneficiaryMutation" + _mutation_module = "social_protection" + _model = Beneficiary + + @classmethod + def _validate_mutation(cls, user, **data): + if type(user) is AnonymousUser or not user.has_perms( + SocialProtectionConfig.gql_beneficiary_create_perms): + raise ValidationError("mutation.authentication_required") + + @classmethod + def _mutate(cls, user, **data): + if "client_mutation_id" in data: + data.pop('client_mutation_id') + if "client_mutation_label" in data: + data.pop('client_mutation_label') + + service = BeneficiaryService(user) + print(data) + d = service.create(data) + print(d) + + class Input(CreateBeneficiaryInputType): + pass + + +class UpdateBeneficiaryMutation(BaseHistoryModelUpdateMutationMixin, BaseMutation): + _mutation_class = "UpdateBeneficiaryMutation" + _mutation_module = "social_protection" + _model = Beneficiary + + @classmethod + def _validate_mutation(cls, user, **data): + super()._validate_mutation(user, **data) + if type(user) is AnonymousUser or not user.has_perms( + SocialProtectionConfig.gql_beneficiary_update_perms): + raise ValidationError("mutation.authentication_required") + + @classmethod + def _mutate(cls, user, **data): + if "date_valid_to" not in data: + data['date_valid_to'] = None + if "client_mutation_id" in data: + data.pop('client_mutation_id') + if "client_mutation_label" in data: + data.pop('client_mutation_label') + + service = BeneficiaryService(user) + service.update(data) + + class Input(UpdateBeneficiaryInputType): + pass + + +class DeleteBeneficiaryMutation(BaseHistoryModelDeleteMutationMixin, BaseMutation): + _mutation_class = "DeleteBeneficiaryMutation" + _mutation_module = "social_protection" + _model = Beneficiary + + @classmethod + def _validate_mutation(cls, user, **data): + if type(user) is AnonymousUser or not user.id or not user.has_perms( + SocialProtectionConfig.gql_beneficiary_delete_perms): + raise ValidationError("mutation.authentication_required") + + @classmethod + def _mutate(cls, user, **data): + if "client_mutation_id" in data: + data.pop('client_mutation_id') + if "client_mutation_label" in data: + data.pop('client_mutation_label') + + service = BeneficiaryService(user) + + ids = data.get('ids') + if ids: + with transaction.atomic(): + for id in ids: + service.delete({'id': id}) + + class Input(OpenIMISMutation.Input): + ids = graphene.List(graphene.UUID) diff --git a/social_protection/schema.py b/social_protection/schema.py index 3c83d33..4a5ae99 100644 --- a/social_protection/schema.py +++ b/social_protection/schema.py @@ -8,8 +8,14 @@ from core.schema import OrderedDjangoFilterConnectionField from core.utils import append_validity_filter from social_protection.apps import SocialProtectionConfig -from social_protection.gql_mutations import CreateBenefitPlanMutation, UpdateBenefitPlanMutation, \ - DeleteBenefitPlanMutation +from social_protection.gql_mutations import ( + CreateBenefitPlanMutation, + UpdateBenefitPlanMutation, + DeleteBenefitPlanMutation, + CreateBeneficiaryMutation, + UpdateBeneficiaryMutation, + DeleteBeneficiaryMutation +) from social_protection.gql_queries import ( BenefitPlanGQLType, BeneficiaryGQLType @@ -106,3 +112,7 @@ class Mutation(graphene.ObjectType): create_benefit_plan = CreateBenefitPlanMutation.Field() update_benefit_plan = UpdateBenefitPlanMutation.Field() delete_benefit_plan = DeleteBenefitPlanMutation.Field() + + create_beneficiary = CreateBeneficiaryMutation.Field() + update_beneficiary = UpdateBeneficiaryMutation.Field() + delete_beneficiary = DeleteBeneficiaryMutation.Field() diff --git a/social_protection/services.py b/social_protection/services.py index c9d9157..dfd7c55 100644 --- a/social_protection/services.py +++ b/social_protection/services.py @@ -6,7 +6,10 @@ BenefitPlan, Beneficiary ) -from social_protection.validation import BenefitPlanValidation +from social_protection.validation import ( + BeneficiaryValidation, + BenefitPlanValidation +) logger = logging.getLogger(__name__) @@ -33,7 +36,7 @@ def delete(self, obj_data): class BeneficiaryService(BaseService): OBJECT_TYPE = Beneficiary - def __init__(self, user, validation_class=None): + def __init__(self, user, validation_class=BeneficiaryValidation): super().__init__(user, validation_class) @register_service_signal('beneficiary_service.create') diff --git a/social_protection/validation.py b/social_protection/validation.py index ad3bfb3..726dd73 100644 --- a/social_protection/validation.py +++ b/social_protection/validation.py @@ -3,7 +3,7 @@ from django.core.exceptions import ValidationError from core.validation import BaseModelValidation -from social_protection.models import BenefitPlan +from social_protection.models import Beneficiary, BenefitPlan class BenefitPlanValidation(BaseModelValidation): @@ -67,3 +67,7 @@ def is_valid_json_schema(schema): return [] except jsonschema.exceptions.SchemaError: return [{"message": "BenefitPlan schema is not valid"}] + + +class BeneficiaryValidation(BaseModelValidation): + OBJECT_TYPE = Beneficiary From 3f676eaa3fe8cbf90a5547eeb3416ea06f0b02e0 Mon Sep 17 00:00:00 2001 From: sniedzielski Date: Mon, 22 May 2023 16:20:12 +0200 Subject: [PATCH 39/50] CM-27: added tests for beneficiary service --- .../tests/beneficiary_service_test.py | 81 +++++++++++++++++++ social_protection/tests/data.py | 14 ++++ 2 files changed, 95 insertions(+) create mode 100644 social_protection/tests/beneficiary_service_test.py diff --git a/social_protection/tests/beneficiary_service_test.py b/social_protection/tests/beneficiary_service_test.py new file mode 100644 index 0000000..1ecebf8 --- /dev/null +++ b/social_protection/tests/beneficiary_service_test.py @@ -0,0 +1,81 @@ +import copy + +from django.test import TestCase + +from individual.models import Individual +from individual.tests.data import service_add_payload as service_add_individual_payload + +from social_protection.models import Beneficiary, BenefitPlan +from social_protection.services import BeneficiaryService +from social_protection.tests.data import ( + service_beneficiary_add_payload, + service_beneficiary_update_payload +) +from social_protection.tests.helpers import LogInHelper + + +class BeneficiaryServiceTest(TestCase): + user = None + service = None + query_all = None + + @classmethod + def setUpClass(cls): + super().setUpClass() + + cls.user = LogInHelper().get_or_create_user_api() + cls.service = BeneficiaryService(cls.user) + cls.query_all = Beneficiary.objects.filter(is_deleted=False) + cls.benefit_plan = cls.__create_benefit_plan() + cls.individual = cls.__create_individual() + + def test_add_benefitiary(self): + result = self.service.create(service_beneficiary_add_payload) + self.assertTrue(result.get('success', False), result.get('detail', "No details provided")) + uuid = result.get('data', {}).get('uuid', None) + query = self.query_all.filter(uuid=uuid) + self.assertEqual(query.count(), 1) + + def test_update_benefit_plan(self): + result = self.service.create(service_beneficiary_add_payload) + self.assertTrue(result.get('success', False), result.get('detail', "No details provided")) + uuid = result.get('data', {}).get('uuid') + update_payload = copy.deepcopy(service_beneficiary_update_payload) + update_payload['id'] = uuid + result = self.service.update(service_beneficiary_update_payload) + self.assertTrue(result.get('success', False), result.get('detail', "No details provided")) + query = self.query_all.filter(uuid=uuid) + self.assertEqual(query.count(), 1) + self.assertEqual(query.first().first_name, update_payload.get('first_name')) + + def test_delete_benefit_plan(self): + result = self.service.create(service_beneficiary_add_payload) + self.assertTrue(result.get('success', False), result.get('detail', "No details provided")) + uuid = result.get('data', {}).get('uuid') + delete_payload = {'id': uuid} + result = self.service.delete(delete_payload) + self.assertTrue(result.get('success', False), result.get('detail', "No details provided")) + query = self.query_all.filter(uuid=uuid) + self.assertEqual(query.count(), 0) + + @classmethod + def __create_benefit_plan(cls): + object_data = { + **service_beneficiary_add_payload + } + + benefit_plan = BenefitPlan(**object_data) + benefit_plan.save(username=cls.user.username) + + return benefit_plan + + @classmethod + def __create_individual(cls): + object_data = { + **service_add_individual_payload + } + + individual = Individual(**object_data) + individual.save(username=cls.user.username) + + return individual diff --git a/social_protection/tests/data.py b/social_protection/tests/data.py index 052fdbb..423c677 100644 --- a/social_protection/tests/data.py +++ b/social_protection/tests/data.py @@ -81,3 +81,17 @@ "dateValidTo": "2023-12-31", "jsonExt": "{\"key\":\"updated_value\"}" } + +service_beneficiary_add_payload = { + "status": "Potential", + "dateValidFrom": "2023-01-01", + "dateValidTo": "2023-12-31", + "jsonExt": "{\"key\":\"value\"}" +} + +service_beneficiary_update_payload = { + "status": "Active", + "dateValidFrom": "2023-01-01", + "dateValidTo": "2023-12-31", + "jsonExt": "{\"key\":\"value\"}" +} From 8d2312b8006eeb6ee9b77c9def29841b3ab2b1c3 Mon Sep 17 00:00:00 2001 From: sniedzielski Date: Mon, 22 May 2023 16:35:40 +0200 Subject: [PATCH 40/50] CM-27: fixing one unresolved conflict, removed redundant print --- social_protection/gql_mutations.py | 2 -- social_protection/gql_queries.py | 3 --- 2 files changed, 5 deletions(-) diff --git a/social_protection/gql_mutations.py b/social_protection/gql_mutations.py index a86ad3a..f590a1f 100644 --- a/social_protection/gql_mutations.py +++ b/social_protection/gql_mutations.py @@ -150,9 +150,7 @@ def _mutate(cls, user, **data): data.pop('client_mutation_label') service = BeneficiaryService(user) - print(data) d = service.create(data) - print(d) class Input(CreateBeneficiaryInputType): pass diff --git a/social_protection/gql_queries.py b/social_protection/gql_queries.py index f1b15fb..b0cee78 100644 --- a/social_protection/gql_queries.py +++ b/social_protection/gql_queries.py @@ -28,7 +28,6 @@ class Meta: "version": ["exact"], } connection_class = ExtendedConnection -<<<<<<< HEAD class BeneficiaryGQLType(DjangoObjectType): @@ -50,5 +49,3 @@ class Meta: "version": ["exact"], } connection_class = ExtendedConnection -======= ->>>>>>> 16e5bef8f77612b91937f476ab023fceeb6d0511 From 586ba62cbecba021b0c2b1cf1c0b3ac41d6a325b Mon Sep 17 00:00:00 2001 From: sniedzielski Date: Mon, 22 May 2023 16:39:36 +0200 Subject: [PATCH 41/50] CM-27: minor fix in service --- social_protection/gql_mutations.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/social_protection/gql_mutations.py b/social_protection/gql_mutations.py index f590a1f..ebee24c 100644 --- a/social_protection/gql_mutations.py +++ b/social_protection/gql_mutations.py @@ -150,7 +150,7 @@ def _mutate(cls, user, **data): data.pop('client_mutation_label') service = BeneficiaryService(user) - d = service.create(data) + service.create(data) class Input(CreateBeneficiaryInputType): pass From 3dd146d88d31353311561f89419d098536e2e37f Mon Sep 17 00:00:00 2001 From: sniedzielski Date: Mon, 22 May 2023 17:36:25 +0200 Subject: [PATCH 42/50] CM-27: fixed typo in test of services --- social_protection/tests/beneficiary_service_test.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/social_protection/tests/beneficiary_service_test.py b/social_protection/tests/beneficiary_service_test.py index 1ecebf8..d83cc3d 100644 --- a/social_protection/tests/beneficiary_service_test.py +++ b/social_protection/tests/beneficiary_service_test.py @@ -46,7 +46,7 @@ def test_update_benefit_plan(self): self.assertTrue(result.get('success', False), result.get('detail', "No details provided")) query = self.query_all.filter(uuid=uuid) self.assertEqual(query.count(), 1) - self.assertEqual(query.first().first_name, update_payload.get('first_name')) + self.assertEqual(query.first().status, update_payload.get('status')) def test_delete_benefit_plan(self): result = self.service.create(service_beneficiary_add_payload) From 9a772038dbc10e843a7924ef58191956606fa69e Mon Sep 17 00:00:00 2001 From: sniedzielski Date: Mon, 22 May 2023 17:42:43 +0200 Subject: [PATCH 43/50] CM-27: fixed tests naming and creation of test data --- .../tests/beneficiary_service_test.py | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/social_protection/tests/beneficiary_service_test.py b/social_protection/tests/beneficiary_service_test.py index d83cc3d..70cb77a 100644 --- a/social_protection/tests/beneficiary_service_test.py +++ b/social_protection/tests/beneficiary_service_test.py @@ -28,28 +28,35 @@ def setUpClass(cls): cls.query_all = Beneficiary.objects.filter(is_deleted=False) cls.benefit_plan = cls.__create_benefit_plan() cls.individual = cls.__create_individual() + cls.payload = { + **service_beneficiary_add_payload, + "individual_id": cls.individual.id, + "benefit_plan_id": cls.benefit_plan.id + } - def test_add_benefitiary(self): - result = self.service.create(service_beneficiary_add_payload) + def test_add_beneficiary(self): + result = self.service.create(self.payload) self.assertTrue(result.get('success', False), result.get('detail', "No details provided")) uuid = result.get('data', {}).get('uuid', None) query = self.query_all.filter(uuid=uuid) self.assertEqual(query.count(), 1) - def test_update_benefit_plan(self): - result = self.service.create(service_beneficiary_add_payload) + def test_update_beneficiary(self): + result = self.service.create(self.payload) self.assertTrue(result.get('success', False), result.get('detail', "No details provided")) uuid = result.get('data', {}).get('uuid') update_payload = copy.deepcopy(service_beneficiary_update_payload) update_payload['id'] = uuid + update_payload['individual_id'] = self.individual.id + update_payload['benefit_plan_id'] = self.benefit_plan.id result = self.service.update(service_beneficiary_update_payload) self.assertTrue(result.get('success', False), result.get('detail', "No details provided")) query = self.query_all.filter(uuid=uuid) self.assertEqual(query.count(), 1) self.assertEqual(query.first().status, update_payload.get('status')) - def test_delete_benefit_plan(self): - result = self.service.create(service_beneficiary_add_payload) + def test_delete_beneficiary(self): + result = self.service.create(self.payload) self.assertTrue(result.get('success', False), result.get('detail', "No details provided")) uuid = result.get('data', {}).get('uuid') delete_payload = {'id': uuid} From 0646bda398275b4d9daeecb3ced51b8b785aed69 Mon Sep 17 00:00:00 2001 From: sniedzielski Date: Mon, 22 May 2023 18:16:29 +0200 Subject: [PATCH 44/50] CM-27: fixed helper test to take benefit plan data --- social_protection/tests/beneficiary_service_test.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/social_protection/tests/beneficiary_service_test.py b/social_protection/tests/beneficiary_service_test.py index 70cb77a..404afff 100644 --- a/social_protection/tests/beneficiary_service_test.py +++ b/social_protection/tests/beneficiary_service_test.py @@ -8,6 +8,7 @@ from social_protection.models import Beneficiary, BenefitPlan from social_protection.services import BeneficiaryService from social_protection.tests.data import ( + service_add_payload, service_beneficiary_add_payload, service_beneficiary_update_payload ) @@ -68,7 +69,7 @@ def test_delete_beneficiary(self): @classmethod def __create_benefit_plan(cls): object_data = { - **service_beneficiary_add_payload + **service_add_payload } benefit_plan = BenefitPlan(**object_data) From 258942955734c4798523a86d534d9105aea4f17a Mon Sep 17 00:00:00 2001 From: sniedzielski Date: Mon, 22 May 2023 19:08:28 +0200 Subject: [PATCH 45/50] CM-27: fixes and adjustments in data helpers in tests --- .../tests/beneficiary_service_test.py | 2 +- social_protection/tests/data.py | 63 +++++++++---------- 2 files changed, 29 insertions(+), 36 deletions(-) diff --git a/social_protection/tests/beneficiary_service_test.py b/social_protection/tests/beneficiary_service_test.py index 404afff..7d6e72e 100644 --- a/social_protection/tests/beneficiary_service_test.py +++ b/social_protection/tests/beneficiary_service_test.py @@ -50,7 +50,7 @@ def test_update_beneficiary(self): update_payload['id'] = uuid update_payload['individual_id'] = self.individual.id update_payload['benefit_plan_id'] = self.benefit_plan.id - result = self.service.update(service_beneficiary_update_payload) + result = self.service.update(update_payload) self.assertTrue(result.get('success', False), result.get('detail', "No details provided")) query = self.query_all.filter(uuid=uuid) self.assertEqual(query.count(), 1) diff --git a/social_protection/tests/data.py b/social_protection/tests/data.py index 423c677..df60468 100644 --- a/social_protection/tests/data.py +++ b/social_protection/tests/data.py @@ -1,47 +1,44 @@ service_add_payload = { "code": "example", "name": "example_name", - "maxBeneficiaries": 0, - "ceilingPerBeneficiary": "0.00", + "max_beneficiaries": 0, + "ceiling_per_beneficiary": "0.00", "beneficiary_data_schema": { "$schema": "https://json-schema.org/draft/2019-09/schema" }, - "dateValidFrom": "2023-01-01", - "dateValidTo": "2023-12-31", - "jsonExt": "{\"key\":\"value\"}" + "date_valid_from": "2023-01-01", + "date_valid_to": "2023-12-31", } service_add_payload_same_code = { "code": "example", "name": "random", - "maxBeneficiaries": 0, - "ceilingPerBeneficiary": "0.00", + "max_beneficiaries": 0, + "ceiling_per_beneficiary": "0.00", "beneficiary_data_schema": { "$schema": "https://json-schema.org/draft/2019-09/schema" }, - "dateValidFrom": "2023-01-01", - "dateValidTo": "2023-12-31", - "jsonExt": "{\"key\":\"value\"}" + "date_valid_from": "2023-01-01", + "date_valid_to": "2023-12-31", } service_add_payload_same_name = { "code": "random", "name": "example_name", - "maxBeneficiaries": 0, - "ceilingPerBeneficiary": "0.00", + "max_beneficiaries": 0, + "ceiling_per_beneficiary": "0.00", "beneficiary_data_schema": { "$schema": "https://json-schema.org/draft/2019-09/schema" }, - "dateValidFrom": "2023-01-01", - "dateValidTo": "2023-12-31", - "jsonExt": "{\"key\":\"value\"}" + "date_valid_from": "2023-01-01", + "date_valid_to": "2023-12-31", } service_add_payload_invalid_schema = { "code": "random", "name": "example_name", - "maxBeneficiaries": 0, - "ceilingPerBeneficiary": "0.00", + "max_beneficiaries": 0, + "ceiling_per_beneficiary": "0.00", "beneficiary_data_schema": { "$schema": "https://json-schema.org/draft/2019-09/schema", "type": "object", @@ -52,46 +49,42 @@ }, "required": ["invalid_property"] }, - "dateValidFrom": "2023-01-01", - "dateValidTo": "2023-12-31", - "jsonExt": "{\"key\":\"value\"}" + "date_valid_from": "2023-01-01", + "date_valid_to": "2023-12-31", } service_add_payload_no_ext = { "code": "example", "name": "example_name", - "maxBeneficiaries": 0, - "ceilingPerBeneficiary": "0.00", + "max_beneficiaries": 0, + "ceiling_per_beneficiary": "0.00", "beneficiary_data_schema": { "$schema": "https://json-schema.org/draft/2019-09/schema" }, - "dateValidFrom": "2023-01-01", - "dateValidTo": "2023-12-31", + "date_valid_from": "2023-01-01", + "date_valid_to": "2023-12-31", } service_update_payload = { "code": "update", "name": "example_update", - "maxBeneficiaries": 0, - "ceilingPerBeneficiary": "0.00", + "max_beneficiaries": 0, + "ceiling_per_beneficiaryd": "0.00", "beneficiary_data_schema": { "$schema": "https://json-schema.org/draft/2019-09/schema" }, - "dateValidFrom": "2023-01-01", - "dateValidTo": "2023-12-31", - "jsonExt": "{\"key\":\"updated_value\"}" + "date_valid_from": "2023-01-01", + "date_valid_to": "2023-12-31", } service_beneficiary_add_payload = { "status": "Potential", - "dateValidFrom": "2023-01-01", - "dateValidTo": "2023-12-31", - "jsonExt": "{\"key\":\"value\"}" + "date_valid_from": "2023-01-01", + "date_valid_to": "2023-12-31", } service_beneficiary_update_payload = { "status": "Active", - "dateValidFrom": "2023-01-01", - "dateValidTo": "2023-12-31", - "jsonExt": "{\"key\":\"value\"}" + "date_valid_from": "2023-01-01", + "date_valid_to": "2023-12-31", } From 80b9be0a9e6b0667dddd5e188e372f463a7d3739 Mon Sep 17 00:00:00 2001 From: sniedzielski Date: Mon, 22 May 2023 19:21:40 +0200 Subject: [PATCH 46/50] CM-27: added missing initialization of tests files --- social_protection/tests/__init__.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/social_protection/tests/__init__.py b/social_protection/tests/__init__.py index e69de29..d67d38e 100644 --- a/social_protection/tests/__init__.py +++ b/social_protection/tests/__init__.py @@ -0,0 +1,2 @@ +from .beneficiary_service_test import BeneficiaryServiceTest +from .benefit_plan_service_test import BenefitPlanServiceTest From 20fdb5ee3858024726ca030fccba4555378cd646 Mon Sep 17 00:00:00 2001 From: jdolkowski Date: Tue, 23 May 2023 12:34:54 +0200 Subject: [PATCH 47/50] CM-27: fix tests --- .../tests/benefit_plan_service_test.py | 8 ++++---- social_protection/tests/data.py | 13 ++++++++----- 2 files changed, 12 insertions(+), 9 deletions(-) diff --git a/social_protection/tests/benefit_plan_service_test.py b/social_protection/tests/benefit_plan_service_test.py index 01180bb..a41c60e 100644 --- a/social_protection/tests/benefit_plan_service_test.py +++ b/social_protection/tests/benefit_plan_service_test.py @@ -50,7 +50,7 @@ def test_update_benefit_plan(self): self.assertTrue(result.get('success', False), result.get('detail', "No details provided")) query = self.query_all.filter(uuid=uuid) self.assertEqual(query.count(), 1) - self.assertEqual(query.first().first_name, update_payload.get('first_name')) + self.assertEqual(query.first().name, update_payload.get('name')) def test_delete_benefit_plan(self): result = self.service.create(service_add_payload) @@ -70,7 +70,7 @@ def test_add_not_unique_code_benefit_plan(self): self.assertEqual(query.count(), 1) second_bf = self.service.create(service_add_payload_same_code) self.assertFalse(second_bf.get('success', True)) - code = first_bf['code'] + code = first_bf['data']['code'] code_query = self.query_all.filter(code=code) self.assertEqual(code_query.count(), 1) @@ -82,9 +82,9 @@ def test_add_not_unique_name_benefit_plan(self): self.assertEqual(query.count(), 1) second_bf = self.service.create(service_add_payload_same_name) self.assertFalse(second_bf.get('success', True)) - name = first_bf['name'] + name = first_bf['data']['name'] name_query = self.query_all.filter(name=name) - self.assertEqual(name.count(), 1) + self.assertEqual(name_query.count(), 1) def test_add_invalid_schema_benefit_plan(self): result = self.service.create(service_add_payload_invalid_schema) diff --git a/social_protection/tests/data.py b/social_protection/tests/data.py index df60468..8cea2eb 100644 --- a/social_protection/tests/data.py +++ b/social_protection/tests/data.py @@ -40,14 +40,17 @@ "max_beneficiaries": 0, "ceiling_per_beneficiary": "0.00", "beneficiary_data_schema": { - "$schema": "https://json-schema.org/draft/2019-09/schema", "type": "object", "properties": { - "invalid_property": { - "type": "string" + "name": { + "type": "string", + "maxLength": "abc" + }, + "age": { + "type": "integer", + "maximum": -10 } - }, - "required": ["invalid_property"] + } }, "date_valid_from": "2023-01-01", "date_valid_to": "2023-12-31", From 2b007ae2ff372e1d1cbfe9b6d97b80b373dd3bad Mon Sep 17 00:00:00 2001 From: jdolkowski Date: Wed, 24 May 2023 11:22:41 +0200 Subject: [PATCH 48/50] CM-27: make validate_json_schema validate only if schema in mutation --- social_protection/validation.py | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/social_protection/validation.py b/social_protection/validation.py index 63cb1a0..ba314ab 100644 --- a/social_protection/validation.py +++ b/social_protection/validation.py @@ -31,14 +31,19 @@ def validate_delete(cls, user, **data): def validate_benefit_plan(data, uuid=None): - return [ + validations = [ *validate_not_empty_field(data.get("code"), "code"), *validate_bf_unique_code(data.get('code'), uuid), *validate_not_empty_field(data.get("name"), "name"), - *validate_bf_unique_name(data.get('name'), uuid), - *validate_json_schema(data.get('beneficiary_data_schema')) + *validate_bf_unique_name(data.get('name'), uuid) ] + beneficiary_data_schema = data.get('beneficiary_data_schema') + if beneficiary_data_schema: + validations.extend(validate_json_schema(beneficiary_data_schema)) + + return validations + def validate_bf_unique_code(code, uuid=None): instance = BenefitPlan.objects.filter(code=code, is_deleted=False).first() From 47a5445877572d9704a2858eaf4def45e8349496 Mon Sep 17 00:00:00 2001 From: jdolkowski Date: Wed, 24 May 2023 17:51:39 +0200 Subject: [PATCH 49/50] CM-27: fix name validation graphql --- social_protection/schema.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/social_protection/schema.py b/social_protection/schema.py index 6b8eca7..71fb900 100644 --- a/social_protection/schema.py +++ b/social_protection/schema.py @@ -68,7 +68,7 @@ def resolve_bf_code_validity(self, info, **kwargs): def resolve_bf_name_validity(self, info, **kwargs): if not info.context.user.has_perms(SocialProtectionConfig.gql_benefit_plan_search_perms): raise PermissionDenied(_("unauthorized")) - errors = validate_bf_unique_name(kwargs['bf_code']) + errors = validate_bf_unique_name(kwargs['bf_name']) if errors: return ValidationMessageGQLType(False, error_message=errors[0]['message']) else: From 82657eb8d88563739bc4a6d253e50fcbc4923d38 Mon Sep 17 00:00:00 2001 From: jdolkowski Date: Thu, 25 May 2023 13:32:05 +0200 Subject: [PATCH 50/50] CM-27: return mutation errors --- social_protection/gql_mutations.py | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/social_protection/gql_mutations.py b/social_protection/gql_mutations.py index ebee24c..77540e7 100644 --- a/social_protection/gql_mutations.py +++ b/social_protection/gql_mutations.py @@ -67,7 +67,10 @@ def _mutate(cls, user, **data): data.pop('client_mutation_label') service = BenefitPlanService(user) - service.create(data) + res = service.create(data) + if not res['success']: + return res + return None class Input(CreateBenefitPlanInputType): pass @@ -95,7 +98,10 @@ def _mutate(cls, user, **data): data.pop('client_mutation_label') service = BenefitPlanService(user) - service.update(data) + res = service.update(data) + if not res['success']: + return res + return None class Input(UpdateBenefitPlanInputType): pass