diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 1b6e390a3..0ec1c32cf 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -1,4 +1,4 @@ -name: Deploy Employers AI +name: Deploy Software AI on: @@ -7,6 +7,8 @@ on: branches: - main +env: + NODE_VERSION: '22.x' jobs: build-and-deploy: @@ -36,25 +38,26 @@ jobs: rsync -avz --delete ./ ${{ secrets.DEPLOY_USER }}@${{ secrets.DEPLOY_HOST }}:/home/administrator/deploys/softwareai \ --exclude node_modules \ --exclude .git \ - --exclude front-end/node_modules + --exclude frontend/web/node_modules + --exclude electron/web/node_modules - name: Make dir on VPS run: | ssh ${{ secrets.DEPLOY_USER }}@${{ secrets.DEPLOY_HOST }} " - mkdir -p /home/administrator/deploys/softwareai/Back-End/Keys && \ - mkdir -p /home/administrator/deploys/softwareai/Front-End + mkdir -p /home/administrator/deploys/softwareai/backend/Keys && \ + mkdir -p /home/administrator/deploys/softwareai/frontend/web " - name: Create keys.env on VPS run: | ssh ${{ secrets.DEPLOY_USER }}@${{ secrets.DEPLOY_HOST }} " - printf '%s' '${{ secrets.BACK_END_ENV_KEYS }}' > /home/administrator/deploys/softwareai/Back-End/Keys/keys.env + printf '%s' '${{ secrets.BACK_END_ENV_KEYS }}' > /home/administrator/deploys/softwareai/backend/Keys/keys.env " - name: Create .env on VPS run: | ssh ${{ secrets.DEPLOY_USER }}@${{ secrets.DEPLOY_HOST }} " - printf '%s' '${{ secrets.FRONT_END_ENV_KEYS }}' > /home/administrator/deploys/softwareai/Front-End/.env + printf '%s' '${{ secrets.FRONT_END_ENV_KEYS }}' > /home/administrator/deploys/softwareai/frontend/web/.env " - name: Create COMPOSE on VPS @@ -72,3 +75,84 @@ jobs: docker container prune && \ docker compose up --build -d --no-deps softwareai_frontend softwareai_api " + + build-electron: + name: "⚡ Build Electron App" + runs-on: windows-latest + needs: build-frontend + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v3 + with: + node-version: ${{ env.NODE_VERSION }} + - name: Install Modules + run: npm install + - name: Install Electron + run: npm install --save-dev electron@latest + - name: Download frontend/electron build + uses: actions/download-artifact@v4 + with: + name: vite-dist + path: dist + - name: Copy frontend/electron to Electron + shell: bash # ⬅️ use Bash em vez de pwsh + run: | + mkdir -p public + cp -r dist/* public/ + - name: Build Electron App + run: npx electron-builder --win --publish never + - uses: actions/upload-artifact@v4 + with: + name: electron-app + path: dist/*.exe # ◀️ captura o instalador Windows + + release: + name: "🚀 Create GitHub Release" + runs-on: ubuntu-latest + needs: build-electron + if: github.event.pull_request.merged == true + permissions: + contents: write + steps: + - name: "Checkout code (to read package.json)" + uses: actions/checkout@v4 + with: + fetch-depth: 1 + + - name: "Setup Node.js" + uses: actions/setup-node@v3 + with: + node-version: ${{ env.NODE_VERSION }} + + - name: "Get version from package.json" + id: get_version + run: | + version=$(node -p "require('./package.json').version") + echo "version=$version" >> $GITHUB_OUTPUT + + - name: "Download Electron artifact" + uses: actions/download-artifact@v4 + with: + name: electron-app + path: ./release-assets + + - name: Delete existing release (if any) + run: | + version=v${{ steps.get_version.outputs.version }} + gh release delete "$version" --yes || true + git push --delete origin "$version" || true + + env: + GH_TOKEN: ${{ secrets.GH_TOKEN }} + + - name: Create GitHub Release and Upload Assets + id: create_release + uses: softprops/action-gh-release@v1 + with: + tag_name: v${{ steps.get_version.outputs.version }} + name: "Release v${{ steps.get_version.outputs.version }}" + draft: false + prerelease: false + token: ${{ secrets.GH_TOKEN }} + files: | + ./release-assets/** \ No newline at end of file diff --git a/.gitignore b/.gitignore index 1fc2621b9..f337fc35c 100644 --- a/.gitignore +++ b/.gitignore @@ -1,12 +1,58 @@ -Back-End/Save/ +# Local databases +smart_call_triage.db +# OS +.DS_Store +Thumbs.db + +# Python +__pycache__/ +*.py[cod] +*.egg-info/ +.venv/ +.env +ENV/ + +# Node +node_modules/ +npm-debug.log* +yarn-debug.log* +yarn-error.log* +pnpm-debug.log* +*.tsbuildinfo + +# Build artifacts +build/ +dist/ +.vite/ +.coverage/ +coverage/ +__pycache__/ +*.py[cod] +*.egg-info/ +.venv/ +*.env +.ruff_cache/ +.pytest_cache/ +.coverage/ +*.log +backend/Save/ mongo-init.js Legacy/AgentsWorkFlow/ +backend/Agents/gpt_engineer/keys.env +backend/WorkEnv/ +backend/Modules/ChatKit/data_tools/data.py +backend/Agents/AppAI/RequirementsPlanner/Knowledge/keys.env +backend/Agents/AppAI/SprintsSheduler/Sessions/ +backend/Agents/AppAI/RequirementsPlanner/save/ +backend/Modules/ChatKit/Thread_Sessions/ ProductionFiles/Certifi/ ProductionFiles/keys.env ProductionFiles/.env +backend/Agents/JobSearch/Curriculo/ +backend/Agents/JobSearch/Reports/ Legacy/Keys/InternalDocs/ -Back-End/Keys/ -Back-End/Invoices/ +backend/Keys/ +backend/Invoices/ Legacy/LocalProject/ node_modules/ Tests/ @@ -16,7 +62,7 @@ __pycache__/ *.pyc *.cpython-39.pyc **/__pycache__/ -Back-End/Keys/keys.env +backend/Keys/keys.env # Logs logs diff --git a/Back-End/.dockerignore b/Back-End/.dockerignore deleted file mode 100644 index 9d150e95f..000000000 --- a/Back-End/.dockerignore +++ /dev/null @@ -1,4 +0,0 @@ -Back-End/Production/ -Back-End/Keys/ -Back-End/Dev/ -Back-End/keys.env diff --git a/Back-End/LICENSE b/Back-End/LICENSE deleted file mode 100644 index 0ad25db4b..000000000 --- a/Back-End/LICENSE +++ /dev/null @@ -1,661 +0,0 @@ - GNU AFFERO GENERAL PUBLIC LICENSE - Version 3, 19 November 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU Affero General Public License is a free, copyleft license for -software and other kinds of works, specifically designed to ensure -cooperation with the community in the case of network server software. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -our General Public Licenses are intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - Developers that use our General Public Licenses protect your rights -with two steps: (1) assert copyright on the software, and (2) offer -you this License which gives you legal permission to copy, distribute -and/or modify the software. - - A secondary benefit of defending all users' freedom is that -improvements made in alternate versions of the program, if they -receive widespread use, become available for other developers to -incorporate. Many developers of free software are heartened and -encouraged by the resulting cooperation. However, in the case of -software used on network servers, this result may fail to come about. -The GNU General Public License permits making a modified version and -letting the public access it on a server without ever releasing its -source code to the public. - - The GNU Affero General Public License is designed specifically to -ensure that, in such cases, the modified source code becomes available -to the community. It requires the operator of a network server to -provide the source code of the modified version running there to the -users of that server. Therefore, public use of a modified version, on -a publicly accessible server, gives the public access to the source -code of the modified version. - - An older license, called the Affero General Public License and -published by Affero, was designed to accomplish similar goals. This is -a different license, not a version of the Affero GPL, but Affero has -released a new version of the Affero GPL which permits relicensing under -this license. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU Affero General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Remote Network Interaction; Use with the GNU General Public License. - - Notwithstanding any other provision of this License, if you modify the -Program, your modified version must prominently offer all users -interacting with it remotely through a computer network (if your version -supports such interaction) an opportunity to receive the Corresponding -Source of your version by providing access to the Corresponding Source -from a network server at no charge, through some standard or customary -means of facilitating copying of software. This Corresponding Source -shall include the Corresponding Source for any work covered by version 3 -of the GNU General Public License that is incorporated pursuant to the -following paragraph. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the work with which it is combined will remain governed by version -3 of the GNU General Public License. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU Affero General Public License from time to time. Such new versions -will be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU Affero General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU Affero General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU Affero General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If your software can interact with users remotely through a computer -network, you should also make sure that it provides a way for users to -get its source. For example, if your program is a web application, its -interface could display a "Source" link that leads users to an archive -of the code. There are many ways you could offer source, and different -solutions will be better for different programs; see section 13 for the -specific requirements. - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU AGPL, see -. diff --git a/Docs/git context layer.md b/Docs/git context layer.md new file mode 100644 index 000000000..c24b69a09 --- /dev/null +++ b/Docs/git context layer.md @@ -0,0 +1,94 @@ +# Documentação: PR AI - Git Context Layer + +O **Git Context Layer** é um recurso central dentro do aplicativo **PR AI** (Inteligência Artificial para Pull Requests) projetado para analisar diff na camada de pre staging de commit permitindo automatizar e aprimorar o processo de criação de mensagens de commit e o fluxo de trabalho Git/GitHub local do desenvolvedor. Ele utiliza modelos de Inteligência Artificial para gerar mensagens de commit contextuais, facilitando a manutenção de um histórico de commits limpo e descritivo. + +## Funcionalidades Principais + +| Componente | Função | Arquivo de Exemplo | +| :--- | :--- | :--- | +| **Geração de Commit AI** | Gera automaticamente mensagens de commit com base nas alterações do código-fonte (diffs) usando um modelo de IA configurável. | `CommitPreview.tsx` | +| **Configuração** | Permite que o usuário ajuste parâmetros do sistema, como o modelo de IA, limites de alteração (thresholds) e automações. | `ConfigPanel.tsx` | +| **Automação** | Oferece opções para **Auto Push** e **Auto Create PR** (Criação Automática de Pull Request) após um commit bem-sucedido. | `ConfigPanel.tsx` | +| **Interface de Usuário** | Interface de navegação lateral coesa e responsiva, com controle de estado de colapso. | `app-sidebar.tsx` | + +--- + +## 1. Navegação da Aplicação (AppSidebar) + +O componente `AppSidebar` define a estrutura de navegação principal da aplicação, sendo o ponto de entrada para todas as funcionalidades. + +### Componente `AppSidebar` (`app-sidebar.tsx`) + +| Recurso | Descrição | +| :--- | :--- | +| **Identidade Visual** | Exibe o nome **PR AI - Git Context Layer** e um ícone de `Bot` no cabeçalho. O título é ocultado quando a barra lateral está no estado **"collapsed"** (colapsada). | +| **Itens de Navegação** | Os links são definidos no array `navigationItems`. O contexto atual mostra: | +| | - **Git Context Layer** (`/gitcontextlayer`): Principal recurso de IA de Commits. | +| | - **Pull Requests** (`/prs`): Para monitoramento de PRs. | +| **Estilização Ativa** | O `getNavClassName` aplica estilos distintos (`bg-gradient-primary`, `shadow-glow`) ao item de menu que corresponde ao caminho atual, usando a função `isActive`. | +| **Funcionalidade de Logout** | O botão de `Logout` chama a função `handleLogout`, que utiliza o `useAuth().logout()` e, em seguida, recarrega a página (`window.location.reload()`) para efetuar a desconexão completa do usuário. | + +--- + +## 2. Pré-visualização e Ação de Commit (CommitPreview) + +O componente `CommitPreview` é a interface onde a mensagem de commit gerada pela IA é exibida e onde o usuário pode interagir para copiar ou realizar o commit de fato. + +### Componente `CommitPreview` (`CommitPreview.tsx`) + +| Propriedade (Props) | Tipo | Descrição | +| :--- | :--- | :--- | +| `message` | `string` | A mensagem de commit gerada pela IA. | +| `status` | `'SUCCESS' \| 'NO_CHANGES' \| 'ERROR'` | O status da operação de geração de commit. Controla a cor do indicador de status. | +| `onCommit` | `() => void` | Função de callback para ser executada quando o botão "Commit & Push" é clicado. | +| `isLoading` | `boolean` | Indica se o processo de commit está em andamento. | + +### Elementos de Interface + +* **Status do AI-Generated Commit**: Exibido com cores baseadas no `status`: **SUCCESS** (Verde), **NO\_CHANGES** (Laranja/Amarelo) ou **ERROR** (Vermelho). +* **Ação de Copiar**: Um botão com ícone de `Copy` que, ao ser clicado, copia a `message` para a área de transferência do sistema e exibe uma notificação (`toast.success`). +* **Área de Mensagem**: Usa `ScrollArea` para exibir a mensagem de commit (`message`) em uma fonte mono espaçada e com quebras de linha (`whitespace-pre-wrap`), garantindo que o formato do commit seja preservado. +* **Botão de Commit**: "Commit & Push". Está desabilitado se não houver `message`, se estiver `isLoading` ou se o `status` não for **SUCCESS**. O texto muda para "Committing..." durante o carregamento. + +--- + +## 3. Painel de Configuração (ConfigPanel) + +O `ConfigPanel` permite que o usuário gerencie as configurações que afetam tanto o comportamento da IA quanto as automações do Git. + +### Componente `ConfigPanel` (`ConfigPanel.tsx`) + +### Carregamento e Estado + +1. **Obtenção de Configurações**: No `useEffect`, o componente faz uma requisição `GET` para o endpoint de configurações (`/api/settings`) utilizando os dados de autenticação (`access_token`, `user_email`, `user_senha`) armazenados no `localStorage`. +2. **Mapeamento de Dados**: Os dados recebidos da API são mapeados para o estado local (`localConfig`). São fornecidos valores *default* caso algum campo esteja ausente, por exemplo, `ai_model: 'gpt-5-nano'`, `lines_threshold: 50`. + +### Campos de Configuração + +O painel é dividido em seções para gerenciar diferentes aspectos da aplicação: + +#### 3.1. Credenciais e Modelos +* **GitHub API Key**: Campo de `Input` tipo `password` para o `GITHUB_TOKEN`, essencial para interagir com a API do GitHub (ex: para criação de PRs ou push). +* **Language (`commitLanguage`)**: `Select` para definir o idioma das mensagens de commit geradas pela IA (`Português` ou `English`). O valor padrão é `'en'`. +* **AI Model (`ai_model`)**: `Select` para escolher o modelo de Inteligência Artificial que será usado para a geração dos commits. Opções de exemplo incluem: `gpt-5-nano` (padrão), `gpt-5-mini`, `gpt-5`, e `gpt-4`. + +#### 3.2. Limites (Thresholds) + +Esses limites definem as condições sob as quais o sistema de IA deve ser acionado ou as operações devem ocorrer. + +| Configuração | Descrição | Tipo | Padrão | +| :--- | :--- | :--- | :--- | +| **Lines Threshold** (`lines_threshold`) | Número máximo de linhas alteradas (incluindo inserções/deleções) a partir do qual a IA pode ser acionada. | `number` | `50` | +| **Files Threshold** (`files_threshold`) | Número máximo de arquivos alterados. | `number` | `5` | +| **Time Threshold (s)** (`time_threshold`) | Limite de tempo em segundos para alguma métrica interna. | `number` | `60` | +| **Throttle (ms)** (`throttle_ms`) | Intervalo mínimo de tempo em milissegundos entre operações. | `number` | `60000` | + +#### 3.3. Automações (Switches) + +* **Auto Push (`auto_push`)**: `Switch` booleano. Se ativado, o repositório local fará um `git push` automaticamente após um commit bem-sucedido. +* **Auto Create Pr (`auto_create_pr`)**: `Switch` booleano. Se ativado, uma Pull Request será criada automaticamente no GitHub após o `commit` e `push`. + +### Ação de Salvar + +* A função `handleSave` realiza uma requisição `PUT` para o endpoint `/api/settings`, enviando o `localConfig` atualizado. +* O botão **Save Configuration** é desabilitado e tem o texto alterado para "Saving..." enquanto a requisição de salvamento está em andamento. \ No newline at end of file diff --git a/mvp.md b/Docs/mvp.md similarity index 100% rename from mvp.md rename to Docs/mvp.md diff --git a/Front-End/git-genius-commit/.env b/Front-End/git-genius-commit/.env deleted file mode 100644 index dcb08b627..000000000 --- a/Front-End/git-genius-commit/.env +++ /dev/null @@ -1 +0,0 @@ -VITE_BACK_END=http://localhost:5910 \ No newline at end of file diff --git a/Front-End/git-genius-commit/README.md b/Front-End/git-genius-commit/README.md deleted file mode 100644 index 8c7c7c29c..000000000 --- a/Front-End/git-genius-commit/README.md +++ /dev/null @@ -1,73 +0,0 @@ -# Welcome to your Lovable project - -## Project info - -**URL**: https://lovable.dev/projects/1d94e90c-85d7-4aed-8fa2-ede2b4be6989 - -## How can I edit this code? - -There are several ways of editing your application. - -**Use Lovable** - -Simply visit the [Lovable Project](https://lovable.dev/projects/1d94e90c-85d7-4aed-8fa2-ede2b4be6989) and start prompting. - -Changes made via Lovable will be committed automatically to this repo. - -**Use your preferred IDE** - -If you want to work locally using your own IDE, you can clone this repo and push changes. Pushed changes will also be reflected in Lovable. - -The only requirement is having Node.js & npm installed - [install with nvm](https://github.com/nvm-sh/nvm#installing-and-updating) - -Follow these steps: - -```sh -# Step 1: Clone the repository using the project's Git URL. -git clone - -# Step 2: Navigate to the project directory. -cd - -# Step 3: Install the necessary dependencies. -npm i - -# Step 4: Start the development server with auto-reloading and an instant preview. -npm run dev -``` - -**Edit a file directly in GitHub** - -- Navigate to the desired file(s). -- Click the "Edit" button (pencil icon) at the top right of the file view. -- Make your changes and commit the changes. - -**Use GitHub Codespaces** - -- Navigate to the main page of your repository. -- Click on the "Code" button (green button) near the top right. -- Select the "Codespaces" tab. -- Click on "New codespace" to launch a new Codespace environment. -- Edit files directly within the Codespace and commit and push your changes once you're done. - -## What technologies are used for this project? - -This project is built with: - -- Vite -- TypeScript -- React -- shadcn-ui -- Tailwind CSS - -## How can I deploy this project? - -Simply open [Lovable](https://lovable.dev/projects/1d94e90c-85d7-4aed-8fa2-ede2b4be6989) and click on Share -> Publish. - -## Can I connect a custom domain to my Lovable project? - -Yes, you can! - -To connect a domain, navigate to Project > Settings > Domains and click Connect Domain. - -Read more here: [Setting up a custom domain](https://docs.lovable.dev/features/custom-domain#custom-domain) diff --git a/Front-End/git-genius-commit/src/App.tsx b/Front-End/git-genius-commit/src/App.tsx deleted file mode 100644 index d8edb38a7..000000000 --- a/Front-End/git-genius-commit/src/App.tsx +++ /dev/null @@ -1,50 +0,0 @@ - -import { Toaster } from "@/components/ui/toaster"; -import { Toaster as Sonner } from "@/components/ui/sonner"; -import { TooltipProvider } from "@/components/ui/tooltip"; -import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; -import { BrowserRouter, Routes, Route, Navigate } from "react-router-dom"; -import Login from "./pages/Login"; -import Index from "./pages/Index"; - -import { AuthProvider, useAuth } from "./contexts/AuthContext"; -import ProtectedRoute from "./components/ProtectedRoute"; - -const queryClient = new QueryClient(); - -const AppRoutes = () => { - const { isAuthenticated } = useAuth(); - - return ( - - {isAuthenticated ? ( - - } /> - } /> - {/* } /> */} - - ) : ( - - } /> - } /> - - } /> - - )} - - ); -}; - -const App = () => ( - - - - - - - - - -); - -export default App; diff --git a/Front-End/webpr/.dockerignore b/Front-End/webpr/.dockerignore deleted file mode 100644 index 40b878db5..000000000 --- a/Front-End/webpr/.dockerignore +++ /dev/null @@ -1 +0,0 @@ -node_modules/ \ No newline at end of file diff --git a/Front-End/webpr/.env b/Front-End/webpr/.env deleted file mode 100644 index 466e9f8d9..000000000 --- a/Front-End/webpr/.env +++ /dev/null @@ -1,2 +0,0 @@ -VITE_BACK_END=http://localhost:5910 -VITE_STRIPE_PUBLISHABLE_KEY=pk_test_51QpX90Cvm2cRLHtdoF7n2Ea4sRRjYBx8Csiii0e6M6ECTJJ8fKaQ1DKpJApfJZH5hIkWRojaMmaxY9sEcS50tspB00DF2IA12h \ No newline at end of file diff --git a/Front-End/webpr/bun.lockb b/Front-End/webpr/bun.lockb deleted file mode 100644 index 160304d39..000000000 Binary files a/Front-End/webpr/bun.lockb and /dev/null differ diff --git a/Front-End/webpr/components.json b/Front-End/webpr/components.json deleted file mode 100644 index f29e3f161..000000000 --- a/Front-End/webpr/components.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "$schema": "https://ui.shadcn.com/schema.json", - "style": "default", - "rsc": false, - "tsx": true, - "tailwind": { - "config": "tailwind.config.ts", - "css": "src/index.css", - "baseColor": "slate", - "cssVariables": true, - "prefix": "" - }, - "aliases": { - "components": "@/components", - "utils": "@/lib/utils", - "ui": "@/components/ui", - "lib": "@/lib", - "hooks": "@/hooks" - } -} \ No newline at end of file diff --git a/Front-End/webpr/eslint.config.js b/Front-End/webpr/eslint.config.js deleted file mode 100644 index e67846f70..000000000 --- a/Front-End/webpr/eslint.config.js +++ /dev/null @@ -1,29 +0,0 @@ -import js from "@eslint/js"; -import globals from "globals"; -import reactHooks from "eslint-plugin-react-hooks"; -import reactRefresh from "eslint-plugin-react-refresh"; -import tseslint from "typescript-eslint"; - -export default tseslint.config( - { ignores: ["dist"] }, - { - extends: [js.configs.recommended, ...tseslint.configs.recommended], - files: ["**/*.{ts,tsx}"], - languageOptions: { - ecmaVersion: 2020, - globals: globals.browser, - }, - plugins: { - "react-hooks": reactHooks, - "react-refresh": reactRefresh, - }, - rules: { - ...reactHooks.configs.recommended.rules, - "react-refresh/only-export-components": [ - "warn", - { allowConstantExport: true }, - ], - "@typescript-eslint/no-unused-vars": "off", - }, - } -); diff --git a/Front-End/webpr/public/favicon.ico b/Front-End/webpr/public/favicon.ico deleted file mode 100644 index dd5a12627..000000000 Binary files a/Front-End/webpr/public/favicon.ico and /dev/null differ diff --git a/Front-End/webpr/public/icone.png b/Front-End/webpr/public/icone.png deleted file mode 100644 index 42fee2469..000000000 Binary files a/Front-End/webpr/public/icone.png and /dev/null differ diff --git a/Front-End/webpr/public/placeholder.svg b/Front-End/webpr/public/placeholder.svg deleted file mode 100644 index e763910b2..000000000 --- a/Front-End/webpr/public/placeholder.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/Front-End/webpr/public/robots.txt b/Front-End/webpr/public/robots.txt deleted file mode 100644 index 6018e701f..000000000 --- a/Front-End/webpr/public/robots.txt +++ /dev/null @@ -1,14 +0,0 @@ -User-agent: Googlebot -Allow: / - -User-agent: Bingbot -Allow: / - -User-agent: Twitterbot -Allow: / - -User-agent: facebookexternalhit -Allow: / - -User-agent: * -Allow: / diff --git a/Front-End/webpr/src/App.css b/Front-End/webpr/src/App.css deleted file mode 100644 index b9d355df2..000000000 --- a/Front-End/webpr/src/App.css +++ /dev/null @@ -1,42 +0,0 @@ -#root { - max-width: 1280px; - margin: 0 auto; - padding: 2rem; - text-align: center; -} - -.logo { - height: 6em; - padding: 1.5em; - will-change: filter; - transition: filter 300ms; -} -.logo:hover { - filter: drop-shadow(0 0 2em #646cffaa); -} -.logo.react:hover { - filter: drop-shadow(0 0 2em #61dafbaa); -} - -@keyframes logo-spin { - from { - transform: rotate(0deg); - } - to { - transform: rotate(360deg); - } -} - -@media (prefers-reduced-motion: no-preference) { - a:nth-of-type(2) .logo { - animation: logo-spin infinite 20s linear; - } -} - -.card { - padding: 2em; -} - -.read-the-docs { - color: #888; -} diff --git a/Front-End/webpr/src/main.tsx b/Front-End/webpr/src/main.tsx deleted file mode 100644 index 719464e3d..000000000 --- a/Front-End/webpr/src/main.tsx +++ /dev/null @@ -1,5 +0,0 @@ -import { createRoot } from 'react-dom/client' -import App from './App.tsx' -import './index.css' - -createRoot(document.getElementById("root")!).render(); diff --git a/Front-End/webpr/tsconfig.app.json b/Front-End/webpr/tsconfig.app.json deleted file mode 100644 index 0b0e43e6b..000000000 --- a/Front-End/webpr/tsconfig.app.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "compilerOptions": { - "target": "ES2020", - "useDefineForClassFields": true, - "lib": ["ES2020", "DOM", "DOM.Iterable"], - "module": "ESNext", - "skipLibCheck": true, - - /* Bundler mode */ - "moduleResolution": "bundler", - "allowImportingTsExtensions": true, - "isolatedModules": true, - "moduleDetection": "force", - "noEmit": true, - "jsx": "react-jsx", - - /* Linting */ - "strict": false, - "noUnusedLocals": false, - "noUnusedParameters": false, - "noImplicitAny": false, - "noFallthroughCasesInSwitch": false, - - "baseUrl": ".", - "paths": { - "@/*": ["./src/*"] - } - }, - "include": ["src"] -} diff --git a/Front-End/webpr/tsconfig.json b/Front-End/webpr/tsconfig.json deleted file mode 100644 index 129b1a30f..000000000 --- a/Front-End/webpr/tsconfig.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "files": [], - "references": [ - { "path": "./tsconfig.app.json" }, - { "path": "./tsconfig.node.json" } - ], - "compilerOptions": { - "baseUrl": ".", - "paths": { - "@/*": ["./src/*"] - }, - "noImplicitAny": false, - "noUnusedParameters": false, - "skipLibCheck": true, - "allowJs": true, - "noUnusedLocals": false, - "strictNullChecks": false - } -} diff --git a/Front-End/webpr/tsconfig.node.json b/Front-End/webpr/tsconfig.node.json deleted file mode 100644 index 3133162c2..000000000 --- a/Front-End/webpr/tsconfig.node.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "compilerOptions": { - "target": "ES2022", - "lib": ["ES2023"], - "module": "ESNext", - "skipLibCheck": true, - - /* Bundler mode */ - "moduleResolution": "bundler", - "allowImportingTsExtensions": true, - "isolatedModules": true, - "moduleDetection": "force", - "noEmit": true, - - /* Linting */ - "strict": true, - "noUnusedLocals": false, - "noUnusedParameters": false, - "noFallthroughCasesInSwitch": true - }, - "include": ["vite.config.ts"] -} diff --git a/Front-End/webpr/vite.config.ts b/Front-End/webpr/vite.config.ts deleted file mode 100644 index 1343bcde0..000000000 --- a/Front-End/webpr/vite.config.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { defineConfig } from "vite"; -import react from "@vitejs/plugin-react-swc"; -import path from "path"; -import { componentTagger } from "lovable-tagger"; - -// https://vitejs.dev/config/ -export default defineConfig(({ mode }) => ({ - server: { - host: "0.0.0.0", - port: 4343, - allowedHosts: ["5f063a99e43d.ngrok-free.app"], - hmr: { - protocol: 'wss', - host: '5f063a99e43d.ngrok-free.app', - }, - watch: { - ignored: ['**/node_modules/**'], - usePolling: true, - interval: 100, - }, - }, - - - plugins: [ - react(), - mode === 'development' && - componentTagger(), - ].filter(Boolean), - resolve: { - alias: { - "@": path.resolve(__dirname, "./src"), - }, - }, -})); diff --git a/ProductionFiles/docker-compose.yml b/ProductionFiles/docker-compose.yml index a4e067cc0..f580b70ad 100644 --- a/ProductionFiles/docker-compose.yml +++ b/ProductionFiles/docker-compose.yml @@ -62,7 +62,7 @@ services: softwareai_frontend: image: softwareai-frontend-server:latest build: - context: ./Front-End + context: ./Front-End/webpr dockerfile: Dockerfile container_name: softwareai_frontend working_dir: /app diff --git a/backend/Agents/AppAI/CodeBackend/CodeKnowledge/Architectures/Stack1/.github/workflows/deploy.yml b/backend/Agents/AppAI/CodeBackend/CodeKnowledge/Architectures/Stack1/.github/workflows/deploy.yml new file mode 100644 index 000000000..61b790b72 --- /dev/null +++ b/backend/Agents/AppAI/CodeBackend/CodeKnowledge/Architectures/Stack1/.github/workflows/deploy.yml @@ -0,0 +1,74 @@ +name: Deploy Software AI + + +on: + pull_request: + types: [closed] + branches: + - main + + +jobs: + build-and-deploy: + if: github.event.pull_request.merged == true + runs-on: ubuntu-latest + + steps: + - name: Checkout code + uses: actions/checkout@v3 + + - name: Setup SSH + uses: webfactory/ssh-agent@v0.9.1 + with: + ssh-private-key: ${{ secrets.SSH_PRIVATE_KEY }} + + - name: Add remote host to known_hosts + run: | + mkdir -p ~/.ssh + chmod 700 ~/.ssh + ssh-keyscan -H ${{ secrets.DEPLOY_HOST }} >> ~/.ssh/known_hosts + chmod 644 ~/.ssh/known_hosts + echo "known_hosts:" + cat ~/.ssh/known_hosts + + - name: Copy entire project to VPS + run: | + rsync -avz --delete ./ ${{ secrets.DEPLOY_USER }}@${{ secrets.DEPLOY_HOST }}:/home/administrator/deploys/softwareai \ + --exclude node_modules \ + --exclude .git \ + --exclude front-end/node_modules + + - name: Make dir on VPS + run: | + ssh ${{ secrets.DEPLOY_USER }}@${{ secrets.DEPLOY_HOST }} " + mkdir -p /home/administrator/deploys/softwareai/Back-End/Keys && \ + mkdir -p /home/administrator/deploys/softwareai/Front-End + " + + - name: Create keys.env on VPS + run: | + ssh ${{ secrets.DEPLOY_USER }}@${{ secrets.DEPLOY_HOST }} " + printf '%s' '${{ secrets.BACK_END_ENV_KEYS }}' > /home/administrator/deploys/softwareai/Back-End/Keys/keys.env + " + + - name: Create .env on VPS + run: | + ssh ${{ secrets.DEPLOY_USER }}@${{ secrets.DEPLOY_HOST }} " + printf '%s' '${{ secrets.FRONT_END_ENV_KEYS }}' > /home/administrator/deploys/softwareai/Front-End/.env + " + + - name: Create COMPOSE on VPS + run: | + ssh ${{ secrets.DEPLOY_USER }}@${{ secrets.DEPLOY_HOST }} " + echo '${{ secrets.COMPOSE }}' | base64 --decode > /home/administrator/deploys/softwareai/docker-compose.yml + " + + - name: Deploy Docker Compose + run: | + ssh ${{ secrets.DEPLOY_USER }}@${{ secrets.DEPLOY_HOST }} " + cd /home/administrator/deploys/softwareai && \ + + docker rm -f softwareai_frontend softwareai_api || true && \ + docker container prune && \ + docker compose up --build -d --no-deps softwareai_frontend softwareai_api + " diff --git a/Back-End/Dockerfile b/backend/Agents/AppAI/CodeBackend/CodeKnowledge/Architectures/Stack1/Back-End/Dockerfile similarity index 100% rename from Back-End/Dockerfile rename to backend/Agents/AppAI/CodeBackend/CodeKnowledge/Architectures/Stack1/Back-End/Dockerfile diff --git a/backend/Agents/AppAI/CodeBackend/CodeKnowledge/Architectures/Stack1/Back-End/Models/mongoDB/audit.py b/backend/Agents/AppAI/CodeBackend/CodeKnowledge/Architectures/Stack1/Back-End/Models/mongoDB/audit.py new file mode 100644 index 000000000..ff11d4d2b --- /dev/null +++ b/backend/Agents/AppAI/CodeBackend/CodeKnowledge/Architectures/Stack1/Back-End/Models/mongoDB/audit.py @@ -0,0 +1,34 @@ +from datetime import datetime, timedelta +from pymongo import MongoClient +from dotenv import load_dotenv +import os + +MONGO_URI = os.getenv('MONGO_URI', 'None') +MONGO_DB_NAME = os.getenv('MONGO_DB_NAME', 'controls_logs') +if MONGO_URI == 'None': + load_dotenv(dotenv_path=os.path.join(os.path.dirname(__file__), '../', '../', 'Keys', 'keys.env')) + MONGO_URI = os.getenv('MONGO_URI', 'mongodb://localhost:27017/') + + +mongo_client = MongoClient(MONGO_URI) +mongo_db = mongo_client[MONGO_DB_NAME] +logs_collection = mongo_db.logs + +class AuditTrail: + collection = mongo_db['audit_trail'] + + @classmethod + def create(cls, entity, action, user, metadata=None): + entry = { + "entity": entity, + "action": action, + "user": user, + "metadata": metadata or {}, + "timestamp": datetime.utcnow() + } + result = cls.collection.insert_one(entry) + return str(result.inserted_id) + + @classmethod + def find_by_entity(cls, entity): + return list(cls.collection.find({"entity": entity}).sort("timestamp", -1)) \ No newline at end of file diff --git a/backend/Agents/AppAI/CodeBackend/CodeKnowledge/Architectures/Stack1/Back-End/Models/mongoDB/logs.py b/backend/Agents/AppAI/CodeBackend/CodeKnowledge/Architectures/Stack1/Back-End/Models/mongoDB/logs.py new file mode 100644 index 000000000..e8f28e763 --- /dev/null +++ b/backend/Agents/AppAI/CodeBackend/CodeKnowledge/Architectures/Stack1/Back-End/Models/mongoDB/logs.py @@ -0,0 +1,39 @@ +from datetime import datetime, timedelta +from pymongo import MongoClient +from dotenv import load_dotenv +import os + +MONGO_URI = os.getenv('MONGO_URI', 'None') +MONGO_DB_NAME = os.getenv('MONGO_DB_NAME', 'controls_logs') +if MONGO_URI == 'None': + load_dotenv(dotenv_path=os.path.join(os.path.dirname(__file__), '../', '../', 'Keys', 'keys.env')) + MONGO_URI = os.getenv('MONGO_URI', 'mongodb://localhost:27017/') + + +mongo_client = MongoClient(MONGO_URI) +mongo_db = mongo_client[MONGO_DB_NAME] +logs_collection = mongo_db.logs + +class Log: + collection = mongo_db['logs'] + + @classmethod + def create(cls, action, details, user, level="INFO"): + log_entry = { + "timestamp": datetime.utcnow(), + "action": action, + "details": details, + "user": user, + "level": level + } + result = cls.collection.insert_one(log_entry) + return str(result.inserted_id) + + @classmethod + def find_all(cls, limit=50): + return list(cls.collection.find().sort("timestamp", -1).limit(limit)) + + @classmethod + def find_by_user(cls, user): + return list(cls.collection.find({"user": user}).sort("timestamp", -1)) + diff --git a/backend/Agents/AppAI/CodeBackend/CodeKnowledge/Architectures/Stack1/Back-End/Models/postgreSQL/user.py b/backend/Agents/AppAI/CodeBackend/CodeKnowledge/Architectures/Stack1/Back-End/Models/postgreSQL/user.py new file mode 100644 index 000000000..db1cb2ee0 --- /dev/null +++ b/backend/Agents/AppAI/CodeBackend/CodeKnowledge/Architectures/Stack1/Back-End/Models/postgreSQL/user.py @@ -0,0 +1,39 @@ +# user.py +from flask_sqlalchemy import SQLAlchemy +import bcrypt +from datetime import datetime, timedelta +import secrets +import json +from sqlalchemy import Numeric + +TOKEN_DEFAULT_EXPIRES_DAYS = 30 + +db = SQLAlchemy() + +class User(db.Model): + __tablename__ = 'users' + + id = db.Column(db.Integer, primary_key=True) + user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=True) + email = db.Column(db.String(120), unique=True, nullable=False) + username = db.Column(db.String(80), unique=True, nullable=True) + password_hash = db.Column(db.String(128), nullable=False) + acess_token = db.Column(db.String(255), nullable=True) + created_at = db.Column(db.DateTime, default=datetime.utcnow) + expires_at = db.Column(db.DateTime, nullable=True) + revoked_at = db.Column(db.DateTime, nullable=True) + + def set_password(self, password): + self.password_hash = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8') + + def check_password(self, password): + return bcrypt.checkpw(password.encode('utf-8'), self.password_hash.encode('utf-8')) + + def create_access_token_for_user(self, expires_days: int = TOKEN_DEFAULT_EXPIRES_DAYS): + token = secrets.token_urlsafe(32) + self.acess_token = token + if expires_days: + self.expires_at = datetime.utcnow() + timedelta(days=int(expires_days)) + self.revoked_at = None + return token + \ No newline at end of file diff --git a/backend/Agents/AppAI/CodeBackend/CodeKnowledge/Architectures/Stack1/Back-End/Modules/Config/setup.py b/backend/Agents/AppAI/CodeBackend/CodeKnowledge/Architectures/Stack1/Back-End/Modules/Config/setup.py new file mode 100644 index 000000000..3b221006c --- /dev/null +++ b/backend/Agents/AppAI/CodeBackend/CodeKnowledge/Architectures/Stack1/Back-End/Modules/Config/setup.py @@ -0,0 +1,42 @@ +import logging +import os +from dotenv import load_dotenv + +class Settings: + def __init__(self): + self.ENV = __import__('os').environ.get('FLASK_ENV', 'development') + self.SQLALCHEMY_DATABASE_URI = __import__('os').environ.get('DATABASE_URL', 'postgresql://postgres:postgres@meu_postgres2:5432/meubanco') + self.MONGO_URI = __import__('os').environ.get('MONGO_URI', 'mongodb://root:rootpassword@mongodb:27017/controls_logs?authSource=admin') + self.CELERY_BROKER_URL = __import__('os').environ.get('CELERY_BROKER_URL', 'redis://localhost:6379/0') + self.CELERY_RESULT_BACKEND = __import__('os').environ.get('CELERY_RESULT_BACKEND', 'redis://localhost:6379/0') + self.JWT_SECRET = __import__('os').environ.get('JWT_SECRET', 'supersecret') + self.SECRET_KEY = __import__('os').environ.get('SECRET_KEY', 'your-secret-key-here') + + diretorio_script = os.path.dirname(os.path.abspath(__file__)) + logger = logging.getLogger(__name__) + logger.setLevel(logging.INFO) + formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') + os.makedirs(os.path.join(diretorio_script, '../', '../', 'Logs'), exist_ok=True) + file_handler = logging.FileHandler(os.path.join(diretorio_script, '../', '../', 'Logs', 'api.log')) + file_handler.setFormatter(formatter) + console_handler = logging.StreamHandler() + console_handler.setFormatter(formatter) + logger.addHandler(file_handler) + logger.addHandler(console_handler) + self.logger = logger + + load_dotenv(dotenv_path=os.path.join(os.path.dirname(__file__), '../', '../', "Keys", 'keys.env')) + + + self.INVOICES_DIR = os.path.join(os.path.dirname(__file__), '../', '../', 'Invoices') + os.makedirs(self.INVOICES_DIR, exist_ok=True) + + + self.SMTP_HOST = os.getenv('SMTP_HOST') + self.SMTP_PORT = int(os.getenv('SMTP_PORT', 587)) + self.SMTP_USER = os.getenv('SMTP_USER') + self.SMTP_PASSWORD = os.getenv('SMTP_PASSWORD') + self.use_tls = os.getenv('SMTP_USE_TLS', 'true').lower() == 'true' + + self.STRIPE_SECRET_KEY = os.getenv("STRIPE_SECRET_KEY") + \ No newline at end of file diff --git a/backend/Agents/AppAI/CodeBackend/CodeKnowledge/Architectures/Stack1/Back-End/Modules/Geters/logs.py b/backend/Agents/AppAI/CodeBackend/CodeKnowledge/Architectures/Stack1/Back-End/Modules/Geters/logs.py new file mode 100644 index 000000000..cb8536fe3 --- /dev/null +++ b/backend/Agents/AppAI/CodeBackend/CodeKnowledge/Architectures/Stack1/Back-End/Modules/Geters/logs.py @@ -0,0 +1,91 @@ +# Back-End\Modules\Geters\logs.py + +from Models.mongoDB.logs import logs_collection, mongo_db +from datetime import datetime, timedelta + +def get_recent_logs(user_id=None, limit=10): + """ + Retorna os logs mais recentes. Se user_id fornecido, filtra por user_id ou user. + Cada log terá 'timestamp' como ISO string. + """ + query = {} + if user_id is not None: + query = {"$or": [{"user_id": user_id}, {"user": user_id}]} + + raw = list(logs_collection.find(query).sort("timestamp", -1).limit(limit)) + adapted = [] + for log in raw: + ts = log.get("timestamp") + try: + ts_iso = ts.isoformat() if hasattr(ts, "isoformat") else str(ts) + except Exception: + ts_iso = str(ts) + adapted.append({ + "_id": str(log.get("_id")), + "timestamp": ts_iso, + "level": log.get("level"), + "action": log.get("action"), + "details": log.get("details", {}), + "prNumber": log.get("prNumber") or (log.get("details") or {}).get("pr_number") or (log.get("details") or {}).get("prNumber"), + "user": log.get("user"), + "user_id": log.get("user_id") + }) + return adapted + +def get_logs_by_user(user, limit=50): + """ + Recupera logs por usuário. + """ + return list( + logs_collection.find({"user": user}) + .sort("timestamp", -1) + .limit(limit) + ) + +def get_audit_trail(entity=None, limit=50): + """ + Recupera auditorias do MongoDB. + """ + audit_collection = mongo_db['audit_trail'] + query = {} + if entity: + query["entity"] = entity + + return list( + audit_collection.find(query) + .sort("timestamp", -1) + .limit(limit) + ) + +def get_system_health_recent(limit=50): + """ + Recupera registros recentes de health_check. + """ + system_health_collection = mongo_db['system_health'] + return list( + system_health_collection.find({}) + .sort("timestamp", -1) + .limit(limit) + ) + +def get_system_health_by_user(user_id, limit=50): + """ + Recupera registros de health_check filtrados por usuário. + """ + system_health_collection = mongo_db['system_health'] + return list( + system_health_collection.find({"user_id": user_id}) + .sort("timestamp", -1) + .limit(limit) + ) + +def get_system_health_by_status(status, limit=50): + """ + Recupera registros de health_check filtrados por status (ok, warning, error). + """ + system_health_collection = mongo_db['system_health'] + return list( + system_health_collection.find({"status": status}) + .sort("timestamp", -1) + .limit(limit) + ) \ No newline at end of file diff --git a/backend/Agents/AppAI/CodeBackend/CodeKnowledge/Architectures/Stack1/Back-End/Modules/Geters/user_by_access_token.py b/backend/Agents/AppAI/CodeBackend/CodeKnowledge/Architectures/Stack1/Back-End/Modules/Geters/user_by_access_token.py new file mode 100644 index 000000000..f5afead12 --- /dev/null +++ b/backend/Agents/AppAI/CodeBackend/CodeKnowledge/Architectures/Stack1/Back-End/Modules/Geters/user_by_access_token.py @@ -0,0 +1,8 @@ + +from Models.postgreSQL.user import db, User +from datetime import datetime, timedelta + +def get_user_by_access_token(token_str): + if not token_str: + return None + return User.query.filter_by(acess_token=token_str).first() diff --git a/backend/Agents/AppAI/CodeBackend/CodeKnowledge/Architectures/Stack1/Back-End/Modules/Geters/user_by_email.py b/backend/Agents/AppAI/CodeBackend/CodeKnowledge/Architectures/Stack1/Back-End/Modules/Geters/user_by_email.py new file mode 100644 index 000000000..eae68e25e --- /dev/null +++ b/backend/Agents/AppAI/CodeBackend/CodeKnowledge/Architectures/Stack1/Back-End/Modules/Geters/user_by_email.py @@ -0,0 +1,8 @@ + +from Models.postgreSQL.user import db, User +from datetime import datetime, timedelta + +def get_user_by_email(email): + if not email: + return None + return User.query.filter_by(email=email).first() diff --git a/Back-End/Modules/Resolvers/generate_invoice_pdf.py b/backend/Agents/AppAI/CodeBackend/CodeKnowledge/Architectures/Stack1/Back-End/Modules/Resolvers/generate_invoice_pdf.py similarity index 100% rename from Back-End/Modules/Resolvers/generate_invoice_pdf.py rename to backend/Agents/AppAI/CodeBackend/CodeKnowledge/Architectures/Stack1/Back-End/Modules/Resolvers/generate_invoice_pdf.py diff --git a/Back-End/Modules/Resolvers/send_email.py b/backend/Agents/AppAI/CodeBackend/CodeKnowledge/Architectures/Stack1/Back-End/Modules/Resolvers/send_email.py similarity index 100% rename from Back-End/Modules/Resolvers/send_email.py rename to backend/Agents/AppAI/CodeBackend/CodeKnowledge/Architectures/Stack1/Back-End/Modules/Resolvers/send_email.py diff --git a/backend/Agents/AppAI/CodeBackend/CodeKnowledge/Architectures/Stack1/Back-End/Modules/Resolvers/user_identifier.py b/backend/Agents/AppAI/CodeBackend/CodeKnowledge/Architectures/Stack1/Back-End/Modules/Resolvers/user_identifier.py new file mode 100644 index 000000000..e32ebb558 --- /dev/null +++ b/backend/Agents/AppAI/CodeBackend/CodeKnowledge/Architectures/Stack1/Back-End/Modules/Resolvers/user_identifier.py @@ -0,0 +1,112 @@ +# Back-End\Modules\Resolvers\user_identifier.py +from datetime import datetime, timedelta +from functools import wraps +from flask import g, Flask, Response, request, jsonify +import logging +from Modules.Savers.log_action import log_action +from Modules.Geters.user_by_access_token import get_user_by_access_token +from Models.mongoDB.logs import ( + Log, + logs_collection, + mongo_client, + mongo_db, + ) +from Models.postgreSQL.user import db, User + +logging.basicConfig( + level=logging.INFO, + format="%(asctime)s [%(levelname)s] %(message)s", + handlers=[ + logging.StreamHandler() + ] +) +logger = logging.getLogger(__name__) + +def auth_user(logs_collection, app, email='', password=''): + with app.app_context(): + header_token = request.headers.get('X-API-TOKEN') + + user = None + if header_token: + try: + user = get_user_by_access_token(header_token) + if user: + logger.info(f"auth_user login sucess") + return user, user.id, "success" + else: + logger.info(f"auth_user invalid token") + + user = resolve_user_identifier(email) + # evita usar user.id quando user é None (corrige crash no log) + if not user or not user.check_password(password): + log_action(logs_collection, 'login_failed', {'message': 'login_failed in if not user or not user.check_password(password):'}, level='warning', user=(user.id if user else None)) + return None, None, "invalid" + else: + logger.info(f"auth_user login sucess") + return user, user.id, "success" + + except Exception as e: + logger.info(f"auth_user_error {e}") + log_action( + logs_collection, + 'auth_user_error', + {'message': str(e)}, + level='warning' + ) + return None, None, "invalid" + + if not user: + return None, None, "invalid" + + return user, user.id, "success" + +def resolve_user_identifier(identifier): + """ + Aceita: + - None -> retorna None + - número (string ou int) -> busca por id + - string com @ -> busca por email + - string sem @ -> tenta converter para int, senão retorna None + Retorna User instance ou None. + """ + if not identifier: + return None + + try: + uid = int(identifier) + return User.query.get(uid) + except (ValueError, TypeError): + pass + + if isinstance(identifier, str) and "@" in identifier: + return User.query.filter_by(email=identifier).first() + + return User.query.filter_by(email=str(identifier).strip()).first() + +def is_token_revoked_or_expired(user: User): + if not user: + log_action(logs_collection, 'is_token_revoked_or_expired', {'message': "Usuário não encontrado"}, user=None) + + return True, "Usuário não encontrado" + if user.revoked_at is not None: + log_action(logs_collection, 'is_token_revoked_or_expired', {'username': user.email, 'message': "Token revogado"}, user=user.id) + + return True, "Token revogado" + if user.expires_at is not None: + try: + if datetime.utcnow() > user.expires_at: + log_action(logs_collection, 'is_token_revoked_or_expired', {'username': user.email, 'message': "Token expirado"}, user=user.id) + + return True, "Token expirado" + except Exception as err_unkwnow: + log_action(logs_collection, 'is_token_revoked_or_expired', {'username': user.email, 'message': f"err_unkwnow {err_unkwnow}"}, user=user.id) + + if not user.acess_token: + log_action(logs_collection, 'is_token_revoked_or_expired', {'username': user.email, 'message': "Usuário sem access token"}, user=user.id) + + return True, "Usuário sem access token" + return False, None + +def check_user_quota(user: User, required_tokens: int): + remaining = (user.limit_monthly_tokens or 0) - (user.tokens_used or 0) + return remaining >= required_tokens, remaining \ No newline at end of file diff --git a/backend/Agents/AppAI/CodeBackend/CodeKnowledge/Architectures/Stack1/Back-End/Modules/Routes/auth.py b/backend/Agents/AppAI/CodeBackend/CodeKnowledge/Architectures/Stack1/Back-End/Modules/Routes/auth.py new file mode 100644 index 000000000..435098431 --- /dev/null +++ b/backend/Agents/AppAI/CodeBackend/CodeKnowledge/Architectures/Stack1/Back-End/Modules/Routes/auth.py @@ -0,0 +1,74 @@ +from flask import Blueprint, request, jsonify +from Models.postgreSQL.user import User, TOKEN_DEFAULT_EXPIRES_DAYS +from Modules.Savers.log_action import log_action +from Models.mongoDB.logs import ( + Log, + logs_collection, + mongo_client, + mongo_db, + ) +from Modules.Resolvers.user_identifier import auth_user + + +from api import db, app + +auth_bp = Blueprint('auth', __name__) + +@auth_bp.route('/register', methods=['POST']) +def register(): + """ + Registro simples: cria usuário, seta senha e cria acess_token, persiste. + """ + data = request.get_json() or {} + email = data.get("email") + password = data.get("password") + expires_days = data.get("expires_days", None) # opcional + + if not email or not password: + return jsonify({"error": "Email e senha são obrigatórios"}), 400 + if User.query.filter_by(email=email).first(): + return jsonify({"error": "Usuário já existe"}), 400 + try: + new_user = User(email=email) + new_user.set_password(password) + acess_token = new_user.create_access_token_for_user(expires_days if expires_days is not None else TOKEN_DEFAULT_EXPIRES_DAYS) + db.session.add(new_user) + db.session.commit() + log_action(logs_collection, 'user_registered', {'message': "Usuário criado com sucesso", 'username': email}) + + return jsonify({ + "message": "Usuário criado com sucesso", + "acess_token": acess_token, + "user_id": new_user.id, + "expires_at": new_user.expires_at.isoformat() if new_user.expires_at else None + }), 201 + except Exception as e: + db.session.rollback() + log_action(logs_collection, 'register_error', {'username': email, 'message': str(e)}, level='error') + return jsonify({'error': 'Failed to register user', 'detail': str(e)}), 500 + +@auth_bp.route('/login', methods=['GET']) +def login(): + try: + email = request.args.get('email') + password = request.args.get('password') + user, access_token_to_return, status = auth_user(logs_collection, app, email, password) + + if status == "invalid" or not user: + return jsonify({"error": "Credenciais inválidas"}), 401 + + log_action(logs_collection, 'login_success', {'message': f"Bem-vindo, {user.email}!"}, user=user.id) + return jsonify({ + "message": f"Bem-vindo, {user.email}!", + "acess_token": user.acess_token, + "user_id": user.id, + "plan_name": user.plan_name, + "limit_monthly_tokens": user.limit_monthly_tokens, + "tokens_used": user.tokens_used, + "expires_at": user.expires_at.isoformat() if user.expires_at else None + }), 200 + + except Exception as error_login: + db.session.rollback() + log_action(logs_collection, f'login_error {error_login}', {'message': 'Erro no login'}, level='error') + return jsonify({"error": "Erro no login"}), 500 diff --git a/Back-End/Modules/Savers/log_action.py b/backend/Agents/AppAI/CodeBackend/CodeKnowledge/Architectures/Stack1/Back-End/Modules/Savers/log_action.py similarity index 100% rename from Back-End/Modules/Savers/log_action.py rename to backend/Agents/AppAI/CodeBackend/CodeKnowledge/Architectures/Stack1/Back-End/Modules/Savers/log_action.py diff --git a/backend/Agents/AppAI/CodeBackend/CodeKnowledge/Architectures/Stack1/Back-End/Modules/Savers/log_audit.py b/backend/Agents/AppAI/CodeBackend/CodeKnowledge/Architectures/Stack1/Back-End/Modules/Savers/log_audit.py new file mode 100644 index 000000000..52c6246ec --- /dev/null +++ b/backend/Agents/AppAI/CodeBackend/CodeKnowledge/Architectures/Stack1/Back-End/Modules/Savers/log_audit.py @@ -0,0 +1,21 @@ +# Back-End\Modules\Savers\log_audit.py + +from datetime import datetime, timedelta +from Models.mongoDB.audit import mongo_db + +audit_collection = mongo_db['audit_trail'] + +def log_audit(entity, action, user=None, metadata=None): + """ + Registra uma auditoria no MongoDB (coleção audit_trail). + """ + entry = { + "entity": entity, + "action": action, + "user": user, + "metadata": metadata or {}, + "timestamp": datetime.utcnow() + } + result = audit_collection.insert_one(entry) + return str(result.inserted_id) + diff --git a/backend/Agents/AppAI/CodeBackend/CodeKnowledge/Architectures/Stack1/Back-End/Modules/Savers/log_system_health.py b/backend/Agents/AppAI/CodeBackend/CodeKnowledge/Architectures/Stack1/Back-End/Modules/Savers/log_system_health.py new file mode 100644 index 000000000..bb835e174 --- /dev/null +++ b/backend/Agents/AppAI/CodeBackend/CodeKnowledge/Architectures/Stack1/Back-End/Modules/Savers/log_system_health.py @@ -0,0 +1,23 @@ +# Back-End\Modules\Savers\log_system_health.py +from datetime import datetime, timedelta +from Models.mongoDB.logs import mongo_db + +system_health_collection = mongo_db['system_health'] + +def log_system_health(user_id, health_status: dict): + """ + Registra status de saúde do sistema no MongoDB (coleção system_health). + """ + entry = { + "user_id": user_id, + "timestamp": datetime.utcnow(), + "postgres_status": health_status.get("postgres_connected", False), + "mongodb_status": health_status.get("mongodb_connected", False), + "github_status": health_status.get("github_api_reachable", False), + "openai_status": health_status.get("openai_api_reachable", False), + "status": health_status.get("status", "unknown"), + "message": health_status.get("message", ""), + "details": health_status + } + result = system_health_collection.insert_one(entry) + return str(result.inserted_id) diff --git a/backend/Agents/AppAI/CodeBackend/CodeKnowledge/Architectures/Stack1/Back-End/api.py b/backend/Agents/AppAI/CodeBackend/CodeKnowledge/Architectures/Stack1/Back-End/api.py new file mode 100644 index 000000000..f19da81c6 --- /dev/null +++ b/backend/Agents/AppAI/CodeBackend/CodeKnowledge/Architectures/Stack1/Back-End/api.py @@ -0,0 +1,64 @@ +# app.py +import os +import threading +import requests +import json +import stripe +import asyncio +from decimal import Decimal +from bson.json_util import dumps +from datetime import datetime, timedelta, timezone +import hmac +import hashlib +from flask import g, Flask, Response, request, jsonify, send_file, abort, redirect +from flask_cors import CORS +from asgiref.wsgi import WsgiToAsgi +from flask_limiter import Limiter +from flask_limiter.util import get_remote_address + + +from Models.postgreSQL.user import db +from Modules.Config.setup import Settings +from Modules.Routes.auth import auth_bp + +app = Flask(__name__) +asgi_app = WsgiToAsgi(app) +settings = Settings() + +app.config['SQLALCHEMY_DATABASE_URI'] = settings.SQLALCHEMY_DATABASE_URI +app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False +app.config['JWT_SECRET'] = settings.JWT_SECRET +app.config['MONGO_URI'] = settings.MONGO_URI +app.config['SECRET_KEY'] = settings.SECRET_KEY + +INVOICES_DIR = settings.INVOICES_DIR +SMTP_HOST = settings.SMTP_HOST +SMTP_PORT = settings.SMTP_PORT +SMTP_USER = settings.SMTP_USER +SMTP_PASSWORD = settings.SMTP_PASSWORD +use_tls = settings.use_tls +stripe.api_key = settings.STRIPE_SECRET_KEY + +if os.getenv("FLASK_ENV") == "development": + CORS(app, origins=os.getenv("FRONTEND_ORIGINS", "*").split(","), supports_credentials=True) + +limiter = Limiter( + get_remote_address, + app=app, + default_limits=[] +) + +db.init_app(app) + +@app.route('/') +def index(): + return jsonify({ + "message": "Backend Flask - API Principal", + "version": "1.0", + "database": "PostgreSQL + MongoDB", + "status": "running" + }) + + +app.register_blueprint(auth_bp, url_prefix='/auth') + diff --git a/backend/Agents/AppAI/CodeBackend/CodeKnowledge/Architectures/Stack1/Back-End/requirements.txt b/backend/Agents/AppAI/CodeBackend/CodeKnowledge/Architectures/Stack1/Back-End/requirements.txt new file mode 100644 index 000000000..e69de29bb diff --git a/backend/Agents/AppAI/CodeBackend/CodeKnowledge/Architectures/Stack1/Readme.md b/backend/Agents/AppAI/CodeBackend/CodeKnowledge/Architectures/Stack1/Readme.md new file mode 100644 index 000000000..6385bac87 --- /dev/null +++ b/backend/Agents/AppAI/CodeBackend/CodeKnowledge/Architectures/Stack1/Readme.md @@ -0,0 +1,8 @@ +### 🧠 Diretrizes de tecnologia: +**Banco de dados:** PostgreSQL para dados, MongoDB Para logs +**Back End:** Flask + blueprint para api +**Front End:** Vite + React +**Filas e Agendamentos:** Celery + Redis +**Autenticação/Autorização:** Funcao propria do sistema que verifica se o usuario esta registrado no sistema, nao há necessidade de jwt +**Pagamentos:** Stripe (planos, subscriptions, webhooks) +**Observabilidade:** logs MongoDB centralizados, deploy com CI/CD via Git Actions diff --git a/build.py b/backend/Agents/AppAI/CodeBackend/CodeKnowledge/Architectures/Stack1/build.py similarity index 100% rename from build.py rename to backend/Agents/AppAI/CodeBackend/CodeKnowledge/Architectures/Stack1/build.py diff --git a/backend/Agents/AppAI/CodeBackend/CodeKnowledge/Architectures/Stack1/docker-compose.yml b/backend/Agents/AppAI/CodeBackend/CodeKnowledge/Architectures/Stack1/docker-compose.yml new file mode 100644 index 000000000..efcb512a3 --- /dev/null +++ b/backend/Agents/AppAI/CodeBackend/CodeKnowledge/Architectures/Stack1/docker-compose.yml @@ -0,0 +1,124 @@ + +version: '3.8' +services: + + meu_postgres2: + image: postgres:15 + container_name: meu_postgres2 + restart: always + environment: + POSTGRES_USER: postgres + POSTGRES_PASSWORD: postgres + POSTGRES_DB: meubanco + ports: + - "5932:5432" + networks: + - rede_externa + volumes: + - postgres_data:/var/lib/postgresql/data + mem_limit: 1g + cpus: "0.8" + + mongodb: + image: mongo:7 + environment: + MONGO_INITDB_ROOT_USERNAME: root + MONGO_INITDB_ROOT_PASSWORD: rootpassword + MONGO_INITDB_DATABASE: controls_logs + ports: + - "21017:21017" + restart: always + volumes: + - mongodb_data:/data/db + - ./mongo-init.js:/docker-entrypoint-initdb.d/mongo-init.js:ro + healthcheck: + test: ["CMD", "mongosh", "--eval", "db.adminCommand('ping')"] + interval: 30s + timeout: 10s + retries: 3 + networks: + - rede_externa + mem_limit: 1g + cpus: "0.8" + + redis: + image: redis:7-alpine + ports: + - "6189:6379" + command: redis-server --appendonly yes + restart: always + volumes: + - redis_data:/data + healthcheck: + test: ["CMD", "redis-cli", "ping"] + interval: 30s + timeout: 10s + retries: 3 + networks: + - rede_externa + mem_limit: 100MB + cpus: "0.3" + + nomedoapp_frontend: + image: nomedoapp-frontend-server:latest + build: + context: ./Front-End + dockerfile: Dockerfile + container_name: nomedoapp_frontend + working_dir: /app + environment: + - CHOKIDAR_USEPOLLING=true + - CHOKIDAR_INTERVAL=100 + ports: + - "4494:4494" + restart: always + command: > + sh -c "npm ci && npm run build && npx serve -s dist -l 4494" + + healthcheck: + test: ["CMD", "curl", "-f", "http://127.0.0.1:4494"] + interval: 129s + timeout: 2s + retries: 5 + mem_limit: 850MB + cpus: "0.8" + + nomedoapp_api: + image: nomedoapp-api-server:latest + build: + context: ./Back-End + dockerfile: Dockerfile + container_name: nomedoapp_api + working_dir: /app + privileged: true + volumes: + - /var/run/docker.sock:/var/run/docker.sock + restart: always + ports: + - "4941:4941" + command: > + sh -c "uvicorn api:asgi_app --host 0.0.0.0 --port 4941" + environment: + - FLASK_ENV=development + - DATABASE_URL=postgresql://postgres:postgres@meu_postgres2:5432/meubanco + - MONGO_URI=mongodb://root:rootpassword@mongodb:27017/controls_logs?authSource=admin + - REDIS_URL=redis://redis:6189/0 + depends_on: + - meu_postgres2 + - mongodb + - redis + mem_limit: 850MB + cpus: "0.80" + networks: + - rede_externa + +networks: + rede_externa: + external: true + +volumes: + postgres_data: + mongodb_data: + logger_data: + redis_data: + npm-modules: \ No newline at end of file diff --git a/backend/Agents/AppAI/CodeBackend/CodeKnowledge/Docs/folder_convetions.md b/backend/Agents/AppAI/CodeBackend/CodeKnowledge/Docs/folder_convetions.md new file mode 100644 index 000000000..246f49c28 --- /dev/null +++ b/backend/Agents/AppAI/CodeBackend/CodeKnowledge/Docs/folder_convetions.md @@ -0,0 +1,83 @@ +``` +nomedoprojeto\ +├── Readme.md +├── docker-compose.yml +└── .github\ + └── workflows\ + ├── deploy.yml +└── Front-End\ + └── vite.config.ts + └── tsconfig.node.json + └── tsconfig.json + └── tsconfig.app.json + └── tailwind.config.ts + └── postcss.config.js + └── package.json + └── Dockerfile + └── package-lock.json + └── index.html + └── eslint.config.js + └── components.json + └── .env + └── public\ + └── src\ + └── components\ + ├── ... + └── constants\ + ├── ... + └── contexts\ + ├── ... + └── hooks\ + ├── ... + └── lib\ + ├── ... + └── pages\ + ├── Login.tsx + ├── ... + └── App.css + └── App.tsx + └── index.css + └── main.tsx + └── vite-env.d.ts + +└── Back-End\ + ├── requirements.txt + ├── Dockerfile + ├── api.py + └── Keys\ + ├── keys.env + └── Models\ + └── mongoDB\ + ├── audit.py + ├── logs.py + └── postgreSQL\ + ├── user.py + ├── ... + └── Modules\ + └── Config\ + ├── setup.py + ├── ... + └── Geters\ + ├── logs.py + ├── user_by_access_token.py + ├── user_by_email.py + ├── ... + └── Helpers\ + ├── ... + └── Resolvers\ + ├── generate_invoice_pdf.py + ├── send_email.py + ├── user_identifier.py + ├── ... + └── Routes\ + ├── auth.py + ├── ... + └── Savers\ + ├── log_action.py + ├── log_audit.py + ├── log_system_health.py + ├── ... + └── Updaters\ + ├── ... + +``` diff --git a/backend/Agents/AppAI/CodeBackend/CodeKnowledge/_Test_embedings.py b/backend/Agents/AppAI/CodeBackend/CodeKnowledge/_Test_embedings.py new file mode 100644 index 000000000..c4ff8932c --- /dev/null +++ b/backend/Agents/AppAI/CodeBackend/CodeKnowledge/_Test_embedings.py @@ -0,0 +1,101 @@ +# requirements: openai, openai-agents, chromadb, tiktoken (opcional) +# pip install openai openai-agents chromadb + +import os +from agents import Agent, Runner, function_tool, SQLiteSession +import openai +import chromadb +from chromadb.config import Settings +from dotenv import load_dotenv +from openai import OpenAI + + +os.chdir(os.path.join(os.path.dirname(__file__))) +load_dotenv(dotenv_path=os.path.join(os.path.dirname(__file__), '../', '../', '../', '../', 'Keys', 'keys.env')) + +OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY") +openai.api_key = OPENAI_API_KEY +client = OpenAI(api_key=OPENAI_API_KEY) + +# ---------- 1) Indexador simples: chunk + embeddings -> Chroma ---------- +def chunk_text(text, max_chars=1000): + # simples: quebrar por parágrafos ou janelas deslizantes + paragraphs = [p.strip() for p in text.split("\n\n") if p.strip()] + chunks = [] + cur = "" + for p in paragraphs: + if len(cur) + len(p) + 1 > max_chars: + if cur: + chunks.append(cur) + cur = p + else: + cur = (cur + "\n\n" + p).strip() if cur else p + if cur: chunks.append(cur) + return chunks + + + +def embed_texts(texts): + response = client.embeddings.create( + model="text-embedding-3-small", + input=texts + ) + return [item.embedding for item in response.data] + +def build_or_update_index(doc_id, full_text, chroma_dir="./chroma_store"): + # novo cliente persistente (substitui chromadb.Client(Settings(...))) + client = chromadb.PersistentClient(path=chroma_dir) + + collection = client.get_or_create_collection(name="backend_skeleton") + + # divide e embeda + chunks = chunk_text(full_text, max_chars=800) + embeddings = embed_texts(chunks) + ids = [f"{doc_id}__{i}" for i in range(len(chunks))] + metadatas = [{"doc_id": doc_id, "chunk_index": i} for i in range(len(chunks))] + + collection.add( + documents=chunks, + embeddings=embeddings, + ids=ids, + metadatas=metadatas + ) + print(f"Indexed {len(chunks)} chunks from {doc_id}") +# ---------- 2) Tool retriever: função registrada no SDK ---------- +@function_tool +def retrieve_backend_context(query: str, k: int = 4) -> str: + client_chroma = chromadb.PersistentClient(path="./chroma_store") + collection = client_chroma.get_collection("backend_skeleton") + + q_emb = client.embeddings.create( + model="text-embedding-3-small", + input=[query] + ).data[0].embedding + + results = collection.query( + query_embeddings=[q_emb], + n_results=k, + include=["documents", "metadatas"] + ) + + docs = results["documents"][0] + joined = "\n\n---\n\n".join(docs) + return f"Contexto recuperado (top {k}):\n\n{joined}" + +# # ---------- 3) Agente + sessão + runner ---------- +# agent = Agent( +# name="BackendExpert", +# instructions="Você é um especialista backend. Use as ferramentas quando precisar recuperar regras/estrutura do projeto.", +# tools=[retrieve_backend_context] +# ) + +# # usar SQLiteSession (memória persistente entre turns) +# session = SQLiteSession("agent_session_backend_01", db_path="embeddings.db") + +# # entrada do usuário +# user_input = "Como eu crio o endpoint de login seguindo a stack padrão do projeto?" + +# # rodar (Runner vai permitir tool calls automaticamente) +# result = Runner.run_sync(agent, user_input, session=session, max_turns=6) + +# print("Resposta final do agente:\n", result.final_output) diff --git a/backend/Agents/AppAI/CodeBackend/CodeKnowledge/_Test_index_skeleton.py b/backend/Agents/AppAI/CodeBackend/CodeKnowledge/_Test_index_skeleton.py new file mode 100644 index 000000000..c3a90506c --- /dev/null +++ b/backend/Agents/AppAI/CodeBackend/CodeKnowledge/_Test_index_skeleton.py @@ -0,0 +1,98 @@ +""" +Script: index_skeleton.py +Função: Indexar automaticamente todos os arquivos do esqueleto backend (core/, services/, routes/, etc) +para o vetor store Chroma (./chroma_store). + +Requisitos: + pip install openai openai-agents chromadb +Execução: + python index_skeleton.py +""" + +import os +import sys +import openai +import chromadb +from chromadb.config import Settings +from pathlib import Path + +# Importa a função que você já tem +from _Test_embedings import build_or_update_index # ajuste o caminho se necessário +from dotenv import load_dotenv + +os.chdir(os.path.join(os.path.dirname(__file__))) +load_dotenv(dotenv_path=os.path.join(os.path.dirname(__file__), '../', '../', '../', '../', 'Keys', 'keys.env')) + +# ---------- CONFIGURAÇÕES ---------- +OPENAI_API_KEY = os.getenv("OPENAI_API_KEY") +if not OPENAI_API_KEY: + print("❌ ERRO: variável OPENAI_API_KEY não definida.") + sys.exit(1) + +openai.api_key = OPENAI_API_KEY + +# diretórios padrão do seu backend +TARGET_DIRS = ["Architectures/Stack1", 'Docs'] + +# extensões de código relevantes +ALLOWED_EXTS = [".py", ".json", ".yml", ".yaml", ".toml", ".md"] + +# tamanho máximo por arquivo em bytes (para evitar binários ou logs enormes) +MAX_FILE_SIZE = 200_000 # ~200 KB + +# diretório base +BASE_DIR = Path(__file__).resolve().parent + + +# ---------- FUNÇÃO PRINCIPAL ---------- +def collect_files(base_dir: Path): + """Percorre os diretórios alvo e retorna lista de arquivos válidos""" + all_files = [] + for folder in TARGET_DIRS: + path = base_dir / folder + if not path.exists(): + print(f"⚠️ Diretório {folder}/ não encontrado, ignorando...") + continue + + for root, _, files in os.walk(path): + for f in files: + full_path = Path(root) / f + if full_path.suffix.lower() not in ALLOWED_EXTS: + continue + if full_path.stat().st_size > MAX_FILE_SIZE: + print(f"⚠️ Ignorando arquivo muito grande: {full_path.name}") + continue + if "__pycache__" in full_path.parts or f.startswith("."): + continue + all_files.append(full_path) + return all_files + + +def index_repository(): + """Percorre todos os arquivos e adiciona ao índice""" + files = collect_files(BASE_DIR) + if not files: + print("❌ Nenhum arquivo encontrado para indexar.") + return + + total_chunks = 0 + print(f"📂 Encontrados {len(files)} arquivos para indexar...") + + for file_path in files: + try: + with open(file_path, "r", encoding="utf-8") as f: + content = f.read().strip() + if not content: + continue + doc_id = str(file_path.relative_to(BASE_DIR)) + build_or_update_index(doc_id, content) + print(f"✅ Indexado: {doc_id}") + except Exception as e: + print(f"⚠️ Falha ao processar {file_path}: {e}") + + print("✅ Indexação concluída com sucesso!") + print(f"🧠 Dados salvos no diretório: ./chroma_store") + + +if __name__ == "__main__": + index_repository() diff --git a/backend/Agents/AppAI/CodeBackend/CodeKnowledge/chroma_store/2ed8a0d6-aedd-45cd-9366-a8c73d87e45d/data_level0.bin b/backend/Agents/AppAI/CodeBackend/CodeKnowledge/chroma_store/2ed8a0d6-aedd-45cd-9366-a8c73d87e45d/data_level0.bin new file mode 100644 index 000000000..127a6da40 Binary files /dev/null and b/backend/Agents/AppAI/CodeBackend/CodeKnowledge/chroma_store/2ed8a0d6-aedd-45cd-9366-a8c73d87e45d/data_level0.bin differ diff --git a/backend/Agents/AppAI/CodeBackend/CodeKnowledge/chroma_store/2ed8a0d6-aedd-45cd-9366-a8c73d87e45d/header.bin b/backend/Agents/AppAI/CodeBackend/CodeKnowledge/chroma_store/2ed8a0d6-aedd-45cd-9366-a8c73d87e45d/header.bin new file mode 100644 index 000000000..2349a18e8 Binary files /dev/null and b/backend/Agents/AppAI/CodeBackend/CodeKnowledge/chroma_store/2ed8a0d6-aedd-45cd-9366-a8c73d87e45d/header.bin differ diff --git a/backend/Agents/AppAI/CodeBackend/CodeKnowledge/chroma_store/2ed8a0d6-aedd-45cd-9366-a8c73d87e45d/length.bin b/backend/Agents/AppAI/CodeBackend/CodeKnowledge/chroma_store/2ed8a0d6-aedd-45cd-9366-a8c73d87e45d/length.bin new file mode 100644 index 000000000..659918b60 --- /dev/null +++ b/backend/Agents/AppAI/CodeBackend/CodeKnowledge/chroma_store/2ed8a0d6-aedd-45cd-9366-a8c73d87e45d/length.bin @@ -0,0 +1 @@ +invalid type: string "@auth_bp.route('/login', methods=['GET'])\ndef login():\n try:\n email = request.args.get('email')\n password = request.args.get('password')\n user, access_token_to_return, status = auth_user(logs_collection, app, email, password)\n\nif status == \"invalid\" or not user:\n return jsonify({\"error\": \"Credenciais inválidas\"}), 401"/login\n \ No newline at end of file diff --git a/backend/Agents/AppAI/CodeBackend/CodeKnowledge/chroma_store/2ed8a0d6-aedd-45cd-9366-a8c73d87e45d/link_lists.bin b/backend/Agents/AppAI/CodeBackend/CodeKnowledge/chroma_store/2ed8a0d6-aedd-45cd-9366-a8c73d87e45d/link_lists.bin new file mode 100644 index 000000000..e69de29bb diff --git a/backend/Agents/AppAI/CodeBackend/CodeKnowledge/chroma_store/chroma.sqlite3 b/backend/Agents/AppAI/CodeBackend/CodeKnowledge/chroma_store/chroma.sqlite3 new file mode 100644 index 000000000..b8e2b01e1 Binary files /dev/null and b/backend/Agents/AppAI/CodeBackend/CodeKnowledge/chroma_store/chroma.sqlite3 differ diff --git a/backend/Agents/AppAI/CodeBackend/Sessions/session_1.db b/backend/Agents/AppAI/CodeBackend/Sessions/session_1.db new file mode 100644 index 000000000..b1229db1e Binary files /dev/null and b/backend/Agents/AppAI/CodeBackend/Sessions/session_1.db differ diff --git a/backend/Agents/AppAI/CodeBackend/ai.py b/backend/Agents/AppAI/CodeBackend/ai.py new file mode 100644 index 000000000..b3568862d --- /dev/null +++ b/backend/Agents/AppAI/CodeBackend/ai.py @@ -0,0 +1,238 @@ +# Back-End\Agents\GitContextLayer\ai.py +from agents import Agent, Runner, ModelSettings +import logging +import os +from pydantic import BaseModel +from typing import List + +import os +from agents import Agent, Runner, function_tool, SQLiteSession +import openai +import chromadb +from chromadb.config import Settings +from dotenv import load_dotenv +from openai import OpenAI + + +from Functions.autosave.autosave import autosave +from Functions.autolistlocalproject.autolistlocalproject import autolistlocalproject +from Functions.retrieve_backend_context.retrieve_backend_context import retrieve_backend_context + + +logging.basicConfig(level=logging.INFO) +logger = logging.getLogger("SprintsPlanner_logger") + +class CodeBackEndAgentOutput(BaseModel): + saved_files: List[str] + + +async def CodeBackEndAgent( + OPENAI_API_KEY, + user_id, + tipo_app, + descricao, + user_content, + commit_language = 'pt', + model = "gpt-5-nano", + local_to_save = "./", + + ): + os.environ['OPENAI_API_KEY'] = OPENAI_API_KEY + os.makedirs(os.path.join(os.path.dirname(__file__), 'Sessions'), exist_ok=True) + logger.info(f"CodeBackEndAgent Agent") + name_chroma_store = "backend_skeleton" + chroma_store = os.path.join(os.path.dirname(__file__), 'CodeKnowledge', 'chroma_store') + + total_usage = { + "input": 0, "cached": 0, "reasoning": 0, "output": 0, "total": 0 + } + logger.info(f"language {commit_language}") + + if commit_language == 'en': + prompt_system_direct = f""" + + """ + + elif commit_language == 'pt': + prompt_system_direct = f""" +# IDENTIDADE E CONTEXTO +Você é um desenvolvedor backend sênior especializado em Python/Flask, responsável por implementar tarefas de backend de forma autônoma e eficiente. + +## INFORMAÇÕES DO PROJETO +- **Tipo**: {tipo_app} +- **Descrição**: {descricao} +- **Diretório Base**: {local_to_save} +- **Stack Tecnológica**: Flask (blueprints), SQLAlchemy (PostgreSQL), MongoDB (logs), Celery+Redis, Pydantic Settings + +--- + +# FLUXO DE TRABALHO OBRIGATÓRIO + +## 1️⃣ ANÁLISE INICIAL (SEMPRE EXECUTAR PRIMEIRO) +Antes de qualquer implementação, você DEVE: + +### A) Listar Estado Atual do Projeto + +{{ + "autolistlocalproject": {{ + "path_project": "{local_to_save}" + }} +}} +Objetivo: Mapear arquivos existentes, estrutura de diretórios e evitar conflitos. +B) Consultar Base de Conhecimento +json{{ + "retrieve_backend_context": {{ + "query": "[descreva claramente o que precisa: ex: 'padrões de autenticação JWT', 'estrutura de models SQLAlchemy']", + "k": 8, + "path": "{chroma_store}", + "name": "{name_chroma_store}" + }} +}} +Quando usar: + +Antes de criar novos endpoints +Ao definir schemas de banco de dados +Para decisões arquiteturais (autenticação, validação, etc.) + + +2️⃣ DESENVOLVIMENTO E SALVAMENTO +Regras de Implementação +✅ SEMPRE: + +Use nomenclatura clara e descritiva (snake_case para arquivos/funções) +Implemente tratamento de erros com logging adequado +Adicione docstrings em todas as funções/classes +Siga padrões RESTful para APIs +Use type hints (Python 3.10+) +Valide inputs com Pydantic models + +❌ NUNCA: + +Hardcode credenciais ou secrets +Crie arquivos fora de {local_to_save} +Sobrescreva arquivos sem verificar o conteúdo atual via autolistlocalproject + +Estrutura de Diretórios Padrão +{local_to_save}/ +├── app/ +│ ├── __init__.py +│ ├── models/ # SQLAlchemy models +│ ├── routes/ # Flask blueprints +│ ├── schemas/ # Pydantic schemas +│ ├── services/ # Business logic +│ └── utils/ # Helpers +├── tasks/ # Celery tasks +├── config/ # Settings (BaseSettings) +├── tests/ # Testes unitários +└── manifest.json # Metadata do projeto +Salvamento de Arquivos +Para cada arquivo implementado: +json{{ + "autosave": {{ + "code": "# Conteúdo completo do arquivo aqui\n# Inclua imports, docstrings, type hints\n\nfrom flask import Blueprint\n\nauth_bp = Blueprint('auth', __name__)\n\n@auth_bp.route('/login', methods=['POST'])\ndef login():\n \"\"\"Endpoint de autenticação.\"\"\"\n pass", + "path": "{local_to_save}/app/routes/auth.py" + }} +}} + +3️⃣ ATUALIZAÇÃO DO MANIFEST +Após salvar arquivos, atualize {local_to_save}/manifest.json: +json{{ + "autosave": {{ + "code": "{{\n \"project_name\": \"{tipo_app}\",\n \"last_update\": \"2025-10-07T10:30:00Z\",\n \"files\": [\n {{\n \"path\": \"app/routes/auth.py\",\n \"size_bytes\": 1024,\n \"created_at\": \"2025-10-07T10:30:00Z\"\n }}\n ]\n}}", + "path": "{local_to_save}/manifest.json" + }} +}} + +FORMATO DE RESPOSTA FINAL +Após concluir todas as etapas, retorne SOMENTE este JSON (sem texto adicional): +json{{ + "analysis_summary": {{ + "existing_files": ["lista de arquivos encontrados no autolistlocalproject"], + "knowledge_retrieved": "resumo breve do que foi consultado no retrieve_backend_context" + }}, + "implementation_details": {{ + "approach": "breve descrição da estratégia de implementação", + "stack_decisions": ["Flask blueprints", "SQLAlchemy models", "Pydantic validation"] + }}, + "saved_files": [ + "{local_to_save}/app/routes/auth.py", + "{local_to_save}/app/models/user.py", + "{local_to_save}/manifest.json" + ], + "next_steps": [ + "Configurar variáveis de ambiente no .env", + "Executar migrações do banco de dados" + ] +}} + +EXEMPLOS DE USO DAS FERRAMENTAS +Exemplo 1: Criar Endpoint de Autenticação +Sequência: + +autolistlocalproject → Verificar se já existe app/routes/auth.py +retrieve_backend_context → query: "melhores práticas JWT Flask" +autosave → Criar app/routes/auth.py com blueprint +autosave → Criar app/schemas/auth.py com Pydantic models +autosave → Atualizar manifest.json + +Exemplo 2: Implementar Model de Usuário +Sequência: + +autolistlocalproject → Mapear models existentes +retrieve_backend_context → query: "schema usuário autenticação PostgreSQL" +autosave → Criar app/models/user.py com SQLAlchemy +autosave → Atualizar manifest.json + + +CHECKLIST PRÉ-RESPOSTA +Antes de enviar o JSON final, confirme: + + Executei autolistlocalproject? + Consultei retrieve_backend_context para decisões importantes? + Todos os arquivos foram salvos via autosave? + O manifest.json foi atualizado? + O JSON de resposta está válido e completo? + +COMECE AGORA: Execute autolistlocalproject e retrieve_backend_context antes de qualquer implementação. + + """ + + imported_tools = [autosave, retrieve_backend_context, autolistlocalproject] + + session = SQLiteSession("agent_session_backend_01", db_path=os.path.join(os.path.dirname(__file__), 'Sessions', f"session_{user_id}.db")) + + agent = Agent( + name="Agent Code BackEnd", + instructions=prompt_system_direct, + model=model, + output_type=CodeBackEndAgentOutput, + model_settings=ModelSettings(include_usage=True), + tools=imported_tools + ) + result = await Runner.run( + agent, + user_content, + max_turns=300, + session=session + ) + final_output = result.final_output + saved_files = final_output.saved_files + + usage = result.context_wrapper.usage + total_usage["input"] = usage.input_tokens + total_usage["cached"] = usage.input_tokens_details.cached_tokens + total_usage["reasoning"] = usage.output_tokens_details.reasoning_tokens + total_usage["output"] = usage.output_tokens + total_usage["total"] = usage.total_tokens + + logger.info(f"Agent Final Usage: {total_usage['total']} total tokens.") + + + return total_usage["total"], saved_files + + + + + + + diff --git "a/backend/Agents/AppAI/CodeFrontend/Knowledge/Docs/Padr\303\265es de Arquitetura.md" "b/backend/Agents/AppAI/CodeFrontend/Knowledge/Docs/Padr\303\265es de Arquitetura.md" new file mode 100644 index 000000000..b72b0119e --- /dev/null +++ "b/backend/Agents/AppAI/CodeFrontend/Knowledge/Docs/Padr\303\265es de Arquitetura.md" @@ -0,0 +1,62 @@ +Padrões de Arquitetura Simplificada (Front-End) +0. Padrões de Arquitetura Simplificada +Arquitetura Padrão: SPA Simples (Vite/React) +ID: ARQ-SPA-SIMPLES +Palavras-Chave: arquitetura spa simples react componentes +Padrão: Adotar o padrão de Componentes (Pages -> Components -> Hooks/Lib) para organizar a interface. +Fluxo: A Page (View) coordena a aplicação (ex: carrega dados), chamando Hooks (Service) para a lógica de dados, que, por sua vez, usa a camada de Lib (Communication/API) para interagir com o Back-End. +Vantagem: É altamente modular, fácil de testar isoladamente e é a arquitetura inicial mais recomendada para aprender a base de React. + +2. Convenções de Nomenclatura e Arquivos +2.1. Nomenclatura de Arquivos +ID: CONV-FILE-NAMING-FE +Regra: Usar PascalCase para componentes React e camelCase para hooks e arquivos utilitários/lib. Extensão .tsx para componentes e .ts para lógica pura. +Bom: UserProfileCard.tsx, useFetchData.ts, apiClient.ts +Ruim: user_profile_card.tsx, usefetchdata.ts + +2.2. Nomenclatura de Funções/Hooks +ID: CONV-FUNC-NAMING-FE +Regra: Hooks customizados devem começar com use (ex: useUser()). Funções em Libs devem usar verbos no infinitivo para indicar a ação que realizam (ex: formatDate, getAuthToken). + +2.3. Uso de try...catch (Comunicação API) +ID: CONV-TRY-CATCH-FE +Regra: O bloco try...catch para chamadas de API (e tratamento de erro HTTP) DEVE ser usado na camada de Hooks (Service). A camada de Pages deve apenas receber a exceção tratada (ex: um erro amigável já formatado) para exibição. + +3. Arquitetura Desejável (Front-End) + +nomedoprojeto/ +├── Front-End/ +│ ├── ... (arquivos de config do Front-End como package.json, vite.config.ts) +│ └── src/ +│ ├── components/ +│ │ ├── Common/ +│ │ │ ├── Button.tsx +│ │ │ ├── ... +│ │ ├── Forms/ +│ │ │ ├── LoginForm.tsx +│ │ │ ├── ... +│ ├── constants/ +│ │ ├── apiUrls.ts +│ │ ├── ... +│ ├── contexts/ +│ │ ├── AuthContext.tsx +│ │ ├── ... +│ ├── hooks/ +│ │ ├── useAuth.ts +│ │ ├── useProductList.ts +│ │ ├── ... +│ ├── lib/ +│ │ ├── apiClient.ts // Cliente HTTP configurado +│ │ ├── typeguards.ts +│ │ ├── formatDate.ts +│ │ ├── ... +│ ├── pages/ +│ │ ├── Login.tsx +│ │ ├── Dashboard.tsx +│ │ ├── ... +│ ├── types/ +│ │ ├── api.ts +│ │ ├── models.ts +│ │ ├── ... +│ ├── App.tsx +│ └── main.tsx diff --git "a/backend/Agents/AppAI/CodeFrontend/Knowledge/Docs/Padr\303\265es de Comunica\303\247\303\243o.md" "b/backend/Agents/AppAI/CodeFrontend/Knowledge/Docs/Padr\303\265es de Comunica\303\247\303\243o.md" new file mode 100644 index 000000000..f3b1de4aa --- /dev/null +++ "b/backend/Agents/AppAI/CodeFrontend/Knowledge/Docs/Padr\303\265es de Comunica\303\247\303\243o.md" @@ -0,0 +1,20 @@ +Padrões de Comunicação (Front-End) + +1.1. Configuração de Requisições HTTP +ID: FRONT-API-COMMUNICATION +Palavras-Chave: front-end comunicação api axios fetch base url mock +Regra: O Front-End DEVE usar uma única instância de cliente HTTP configurada. Esta instância DEVE ser adaptável para chamar a API Real (usando BASE_URL) ou o Módulo de Mocking com base na variável de ambiente. + +1.2. Tratamento de Erro na Comunicação (Front-End) +ID: FRONT-API-ERROR-HANDLE +Palavras-Chave: front-end tratamento erro 400 401 +Regra: O Front-End DEVE capturar os status HTTP na camada de Hooks e reagir de acordo, utilizando o formato JSON de erro definido no Back-End (ID: CODE-API-ERROR-HANDLING). + +Status Code Ação Obrigatória do Front-End (Na camada de Hook/Context) +401 Unauthorized Redirecionar o usuário para a página de Login.tsx e limpar o token localmente (no Context/Storage). +400 Bad Request Retornar a mensagem de erro (campo message no JSON de erro) para a Page que irá exibir a mensagem no formulário. +404 Not Found Exibir mensagem genérica de "Recurso não encontrado" ou redirecionar para uma página de erro 404. +1.3. Padrão de Autenticação (Token) +ID: FRONT-API-AUTH-TOKEN +Palavras-Chave: front-end autenticação token jwt bearer +Regra: Após o login, o token de acesso (JWT) DEVE ser armazenado em um local seguro (ex: localStorage ou sessionStorage com as devidas precauções) e enviado em TODAS as requisições subsequentes no cabeçalho Authorization: Bearer . \ No newline at end of file diff --git "a/backend/Agents/AppAI/CodeFrontend/Knowledge/Docs/Padr\303\265es de Cont\303\252ineres.md" "b/backend/Agents/AppAI/CodeFrontend/Knowledge/Docs/Padr\303\265es de Cont\303\252ineres.md" new file mode 100644 index 000000000..80621fcb9 --- /dev/null +++ "b/backend/Agents/AppAI/CodeFrontend/Knowledge/Docs/Padr\303\265es de Cont\303\252ineres.md" @@ -0,0 +1,20 @@ +Padrões de Contêineres (Front-End) +1. Padrões de Contêineres (Docker) + +1.1. Dockerfile do Front-End (Vite/React) +ID: DEVOPS-DOCKER-FRONT +Palavras-Chave: dockerfile frontend react vite otimizacao +Regra: O Dockerfile do Front-End DEVE ser otimizado para a build estática do Vite, utilizando multi-stage build: + +Stage 1 (Build): Usar uma imagem Node.js (ex: node:20-slim) para instalar dependências (npm install) e realizar a build (npm run build). + +Stage 2 (Servidor): Usar uma imagem leve de servidor HTTP (ex: Nginx ou Caddy) para servir os arquivos estáticos gerados na etapa de build. + +1.2. Docker Compose para Ambiente Local +ID: DEVOPS-COMPOSE-LOCAL +Palavras-Chave: docker-compose ambiente local frontend +Regra: O docker-compose.yml é o padrão para o desenvolvimento local. Ele DEVE orquestrar o serviço: + +front: O contêiner Vite (Front-End). + +Regra de Conexão: O Front-End DEVE usar o nome do serviço do Back-End definido no docker-compose (ex: http://web:8080/api) para a BASE_URL de desenvolvimento, e NUNCA localhost. \ No newline at end of file diff --git "a/backend/Agents/AppAI/CodeFrontend/Knowledge/Docs/Padr\303\265es de C\303\263digo.md" "b/backend/Agents/AppAI/CodeFrontend/Knowledge/Docs/Padr\303\265es de C\303\263digo.md" new file mode 100644 index 000000000..51eab2388 --- /dev/null +++ "b/backend/Agents/AppAI/CodeFrontend/Knowledge/Docs/Padr\303\265es de C\303\263digo.md" @@ -0,0 +1,39 @@ +Padrões de Convenção e Estrutura de Código (Front-End) +Este documento mapeia a estrutura de pastas do Front-End para as responsabilidades do código, garantindo que o time júnior saiba onde colocar cada tipo de lógica. + +1. Mapeamento da Estrutura de Módulos (Separation of Concerns) +A estrutura de Front-End/src implementa o padrão de Camadas de Apresentação (Presentation Layer), separando as preocupações: + +Pasta Responsabilidade Descrição Padrões de Uso (ID RAG) +pages View Principal (Controller/Coordinator) Contém os componentes principais (ex: Login.tsx, Dashboard.tsx). Sua única responsabilidade é coordenar o estado global, chamar hooks e renderizar os componentes de UI. NUNCA deve conter lógica de formatação ou acesso direto à API. ARQ-SPA-SIMPLES +components Componentes de UI (View) Blocos de construção reutilizáveis (ex: Button, Card, Header). Devem ser puros (stateless) e receber dados via props. ARQ-SPA-SIMPLES, CODE-REACT-PURE-COMPONENTS +hooks Lógica de Dados/Estado (Service) Lógica reusável para manipular o estado local ou chamar a API. Ex: useAuth(), useUserData(). É o ponto de contato entre a Page e a camada de Lib. CODE-REACT-HOOKS, FRONT-API-COMMUNICATION +lib Funções Utilitárias/API Código sem estado, reutilizável (ex: formatDate(), calculateTax()) e o cliente HTTP configurado. Ex: apiClient.ts. FRONT-API-COMMUNICATION, FRONT-API-ERROR-HANDLE +contexts Estado Global Mecanismo para gerenciar o estado global da aplicação (ex: Tema, Usuário Autenticado) sem prop-drilling. - +constants Constantes Globais Variáveis que não mudam (ex: URLs de API, textos estáticos). - + +Padrões de Código Essenciais (Front-End) +1. Padrão de Componentes React + +1.1. Componentes Puros e Tipagem (TypeScript) +ID: CODE-REACT-PURE-COMPONENTS +Palavras-Chave: react typescript componentes puros props +Regra: A maioria dos componentes em src/components DEVE ser funcional e pura (stateless), aceitando as propriedades (props) e emitindo eventos se necessário. Toda prop DEVE ser explicitamente tipada com interface ou type do TypeScript. + +1.2. Evitar Lógica de Negócio em Componentes (Separação de Preocupações) +ID: CODE-REACT-NO-BUSINESS-LOGIC +Regra: Componentes em src/components NÃO DEVEM conter lógica de negócio complexa, chamadas de API diretas (fetch ou axios dentro do componente), ou manipulação de estado que não seja puramente de UI. Delegar isso aos Hooks e Pages. + +2. Padrões de Hooks e Estado + +2.1. Hooks para Lógica de Dados +ID: CODE-REACT-HOOKS +Palavras-Chave: react hooks usememo usecallback +Regra: Utilizar Hooks customizados em src/hooks para isolar a lógica de acesso a dados, manipulação de estado complexa ou efeitos colaterais (useEffect). Isso torna a lógica reutilizável e mais fácil de testar. + +2.2. Otimização de Performance (Básica) +ID: CODE-REACT-PERFORMANCE-JUNIOR +Regra: Usar useMemo para memorizar cálculos caros e useCallback para memorizar funções que são passadas como props para componentes filhos, evitando re-renderizações desnecessárias. + +3. Padrão de Comunicação com a API (Ver documento de Comunicação) +Regra: A comunicação deve ser centralizada em lib/apiClient.ts e consumida pelos Hooks. \ No newline at end of file diff --git "a/backend/Agents/AppAI/CodeFrontend/Knowledge/Docs/Padr\303\265es de Design System.md" "b/backend/Agents/AppAI/CodeFrontend/Knowledge/Docs/Padr\303\265es de Design System.md" new file mode 100644 index 000000000..eb32ea098 --- /dev/null +++ "b/backend/Agents/AppAI/CodeFrontend/Knowledge/Docs/Padr\303\265es de Design System.md" @@ -0,0 +1,56 @@ +Padrões de Design System (DS) e Componentização de Alto Nível +Este documento eleva os componentes (já definidos em) a um Design System, fornecendo regras claras para a criação e uso de elementos de interface (UI/UX) consistentes. + +1. Princípios Fundamentais do Design System (DS) +1.1. Fonte Única da Verdade Visual (Single Source of Truth) +ID: DS-VISUAL-SSOT +Palavras-Chave: design system single source of truth atomic design +Regra: Todos os elementos de UI (Cores, Fontes, Espaçamentos, Componentes) DEVEM ser definidos e importados de um local central. O time júnior e o Agente de IA NUNCA devem aplicar estilos diretamente nos componentes de Pages ou Hooks; eles devem sempre usar os componentes de UI de src/components/Common/ ou tokens do Tailwind. + +1.2. Componentes Adaptáveis e Responsivos +ID: DS-RESPONSIVE-FIRST +Palavras-Chave: design system responsivo mobile first +Regra: O desenvolvimento DEVE ser Mobile First. Todos os componentes, por padrão, devem ser projetados e codificados para funcionar e parecerem excelentes em telas pequenas antes de serem adaptados para telas maiores (desktop). O uso de utilitários de responsividade do Tailwind CSS (ex: md:, lg:) é obrigatório. + +1.3. Documentação de Componentes +ID: DS-COMPONENT-DOCS +Regra: Embora estejamos focados na velocidade, cada componente de UI não trivial (ex: Modal, Table, Card) DEVE ter um arquivo de documentação ou story adjacente (ex: usando Storybook ou um README simples no componente) descrevendo suas props e casos de uso. +Requisito para o Agente de IA: A IA deve gerar comentários no código-fonte do componente descrevendo suas funcionalidades. + +2. Padrões de Componentização Específicos +2.1. Nomenclatura e Tipos de Componentes +ID: DS-COMPONENT-ATOMIC +Palavras-Chave: atomic design nomenclatura +Regra: Adotar a lógica do Atomic Design (Átomos, Moléculas, Organismos) para organizar a pasta src/components/ + +Nível Exemplo de Pasta/Nome Descrição Onde Usar +Átomos Button.tsx, Input.tsx Elementos HTML puros e básicos, com pouco ou nenhum estado interno. Em toda parte. +Moléculas LoginForm.tsx, UserCard.tsx Grupos de Átomos que funcionam juntos (ex: Input + Rótulo + Botão). Dentro de Organismos ou Pages. +Organismos Header.tsx, Sidebar.tsx Seções complexas da interface (ex: um Header com navegação e busca). Dentro de Pages. +2.2. Separação de Estilos (Tokens de Design) +ID: DS-STYLE-TOKENS +Regra: Todos os valores de estilo (cores, espaçamento, tamanhos de borda) DEVEM ser referenciados por meio de tokens definidos no arquivo de configuração do Tailwind (ou variáveis CSS se necessário) e NUNCA por valores literais. +Exemplo: Usar className="bg-primary-500" ao invés de style={{ backgroundColor: '#1A73E8' }}. + +3. Padrões de Interação e Feedback (Avançado) +3.1. Feedback Visual de Interação +ID: DS-INTERACTION-FEEDBACK +Palavras-Chave: hover focus active +Regra: Todo elemento interativo (botões, links, ícones clicáveis) DEVE fornecer feedback visual claro para os estados de Hover, Focus (acessibilidade com teclado), e Active (clique). O Tailwind deve ser usado para definir estes estados. + +3.2. Hierarquia Visual de Ações +ID: DS-ACTION-HIERARCHY +Palavras-Chave: botões primário secundário destrutivo +Regra: Botões e Ações devem ter uma hierarquia visual clara, geralmente usando apenas um Botão Primário (destacado, ex: cor principal) por tela/formulário, e os demais como Secundários (contorno/fundo claro) ou Destrutivos (cor de alerta/vermelha). + +3.3. Uso de Cores Semânticas +ID: DS-SEMANTIC-COLOR +Regra: As cores DEVEM ser usadas de forma consistente para transmitir significado, NUNCA apenas por estética: + +Primary (Azul/Verde): Ações Principais, Links. + +Success (Verde): Confirmação, Operação Bem-Sucedida. + +Warning (Amarelo): Atenção, Ações que Requerem Cuidado. + +Danger (Vermelho): Erros, Ações Destrutivas ou Irreversíveis. \ No newline at end of file diff --git "a/backend/Agents/AppAI/CodeFrontend/Knowledge/Docs/Padr\303\265es de Integra\303\247\303\243o Cont\303\255nua.md" "b/backend/Agents/AppAI/CodeFrontend/Knowledge/Docs/Padr\303\265es de Integra\303\247\303\243o Cont\303\255nua.md" new file mode 100644 index 000000000..5f30b26f4 --- /dev/null +++ "b/backend/Agents/AppAI/CodeFrontend/Knowledge/Docs/Padr\303\265es de Integra\303\247\303\243o Cont\303\255nua.md" @@ -0,0 +1,14 @@ +Padrões de Integração Contínua (Front-End) +2. Padrões de Integração Contínua (CI/CD) + +2.1. Arquivo de Deploy (deploy.yml) +ID: DEVOPS-CI-DEPLOY-FRONT +Palavras-Chave: ci/cd github actions deploy.yml frontend +Regra: O pipeline de CI/CD (localizado em .github/workflows/deploy.yml) DEVE ter, no mínimo, as seguintes etapas antes de qualquer deploy: + +Instalação/Build: Instalar dependências (npm install) e gerar a build de produção (npm run build). + +Testes: Executar os testes unitários (TEST-FE-TOOL) nas camadas de Hooks e Lib. + +Lint/Tipagem: Garantir que o código siga os padrões de formatação e que o TypeScript não gere erros (npm run lint e npm run type-check). + diff --git "a/backend/Agents/AppAI/CodeFrontend/Knowledge/Docs/Padr\303\265es de Mocking.md" "b/backend/Agents/AppAI/CodeFrontend/Knowledge/Docs/Padr\303\265es de Mocking.md" new file mode 100644 index 000000000..95b64633b --- /dev/null +++ "b/backend/Agents/AppAI/CodeFrontend/Knowledge/Docs/Padr\303\265es de Mocking.md" @@ -0,0 +1,49 @@ +Padrões de Mocking e Desenvolvimento Desacoplado (Front-End) +Este documento estabelece as regras para simular a API do Back-End no Front-End, permitindo que o desenvolvimento da interface e da experiência do usuário (UI/UX) ocorra em paralelo e seja validado rapidamente. + +1. Padrão de Contrato e Tipagem da API +1.1. Definição do Contrato da API (TypeScript Types) +ID: MOCK-CONTRACT-TYPES +Palavras-Chave: contrato api typescript interface mocking +Regra: Toda requisição e resposta de API DEVE ser primeiro definida em TypeScript Interfaces/Types em src/types/api.ts. Esta tipagem serve como o Contrato Oficial da API. O Front-End e o Back-End devem aderir a este contrato. +Exemplo: Antes de fazer a chamada, defina interface User { id: number; name: string; email: string; }. + +1.2. Mapeamento de Tipagem para Dados Mockados +ID: MOCK-DATA-STRUCTURE +Regra: Todos os dados mockados (simulados) DEVEM ser gerados de forma que correspondam exatamente às TypeScript Interfaces. Isso garante que, quando o Back-End real for conectado, não haja erros de tipagem no Front-End. + +2. Padrões de Simulação (Mocking) +2.1. Centralização do Mocking +ID: MOCK-TOOL-CENTRALIZATION +Palavras-Chave: mocking centralizado msw json-server +Regra: O Mocking de todas as rotas da API DEVE ser implementado em um módulo centralizado (ex: usando uma biblioteca como MSW - Mock Service Worker ou um serviço local simples em src/lib/mockApi.ts). + +2.2. Uso Obrigatório do Mocking no Desenvolvimento Local +ID: MOCK-ENV-DEV +Palavras-Chave: ambiente desenvolvimento mocking +Regra: Durante o desenvolvimento local (npm run dev), o Front-End DEVE consumir os dados mockados por padrão (lido de uma variável de ambiente como VITE_USE_MOCKING=true). +Justificativa: Isso permite que a IA gere a interface e o time júnior veja e valide a UI/UX imediatamente. + +2.3. Estrutura de Resposta Mockada (Padrão JSON) +ID: MOCK-RESPONSE-FORMAT +Regra: Os mocks de sucesso DEVEM retornar a resposta no formato JSON de sucesso definido (ID: CODE-API-SUCCESS), e os mocks de erro DEVEM retornar no formato de erro (ID: CODE-API-ERROR-HANDLING). +Exemplo de Mock de Sucesso (para uma lista de usuários): + +TypeScript + +{ + status: 'success', + message: 'Dados mockados com sucesso.', + data: [{ id: 1, name: 'Usuário Mock 1' }, { id: 2, name: 'Usuário Mock 2' }] +} +3. Integração com o Workflow de Aprovação +3.1. Chave de Toggle para Mocking +ID: MOCK-TOGGLE-KEY +Palavras-Chave: chave toggle mock +Regra: Deve haver uma chave de ambiente (ex: VITE_API_BASE_URL ou VITE_USE_MOCKING) que possa ser facilmente alternada para mudar o Front-End de Mock (Desenvolvimento/Aprovação Rápida) para API Real (Testes de Integração). +Requisito para Juniores: O Front-End gerado DEVE funcionar perfeitamente em ambos os modos, sem alterações no código dos componentes ou hooks. + +3.2. Mocks de Erro para UI/UX +ID: MOCK-ERROR-SIMULATION +Palavras-Chave: simulação de erro ui ux +Regra: O time Front-End DEVE criar mocks específicos para simular os erros de API mais comuns (400, 401, 500) para garantir que os estados de erro da UI/UX (ex: Toast de falha, redirecionamento para Login, mensagens de formulário) sejam exibidos corretamente e sejam amigáveis. \ No newline at end of file diff --git "a/backend/Agents/AppAI/CodeFrontend/Knowledge/Docs/Padr\303\265es de Requisitos.md" "b/backend/Agents/AppAI/CodeFrontend/Knowledge/Docs/Padr\303\265es de Requisitos.md" new file mode 100644 index 000000000..e3a3b57ed --- /dev/null +++ "b/backend/Agents/AppAI/CodeFrontend/Knowledge/Docs/Padr\303\265es de Requisitos.md" @@ -0,0 +1,39 @@ +Padrões de Requisitos Simplificados (Front-End) +3. Padrões de Requisitos Simplificados + +3.1. Template de Requisito Funcional (RF) - Básico +ID: TEMPLATE-RF-BASICO-FE +Palavras-Chave: modelo requisito funcional basico frontend +Foco em clareza, na Interação do Usuário e nos Passos de Teste para verificação manual. + +Exemplo Modelo: +RF-XXX: [Módulo] - Título da Funcionalidade +Descrição (O que deve fazer): O usuário deve ser capaz de realizar o cadastro no sistema através do formulário na página de Login.tsx. +Regras de Negócio Chave (Front-End): + +O campo de e-mail deve ser validado para o formato padrão. + +A confirmação de senha deve ser idêntica à senha (validação local). + +Em caso de sucesso na API (201 Created), o Front-End deve redirecionar o usuário para a página de /dashboard. +Passos de Teste (Para Estagiário): + +[ ] Tentar enviar o formulário com o campo de e-mail vazio. Esperar a mensagem de erro local. + +[ ] Tentar cadastrar com senha diferente da confirmação. Esperar a mensagem de erro local. + +[ ] Tentar cadastrar com dados válidos. Verificar se o usuário é redirecionado para o dashboard. + +3.2. Template de Requisito Não-Funcional (RNF) - Foco em Usabilidade/Performance +ID: TEMPLATE-RNF-SIMPLES-FE +Palavras-Chave: modelo requisito nao-funcional junior usabilidade performance +Os RNFs devem ser simples e diretamente relacionados à experiência do usuário ou à performance básica. + +Exemplo Modelo: +RNF-XXX: [Categoria: Usabilidade] - Estados de Carregamento +Especificação: Todo botão que dispara uma chamada de API (POST/PUT) DEVE exibir um estado de carregamento (loading=true) para evitar cliques duplos e informar ao usuário que a requisição está em andamento. +Justificativa: Melhorar a experiência do usuário e evitar envio de dados duplicados. + +RNF-YYY: [Categoria: Performance] - Carregamento Lento (Lazy Loading) +Especificação: As rotas menos acessadas (ex: /admin-panel) DEVERÃO utilizar o Lazy Loading (carregamento sob demanda) para não atrasar o carregamento inicial da aplicação. +Justificativa: Reduzir o initial load time da aplicação. \ No newline at end of file diff --git "a/backend/Agents/AppAI/CodeFrontend/Knowledge/Docs/Padr\303\265es de Testes Unit\303\241rios.md" "b/backend/Agents/AppAI/CodeFrontend/Knowledge/Docs/Padr\303\265es de Testes Unit\303\241rios.md" new file mode 100644 index 000000000..392053157 --- /dev/null +++ "b/backend/Agents/AppAI/CodeFrontend/Knowledge/Docs/Padr\303\265es de Testes Unit\303\241rios.md" @@ -0,0 +1,21 @@ +Padrões de Testes Unitários (Front-End React) +Garantir que os juniores saibam como testar a UI e a lógica isoladamente. + +2.1. Ferramenta de Teste +ID: TEST-FE-TOOL +Palavras-Chave: testes frontend unitarios jest rtl +Regra: Utilizar Vitest como runner de testes e React Testing Library (RTL) como biblioteca principal para testes de componentes. Foco em testar o comportamento (o que o usuário vê) e não os detalhes de implementação do React. + +2.2. Testes para a Camada de Componentes (UI) +ID: TEST-FE-UI-COMPONENT +Palavras-Chave: testes componentes react rtl mock +Regra: Ao testar um componente em src/components/, é OBRIGATÓRIO utilizar mocking para simular funções passadas como props ou context (se aplicável). O teste deve verificar se o componente renderiza corretamente com as props fornecidas e se o evento correto é disparado (ex: fireEvent.click). + +2.3. Testes para a Camada de Lógica (Hooks/Lib) +ID: TEST-FE-LOGIC-HOOKS +Palavras-Chave: testes hooks lógica reativa +Regra: Testes de Hooks customizados devem usar a função renderHook do RTL (ou similar) para garantir que a lógica de estado e side effects esteja correta. O acesso à API (apiClient) DEVE ser mockado para que o teste seja unitário, verificando apenas o fluxo de sucesso/erro do hook. + +2.4. Localização dos Testes +ID: TEST-FE-LOCATION +Regra: Todos os arquivos de teste devem residir na mesma pasta que o código que está sendo testado (ex: src/components/Button.test.tsx) ou em uma pasta __tests__ adjacente, e ter o sufixo .test.tsx ou .test.ts. \ No newline at end of file diff --git "a/backend/Agents/AppAI/CodeFrontend/Knowledge/Docs/Padr\303\265es de UI e UX.md" "b/backend/Agents/AppAI/CodeFrontend/Knowledge/Docs/Padr\303\265es de UI e UX.md" new file mode 100644 index 000000000..8fae09807 --- /dev/null +++ "b/backend/Agents/AppAI/CodeFrontend/Knowledge/Docs/Padr\303\265es de UI e UX.md" @@ -0,0 +1,65 @@ +Padrões de Interface e Experiência do Usuário (UI/UX) +Este documento estabelece as regras básicas de design e interação para garantir uma aplicação com excelente usabilidade para o time júnior. O foco é na consistência, clareza e na minimização da frustração do usuário. + +1. Padrões de Formulários e Entradas +1.1. Estado de Feedback Imediato +ID: UX-FORM-FEEDBACK +Palavras-Chave: formulário feedback erro validação +Regra: A validação de campos (erros de formato, campos obrigatórios) DEVE ocorrer imediatamente (on-blur ou on-change) ANTES do envio para o Back-End (validação local no Front-End). O campo com erro DEVE ter sua borda destacada (ex: cor vermelha) e a mensagem de erro deve estar próxima ao campo. + +1.2. Rótulos e Placeholder +ID: UI-FORM-LABELS +Palavras-Chave: formulário rótulo placeholder +Regra: Todo campo de entrada DEVE ter um rótulo (