diff --git a/LICENSE b/LICENSE index f4586ac..8df43b9 100644 --- a/LICENSE +++ b/LICENSE @@ -1,21 +1,219 @@ -MIT License - -Copyright (c) 2025 [Anyer Moreno Alcaraz] - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. +GNU GENERAL PUBLIC LICENSE +Version 3, 29 June 2007 + +Copyright © 2007 Free Software Foundation, Inc. + +Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. + +Preamble +The GNU General Public License is a free, copyleft license for software and other kinds of works. + +The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. + +When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. + +To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. + +For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. + +Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. + +For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. + +Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. + +Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. + +The precise terms and conditions for copying, distribution and modification follow. + +TERMS AND CONDITIONS +0. Definitions. +“This License” refers to version 3 of the GNU General Public License. + +“Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. + +“The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations. + +To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work. + +A “covered work” means either the unmodified Program or a work based on the Program. + +To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. + +To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. + +An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. + +1. Source Code. +The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work. + +A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. + +The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. + +The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. + +The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. + +The Corresponding Source for a work in source code form is that same work. + +2. Basic Permissions. +All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. + +You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. + +Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. + +3. Protecting Users' Legal Rights From Anti-Circumvention Law. +No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. + +When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. + +4. Conveying Verbatim Copies. +You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. + +You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. + +5. Conveying Modified Source Versions. +You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: + +a) The work must carry prominent notices stating that you modified it, and giving a relevant date. +b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”. +c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. +d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. +A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. + +6. Conveying Non-Source Forms. +You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: + +a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. +b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. +c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. +d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. +e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. +A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. + +A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. + +“Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. + +If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). + +The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. + +Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. + +7. Additional Terms. +“Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. + +When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. + +Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: + +a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or +b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or +c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or +d) Limiting the use for publicity purposes of names of licensors or authors of the material; or +e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or +f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. +All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. + +If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. + +Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. + +8. Termination. +You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). + +However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. + +Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. + +Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. + +9. Acceptance Not Required for Having Copies. +You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. + +10. Automatic Licensing of Downstream Recipients. +Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. + +An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. + +You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. + +11. Patents. +A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”. + +A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. + +Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. + +In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. + +If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. + +If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. + +A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. + +Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. + +12. No Surrender of Others' Freedom. +If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. + +13. Use with the GNU Affero General Public License. +Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. + +14. Revised Versions of this License. +The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. + +If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. + +Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. + +15. Disclaimer of Warranty. +THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +16. Limitation of Liability. +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +17. Interpretation of Sections 15 and 16. +If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. + +END OF TERMS AND CONDITIONS + +How to Apply These Terms to Your New Programs +If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. + +To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +Also add information on how to contact you by electronic and paper mail. + +If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. +The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an “about box”. + +You should also get your employer (if you work as a programmer) or school, if any, to sign a “copyright disclaimer” for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . + +The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . \ No newline at end of file diff --git a/README.md b/README.md index ce07ad6..95dfcb4 100644 --- a/README.md +++ b/README.md @@ -100,7 +100,7 @@ Abans d’enviar, assegura’t de seguir l’estil de codi del projecte i escriu ## ✉️ Contacte Per dubtes tècnics o col·laboració, contacta amb el desenvolupador principal: -📧 a.moreno@estudiantat.upc.edu +📧 anyer.moreno@estudiantat.upc.edu ## 📄 Llicència -Aquest projecte està llicenciat sota la MIT License – consulta el fitxer LICENSE per a més informació. \ No newline at end of file +This project is licensed under the terms of the GNU General Public License v3.0 – see the LICENSE file for details. \ No newline at end of file diff --git a/app/management/__init__.py b/app/management/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/management/commands/__init__.py b/app/management/commands/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/management/commands/create_basic_db.py b/app/management/commands/create_basic_db.py new file mode 100644 index 0000000..db0f689 --- /dev/null +++ b/app/management/commands/create_basic_db.py @@ -0,0 +1,184 @@ +import random +from datetime import timedelta + +from django.contrib.auth.models import User +from django.core.management.base import BaseCommand +from django.utils import timezone + +from app.models import App +from app.services import AppService +from metric.constants import MetricCode +from metric.models import Metric, MetricValue +from source.models import Source + + +class Command(BaseCommand): + help = "Crea les Sources i Metric bàsiques" + + def handle(self, *args, **kwargs): + average_rating = Metric.objects.create( + code="average_rating", + name="Average Rating", + value_type="float", + description="Valoració mitjana de l'app", + ) + total_reviews = Metric.objects.create( + code="total_reviews", + name="Total Reviews", + value_type="integer", + description="Nombre total de ressenyes", + ) + daily_news_blog_mentions = Metric.objects.create( + code="daily_news_blog_mentions", + name="Daily News Blog Mentions", + value_type="integer", + description="Nombre de mencions diàries a blogs de notícies", + ) + daily_social_network_mentions = Metric.objects.create( + code="daily_social_network_mentions", + name="Daily Social Network Mentions", + value_type="integer", + description="Nombre de mencions diàries a Reddit", + ) + total_downloads = Metric.objects.create( + code="total_downloads", + name="Total Downloads", + value_type="integer", + description="Número de descàrregues de l'app", + ) + last_update_date = Metric.objects.create( + code="last_update_date", + name="Last Update Date", + value_type="date", + description="Data de la darrera actualització.", + ) + Metric.objects.create( + code="bug_rate", + name="Bug Rate", + value_type="float", + description="Proporció de reviews que mencionen errors" + " o bugs respecte al total de reviews.", + is_derived=True, + ) + Metric.objects.create( + code="positive_rate", + name="Positive Rate", + value_type="float", + description="Proporció de reviews amb sentiment positiu respecte al total de reviews.", + is_derived=True, + ) + Metric.objects.create( + code="update_changed", + name="Update Changed", + value_type="integer", + description="Indica si la data de darrera actualització ha " + "canviat respecte al dia anterior." + "\nEl valor és 1 si hi ha un canvi i 0 si es manté igual.", + id_derived=True, + ) + Source.objects.create( + code="itunes", + name="App Store", + type="api", + url="https://itunes.apple.com", + ).metrics.set([average_rating, total_reviews]) + Source.objects.create( + code="google_play", + name="Google Play Scraper", + type="scraper", + url="https://play.google.com", + ).metrics.set([average_rating, total_reviews, total_downloads, last_update_date]) + Source.objects.create( + code="news", + name="News API", + type="api", + url="https://newsapi.org/v2", + ).metrics.set([daily_news_blog_mentions]) + Source.objects.create( + code="reddit", + name="Reddit API", + type="api", + ).metrics.set([daily_social_network_mentions]) + + user = User.objects.create_superuser( + username="Anyer", email="anyer@example.com", password="Anyer123" + ) + + service = AppService() + + validated_data = { + "code": "discord", + "name": "Discord", + "description": "Discord is designed for gaming and great for just " + "chilling with friends or building a community.", + "appstore_id": "985746746", + "playstore_id": "com.discord", + } + service.create_app(validated_data, user) + + validated_data = { + "code": "gemini", + "name": "Google Gemini", + "description": "La aplicación de Google Gemini es un asistente de" + " IA que puede ayudarte a dar rienda suelta a tu creatividad y productividad.", + "appstore_id": "6477489729", + "playstore_id": "com.google.android.apps.bard", + } + service.create_app(validated_data, user) + + validated_data = { + "code": "instagram", + "name": "Instagram", + "description": "Aplicació per a socialitzar i compartir fotos i vídeos.", + "appstore_id": "389801252", + "playstore_id": "bla", + } + service.create_app(validated_data, user) + + apps = App.objects.all() + metrics = Metric.objects.all() + + if not apps.exists() or not metrics.exists(): + self.stdout.write(self.style.ERROR("Debes tener apps y métricas creadas")) + return + + created_count = 0 + + for app in apps: + for metric in metrics: + for source in metric.sources.all(): + for days_ago in range(45): # últimos 30 días + date = timezone.now() - timedelta(days=days_ago) + if metric.code == MetricCode.AVERAGE_RATING: + value = round(random.uniform(4.4, 4.5), 5) + elif metric.code == MetricCode.TOTAL_REVIEWS: + value = str(random.randint(3050000, 3080000)) + elif metric.code == MetricCode.DAILY_NEWS_BLOG_MENTIONS: + value = str(random.randint(0, 5)) + elif metric.code == MetricCode.DAILY_SOCIAL_NETWORK_MENTIONS: + value = str(random.randint(150, 300)) + elif metric.code == MetricCode.LAST_UPDATE_DATE: + if days_ago < 15: + value = date.date() - timedelta(days=10) + elif days_ago < 30: + value = date.date() - timedelta(days=20) + else: + value = date.date() + else: + value = str(random.randint(500000000, 600000000)) + + MetricValue.objects.create( + app=app, + metric=metric, + source=source, + value=str(value), + retrieved_at=date, + ) + created_count += 1 + + self.stdout.write( + self.style.SUCCESS( + f"✔ {created_count} MetricValues creados correctamente." + f"✔ Valors per defecte de Source i Metrics creats correctement." + ) + ) diff --git a/app/migrations/0001_initial.py b/app/migrations/0001_initial.py index 2c43749..278ad65 100644 --- a/app/migrations/0001_initial.py +++ b/app/migrations/0001_initial.py @@ -1,5 +1,7 @@ -# Generated by Django 5.1.7 on 2025-03-31 18:07 +# Generated by Django 5.1.7 on 2025-05-30 17:42 +import django.db.models.deletion +from django.conf import settings from django.db import migrations, models @@ -7,7 +9,9 @@ class Migration(migrations.Migration): initial = True - dependencies = [] + dependencies = [ + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ] operations = [ migrations.CreateModel( @@ -16,28 +20,41 @@ class Migration(migrations.Migration): ( "id", models.BigAutoField( - auto_created=True, - primary_key=True, - serialize=False, - verbose_name="ID", + auto_created=True, primary_key=True, serialize=False, verbose_name="ID" ), ), + ("code", models.CharField(max_length=100)), ("name", models.CharField(max_length=200)), - ("description", models.TextField()), - ( - "appstore_id", - models.CharField(max_length=100, null=True, unique=True), - ), - ( - "playstore_id", - models.CharField(max_length=100, null=True, unique=True), - ), - ("developer", models.CharField(max_length=100, null=True, unique=True)), + ("description", models.TextField(blank=True, null=True)), + ("appstore_id", models.CharField(max_length=100, null=True)), + ("playstore_id", models.CharField(max_length=100, null=True)), + ("developer", models.CharField(max_length=100, null=True)), ("available_on_ios", models.BooleanField(default=False)), ("available_on_android", models.BooleanField(default=False)), ("pegi_rating", models.CharField(max_length=10, null=True)), ("release_date", models.DateField(null=True)), ("min_ios_version", models.CharField(max_length=10, null=True)), + ("icon_url", models.URLField(null=True)), + ("size_in_bytes", models.BigIntegerField(null=True)), + ( + "user", + models.ForeignKey( + on_delete=django.db.models.deletion.CASCADE, + related_name="apps", + to=settings.AUTH_USER_MODEL, + ), + ), ], + options={ + "constraints": [ + models.UniqueConstraint(fields=("user", "code"), name="unique_user_code"), + models.UniqueConstraint( + fields=("user", "appstore_id"), name="unique_user_appstore_id" + ), + models.UniqueConstraint( + fields=("user", "playstore_id"), name="unique_user_playstore_id" + ), + ], + }, ), ] diff --git a/app/migrations/0002_app_code.py b/app/migrations/0002_app_code.py deleted file mode 100644 index f9cc194..0000000 --- a/app/migrations/0002_app_code.py +++ /dev/null @@ -1,19 +0,0 @@ -# Generated by Django 5.1.7 on 2025-04-05 14:17 - -from django.db import migrations, models - - -class Migration(migrations.Migration): - - dependencies = [ - ("app", "0001_initial"), - ] - - operations = [ - migrations.AddField( - model_name="app", - name="code", - field=models.CharField(default="default_code", max_length=100, unique=True), - preserve_default=False, - ), - ] diff --git a/app/migrations/0003_alter_app_developer.py b/app/migrations/0003_alter_app_developer.py deleted file mode 100644 index 099d203..0000000 --- a/app/migrations/0003_alter_app_developer.py +++ /dev/null @@ -1,18 +0,0 @@ -# Generated by Django 5.1.7 on 2025-04-27 12:31 - -from django.db import migrations, models - - -class Migration(migrations.Migration): - - dependencies = [ - ("app", "0002_app_code"), - ] - - operations = [ - migrations.AlterField( - model_name="app", - name="developer", - field=models.CharField(max_length=100, null=True), - ), - ] diff --git a/app/migrations/0004_app_icon_url_app_size_in_bytes.py b/app/migrations/0004_app_icon_url_app_size_in_bytes.py deleted file mode 100644 index 8dae77a..0000000 --- a/app/migrations/0004_app_icon_url_app_size_in_bytes.py +++ /dev/null @@ -1,23 +0,0 @@ -# Generated by Django 5.1.7 on 2025-05-15 16:39 - -from django.db import migrations, models - - -class Migration(migrations.Migration): - - dependencies = [ - ("app", "0003_alter_app_developer"), - ] - - operations = [ - migrations.AddField( - model_name="app", - name="icon_url", - field=models.URLField(null=True), - ), - migrations.AddField( - model_name="app", - name="size_in_bytes", - field=models.BigIntegerField(null=True), - ), - ] diff --git a/app/migrations/0005_app_user_alter_app_appstore_id_alter_app_code_and_more.py b/app/migrations/0005_app_user_alter_app_appstore_id_alter_app_code_and_more.py deleted file mode 100644 index b912d1a..0000000 --- a/app/migrations/0005_app_user_alter_app_appstore_id_alter_app_code_and_more.py +++ /dev/null @@ -1,58 +0,0 @@ -# Generated by Django 5.1.7 on 2025-05-23 10:40 - -import django.db.models.deletion -from django.conf import settings -from django.db import migrations, models - - -class Migration(migrations.Migration): - - dependencies = [ - ("app", "0004_app_icon_url_app_size_in_bytes"), - migrations.swappable_dependency(settings.AUTH_USER_MODEL), - ] - - operations = [ - migrations.AddField( - model_name="app", - name="user", - field=models.ForeignKey( - default=2, - on_delete=django.db.models.deletion.CASCADE, - related_name="apps", - to=settings.AUTH_USER_MODEL, - ), - preserve_default=False, - ), - migrations.AlterField( - model_name="app", - name="appstore_id", - field=models.CharField(max_length=100, null=True), - ), - migrations.AlterField( - model_name="app", - name="code", - field=models.CharField(max_length=100), - ), - migrations.AlterField( - model_name="app", - name="playstore_id", - field=models.CharField(max_length=100, null=True), - ), - migrations.AddConstraint( - model_name="app", - constraint=models.UniqueConstraint(fields=("user", "code"), name="unique_user_code"), - ), - migrations.AddConstraint( - model_name="app", - constraint=models.UniqueConstraint( - fields=("user", "appstore_id"), name="unique_user_appstore_id" - ), - ), - migrations.AddConstraint( - model_name="app", - constraint=models.UniqueConstraint( - fields=("user", "playstore_id"), name="unique_user_playstore_id" - ), - ), - ] diff --git a/app/migrations/0006_alter_app_description.py b/app/migrations/0006_alter_app_description.py deleted file mode 100644 index a675255..0000000 --- a/app/migrations/0006_alter_app_description.py +++ /dev/null @@ -1,18 +0,0 @@ -# Generated by Django 5.1.7 on 2025-05-26 17:25 - -from django.db import migrations, models - - -class Migration(migrations.Migration): - - dependencies = [ - ("app", "0005_app_user_alter_app_appstore_id_alter_app_code_and_more"), - ] - - operations = [ - migrations.AlterField( - model_name="app", - name="description", - field=models.TextField(blank=True, null=True), - ), - ] diff --git a/app/repositories.py b/app/repositories.py index b7cf878..1846b8c 100644 --- a/app/repositories.py +++ b/app/repositories.py @@ -8,6 +8,9 @@ def get_all(self, user): def get_by_id(self, app_id): return App.objects.get(id=app_id) + def get_by_id_and_user(self, app_id, user): + return App.objects.get(id=app_id, user=user) + def create(self, data, user): return App.objects.create(user=user, **data) diff --git a/app/services.py b/app/services.py index bf44e5a..6b745f4 100644 --- a/app/services.py +++ b/app/services.py @@ -9,10 +9,11 @@ class AppService: - def __init__(self, itunes_adapter=None, google_play_adapter=None): + def __init__(self, itunes_adapter=None, google_play_adapter=None, polling_service=None): self.repo = AppRepository() self.metric_service = MetricService() self.metric_value_service = MetricValueService() + self._polling_service = polling_service self._itunes_adapter = itunes_adapter self._google_play_adapter = google_play_adapter @@ -32,6 +33,14 @@ def google_play_adapter(self): self._google_play_adapter = GooglePlayScraperAdapter() return self._google_play_adapter + @property + def polling_service(self): + if self._polling_service is None: + from polling.services import PollingService + + self._polling_service = PollingService() + return self._polling_service + def list_apps(self, user): return self.repo.get_all(user) @@ -41,10 +50,19 @@ def get_app(self, app_id): except ObjectDoesNotExist: raise NotFound(f"The app with ID '{app_id}' is not registered.") + def get_app_by_user(self, app_id, user): + try: + return self.repo.get_by_id_and_user(app_id, user) + except ObjectDoesNotExist: + raise NotFound(f"The app with ID '{app_id}' is not registered.") + def create_app(self, validated_data, user): self._fetch_appstore_data(validated_data) self._fetch_playstore_data(validated_data) - return self.repo.create(validated_data, user) + app = self.repo.create(validated_data, user) + self.polling_service.create_polling_schedule(app.id, 24, "metrics") + self.polling_service.create_polling_schedule(app.id, 24, "reviews") + return app def _fetch_appstore_data(self, validated_data): if not validated_data.get("appstore_id"): @@ -66,7 +84,7 @@ def _fetch_appstore_data(self, validated_data): try: validated_data["size_in_bytes"] = int(file_size_str) except ValueError: - print(f"Error al convertir fileSizeBytes: {file_size_str}") + print(f"Error al convertir fileSizeBytes: {str(file_size_str)}") released_str = result.get("releaseDate") if released_str: try: @@ -107,14 +125,32 @@ def delete_app(self, instance): def get_metric_dashboard(self, app_id: str, metric_id: str) -> dict: metric = self.metric_service.get_metric(metric_id) - values = self.metric_value_service.get_metric_values_by_app_and_metric(app_id, metric_id) + if not metric.is_derived: + metric_values = self.metric_value_service.get_metric_values_by_app_and_metric( + app_id, metric_id + ) + values = [ + { + "retrieved_at": metric_value.retrieved_at.date(), + "value": metric_value.value, + "source": metric_value.source.name if metric_value.source else "Internal", + } + for metric_value in metric_values + ] + else: + values = self.metric_value_service.get_derived_metric_values_by_app_and_metric( + app_id, metric.code + ) + for value in values: + if "source" not in value: + value["source"] = "Internal" sources_data = {} for value in values: - source_name = value.source.name if value.source else "Internal" + source_name = value["source"] sources_data.setdefault(source_name, {"source": source_name, "history": []}) sources_data[source_name]["history"].append( - {"date": value.retrieved_at.date(), "value": value.value} + {"date": value["retrieved_at"], "value": value["value"]} ) return { diff --git a/app/tests.py b/app/tests.py index f359d1c..84f76aa 100644 --- a/app/tests.py +++ b/app/tests.py @@ -1,11 +1,14 @@ import pytest +from django.contrib.auth.models import User from app.models import App @pytest.mark.django_db def test_create_source(): + user = User.objects.create(username="testuser", email="testuser@gmail.com", password="testuser") a = App.objects.create( + user=user, code="test_app", name="Test App", description="Descripction of the test app", diff --git a/app/views.py b/app/views.py index f080428..c953f8f 100644 --- a/app/views.py +++ b/app/views.py @@ -1,7 +1,6 @@ from drf_spectacular.utils import OpenApiParameter, extend_schema from rest_framework import status, viewsets from rest_framework.decorators import action -from rest_framework.exceptions import PermissionDenied from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response @@ -13,45 +12,51 @@ class AppViewSet(viewsets.ViewSet): permission_classes = [IsAuthenticated] service = AppService() - def _get_user_app(self, pk): - app = self.service.get_app(pk) - if app.user != self.request.user: - raise PermissionDenied("No tens accés a aquesta aplicació.") - return app - @extend_schema( + summary="List all apps", + description=( + "Returns a list of all mobile apps associated with the authenticated user.\n\n" + "Each app includes metadata such as store identifiers, availability, ratings, and more." + ), responses=AppSerializer(many=True), tags=["Apps"], ) def list(self, request): - print("👤 Usuari:", request.user) - print("🔐 Auth:", request.auth) + print("👤 Usuari:", str(request.user)) + print("🔐 Auth:", str(request.auth)) apps = self.service.list_apps(user=request.user) serializer = AppSerializer(apps, many=True) return Response(serializer.data) @extend_schema( + summary="Retrieve a specific app", + description=( + "Returns detailed information about a specific app identified by its ID.\n\n" + "Only apps owned by the authenticated user can be accessed." + ), parameters=[OpenApiParameter(name="id", required=True, type=int, location="path")], responses=AppSerializer, tags=["Apps"], ) def retrieve(self, request, pk=None): - app = self._get_user_app(pk) + app = self.service.get_app_by_user(pk, user=request.user) serializer = AppSerializer(app) return Response(serializer.data) @extend_schema( - request=AppCreateSerializer, - responses=AppSerializer, + summary="Create a new app", description=( - "Creates a new app.\n\n" - "The fields 'available_on_ios', 'available_on_android', 'pegi_rating', " - "'release_date', and 'min_ios_version' will be automatically populated " - "by fetching data from the App Store and/or Google Play APIs based " - "on the provided identifiers.\n\n" - "You do not need to manually provide these fields when creating an app." + "Creates a new app associated with the authenticated user.\n\n" + "Fields like `available_on_ios`, `available_on_android`, `pegi_rating`, " + "`release_date`, and `min_ios_version` are automatically populated " + "based on data fetched from the App Store and/or Google Play APIs using " + "the provided store identifiers.\n\n" + "**Note:** Upon creation, two polling services are automatically scheduled " + "for this app — one for metrics and one for reviews — both executed every 24 hours." ), + request=AppCreateSerializer, + responses=AppSerializer, tags=["Apps"], ) def create(self, request): @@ -61,28 +66,49 @@ def create(self, request): return Response(AppSerializer(app).data, status=status.HTTP_201_CREATED) @extend_schema( + summary="Update an existing app", + description=( + "Updates the information of an existing app. Only apps owned by the " + "authenticated user can be updated.\n\n" + "All fields must be provided; partial updates are not supported." + ), request=AppSerializer, responses=AppSerializer, tags=["Apps"], ) def update(self, request, pk=None): - app = self._get_user_app(pk) + app = self.service.get_app_by_user(pk, user=request.user) serializer = AppSerializer(app, data=request.data) serializer.is_valid(raise_exception=True) updated_app = self.service.update_app(app, serializer.validated_data) return Response(AppSerializer(updated_app).data) @extend_schema( + summary="Delete an app", + description=( + "Deletes a specific app owned by the authenticated user. " + "This action is irreversible." + ), parameters=[OpenApiParameter(name="id", required=True, type=int, location="path")], responses={204: None}, tags=["Apps"], ) def destroy(self, request, pk=None): - app = self._get_user_app(pk) + app = self.service.get_app_by_user(pk, user=request.user) self.service.delete_app(app) return Response(status=status.HTTP_204_NO_CONTENT) @extend_schema( + summary="Get app metric dashboard", + description=( + "Retrieves the historical dashboard for a specific metric of a given app.\n\n" + "If the metric is a direct (raw) metric, this endpoint returns its historical values " + "grouped by data source (e.g. App Store, Google Play, or internal sources).\n" + "If the metric is a derived one, it is computed dynamically " + "and presented similarly.\n\n" + "Each source includes a list of historical records, each with a date and value. " + "Derived metrics are labeled as coming from the 'Internal' source." + ), parameters=[ OpenApiParameter(name="id", required=True, type=int, location="path"), OpenApiParameter(name="metric_id", required=True, type=int, location="path"), @@ -92,7 +118,7 @@ def destroy(self, request, pk=None): ) @action(detail=True, methods=["get"], url_path="metrics/(?P[^/.]+)") def get_app_metric(self, request, pk=None, metric_id=None): - app = self._get_user_app(pk) + app = self.service.get_app_by_user(pk, user=request.user) response_data = self.service.get_metric_dashboard(app_id=app.id, metric_id=metric_id) serializer = MetricResponseSerializer(response_data) return Response(serializer.data) diff --git a/metric/constants/__init__.py b/metric/constants/__init__.py index 232a183..6c3c89a 100644 --- a/metric/constants/__init__.py +++ b/metric/constants/__init__.py @@ -1,7 +1,13 @@ -class MetricCodes: +from enum import Enum + + +class MetricCode(str, Enum): AVERAGE_RATING = "average_rating" TOTAL_REVIEWS = "total_reviews" DAILY_NEWS_BLOG_MENTIONS = "daily_news_blog_mentions" DAILY_SOCIAL_NETWORK_MENTIONS = "daily_social_network_mentions" TOTAL_DOWNLOADS = "total_downloads" LAST_UPDATE_DATE = "last_update_date" + BUG_RATE = "bug_rate" + POSITIVE_RATE = "positive_rate" + UPDATE_CHANGED = "update_changed" diff --git a/metric/management/commands/create_dummy_metric_values.py b/metric/management/commands/create_dummy_metric_values.py index e330afe..bd3aad0 100644 --- a/metric/management/commands/create_dummy_metric_values.py +++ b/metric/management/commands/create_dummy_metric_values.py @@ -25,7 +25,7 @@ def handle(self, *args, **kwargs): for app in apps: for metric in metrics: - if metric.code == "average_rating": + if metric.code == "total_reviews": for source in sources: if ( source.code in ["itunes", "google_play"] @@ -36,10 +36,11 @@ def handle(self, *args, **kwargs): value = ( round(random.uniform(4.4, 4.5), 5) if metric.value_type == "float" - else str(random.randint(1, 1000)) + else str(random.randint(3050000, 3080000)) ) MetricValue.objects.create( + user=app.user, app=app, metric=metric, source=source, diff --git a/metric/migrations/0001_initial.py b/metric/migrations/0001_initial.py index 146a52d..bafd664 100644 --- a/metric/migrations/0001_initial.py +++ b/metric/migrations/0001_initial.py @@ -1,6 +1,7 @@ -# Generated by Django 5.1.7 on 2025-03-31 18:48 +# Generated by Django 5.1.7 on 2025-05-30 17:42 import django.db.models.deletion +import django.utils.timezone from django.db import migrations, models @@ -10,7 +11,6 @@ class Migration(migrations.Migration): dependencies = [ ("app", "0001_initial"), - ("source", "0001_initial"), ] operations = [ @@ -20,12 +20,10 @@ class Migration(migrations.Migration): ( "id", models.BigAutoField( - auto_created=True, - primary_key=True, - serialize=False, - verbose_name="ID", + auto_created=True, primary_key=True, serialize=False, verbose_name="ID" ), ), + ("code", models.CharField(max_length=100, unique=True)), ("name", models.CharField(max_length=100)), ("description", models.TextField()), ( @@ -49,14 +47,11 @@ class Migration(migrations.Migration): ( "id", models.BigAutoField( - auto_created=True, - primary_key=True, - serialize=False, - verbose_name="ID", + auto_created=True, primary_key=True, serialize=False, verbose_name="ID" ), ), ("value", models.CharField(max_length=255)), - ("retrieved_at", models.DateTimeField(auto_now_add=True)), + ("retrieved_at", models.DateTimeField(default=django.utils.timezone.now)), ( "app", models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to="app.app"), @@ -67,12 +62,6 @@ class Migration(migrations.Migration): on_delete=django.db.models.deletion.CASCADE, to="metric.metric" ), ), - ( - "source", - models.ForeignKey( - on_delete=django.db.models.deletion.CASCADE, to="source.source" - ), - ), ], ), ] diff --git a/metric/migrations/0004_alter_metricvalue_source.py b/metric/migrations/0002_initial.py similarity index 72% rename from metric/migrations/0004_alter_metricvalue_source.py rename to metric/migrations/0002_initial.py index f6e8e26..6a4bfe3 100644 --- a/metric/migrations/0004_alter_metricvalue_source.py +++ b/metric/migrations/0002_initial.py @@ -1,4 +1,4 @@ -# Generated by Django 5.1.7 on 2025-05-04 17:49 +# Generated by Django 5.1.7 on 2025-05-30 17:42 import django.db.models.deletion from django.db import migrations, models @@ -6,13 +6,15 @@ class Migration(migrations.Migration): + initial = True + dependencies = [ - ("metric", "0003_alter_metric_code"), - ("source", "0003_source_metrics"), + ("metric", "0001_initial"), + ("source", "0001_initial"), ] operations = [ - migrations.AlterField( + migrations.AddField( model_name="metricvalue", name="source", field=models.ForeignKey( diff --git a/metric/migrations/0002_metric_code.py b/metric/migrations/0002_metric_code.py deleted file mode 100644 index a77834c..0000000 --- a/metric/migrations/0002_metric_code.py +++ /dev/null @@ -1,19 +0,0 @@ -# Generated by Django 5.1.7 on 2025-04-04 18:34 - -from django.db import migrations, models - - -class Migration(migrations.Migration): - - dependencies = [ - ("metric", "0001_initial"), - ] - - operations = [ - migrations.AddField( - model_name="metric", - name="code", - field=models.CharField(default="default_code", max_length=100), - preserve_default=False, - ), - ] diff --git a/metric/migrations/0003_alter_metric_code.py b/metric/migrations/0003_alter_metric_code.py deleted file mode 100644 index 154fa17..0000000 --- a/metric/migrations/0003_alter_metric_code.py +++ /dev/null @@ -1,18 +0,0 @@ -# Generated by Django 5.1.7 on 2025-04-05 14:17 - -from django.db import migrations, models - - -class Migration(migrations.Migration): - - dependencies = [ - ("metric", "0002_metric_code"), - ] - - operations = [ - migrations.AlterField( - model_name="metric", - name="code", - field=models.CharField(max_length=100, unique=True), - ), - ] diff --git a/metric/migrations/0005_add_is_internal.py b/metric/migrations/0003_metric_is_derived.py similarity index 69% rename from metric/migrations/0005_add_is_internal.py rename to metric/migrations/0003_metric_is_derived.py index ee3b007..4856c66 100644 --- a/metric/migrations/0005_add_is_internal.py +++ b/metric/migrations/0003_metric_is_derived.py @@ -1,16 +1,18 @@ +# Generated by Django 5.1.7 on 2025-06-01 14:56 + from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ - ("metric", "0004_alter_metricvalue_source"), + ("metric", "0002_initial"), ] operations = [ migrations.AddField( model_name="metric", - name="is_internal", + name="is_derived", field=models.BooleanField(default=False), ), ] diff --git a/metric/migrations/0007_alter_metricvalue_retrieved_at.py b/metric/migrations/0007_alter_metricvalue_retrieved_at.py deleted file mode 100644 index 3cbd97f..0000000 --- a/metric/migrations/0007_alter_metricvalue_retrieved_at.py +++ /dev/null @@ -1,19 +0,0 @@ -# Generated by Django 5.1.7 on 2025-05-20 14:28 - -import django.utils.timezone -from django.db import migrations, models - - -class Migration(migrations.Migration): - - dependencies = [ - ("metric", "0006_remove_metric_is_internal"), - ] - - operations = [ - migrations.AlterField( - model_name="metricvalue", - name="retrieved_at", - field=models.DateTimeField(default=django.utils.timezone.now), - ), - ] diff --git a/metric/migrations/0008_metric_user_metricvalue_user_alter_metric_code_and_more.py b/metric/migrations/0008_metric_user_metricvalue_user_alter_metric_code_and_more.py deleted file mode 100644 index 84f584f..0000000 --- a/metric/migrations/0008_metric_user_metricvalue_user_alter_metric_code_and_more.py +++ /dev/null @@ -1,49 +0,0 @@ -# Generated by Django 5.1.7 on 2025-05-23 10:40 - -import django.db.models.deletion -from django.conf import settings -from django.db import migrations, models - - -class Migration(migrations.Migration): - - dependencies = [ - ("metric", "0007_alter_metricvalue_retrieved_at"), - migrations.swappable_dependency(settings.AUTH_USER_MODEL), - ] - - operations = [ - migrations.AddField( - model_name="metric", - name="user", - field=models.ForeignKey( - default=2, - on_delete=django.db.models.deletion.CASCADE, - related_name="metrics", - to=settings.AUTH_USER_MODEL, - ), - preserve_default=False, - ), - migrations.AddField( - model_name="metricvalue", - name="user", - field=models.ForeignKey( - default=2, - on_delete=django.db.models.deletion.CASCADE, - related_name="metrics_values", - to=settings.AUTH_USER_MODEL, - ), - preserve_default=False, - ), - migrations.AlterField( - model_name="metric", - name="code", - field=models.CharField(max_length=100), - ), - migrations.AddConstraint( - model_name="metric", - constraint=models.UniqueConstraint( - fields=("user", "code"), name="unique_user_metric_code" - ), - ), - ] diff --git a/metric/models.py b/metric/models.py index 0cb04bf..e4adfe0 100644 --- a/metric/models.py +++ b/metric/models.py @@ -1,4 +1,3 @@ -from django.contrib.auth.models import User from django.db import models from django.utils import timezone @@ -7,23 +6,17 @@ class Metric(models.Model): - user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="metrics") - code = models.CharField(max_length=100) + code = models.CharField(max_length=100, unique=True) name = models.CharField(max_length=100) description = models.TextField() value_type = models.CharField(max_length=10, choices=MetricValueType.choices) - - class Meta: - constraints = [ - models.UniqueConstraint(fields=["user", "code"], name="unique_user_metric_code") - ] + is_derived = models.BooleanField(default=False) def __str__(self): return self.name class MetricValue(models.Model): - user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="metrics_values") app = models.ForeignKey(App, on_delete=models.CASCADE) metric = models.ForeignKey(Metric, on_delete=models.CASCADE) source = models.ForeignKey("source.Source", on_delete=models.CASCADE, null=True, blank=True) diff --git a/metric/repositories.py b/metric/repositories.py index 988d692..8c275e8 100644 --- a/metric/repositories.py +++ b/metric/repositories.py @@ -30,6 +30,9 @@ def remove_sources(self, instance, sources_ids): instance.save() return instance + def get_by_code(self, code): + return Metric.objects.get(code=code) + class MetricValueRepository: def get_all(self): diff --git a/metric/serializers.py b/metric/serializers.py index 25a7269..b156a0e 100644 --- a/metric/serializers.py +++ b/metric/serializers.py @@ -9,7 +9,7 @@ class MetricSerializer(serializers.ModelSerializer): class Meta: model = Metric - fields = ["id", "code", "name", "description", "value_type", "sources"] + fields = ["id", "code", "name", "description", "value_type", "is_derived", "sources"] read_only_fields = ["sources"] diff --git a/metric/services.py b/metric/services.py index ea54f89..ca147b5 100644 --- a/metric/services.py +++ b/metric/services.py @@ -1,6 +1,9 @@ from django.core.exceptions import ObjectDoesNotExist from rest_framework.exceptions import NotFound +from review.services import ReviewService + +from .constants import MetricCode from .repositories import MetricRepository, MetricValueRepository @@ -32,10 +35,18 @@ def add_sources(self, instance, sources_ids): def remove_sources(self, instance, sources_ids): return self.repo.remove_sources(instance, sources_ids) + def get_metric_by_code(self, code): + try: + return self.repo.get_by_code(code) + except ObjectDoesNotExist: + raise NotFound(f"The metric with code '{code}' is not registered.") + class MetricValueService: def __init__(self): self.repo = MetricValueRepository() + self.review_service = ReviewService() + self.metric_service = MetricService() def list_metric_values(self): return self.repo.get_all() @@ -57,3 +68,87 @@ def delete_metric_value(self, instance): def get_metric_values_by_app_and_metric(self, app_id, metric_id): return self.repo.get_by_app_and_metric(app_id, metric_id) + + def get_derived_metric_values_by_app_and_metric(self, app_id, metric_code): + reviews = self.review_service.list_reviews(filters={"app_id": app_id}) + derived_values = [] + if metric_code == MetricCode.BUG_RATE: + # Comptem tots els reviews per data + total_reviews_by_date = {} + for review in reviews: + date = review.date.strftime("%Y-%m-%d") + if date not in total_reviews_by_date: + total_reviews_by_date[date] = 0 + total_reviews_by_date[date] += 1 + + # Comptem només els reviews amb bugs per data + bug_reviews_by_date = {} + for review in reviews: + if review.type == "Bug": + date = review.date.strftime("%Y-%m-%d") + if date not in bug_reviews_by_date: + bug_reviews_by_date[date] = 0 + bug_reviews_by_date[date] += 1 + + # Calculem la freqüència com a proporció + derived_values = [] + for date in total_reviews_by_date: + total = total_reviews_by_date[date] + bugs = bug_reviews_by_date.get(date, 0) + frequency = bugs / total if total > 0 else 0 + derived_values.append( + { + "retrieved_at": date, + "value": frequency, + } + ) + + elif metric_code == MetricCode.POSITIVE_RATE: + polarity_counts_by_date = {} + + for review in reviews: + date = review.date.strftime("%Y-%m-%d") + if date not in polarity_counts_by_date: + polarity_counts_by_date[date] = {"negative": 0, "positive": 0} + if review.polarity in ["positive", "negative"]: + polarity_counts_by_date[date][review.polarity] += 1 + + derived_values = [] + for date, counts in polarity_counts_by_date.items(): + total = counts["positive"] + counts["negative"] + frequency = counts["positive"] / total if total > 0 else 0 + derived_values.append( + { + "retrieved_at": date, + "value": frequency, + } + ) + + elif metric_code == MetricCode.UPDATE_CHANGED: + metric = self.metric_service.get_metric_by_code(MetricCode.LAST_UPDATE_DATE) + last_update_values = self.repo.get_by_app_and_metric(app_id, metric.id) + grouped_by_source = {} + for value in last_update_values: + source_name = value.source.name if value.source else "Internal" + grouped_by_source.setdefault(source_name, []).append(value) + + # Tractem cada font independentment + for source, values in grouped_by_source.items(): + previous_value = None + for value in values: + current_update_date = ( + value.value.date() if hasattr(value.value, "date") else value.value + ) + change_detected = 0 + if previous_value is not None and current_update_date != previous_value: + change_detected = 1 + derived_values.append( + { + "retrieved_at": value.retrieved_at.strftime("%Y-%m-%d"), + "value": change_detected, + "source": source, + } + ) + previous_value = current_update_date + + return derived_values diff --git a/metric/tests.py b/metric/tests.py index 7fe1653..7df47ce 100644 --- a/metric/tests.py +++ b/metric/tests.py @@ -1,4 +1,5 @@ import pytest +from django.contrib.auth.models import User from app.models import App from metric.constants.value_types import MetricValueType @@ -21,7 +22,9 @@ def test_create_metric(): @pytest.mark.django_db def test_create_metric_value(): + user = User.objects.create(username="testuser", email="testuser@gmail.com", password="testuser") a = App.objects.create( + user=user, code="test_app", name="Test App", description="Descripction of the test app", diff --git a/metric/views.py b/metric/views.py index 7816fce..4335c5a 100644 --- a/metric/views.py +++ b/metric/views.py @@ -13,6 +13,12 @@ class MetricViewSet(viewsets.ViewSet): service = MetricService() @extend_schema( + summary="List all metrics", + description=( + "Returns all available metrics in the system.\n\n" + "If the optional query parameter `only_numeric=true` is passed, " + "filters the result to include only metrics whose `value_type` is 'integer' or 'float'." + ), parameters=[ OpenApiParameter( name="only_numeric", @@ -35,6 +41,8 @@ def list(self, request): return Response(serializer.data) @extend_schema( + summary="Retrieve a specific metric", + description="Returns detailed information for a specific metric identified by its ID.", parameters=[OpenApiParameter(name="id", required=True, type=int, location="path")], responses=MetricSerializer, tags=["Metrics"], @@ -45,12 +53,23 @@ def retrieve(self, request, pk=None): return Response(serializer.data) @extend_schema( - request=MetricSerializer, - responses=MetricSerializer, + summary="Create a new metric", description=( - "Creates a new data metric.\n\n" - "The 'source' field is read-only and cannot be set directly on creation." + "Creates a new metric.\n\n" + "The `source` field is read-only and cannot be assigned manually. " + "To link data sources, use the `add_sources` endpoint after creation.\n\n" + "**Important:** Creating a metric does not make it functional by itself.\n\n" + "- If the metric is **not derived** (`is_derived=False`)," + " the system will only collect data " + "if at least one data source adapter implements support for this metric. " + "This requires the adapter class to handle the metric code explicitly.\n\n" + "- If the metric **is derived** (`is_derived=True`), " + "its calculation logic must be implemented manually " + "in the `get_derived_metric_values_by_app_and_metric` method in `MetricValueService`. " + "Otherwise, no values will be returned for this metric." ), + request=MetricSerializer, + responses=MetricSerializer, tags=["Metrics"], ) def create(self, request): @@ -60,6 +79,8 @@ def create(self, request): return Response(MetricSerializer(metric).data, status=status.HTTP_201_CREATED) @extend_schema( + summary="Update an existing metric", + description="Updates the details of an existing metric. All fields are required.", request=MetricSerializer, responses=MetricSerializer, tags=["Metrics"], @@ -72,6 +93,8 @@ def update(self, request, pk=None): return Response(MetricSerializer(updated_metric).data) @extend_schema( + summary="Delete a metric", + description="Deletes an existing metric identified by its ID. This action is irreversible.", parameters=[OpenApiParameter(name="id", required=True, type=int, location="path")], responses={204: None}, tags=["Metrics"], @@ -82,10 +105,15 @@ def destroy(self, request, pk=None): return Response(status=status.HTTP_204_NO_CONTENT) @extend_schema( + summary="Add sources to a metric", + description=( + "Adds a list of source IDs to the metric without removing existing sources.\n\n" + "The input must be a JSON object with a `sources` field containing a list of IDs.\n\n" + "**Example**:\n" + '`{ "sources": [1, 2, 3] }`' + ), request=LinkSourceSerializer, responses=MetricSerializer, - description="Adds a list of source IDs to an existing " - "metric without removing existing ones.", tags=["Metrics"], ) @action(detail=True, methods=["post"], url_path="sources") @@ -103,9 +131,15 @@ def add_sources(self, request, pk=None): return Response(MetricSerializer(metric).data, status=status.HTTP_200_OK) @extend_schema( + summary="Remove sources from a metric", + description=( + "Removes a list of source IDs from the metric.\n\n" + "The input must be a JSON object with a `sources` field containing a list of IDs.\n\n" + "**Example**:\n" + '`{ "sources": [2, 3] }`' + ), request=LinkSourceSerializer, responses=MetricSerializer, - description="Removes a list of source IDs from an existing metric.", tags=["Metrics"], methods=["DELETE"], ) @@ -128,6 +162,13 @@ class MetricValueViewSet(viewsets.ViewSet): service = MetricValueService() @extend_schema( + summary="List all metric values", + description=( + "Returns a complete list of all stored metric values.\n\n" + "Each metric value includes its associated app, metric code," + " source, value, and the timestamp " + "when it was retrieved." + ), responses=MetricValueSerializer(many=True), tags=["Metrics"], ) @@ -137,6 +178,12 @@ def list(self, request): return Response(serializer.data) @extend_schema( + summary="Retrieve a specific metric value", + description=( + "Retrieves a single metric value by its ID.\n\n" + "This includes detailed information about the value, such as the metric code, " + "source, retrieval date, and associated app." + ), parameters=[OpenApiParameter(name="id", required=True, type=int, location="path")], responses=MetricValueSerializer, tags=["Metrics"], diff --git a/polling/migrations/0001_initial.py b/polling/migrations/0001_initial.py index 9c5b805..e77bb6c 100644 --- a/polling/migrations/0001_initial.py +++ b/polling/migrations/0001_initial.py @@ -1,4 +1,4 @@ -# Generated by Django 5.1.7 on 2025-05-04 19:10 +# Generated by Django 5.1.7 on 2025-05-30 17:42 import django.db.models.deletion from django.db import migrations, models @@ -9,7 +9,8 @@ class Migration(migrations.Migration): initial = True dependencies = [ - ("app", "0003_alter_app_developer"), + ("app", "0001_initial"), + ("django_celery_beat", "0019_alter_periodictasks_options"), ] operations = [ @@ -23,8 +24,8 @@ class Migration(migrations.Migration): ), ), ("interval_hours", models.IntegerField()), - ("start_at", models.DateTimeField(auto_now_add=True)), - ("next_run", models.DateTimeField()), + ("start_at", models.DateTimeField(blank=True, null=True)), + ("next_run", models.DateTimeField(blank=True, null=True)), ( "poll_type", models.CharField( @@ -37,7 +38,7 @@ class Migration(migrations.Migration): max_length=10, ), ), - ("is_active", models.BooleanField(default=True)), + ("is_active", models.BooleanField(default=False)), ( "app", models.ForeignKey( @@ -46,9 +47,23 @@ class Migration(migrations.Migration): to="app.app", ), ), + ( + "periodic_task", + models.OneToOneField( + blank=True, + null=True, + on_delete=django.db.models.deletion.CASCADE, + related_name="polling_schedule", + to="django_celery_beat.periodictask", + ), + ), ], options={ - "unique_together": {("app", "poll_type")}, + "constraints": [ + models.UniqueConstraint( + fields=("app_id", "poll_type"), name="unique_polling_schedule_per_app" + ) + ], }, ), ] diff --git a/polling/migrations/0002_pollingschedule_periodic_task.py b/polling/migrations/0002_pollingschedule_periodic_task.py deleted file mode 100644 index 4389c85..0000000 --- a/polling/migrations/0002_pollingschedule_periodic_task.py +++ /dev/null @@ -1,26 +0,0 @@ -# Generated by Django 5.1.7 on 2025-05-05 10:20 - -import django.db.models.deletion -from django.db import migrations, models - - -class Migration(migrations.Migration): - - dependencies = [ - ("django_celery_beat", "0019_alter_periodictasks_options"), - ("polling", "0001_initial"), - ] - - operations = [ - migrations.AddField( - model_name="pollingschedule", - name="periodic_task", - field=models.OneToOneField( - blank=True, - null=True, - on_delete=django.db.models.deletion.CASCADE, - related_name="polling_schedule", - to="django_celery_beat.periodictask", - ), - ), - ] diff --git a/metric/migrations/0006_remove_metric_is_internal.py b/polling/migrations/0002_remove_pollingschedule_start_at.py similarity index 52% rename from metric/migrations/0006_remove_metric_is_internal.py rename to polling/migrations/0002_remove_pollingschedule_start_at.py index 095927a..07aec44 100644 --- a/metric/migrations/0006_remove_metric_is_internal.py +++ b/polling/migrations/0002_remove_pollingschedule_start_at.py @@ -1,4 +1,4 @@ -# Generated by Django 5.1.7 on 2025-05-15 16:44 +# Generated by Django 5.1.7 on 2025-06-04 19:38 from django.db import migrations @@ -6,12 +6,12 @@ class Migration(migrations.Migration): dependencies = [ - ("metric", "0005_add_is_internal"), + ("polling", "0001_initial"), ] operations = [ migrations.RemoveField( - model_name="metric", - name="is_internal", + model_name="pollingschedule", + name="start_at", ), ] diff --git a/polling/migrations/0003_alter_pollingschedule_unique_together_and_more.py b/polling/migrations/0003_alter_pollingschedule_unique_together_and_more.py deleted file mode 100644 index 8e00a7b..0000000 --- a/polling/migrations/0003_alter_pollingschedule_unique_together_and_more.py +++ /dev/null @@ -1,39 +0,0 @@ -# Generated by Django 5.1.7 on 2025-05-23 10:40 - -import django.db.models.deletion -from django.conf import settings -from django.db import migrations, models - - -class Migration(migrations.Migration): - - dependencies = [ - ("app", "0005_app_user_alter_app_appstore_id_alter_app_code_and_more"), - ("django_celery_beat", "0019_alter_periodictasks_options"), - ("polling", "0002_pollingschedule_periodic_task"), - migrations.swappable_dependency(settings.AUTH_USER_MODEL), - ] - - operations = [ - migrations.AlterUniqueTogether( - name="pollingschedule", - unique_together=set(), - ), - migrations.AddField( - model_name="pollingschedule", - name="user", - field=models.ForeignKey( - default=2, - on_delete=django.db.models.deletion.CASCADE, - related_name="polling_schedules", - to=settings.AUTH_USER_MODEL, - ), - preserve_default=False, - ), - migrations.AddConstraint( - model_name="pollingschedule", - constraint=models.UniqueConstraint( - fields=("user", "app", "poll_type"), name="unique_polling_schedule_per_user" - ), - ), - ] diff --git a/polling/models.py b/polling/models.py index a1dfa61..92a9619 100644 --- a/polling/models.py +++ b/polling/models.py @@ -1,4 +1,3 @@ -from django.contrib.auth.models import User from django.db import models from django_celery_beat.models import PeriodicTask @@ -6,11 +5,9 @@ class PollingSchedule(models.Model): - user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="polling_schedules") app = models.ForeignKey(App, on_delete=models.CASCADE, related_name="polling_schedules") interval_hours = models.IntegerField() - start_at = models.DateTimeField(auto_now_add=True) - next_run = models.DateTimeField() + next_run = models.DateTimeField(null=True, blank=True) POLL_TYPE_CHOICES = [ ("metrics", "Metrics only"), @@ -19,7 +16,7 @@ class PollingSchedule(models.Model): ] poll_type = models.CharField(max_length=10, choices=POLL_TYPE_CHOICES, default="metrics") - is_active = models.BooleanField(default=True) + is_active = models.BooleanField(default=False) periodic_task = models.OneToOneField( PeriodicTask, @@ -32,7 +29,7 @@ class PollingSchedule(models.Model): class Meta: constraints = [ models.UniqueConstraint( - fields=["user", "app", "poll_type"], name="unique_polling_schedule_per_user" + fields=["app_id", "poll_type"], name="unique_polling_schedule_per_app" ) ] diff --git a/polling/repositories.py b/polling/repositories.py index e4578a9..37bd042 100644 --- a/polling/repositories.py +++ b/polling/repositories.py @@ -6,48 +6,31 @@ class PollingRepository: - @staticmethod - def get_all_active(poll_type): - queryset = PollingSchedule.objects.filter(is_active=True) - if poll_type: - queryset = queryset.filter(poll_type=poll_type) + def get_all(self, poll_type): + queryset = PollingSchedule.objects.filter(poll_type=poll_type) return queryset - @staticmethod - def get_by_app_id(app_id, poll_type): - try: - return PollingSchedule.objects.get(app_id=app_id, poll_type=poll_type) - except PollingSchedule.DoesNotExist: - return None + def get_by_app_id(self, app_id, poll_type): + return PollingSchedule.objects.get(app_id=app_id, poll_type=poll_type) - @staticmethod - def create(app_id, interval_hours, poll_type, periodic_task): - from datetime import timedelta - - from django.utils.timezone import now - - start = now() + def create(self, app_id, interval_hours, poll_type, periodic_task): schedule = PollingSchedule.objects.create( app_id=app_id, interval_hours=interval_hours, - start_at=start, - next_run=start + timedelta(hours=interval_hours), poll_type=poll_type, - is_active=True, + is_active=False, periodic_task=periodic_task, ) return schedule - @staticmethod - def get_or_create_interval_schedule(interval_hours): + def get_or_create_interval_schedule(self, interval_hours): schedule, _ = IntervalSchedule.objects.get_or_create( every=interval_hours, period=IntervalSchedule.HOURS, ) return schedule - @staticmethod - def create_periodic_task(schedule, app_id, poll_type, task): + def create_periodic_task(self, schedule, app_id, poll_type, task): name = f"{poll_type}-polling-{app_id}" if PeriodicTask.objects.filter(name=name).exists(): raise ValueError("PeriodicTask already exists with this name") @@ -56,16 +39,49 @@ def create_periodic_task(schedule, app_id, poll_type, task): interval=schedule, name=name, task=task, + enabled=False, args=json.dumps([app_id, poll_type]), ) return task - @staticmethod - def delete(instance): + def delete(self, instance): if instance.periodic_task: instance.periodic_task.delete() instance.delete() - @staticmethod - def exists(app_id, poll_type): + def exists(self, app_id, poll_type): return PollingSchedule.objects.filter(app_id=app_id, poll_type=poll_type).exists() + + def update_periodic_task(self, periodic_task, interval_schedule): + periodic_task.interval = interval_schedule + periodic_task.save() + return periodic_task + + def update(self, instance, data): + for attr, value in data.items(): + setattr(instance, attr, value) + instance.save() + return instance + + def activate(self, instance): + from datetime import timedelta + + from django.utils.timezone import now + + start = now() + instance.next_run = start + timedelta(hours=instance.interval_hours) + instance.is_active = True + instance.save() + if instance.periodic_task: + instance.periodic_task.enabled = True + instance.periodic_task.save() + return instance + + def deactivate(self, instance): + instance.next_run = None + instance.is_active = False + instance.save() + if instance.periodic_task: + instance.periodic_task.enabled = False + instance.periodic_task.save() + return instance diff --git a/polling/serializers.py b/polling/serializers.py index 5f53b8a..9379148 100644 --- a/polling/serializers.py +++ b/polling/serializers.py @@ -19,14 +19,12 @@ class Meta: fields = [ "app", "interval_hours", - "start_at", "next_run", "is_active", "periodic_task", ] read_only_fields = [ "app", - "start_at", "next_run", "is_active", "periodic_task", diff --git a/polling/services.py b/polling/services.py index 6ec84e7..d9edb12 100644 --- a/polling/services.py +++ b/polling/services.py @@ -1,7 +1,12 @@ from datetime import datetime import requests +from django.core.exceptions import ObjectDoesNotExist +from kombu.exceptions import OperationalError as KombuOperationalError +from redis.exceptions import ConnectionError as RedisConnectionError +from rest_framework.exceptions import APIException, NotFound +from app.services import AppService from metric.services import MetricService, MetricValueService from polling.tasks import run_polling_task from review.services import ReviewService @@ -17,6 +22,7 @@ def __init__(self): self.metric_service = MetricService() self.metric_value_service = MetricValueService() self.review_service = ReviewService() + self.app_service = AppService() def _analyze_reviews(self, reviews, service_url: str, label: str = "RE-Miner"): """ @@ -33,7 +39,6 @@ def _analyze_reviews(self, reviews, service_url: str, label: str = "RE-Miner"): for idx, r in enumerate(reviews) ] } - print(f"📤 Sending {len(payload['reviews'])} reviews to {service_url}") response = requests.post(service_url, json=payload, timeout=10) print("📥 Received response from", label) response.raise_for_status() @@ -57,11 +62,16 @@ def _analyze_review_type(self, reviews): label="RE-Miner (Type)", ) - def list_active_polling_schedules(self, poll_type=None): - return self.repo.get_all_active(poll_type) + def list_polling_schedules(self, poll_type=None): + return self.repo.get_all(poll_type) def get_polling_schedule(self, app_id, poll_type=None): - return self.repo.get_by_app_id(app_id, poll_type) + try: + return self.repo.get_by_app_id(app_id, poll_type) + except ObjectDoesNotExist: + raise NotFound( + f"The '{poll_type}' polling process with App ID '{app_id}' is not registered." + ) def create_polling_schedule(self, app_id, interval_hours=None, poll_type=None): if self.repo.exists(app_id, poll_type): @@ -73,8 +83,6 @@ def create_polling_schedule(self, app_id, interval_hours=None, poll_type=None): ) schedule = self.repo.create(app_id, interval_hours, poll_type, periodic_task) - run_polling_task.delay(app_id, poll_type) - return schedule def delete_schedule(self, instance): @@ -87,11 +95,13 @@ def poll_reviews(self, app_id, date_from=None, date_to=None): self.log("🔌 Loading adapters...") adapters = self.source_service.load_sources() self.log("✅ Adapters loaded.") + + app = self.app_service.get_app(app_id) results = [] for adapter in adapters: self.log(f"🔄 Fetching reviews from {adapter.name}...") - reviews = adapter.fetch_reviews(app_id=app_id, date_from=date_from, date_to=date_to) + reviews = adapter.fetch_reviews(app=app, date_from=date_from, date_to=date_to) self.log(f"✅ {len(reviews)} reviews fetched.") if not reviews: @@ -110,7 +120,7 @@ def poll_reviews(self, app_id, date_from=None, date_to=None): r["reviewId"] = r.get("reviewId", str(idx)) # ❌ Comprobación: eliminar las reviews ya guardadas para esa app y adapter - existing_ids = self.review_service.get_existing_review_ids(app_id, adapter.id) + existing_ids = self.review_service.get_existing_review_ids(app.id, adapter.id) new_reviews = [r for r in reviews if r["reviewId"] not in existing_ids] self.log( f"🧹 {len(reviews) - len(new_reviews)} reviews ya existen.{len(new_reviews)} nuevas." @@ -151,7 +161,7 @@ def poll_reviews(self, app_id, date_from=None, date_to=None): review["type"] = type_by_id.get(review["reviewId"], "") self.log("💾 Saving reviews...") - saved_count = self.review_service.save_reviews(app_id, adapter.id, new_reviews) + saved_count = self.review_service.save_reviews(app.id, adapter.id, new_reviews) self.log(f"✅ {saved_count} reviews saved.") results.append( @@ -168,19 +178,16 @@ def poll_reviews(self, app_id, date_from=None, date_to=None): def poll_metrics(self, app_id): adapters = self.source_service.load_sources() print("[🔁] Iniciant recollida de mètriques...") - - metrics = list(self.metric_service.get_all()) - + metrics = list(self.metric_service.list_metrics()) + app = self.app_service.get_app(app_id) # 🔀 Separa mètriques metrics = [m for m in metrics] # ⚡ Caches metric_cache = {m.code: m for m in metrics} - # source_cache = {a.code: Source.objects.get(code=a.code) for a in adapters} # 🔁 EXTERNAL: Per adapters for adapter in adapters: - print("adapter actual: ", adapter.code + " " + adapter.id) source_code = adapter.code available_metrics = [ m.code for m in metrics if source_code in m.sources.values_list("code", flat=True) @@ -189,14 +196,13 @@ def poll_metrics(self, app_id): continue try: - result = adapter.fetch(app_id, available_metrics) + result = adapter.fetch(app, available_metrics) except Exception as e: print(f"❌ Error en adapter `{source_code}`: {e}") continue for metric_code, value in result.items(): if value in [None, ""]: - print(f" ⚠️ {metric_code} no ha retornat valor.") continue metric = metric_cache[metric_code] @@ -204,13 +210,42 @@ def poll_metrics(self, app_id): self.metric_value_service.create_metric_value( { - "app_id": app_id, + "app": app, "metric": metric, "source_id": adapter.id, "value": value, "retrieved_at": datetime.now(), } ) - print(f" ✅ Guardat {metric_code}: {value}") print("\n✅ Procés de recollida completat.") + + def update_polling_schedule(self, polling_schedule, validated_data): + if validated_data.get("interval_hours") is not None: + interval_schedule = self.repo.get_or_create_interval_schedule( + validated_data["interval_hours"] + ) + self.repo.update_periodic_task(polling_schedule.periodic_task, interval_schedule) + + return self.repo.update(polling_schedule, validated_data) + + def activate_polling_schedule(self, polling_schedule): + if polling_schedule.is_active: + raise ValueError("Polling schedule is already active") + + self.repo.activate(polling_schedule) + try: + run_polling_task.delay(polling_schedule.app.id, polling_schedule.poll_type) + except (RedisConnectionError, KombuOperationalError): + raise APIException( + "No se pudo conectar con el servicio de tareas (Redis). Inténtalo más tarde." + ) + + return polling_schedule + + def deactivate_polling_schedule(self, polling_schedule): + if not polling_schedule.is_active: + raise ValueError("Polling schedule is already deactivated") + + self.repo.deactivate(polling_schedule) + return polling_schedule diff --git a/polling/urls.py b/polling/urls.py index 9254a23..ff0b27c 100644 --- a/polling/urls.py +++ b/polling/urls.py @@ -8,6 +8,8 @@ {"get": "retrieve", "post": "create", "delete": "destroy"} ) polling_review_view = PollingScheduleViewSet.as_view({"post": "poll_reviews"}) +activate_polling_view = PollingScheduleViewSet.as_view({"post": "activate"}) +deactivate_polling_view = PollingScheduleViewSet.as_view({"post": "deactivate"}) urlpatterns = [ path("metrics/", polling_list_view, {"poll_type": "metrics"}), @@ -15,4 +17,8 @@ path("metrics/apps//", polling_detail_view, {"poll_type": "metrics"}), path("reviews/apps//", polling_detail_view, {"poll_type": "reviews"}), path("manual/reviews/apps//", polling_review_view), + path("metrics/apps//activate/", activate_polling_view, {"poll_type": "metrics"}), + path("reviews/apps//activate/", activate_polling_view, {"poll_type": "reviews"}), + path("metrics/apps//deactivate/", deactivate_polling_view, {"poll_type": "metrics"}), + path("reviews/apps//deactivate/", deactivate_polling_view, {"poll_type": "reviews"}), ] diff --git a/polling/views.py b/polling/views.py index 5e05245..e7ecfba 100644 --- a/polling/views.py +++ b/polling/views.py @@ -7,21 +7,27 @@ from polling.services import PollingService +# This ViewSet is mounted under two different routes: /polling/metrics/ and /polling/reviews/ +# The `poll_type` argument determines which type of polling is handled in each case. class PollingScheduleViewSet(viewsets.ViewSet): service = PollingService() @extend_schema( - description="List all active metric polling schedules.", + summary="List polling schedules", + description=("Returns all existing polling schedules of the specified type."), responses={200: PollingScheduleSerializer(many=True)}, tags=["Polling"], ) def list(self, request, poll_type=None): - schedules = self.service.list_active_polling_schedules(poll_type) + schedules = self.service.list_polling_schedules(poll_type) serializer = PollingScheduleSerializer(schedules, many=True) return Response(serializer.data, status=status.HTTP_200_OK) @extend_schema( - description="Check if there is an active polling schedule for an app.", + summary="Retrieve polling schedule for an app", + description=( + "Checks whether a polling schedule of the specified type exists for a given app." + ), parameters=[ OpenApiParameter( name="id", required=True, type=OpenApiTypes.INT, location=OpenApiParameter.PATH @@ -36,6 +42,8 @@ def retrieve(self, request, id=None, poll_type=None): return Response(serializer.data, status=status.HTTP_200_OK) @extend_schema( + summary="Create a polling schedule", + description=("Creates a new polling schedule of the specified type for the given app."), request=PollingScheduleSerializer, responses={201: PollingScheduleSerializer}, tags=["Polling"], @@ -44,14 +52,10 @@ def create(self, request, id=None, poll_type=None): serializer = PollingScheduleSerializer(data=request.data) serializer.is_valid(raise_exception=True) interval = serializer.validated_data["interval_hours"] - - try: - schedule = self.service.create_polling_schedule(id, interval, poll_type) - except ValueError as e: - return Response({"detail": str(e)}, status=409) - + schedule = self.service.create_polling_schedule(id, interval, poll_type) return Response(PollingScheduleSerializer(schedule).data, status=201) + # ELIMINAR @extend_schema( parameters=[OpenApiParameter(name="id", required=True, type=int, location="path")], responses={204: None}, @@ -63,6 +67,14 @@ def destroy(self, request, id=None, poll_type=None): return Response(status=status.HTTP_204_NO_CONTENT) @extend_schema( + summary="Poll reviews for an app", + description=( + "Fetches reviews from Google Play for the given " + "app within the specified date range.\n\n" + "If `date_from` and `date_to` are not provided, " + "reviews from **yesterday** will be fetched.\n\n" + "Fetched reviews are stored in the database and returned along with summary stats." + ), request=None, parameters=[ OpenApiParameter( @@ -88,18 +100,78 @@ def destroy(self, request, id=None, poll_type=None): 404: OpenApiResponse(description="App with the given ID was not found."), }, tags=["Polling"], - description=( - "Polls Google Play for reviews of a given app between two dates.\n\n" - "Saves new ones in the database and returns" - "the fetched reviews with stats.\n\n" - "If no `date_from` and `date_to` are provided," - " reviews from **yesterday** will be fetched." - ), ) def poll_reviews(self, request, id=None): date_from = request.query_params.get("date_from") date_to = request.query_params.get("date_to") - print("hola") result = self.service.poll_reviews(app_id=id, date_from=date_from, date_to=date_to) return Response(result) + + @extend_schema( + summary="Activate polling for an app", + description=( + "Enables automatic periodic execution of the polling service " + "for a given app and polling type.\n\n" + "**Note:** Activation will also trigger an immediate execution of the polling task." + ), + parameters=[ + OpenApiParameter( + name="interval_hours", + description="Optional custom interval in hours for the polling schedule.", + required=False, + type=int, + location=OpenApiParameter.QUERY, + ), + ], + responses={200: PollingScheduleSerializer}, + tags=["Polling"], + ) + def activate(self, request, id=None, poll_type=None): + try: + interval_hours = request.query_params.get("interval_hours") + polling_schedule = self.service.get_polling_schedule(id, poll_type) + + if ( + interval_hours is not None + and str(interval_hours).strip() != "" + and int(interval_hours) != polling_schedule.interval_hours + ): + try: + interval_hours = int(interval_hours) + if interval_hours <= 0: + raise ValueError("interval_hours must be greater than 0.") + polling_schedule = self.service.update_polling_schedule( + polling_schedule, {"interval_hours": interval_hours} + ) + except ValueError: + return Response( + {"detail": "Invalid value for interval_hours. Must be a positive integer."}, + status=status.HTTP_400_BAD_REQUEST, + ) + + updated_polling_schedule = self.service.activate_polling_schedule(polling_schedule) + return Response( + PollingScheduleSerializer(updated_polling_schedule).data, status=status.HTTP_200_OK + ) + except ValueError as e: + return Response({"detail": str(e)}, status=status.HTTP_409_CONFLICT) + + @extend_schema( + summary="Deactivate polling for an app", + description=( + "Disables automatic execution of the polling service " + "for a given app and polling type." + ), + responses={200: PollingScheduleSerializer}, + tags=["Polling"], + ) + def deactivate(self, request, id=None, poll_type=None): + try: + polling_schedule = self.service.get_polling_schedule(id, poll_type) + updated_polling_schedule = self.service.deactivate_polling_schedule(polling_schedule) + return Response( + PollingScheduleSerializer(updated_polling_schedule).data, status=status.HTTP_200_OK + ) + except ValueError as e: + return Response({"detail": str(e)}, status=status.HTTP_409_CONFLICT) diff --git a/review/migrations/0001_initial.py b/review/migrations/0001_initial.py index fcecd63..b5d0bfb 100644 --- a/review/migrations/0001_initial.py +++ b/review/migrations/0001_initial.py @@ -1,4 +1,4 @@ -# Generated by Django 5.1.7 on 2025-03-31 18:36 +# Generated by Django 5.1.7 on 2025-05-30 17:42 import django.core.validators import django.db.models.deletion @@ -11,6 +11,7 @@ class Migration(migrations.Migration): dependencies = [ ("app", "0001_initial"), + ("source", "0001_initial"), ] operations = [ @@ -20,12 +21,10 @@ class Migration(migrations.Migration): ( "id", models.BigAutoField( - auto_created=True, - primary_key=True, - serialize=False, - verbose_name="ID", + auto_created=True, primary_key=True, serialize=False, verbose_name="ID" ), ), + ("review_id", models.CharField(blank=True, max_length=255, null=True)), ("author", models.CharField(blank=True, max_length=100, null=True)), ("content", models.TextField()), ( @@ -55,36 +54,24 @@ class Migration(migrations.Migration): models.CharField( choices=[ ("bug", "Bug"), + ("rating", "Rating"), ("feature", "Feature"), - ("general", "General"), + ("user_experience", "User Experience"), ], max_length=20, ), ), - ( - "topic", - models.CharField( - blank=True, - choices=[ - ("aesthetics", "Aesthetics"), - ("compatibility", "Compatibility"), - ("cost", "Cost"), - ("effectiveness", "Effectiveness"), - ("efficiency", "Efficiency"), - ("enjoyability", "Enjoyability"), - ("learnability", "Learnability"), - ("security", "Security"), - ("usability", "Usability"), - ], - max_length=30, - null=True, - ), - ), ("date", models.DateTimeField()), ( "app", models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to="app.app"), ), + ( + "source", + models.ForeignKey( + on_delete=django.db.models.deletion.CASCADE, to="source.source" + ), + ), ], ), ] diff --git a/review/migrations/0002_review_app_version_review_replied_at_and_more.py b/review/migrations/0002_review_app_version_review_replied_at_and_more.py deleted file mode 100644 index ab7e30a..0000000 --- a/review/migrations/0002_review_app_version_review_replied_at_and_more.py +++ /dev/null @@ -1,33 +0,0 @@ -# Generated by Django 5.1.7 on 2025-04-29 09:43 - -from django.db import migrations, models - - -class Migration(migrations.Migration): - - dependencies = [ - ("review", "0001_initial"), - ] - - operations = [ - migrations.AddField( - model_name="review", - name="app_version", - field=models.CharField(blank=True, max_length=100, null=True), - ), - migrations.AddField( - model_name="review", - name="replied_at", - field=models.DateTimeField(blank=True, null=True), - ), - migrations.AddField( - model_name="review", - name="reply_content", - field=models.TextField(blank=True, null=True), - ), - migrations.AddField( - model_name="review", - name="review_id", - field=models.CharField(blank=True, max_length=255, null=True), - ), - ] diff --git a/review/migrations/0003_alter_review_topic_alter_review_type.py b/review/migrations/0003_alter_review_topic_alter_review_type.py deleted file mode 100644 index 6d2cd93..0000000 --- a/review/migrations/0003_alter_review_topic_alter_review_type.py +++ /dev/null @@ -1,50 +0,0 @@ -# Generated by Django 5.1.7 on 2025-05-15 16:39 - -from django.db import migrations, models - - -class Migration(migrations.Migration): - - dependencies = [ - ("review", "0002_review_app_version_review_replied_at_and_more"), - ] - - operations = [ - migrations.AlterField( - model_name="review", - name="topic", - field=models.CharField( - blank=True, - choices=[ - ("aesthetics", "Aesthetics"), - ("compatibility", "Compatibility"), - ("cost", "Cost"), - ("effectiveness", "Effectiveness"), - ("efficiency", "Efficiency"), - ("enjoyability", "Enjoyability"), - ("general", "General"), - ("learnability", "Learnability"), - ("n/a", "N/A"), - ("reliability", "Reliability"), - ("safety", "Safety"), - ("security", "Security"), - ("usability", "Usability"), - ], - max_length=30, - null=True, - ), - ), - migrations.AlterField( - model_name="review", - name="type", - field=models.CharField( - choices=[ - ("bug", "Bug"), - ("rating", "Rating"), - ("feature", "Feature"), - ("user_experience", "User Experience"), - ], - max_length=20, - ), - ), - ] diff --git a/review/migrations/0004_remove_review_topic.py b/review/migrations/0004_remove_review_topic.py deleted file mode 100644 index 5cfa4fe..0000000 --- a/review/migrations/0004_remove_review_topic.py +++ /dev/null @@ -1,17 +0,0 @@ -# Generated by Django 5.1.7 on 2025-05-15 16:41 - -from django.db import migrations - - -class Migration(migrations.Migration): - - dependencies = [ - ("review", "0003_alter_review_topic_alter_review_type"), - ] - - operations = [ - migrations.RemoveField( - model_name="review", - name="topic", - ), - ] diff --git a/review/migrations/0005_review_source.py b/review/migrations/0005_review_source.py deleted file mode 100644 index f394f0b..0000000 --- a/review/migrations/0005_review_source.py +++ /dev/null @@ -1,23 +0,0 @@ -# Generated by Django 5.1.7 on 2025-05-15 16:51 - -import django.db.models.deletion -from django.db import migrations, models - - -class Migration(migrations.Migration): - - dependencies = [ - ("review", "0004_remove_review_topic"), - ("source", "0003_source_metrics"), - ] - - operations = [ - migrations.AddField( - model_name="review", - name="source", - field=models.ForeignKey( - default=4, on_delete=django.db.models.deletion.CASCADE, to="source.source" - ), - preserve_default=False, - ), - ] diff --git a/review/migrations/0006_remove_review_app_version_remove_review_replied_at_and_more.py b/review/migrations/0006_remove_review_app_version_remove_review_replied_at_and_more.py deleted file mode 100644 index 8023618..0000000 --- a/review/migrations/0006_remove_review_app_version_remove_review_replied_at_and_more.py +++ /dev/null @@ -1,25 +0,0 @@ -# Generated by Django 5.1.7 on 2025-05-15 17:27 - -from django.db import migrations - - -class Migration(migrations.Migration): - - dependencies = [ - ("review", "0005_review_source"), - ] - - operations = [ - migrations.RemoveField( - model_name="review", - name="app_version", - ), - migrations.RemoveField( - model_name="review", - name="replied_at", - ), - migrations.RemoveField( - model_name="review", - name="reply_content", - ), - ] diff --git a/review/migrations/0007_review_user.py b/review/migrations/0007_review_user.py deleted file mode 100644 index 4d3051b..0000000 --- a/review/migrations/0007_review_user.py +++ /dev/null @@ -1,27 +0,0 @@ -# Generated by Django 5.1.7 on 2025-05-23 10:40 - -import django.db.models.deletion -from django.conf import settings -from django.db import migrations, models - - -class Migration(migrations.Migration): - - dependencies = [ - ("review", "0006_remove_review_app_version_remove_review_replied_at_and_more"), - migrations.swappable_dependency(settings.AUTH_USER_MODEL), - ] - - operations = [ - migrations.AddField( - model_name="review", - name="user", - field=models.ForeignKey( - default=2, - on_delete=django.db.models.deletion.CASCADE, - related_name="reviews", - to=settings.AUTH_USER_MODEL, - ), - preserve_default=False, - ), - ] diff --git a/review/models.py b/review/models.py index 77176ca..908383d 100644 --- a/review/models.py +++ b/review/models.py @@ -1,4 +1,3 @@ -from django.contrib.auth.models import User from django.core.validators import MaxValueValidator, MinValueValidator from django.db import models @@ -20,7 +19,6 @@ class ReviewType(models.TextChoices): class Review(models.Model): - user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="reviews") review_id = models.CharField(max_length=255, null=True, blank=True) app = models.ForeignKey(App, on_delete=models.CASCADE) source = models.ForeignKey(Source, on_delete=models.CASCADE) diff --git a/review/repositories.py b/review/repositories.py index bdf48e4..11638da 100644 --- a/review/repositories.py +++ b/review/repositories.py @@ -7,7 +7,7 @@ class ReviewRepository: def get_all(self, filters=None): - queryset = Review.objects.all() + queryset = Review.objects.all().order_by("date") if filters: app_id = filters.get("app") @@ -61,7 +61,6 @@ def save_reviews(self, app_id, source_id, reviews_list): created_reviews.append(review) Review.objects.bulk_create(created_reviews) - print(f"Saved {len(created_reviews)} new reviews.") return len(created_reviews) diff --git a/review/tests.py b/review/tests.py index 022ffa5..bb02138 100644 --- a/review/tests.py +++ b/review/tests.py @@ -1,4 +1,5 @@ import pytest +from django.contrib.auth.models import User from django.utils import timezone from app.models import App @@ -8,7 +9,11 @@ @pytest.mark.django_db def test_create_review_no_values(): now = timezone.now() + user = User.objects.create( + username="testuser", email="testuser@gmail.com", password="testpassword" + ) a = App.objects.create( + user=user, code="test_app", name="Test App", description="Descripction of the test app", @@ -31,7 +36,11 @@ def test_create_review_no_values(): @pytest.mark.django_db def test_create_review_with_values(): now = timezone.now() + user = User.objects.create( + username="testuser", email="testuser@gmail.com", password="testpassword" + ) a = App.objects.create( + user=user, code="test_app", name="Test App", description="Descripction of the test app", diff --git a/review/views.py b/review/views.py index c71af10..93b1294 100644 --- a/review/views.py +++ b/review/views.py @@ -11,6 +11,8 @@ class ReviewViewSet(viewsets.ViewSet): service = ReviewService() @extend_schema( + summary="List reviews", + description="Returns all user reviews, optionally filtered by app or date range.", parameters=[ OpenApiParameter(name="app", type=int, description="Filter by app ID"), OpenApiParameter(name="date_from", type=str, description="Start date (YYYY-MM-DD)"), @@ -30,6 +32,8 @@ def list(self, request): return Response(serializer.data) @extend_schema( + summary="Retrieve a specific review", + description="Fetches the details of a review identified by its ID.", parameters=[OpenApiParameter(name="id", required=True, type=int, location="path")], responses=ReviewSerializer, tags=["Reviews"], @@ -39,10 +43,12 @@ def retrieve(self, request, pk=None): serializer = ReviewSerializer(source) return Response(serializer.data) + # ELIMINAR @extend_schema( + summary="Delete all reviews", + description="Deletes all reviews stored in the system. This action is irreversible.", methods=["delete"], - description="Esborra totes les reviews de la base de dades.", - responses={204: OpenApiResponse(description="Totes les reviews han estat esborrades")}, + responses={204: OpenApiResponse(description="All reviews have been deleted")}, tags=["Reviews"], ) @action(detail=False, methods=["delete"], url_path="delete-all") diff --git a/source/adapters/base.py b/source/adapters/base.py index e7458ba..02cfa2b 100644 --- a/source/adapters/base.py +++ b/source/adapters/base.py @@ -21,7 +21,7 @@ def __init__(self): def supports_metric(self, metric: str) -> bool: ... @abstractmethod - def fetch(self, app_id: int, metrics: list[str]) -> dict[str, str]: ... + def fetch(self, app, metrics: list[str]) -> dict[str, str]: ... - def fetch_reviews(self, app_id: int, date_from=None, date_to=None): + def fetch_reviews(self, app, date_from=None, date_to=None): return [] diff --git a/source/adapters/google_play_scraper.py b/source/adapters/google_play_scraper.py index bf20674..165cdf1 100644 --- a/source/adapters/google_play_scraper.py +++ b/source/adapters/google_play_scraper.py @@ -5,8 +5,7 @@ from google_play_scraper import reviews from rest_framework.exceptions import ParseError, ValidationError -from app.services import AppService -from metric.constants import MetricCodes +from metric.constants import MetricCode from source.adapters.base import SourceAdapter from source.services import SourceService @@ -35,18 +34,17 @@ def lookup_app(package_name: str) -> dict | None: print(f"[GooglePlayScraperAdapter] Error fetching app data: {e}") return None - def fetch(self, app_id: int, metrics: list[str]): - app = AppService().get_app(app_id=app_id) + def fetch(self, app, metrics: list[str]): if not app: return {} result = self.lookup_app(app.playstore_id) metric_map = { - MetricCodes.AVERAGE_RATING: str(result.get("score") or ""), - MetricCodes.TOTAL_REVIEWS: str(result.get("reviews") or ""), - MetricCodes.TOTAL_DOWNLOADS: str(result.get("realInstalls") or ""), - MetricCodes.LAST_UPDATE_DATE: str(result.get("lastUpdatedOn") or ""), + MetricCode.AVERAGE_RATING: str(result.get("score") or ""), + MetricCode.TOTAL_REVIEWS: str(result.get("reviews") or ""), + MetricCode.TOTAL_DOWNLOADS: str(result.get("realInstalls") or ""), + MetricCode.LAST_UPDATE_DATE: str(result.get("lastUpdatedOn") or ""), } return { @@ -56,8 +54,7 @@ def fetch(self, app_id: int, metrics: list[str]): def _log(self, msg): print(f"[{datetime.now(timezone.utc).isoformat()}] {msg}") - def fetch_reviews(self, app_id: int, date_from=None, date_to=None): - app = AppService().get_app(app_id=app_id) + def fetch_reviews(self, app, date_from=None, date_to=None): if not app: self._log("❌ App no trobada.") return [] diff --git a/source/adapters/itunes.py b/source/adapters/itunes.py index 0fec35e..1844833 100644 --- a/source/adapters/itunes.py +++ b/source/adapters/itunes.py @@ -1,7 +1,6 @@ import requests -from app.services import AppService -from metric.constants import MetricCodes +from metric.constants import MetricCode from source.adapters.base import SourceAdapter from source.services import SourceService @@ -30,8 +29,7 @@ def lookup_app(self, appstore_id: str): results = data.get("results", []) return results[0] if results else None - def fetch(self, app_id: int, metrics: list[str]): - app = AppService().get_app(app_id=app_id) + def fetch(self, app, metrics: list[str]): if not app: return {} @@ -40,8 +38,8 @@ def fetch(self, app_id: int, metrics: list[str]): return {} metric_map = { - MetricCodes.AVERAGE_RATING: str(result.get("averageUserRating") or ""), - MetricCodes.TOTAL_REVIEWS: str(result.get("userRatingCount") or ""), + MetricCode.AVERAGE_RATING: str(result.get("averageUserRating") or ""), + MetricCode.TOTAL_REVIEWS: str(result.get("userRatingCount") or ""), } return { diff --git a/source/adapters/news.py b/source/adapters/news.py index b9a8bbd..5eb5436 100644 --- a/source/adapters/news.py +++ b/source/adapters/news.py @@ -3,8 +3,7 @@ import requests -from app.services import AppService -from metric.constants import MetricCodes +from metric.constants import MetricCode from source.adapters.base import SourceAdapter from source.services import SourceService @@ -25,8 +24,7 @@ def __init__(self, api_key=None): def supports_metric(self, metric: str) -> bool: return metric in self.supported_metrics - def fetch(self, app_id: int, metrics: list[str]): - app = AppService().get_app(app_id=app_id) + def fetch(self, app, metrics: list[str]): if not app: return {} @@ -51,7 +49,7 @@ def fetch(self, app_id: int, metrics: list[str]): data = response.json() metric_map = { - MetricCodes.DAILY_NEWS_BLOG_MENTIONS: str(data.get("totalResults", 0)), + MetricCode.DAILY_NEWS_BLOG_MENTIONS: str(data.get("totalResults", 0)), } return { diff --git a/source/adapters/reddit.py b/source/adapters/reddit.py index 7e564e4..258f242 100644 --- a/source/adapters/reddit.py +++ b/source/adapters/reddit.py @@ -3,8 +3,7 @@ import praw from rest_framework.exceptions import APIException -from app.services import AppService -from metric.constants import MetricCodes +from metric.constants import MetricCode from source.adapters.base import SourceAdapter from source.services import SourceService @@ -36,8 +35,7 @@ def __init__(self): def supports_metric(self, metric: str) -> bool: return metric in self.supported_metrics - def fetch(self, app_id: int, metrics: list[str]): - app = AppService().get_app(app_id=app_id) + def fetch(self, app, metrics: list[str]): if not app: return {} @@ -65,7 +63,7 @@ def fetch(self, app_id: int, metrics: list[str]): return {} metric_map = { - MetricCodes.DAILY_SOCIAL_NETWORK_MENTIONS: str(total), + MetricCode.DAILY_SOCIAL_NETWORK_MENTIONS: str(total), } return { diff --git a/source/migrations/0001_initial.py b/source/migrations/0001_initial.py index d850624..c4b3f07 100644 --- a/source/migrations/0001_initial.py +++ b/source/migrations/0001_initial.py @@ -1,4 +1,4 @@ -# Generated by Django 5.1.7 on 2025-03-31 18:19 +# Generated by Django 5.1.7 on 2025-05-30 17:42 from django.db import migrations, models @@ -7,7 +7,9 @@ class Migration(migrations.Migration): initial = True - dependencies = [] + dependencies = [ + ("metric", "0001_initial"), + ] operations = [ migrations.CreateModel( @@ -16,12 +18,10 @@ class Migration(migrations.Migration): ( "id", models.BigAutoField( - auto_created=True, - primary_key=True, - serialize=False, - verbose_name="ID", + auto_created=True, primary_key=True, serialize=False, verbose_name="ID" ), ), + ("code", models.CharField(max_length=100, unique=True)), ("name", models.CharField(max_length=100)), ( "type", @@ -35,6 +35,7 @@ class Migration(migrations.Migration): ), ), ("url", models.URLField(blank=True, null=True)), + ("metrics", models.ManyToManyField(related_name="sources", to="metric.metric")), ], ), ] diff --git a/source/migrations/0002_source_code.py b/source/migrations/0002_source_code.py deleted file mode 100644 index e4cdfe1..0000000 --- a/source/migrations/0002_source_code.py +++ /dev/null @@ -1,19 +0,0 @@ -# Generated by Django 5.1.7 on 2025-04-05 14:17 - -from django.db import migrations, models - - -class Migration(migrations.Migration): - - dependencies = [ - ("source", "0001_initial"), - ] - - operations = [ - migrations.AddField( - model_name="source", - name="code", - field=models.CharField(default="default_code", max_length=100, unique=True), - preserve_default=False, - ), - ] diff --git a/source/migrations/0003_source_metrics.py b/source/migrations/0003_source_metrics.py deleted file mode 100644 index f261457..0000000 --- a/source/migrations/0003_source_metrics.py +++ /dev/null @@ -1,19 +0,0 @@ -# Generated by Django 5.1.7 on 2025-04-16 16:49 - -from django.db import migrations, models - - -class Migration(migrations.Migration): - - dependencies = [ - ("metric", "0003_alter_metric_code"), - ("source", "0002_source_code"), - ] - - operations = [ - migrations.AddField( - model_name="source", - name="metrics", - field=models.ManyToManyField(related_name="sources", to="metric.metric"), - ), - ] diff --git a/source/migrations/0004_source_user_alter_source_code_and_more.py b/source/migrations/0004_source_user_alter_source_code_and_more.py deleted file mode 100644 index 70c2125..0000000 --- a/source/migrations/0004_source_user_alter_source_code_and_more.py +++ /dev/null @@ -1,39 +0,0 @@ -# Generated by Django 5.1.7 on 2025-05-23 10:40 - -import django.db.models.deletion -from django.conf import settings -from django.db import migrations, models - - -class Migration(migrations.Migration): - - dependencies = [ - ("metric", "0008_metric_user_metricvalue_user_alter_metric_code_and_more"), - ("source", "0003_source_metrics"), - migrations.swappable_dependency(settings.AUTH_USER_MODEL), - ] - - operations = [ - migrations.AddField( - model_name="source", - name="user", - field=models.ForeignKey( - default=2, - on_delete=django.db.models.deletion.CASCADE, - related_name="sources", - to=settings.AUTH_USER_MODEL, - ), - preserve_default=False, - ), - migrations.AlterField( - model_name="source", - name="code", - field=models.CharField(max_length=100), - ), - migrations.AddConstraint( - model_name="source", - constraint=models.UniqueConstraint( - fields=("user", "code"), name="unique_user_source_code" - ), - ), - ] diff --git a/source/models.py b/source/models.py index 4b5094d..1c3a1b5 100644 --- a/source/models.py +++ b/source/models.py @@ -1,21 +1,14 @@ -from django.contrib.auth.models import User from django.db import models from source.constants.source_type import SourceType class Source(models.Model): - user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="sources") - code = models.CharField(max_length=100) + code = models.CharField(max_length=100, unique=True) name = models.CharField(max_length=100) type = models.CharField(max_length=20, choices=SourceType.choices) url = models.URLField(null=True, blank=True) metrics = models.ManyToManyField("metric.Metric", related_name="sources") - class Meta: - constraints = [ - models.UniqueConstraint(fields=["user", "code"], name="unique_user_source_code") - ] - def __str__(self): return self.name diff --git a/source/views.py b/source/views.py index 5672410..9e338a5 100644 --- a/source/views.py +++ b/source/views.py @@ -13,6 +13,8 @@ class SourceViewSet(viewsets.ViewSet): service = SourceService() @extend_schema( + summary="List all sources", + description="Returns all available data sources registered in the system.", responses=SourceSerializer(many=True), tags=["Sources"], ) @@ -22,6 +24,8 @@ def list(self, request): return Response(serializer.data) @extend_schema( + summary="Retrieve a specific source", + description="Returns details of a single data source identified by its ID.", parameters=[OpenApiParameter(name="id", required=True, type=int, location="path")], responses=SourceSerializer, tags=["Sources"], @@ -32,12 +36,22 @@ def retrieve(self, request, pk=None): return Response(serializer.data) @extend_schema( - request=SourceSerializer, - responses=SourceSerializer, + summary="Create a new source", description=( "Creates a new data source.\n\n" - "The 'metrics' field is read-only and cannot be set directly on creation." + "The `metrics` field is read-only and cannot be set directly during creation. " + "Use the `add_metrics` endpoint to associate metrics after creation.\n\n" + "**Important:** Defining a source in the database is not" + " enough for it to become operational. " + "To make a source functional, a corresponding adapter must be" + " implemented by subclassing `BaseSourceAdapter` " + "in `source.adapters.base`, and the adapter must be registered by" + " importing it in the `load_sources()` " + "function in `SourceService`. If no adapter is implemented and registered," + " the system will not collect data from this source." ), + request=SourceSerializer, + responses=SourceSerializer, tags=["Sources"], ) def create(self, request): @@ -47,6 +61,9 @@ def create(self, request): return Response(SourceSerializer(source).data, status=status.HTTP_201_CREATED) @extend_schema( + summary="Update an existing source", + description="Updates the details of a data source. " + "The `metrics` field is not editable here.", request=SourceSerializer, responses=SourceSerializer, tags=["Sources"], @@ -59,6 +76,8 @@ def update(self, request, pk=None): return Response(SourceSerializer(updated_source).data) @extend_schema( + summary="Delete a source", + description="Deletes a data source from the system. This action is irreversible.", parameters=[OpenApiParameter(name="id", required=True, type=int, location="path")], responses={204: None}, tags=["Sources"], @@ -69,11 +88,15 @@ def destroy(self, request, pk=None): return Response(status=status.HTTP_204_NO_CONTENT) @extend_schema( + summary="Add metrics to a source", + description=( + "Adds a list of metric IDs to the given source," + " without removing existing associations.\n\n" + "The input must include a `metrics` field with a list of IDs." + ), request=LinkMetricsSerializer, parameters=[OpenApiParameter(name="id", required=True, type=int, location="path")], responses=SourceSerializer, - description="Adds a list of metric IDs to an existing " - "source without removing existing ones.", tags=["Sources"], ) @action(detail=True, methods=["post"], url_path="metrics") @@ -91,10 +114,14 @@ def add_metrics(self, request, pk=None): return Response(SourceSerializer(source).data, status=status.HTTP_200_OK) @extend_schema( + summary="Remove metrics from a source", + description=( + "Removes the specified metric IDs from the given source.\n\n" + "The input must include a `metrics` field with a list of IDs." + ), request=LinkMetricsSerializer, parameters=[OpenApiParameter(name="id", required=True, type=int, location="path")], responses=SourceSerializer, - description="Removes a list of metric IDs from an existing source.", tags=["Sources"], ) @action(detail=True, methods=["delete"], url_path="metrics") diff --git a/tests/adapters/test_all_adapters.py b/tests/adapters/test_all_adapters.py index 7015a2f..22f732b 100644 --- a/tests/adapters/test_all_adapters.py +++ b/tests/adapters/test_all_adapters.py @@ -19,7 +19,7 @@ def test_fetch_returns_dict_of_strings(adapter_class, dummy_app): adapter = adapter_class() if not adapter.supported_metrics: pytest.skip(f"No supported metrics for {adapter.code}") - result = adapter.fetch(app_id=dummy_app.id, metrics=adapter.supported_metrics) + result = adapter.fetch(app=dummy_app, metrics=adapter.supported_metrics) assert isinstance(result, dict) assert result is not None, f"{adapter.code}.fetch() returned None" for k, v in result.items(): diff --git a/tests/adapters/test_google_play_scraper.py b/tests/adapters/test_google_play_scraper.py index 45027d0..ef045cd 100644 --- a/tests/adapters/test_google_play_scraper.py +++ b/tests/adapters/test_google_play_scraper.py @@ -4,7 +4,7 @@ import pytest from rest_framework.exceptions import ParseError, ValidationError -from metric.constants import MetricCodes +from metric.constants import MetricCode from source.adapters.google_play_scraper import GooglePlayScraperAdapter @@ -23,26 +23,26 @@ def test_google_play_fetch(mock_gp_app, mock_app_get, dummy_app): adapter = GooglePlayScraperAdapter() - assert adapter.supports_metric(MetricCodes.AVERAGE_RATING) + assert adapter.supports_metric(MetricCode.AVERAGE_RATING) result = adapter.fetch( - dummy_app.id, + dummy_app, [ - MetricCodes.AVERAGE_RATING, - MetricCodes.TOTAL_REVIEWS, - MetricCodes.TOTAL_DOWNLOADS, - MetricCodes.LAST_UPDATE_DATE, + MetricCode.AVERAGE_RATING, + MetricCode.TOTAL_REVIEWS, + MetricCode.TOTAL_DOWNLOADS, + MetricCode.LAST_UPDATE_DATE, ], ) assert result == { - MetricCodes.AVERAGE_RATING: "4.6", - MetricCodes.TOTAL_REVIEWS: "50000", - MetricCodes.TOTAL_DOWNLOADS: "1000000", - MetricCodes.LAST_UPDATE_DATE: "2024-12-10", + MetricCode.AVERAGE_RATING: "4.6", + MetricCode.TOTAL_REVIEWS: "50000", + MetricCode.TOTAL_DOWNLOADS: "1000000", + MetricCode.LAST_UPDATE_DATE: "2024-12-10", } - unsupported = adapter.fetch(dummy_app.id, ["unsupported_metric"]) + unsupported = adapter.fetch(dummy_app, ["unsupported_metric"]) assert unsupported == {} @@ -71,7 +71,7 @@ def test_google_play_fetch_reviews(mock_reviews, mock_app_get, dummy_app): ] adapter = GooglePlayScraperAdapter() - result = adapter.fetch_reviews(dummy_app.id, date_from="2024-05-01", date_to="2024-05-03") + result = adapter.fetch_reviews(dummy_app, date_from="2024-05-01", date_to="2024-05-03") # Ha de contenir les 3 reviews simulades assert isinstance(result, list) @@ -92,7 +92,7 @@ def test_fetch_reviews_stops_on_review_before_date_from(mock_reviews, mock_app_g ) adapter = GooglePlayScraperAdapter() - result = adapter.fetch_reviews(dummy_app.id, date_from="2024-05-01", date_to="2024-05-03") + result = adapter.fetch_reviews(dummy_app, date_from="2024-05-01", date_to="2024-05-03") assert result == [] # Ha de sortir immediatament @@ -104,7 +104,7 @@ def test_fetch_reviews_returns_empty_list_if_no_reviews(mock_reviews, mock_app_g mock_reviews.return_value = ([], None) adapter = GooglePlayScraperAdapter() - result = adapter.fetch_reviews(dummy_app.id) + result = adapter.fetch_reviews(dummy_app) assert result == [] @@ -115,7 +115,7 @@ def test_fetch_reviews_raises_parse_error_on_invalid_date(mock_app_get, dummy_ap adapter = GooglePlayScraperAdapter() with pytest.raises(ParseError): - adapter.fetch_reviews(dummy_app.id, date_from="invalid-date") + adapter.fetch_reviews(dummy_app, date_from="invalid-date") @patch("app.models.App.objects.get") @@ -124,4 +124,4 @@ def test_fetch_reviews_raises_validation_error_if_date_range_invalid(mock_app_ge adapter = GooglePlayScraperAdapter() with pytest.raises(ValidationError): - adapter.fetch_reviews(dummy_app.id, date_from="2024-05-05", date_to="2024-05-01") + adapter.fetch_reviews(dummy_app, date_from="2024-05-05", date_to="2024-05-01") diff --git a/tests/adapters/test_itunes_adapter.py b/tests/adapters/test_itunes_adapter.py index ba448ef..3a94261 100644 --- a/tests/adapters/test_itunes_adapter.py +++ b/tests/adapters/test_itunes_adapter.py @@ -1,6 +1,6 @@ from unittest.mock import patch -from metric.constants import MetricCodes +from metric.constants import MetricCode from source.adapters.itunes import ItunesSearchAPIAdapter @@ -17,10 +17,10 @@ def test_itunes_fetch(mock_requests_get, mock_app_get, dummy_app): adapter = ItunesSearchAPIAdapter() - assert adapter.supports_metric(MetricCodes.AVERAGE_RATING) + assert adapter.supports_metric(MetricCode.AVERAGE_RATING) - result = adapter.fetch(dummy_app.id, [MetricCodes.AVERAGE_RATING, MetricCodes.TOTAL_REVIEWS]) - assert result == {MetricCodes.AVERAGE_RATING: "4.5", MetricCodes.TOTAL_REVIEWS: "1000"} + result = adapter.fetch(dummy_app, [MetricCode.AVERAGE_RATING, MetricCode.TOTAL_REVIEWS]) + assert result == {MetricCode.AVERAGE_RATING: "4.5", MetricCode.TOTAL_REVIEWS: "1000"} - unsupported = adapter.fetch(dummy_app.id, ["unsupported_metric"]) + unsupported = adapter.fetch(dummy_app, ["unsupported_metric"]) assert unsupported == {} diff --git a/tests/adapters/test_news.py b/tests/adapters/test_news.py index 39cb929..473ed66 100644 --- a/tests/adapters/test_news.py +++ b/tests/adapters/test_news.py @@ -1,6 +1,6 @@ from unittest.mock import patch -from metric.constants import MetricCodes +from metric.constants import MetricCode from source.adapters.news import NewsAPIAdapter @@ -22,10 +22,10 @@ def test_news_adapter_fetch(mock_requests_get, mock_app_get, dummy_app): adapter = NewsAPIAdapter("fake-api-key") - result = adapter.fetch(dummy_app.id, [MetricCodes.DAILY_NEWS_BLOG_MENTIONS]) + result = adapter.fetch(dummy_app, [MetricCode.DAILY_NEWS_BLOG_MENTIONS]) assert isinstance(result, dict) - assert result.get(MetricCodes.DAILY_NEWS_BLOG_MENTIONS) == "42" + assert result.get(MetricCode.DAILY_NEWS_BLOG_MENTIONS) == "42" - unsupported = adapter.fetch(dummy_app.id, ["unsupported_metric"]) + unsupported = adapter.fetch(dummy_app, ["unsupported_metric"]) assert unsupported == {} diff --git a/tests/adapters/test_reddit.py b/tests/adapters/test_reddit.py index 625b778..c62c558 100644 --- a/tests/adapters/test_reddit.py +++ b/tests/adapters/test_reddit.py @@ -1,6 +1,6 @@ from unittest.mock import MagicMock, patch -from metric.constants import MetricCodes +from metric.constants import MetricCode from source.adapters.reddit import RedditAPIAdapter @@ -18,14 +18,14 @@ def test_reddit_adapter_fetch(mock_reddit_class, mock_app_get, dummy_app): mock_reddit.subreddit.return_value.search.return_value = mock_results mock_reddit_class.return_value = mock_reddit - metric_code = MetricCodes.DAILY_SOCIAL_NETWORK_MENTIONS + metric_code = MetricCode.DAILY_SOCIAL_NETWORK_MENTIONS # ✅ Instanciar adapter després de tenir la BD a punt adapter = RedditAPIAdapter() - result = adapter.fetch(dummy_app.id, [metric_code]) + result = adapter.fetch(dummy_app, [metric_code]) assert isinstance(result, dict) assert result.get(metric_code) == "23" - unsupported = adapter.fetch(dummy_app.id, ["unsupported_metric"]) + unsupported = adapter.fetch(dummy_app, ["unsupported_metric"]) assert unsupported == {} diff --git a/tests/conftest.py b/tests/conftest.py index 9b107a7..2dfd999 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,22 +1,27 @@ import pytest +from django.contrib.auth.models import User from app.models import App -from metric.constants import MetricCodes +from metric.constants import MetricCode from metric.models import Metric from source.models import Source @pytest.fixture def dummy_app(db): + user = User.objects.create(username="admin", email="admin@example.com", password="admin") return App.objects.create( - code="dummy", name="Dummy App", appstore_id="310633997", playstore_id="com.whatsapp" + code="dummy", + name="Dummy App", + appstore_id="310633997", + playstore_id="com.whatsapp", + user=user, ) @pytest.fixture(autouse=True) def create_default_sources_and_metrics(db): """Crea sources i mètriques per defecte disponibles a tots els tests.""" - itunes = Source.objects.create( code="itunes", name="App Store", type="api", url="https://itunes.apple.com" ) @@ -29,12 +34,12 @@ def create_default_sources_and_metrics(db): ) for metric_code in [ - MetricCodes.AVERAGE_RATING, - MetricCodes.TOTAL_REVIEWS, - MetricCodes.TOTAL_DOWNLOADS, - MetricCodes.LAST_UPDATE_DATE, - MetricCodes.DAILY_SOCIAL_NETWORK_MENTIONS, - MetricCodes.DAILY_NEWS_BLOG_MENTIONS, + MetricCode.AVERAGE_RATING, + MetricCode.TOTAL_REVIEWS, + MetricCode.TOTAL_DOWNLOADS, + MetricCode.LAST_UPDATE_DATE, + MetricCode.DAILY_SOCIAL_NETWORK_MENTIONS, + MetricCode.DAILY_NEWS_BLOG_MENTIONS, ]: metric = Metric.objects.create(code=metric_code, name=metric_code.replace("_", " ").title()) itunes.metrics.add(metric) diff --git a/tests/integration/test_end_to_end.py b/tests/integration/test_end_to_end.py index 9ed79df..65869f6 100644 --- a/tests/integration/test_end_to_end.py +++ b/tests/integration/test_end_to_end.py @@ -11,7 +11,7 @@ def test_full_flow_with_real_adapter(dummy_app): assert itunes_adapter is not None, "iTunes adapter not found in loaded sources" - values = itunes_adapter.fetch(dummy_app.id, ["average_rating"]) + values = itunes_adapter.fetch(dummy_app, ["average_rating"]) # Comprovar que el valor retornat és un diccionari i conté la clau "average_rating" assert isinstance(values, dict), "Expected values to be a dictionary" diff --git a/users/views.py b/users/views.py index 962f2f1..b644cf8 100644 --- a/users/views.py +++ b/users/views.py @@ -13,6 +13,13 @@ class RegisterView(APIView): service = UserService() @extend_schema( + summary="Register a new user", + description=( + "Registers a new user and returns a pair of JWT tokens.\n\n" + "The request body must contain valid user registration data. " + "If the registration is successful, the response" + " will include an access token and a refresh token." + ), request=RegisterSerializer, responses={ 201: { @@ -23,7 +30,6 @@ class RegisterView(APIView): }, } }, - description="Endpoint per registrar un nou usuari. Retorna tokens JWT (access + refresh).", ) def post(self, request): serializer = RegisterSerializer(data=request.data)