diff --git a/.env.example b/.env.example new file mode 100644 index 00000000..dd7b3afb --- /dev/null +++ b/.env.example @@ -0,0 +1,106 @@ +# ============================================================================= +# TryCatch For Match — modelo de variáveis de ambiente +# ============================================================================= +# +# Copie este arquivo para .env e preencha os valores: +# +# cp .env.example .env +# +# ⚠️ NUNCA coloque valores reais aqui. Este arquivo VAI para o repositório. +# O .env, com os valores de verdade, fica só na sua máquina. +# +# Para rodar o projeto localmente, o mínimo é: DATABASE_URL, NEXTAUTH_SECRET +# e NEXTAUTH_URL. O resto habilita funcionalidades específicas. +# ============================================================================= + + +# ----------------------------------------------------------------------------- +# BANCO DE DADOS +# ----------------------------------------------------------------------------- + +# OBRIGATÓRIA. Escolha UMA das três opções abaixo e deixe as outras comentadas. + +# 👉 Opção 1 — Banco compartilhado no Neon +# Peça a string de conexão no Discord. Não precisa instalar nada. +# DATABASE_URL="postgresql://usuario:senha@host.neon.tech/neondb?sslmode=require" + +# 👉 Opção 2 — PostgreSQL via Docker (usa o docker-compose.yml do projeto) +DATABASE_URL="postgresql://postgres:postgres@localhost:5555/trycatch_db" + +# 👉 Opção 3 — PostgreSQL instalado na sua máquina +# DATABASE_URL="postgresql://postgres:postgres@localhost:5432/trycatch_db" + + +# Usadas apenas pelo docker-compose (Opção 2). Se não usar Docker, ignore. +POSTGRES_USER=postgres +POSTGRES_PASSWORD=postgres +POSTGRES_DB=trycatch_db +POSTGRES_PORT=5555 + + +# ----------------------------------------------------------------------------- +# AUTENTICAÇÃO +# ----------------------------------------------------------------------------- + +# OBRIGATÓRIA. Assina os tokens de sessão do NextAuth. +# Gere o SEU valor — nunca reaproveite o de outra pessoa nem de outro ambiente: +# +# node -e "console.log(require('crypto').randomBytes(32).toString('hex'))" +# +NEXTAUTH_SECRET=gere-o-seu-com-o-comando-acima + +# OBRIGATÓRIA. URL onde a aplicação responde. +# Em produção, precisa ser a URL real do deploy — o NextAuth usa este valor +# para montar os redirecionamentos e os links de recuperação de senha. +NEXTAUTH_URL=http://localhost:3000 + + +# ----------------------------------------------------------------------------- +# URL PÚBLICA DA APLICAÇÃO +# ----------------------------------------------------------------------------- + +# Usada para montar os links enviados nos e-mails de convite. +# Em desenvolvimento, normalmente igual à NEXTAUTH_URL. +NEXT_PUBLIC_APP_URL=http://localhost:3000 + + +# ----------------------------------------------------------------------------- +# CLOUDINARY — upload de imagens (avatar e assets de UI) +# ----------------------------------------------------------------------------- + +# Necessárias para o upload de avatar funcionar. +# Crie uma conta gratuita em https://cloudinary.com e copie os valores em +# Dashboard → API Keys. +CLOUDINARY_CLOUD_NAME=seu_cloud_name +CLOUDINARY_API_KEY=sua_api_key +CLOUDINARY_API_SECRET=sua_api_secret + + +# ----------------------------------------------------------------------------- +# E-MAIL (Resend) +# ----------------------------------------------------------------------------- + +# Necessária para: formulário de contato, solicitação de convite e +# recuperação de senha. Crie a chave em https://resend.com +RESEND_API_KEY=re_sua_chave_aqui + +# Remetentes e destinatários usados pelos e-mails automáticos. +# Precisam ser endereços de um domínio verificado no Resend. +CONTACT_SENDER_EMAIL=contato@exemplo.com +RESET_PASSWORD_EMAIL=nao-responda@exemplo.com +INVITE_REQUEST_SENDER_EMAIL=convites@exemplo.com +INVITE_REQUEST_RECEIVER_EMAIL=admin@exemplo.com + + +# ----------------------------------------------------------------------------- +# OPCIONAIS +# ----------------------------------------------------------------------------- + +# Agente de code review (npm run review). Chave gratuita em: +# https://aistudio.google.com/api-keys +# Sem ela, o restante do projeto funciona normalmente. +GEMINI_API_KEY= + +# Ativa os testes de integração, que precisam de banco real. +# Deixe vazio para rodar apenas os testes unitários. +INTEGRATION_TEST= diff --git a/.exapmle.env b/.exapmle.env deleted file mode 100644 index 2db15fa9..00000000 --- a/.exapmle.env +++ /dev/null @@ -1,24 +0,0 @@ -# Usuário e senha do banco de dados (usado tanto localmente quanto no Docker) -POSTGRES_USER=postgres -POSTGRES_PASSWORD=postgres -POSTGRES_DB=trycatch_db -POSTGRES_PORT=5555 - -# JWT e NextAuth -JWT_SECRET=439afb6b5b0d63bacffee8536f99f749b7eccc28ce246e30f7a4e79291e9a34d -NEXTAUTH_SECRET=439afb6b5b0d63bacffee8536f99f749b7eccc28ce246e30f7a4e79291e9a34d -NEXTAUTH_URL=http://localhost:3000/ - -# 👉 Banco rodando no Docker (comente o de baixo e descomente este ao usar Docker) -# DATABASE_URL="postgresql://${POSTGRES_USER}:${POSTGRES_PASSWORD}@localhost:${POSTGRES_PORT}/${POSTGRES_DB}" - -# 👉 Banco rodando localmente (comente este ao usar Docker) -# DATABASE_URL="postgresql://${POSTGRES_USER}:${POSTGRES_PASSWORD}@localhost:5432/${POSTGRES_DB}" - -# Credenciais do Cloudinary, imagens avatar -CLOUDINARY_CLOUD_NAME=seu_cloud_name -CLOUDINARY_API_KEY=sua_api_key -CLOUDINARY_API_SECRET=sua_api_secret - -# 👉 Banco compartilhado no Neon -DATABASE_URL="postgresql://neondb_owner:npg_QqUSVNyoZ4t8@ep-red-dust-acurw617-pooler.sa-east-1.aws.neon.tech/neondb?sslmode=require&channel_binding=require" diff --git a/.github/workflows/docs-translate.yml b/.github/workflows/docs-translate.yml index c2550fec..5a97ae5a 100644 --- a/.github/workflows/docs-translate.yml +++ b/.github/workflows/docs-translate.yml @@ -1,12 +1,18 @@ name: Docs Auto Translate +# Traduz automaticamente apenas o README. +# +# O CONTRIBUTING.md ficou de fora de propósito: ele é o documento operacional, +# cheio de tabelas, âncoras de índice, comandos e nomes de arquivo. A tradução +# automática quebra esse tipo de estrutura — traduz conteúdo dentro de blocos de +# código e desalinha os links do índice. O CONTRIBUTING.en.md é mantido à mão, +# junto com a versão em português, no mesmo pull request. on: push: branches: - main paths: - 'README.md' - - 'CONTRIBUTING.md' jobs: translate: @@ -20,28 +26,20 @@ jobs: - name: Install translate-shell run: sudo apt-get update && sudo apt-get install -y translate-shell - - name: Translate files to English + - name: Translate README to English run: | - # Traduz o README para o novo padrão if [ -f README.md ]; then trans -b :en < README.md > README.en.md echo "README translated." fi - # Traduz o CONTRIBUTING para o novo padrão - if [ -f CONTRIBUTING.md ]; then - trans -b :en < CONTRIBUTING.md > CONTRIBUTING.en.md - echo "CONTRIBUTING translated." - fi - - - name: Commit translated files + - name: Commit translated file run: | git config user.name "github-actions" git config user.email "actions@github.com" - # Adiciona os arquivos com a extensão correta - git add README.en.md CONTRIBUTING.en.md + # Apenas o README — o CONTRIBUTING.en.md e mantido a mao + git add README.en.md - # Commita as alterações - git commit -m "docs: auto-translate docs to English [skip ci]" || echo "No changes" + git commit -m "docs: auto-translate README to English [skip ci]" || echo "No changes" git push origin HEAD:main diff --git a/.gitignore b/.gitignore index 274ab168..a633311a 100644 --- a/.gitignore +++ b/.gitignore @@ -30,6 +30,7 @@ yarn-error.log* # env files (can opt-in for committing if needed) .env* +!.env.example # vercel .vercel diff --git a/CONTRIBUTING.en.md b/CONTRIBUTING.en.md index 65401165..fd03b647 100644 --- a/CONTRIBUTING.en.md +++ b/CONTRIBUTING.en.md @@ -1,335 +1,581 @@ -# 🤝 Contribution Guide - TryCatch For Match +# 🤝 Contributing Guide - TryCatch For Match --- -#### 🌐 **Languages / Idiomas:** [English](./README.en.md) | [Português](./README.md) +#### 🌐 **Languages / Idiomas:** [English](./CONTRIBUTING.en.md) | [Português](./CONTRIBUTING.md) --- -You are very welcome! 🚀   -Here are the rules, standards and agreements to ensure that everyone can collaborate in an organized, light and productive way. +Welcome aboard! 🚀 ---- +This project exists to help people **learn how to contribute to open source**. +It doesn't matter whether this is your first contribution ever or you have years +of experience — there is room and there are tasks for both. -## ✔️ Task distribution +This guide walks you through the whole journey: picking up a task, setting up +your environment, doing the work and opening the pull request. -Tasks are organized into cards/issues, which can be divided into sub-issues, when necessary, for better distribution of work. +> 💡 **First time contributing to open source?** You don't need to know +> everything. Read through the *Getting started* section and ask for help on +> [Discord](https://discord.gg/ZgUHkzf3r) whenever you get stuck. Asking is part +> of the process. -⚠️ **Important:** -Those interested in contributing do not create or assume the issue/card on their own. +> 🌍 **A note on language:** most of this project's documentation is written in +> Portuguese, since the community is Brazilian. **You do not need to speak +> Portuguese to contribute.** This guide is kept in English, and if you use an +> AI assistant in your editor it will talk to you in your own language and +> translate the rest as needed — see +> [Using AI? Set it up before you start](#-using-ai-set-it-up-before-you-start). -### 📌 Correct assignment flow +--- -1. The employee comments on the existing issue/card, stating that he or she is interested in taking on the task. +## 📖 Table of contents -2. A project owner will: -- Evaluate the request -- Officially assign the collaborator to the issue/card -- Define or validate the delivery deadline +1. [How tasks are assigned](#-how-tasks-are-assigned) +2. [Getting started: from fork to running project](#-getting-started-from-fork-to-running-project) +3. [Using AI? Set it up before you start](#-using-ai-set-it-up-before-you-start) +4. [The workflow: branch, commit and PR](#-the-workflow-branch-commit-and-pr) +5. [Working with dependencies](#-working-with-dependencies) +6. [AI code review agent](#-ai-code-review-agent) +7. [Husky and Continuous Integration](#-husky-and-continuous-integration) +8. [Task tracking](#-task-tracking) +9. [Where to ask for help](#-where-to-ask-for-help) +10. [Golden rules](#-golden-rules) +11. [Contributor recognition](#-contributor-recognition) -3. If necessary, the employee can request an extension of the deadline, exclusively via a comment on the issue/card itself. +--- -This flow guarantees control, equity in the distribution and traceability of responsibilities. +## ✔️ How tasks are assigned ---- +Work is organised as **cards/issues** on GitHub Projects, which may be split +into sub-issues when needed. -## 🧭 Task tracking flow +⚠️ **Important:** you don't create or assign yourself to an issue on your own. -After the task is assigned, keep the card updated so the team knows the real state of the work. +### 📌 The assignment flow -### ✔️ Card status: -- **In progress:** use this when you start implementing or reviewing the task. -- **Blocked:** use this when you need a decision, access, scope adjustment or technical help to continue. -- **Done:** use this only after opening the Pull Request, validating locally and leaving the PR link on the card. +1. Comment on the issue/card saying you'd like to take the task. +2. A project maintainer will: + - review your request; + - officially assign you to the issue/card; + - set or confirm the delivery deadline. +3. If you need more time, ask for an extension **on the issue itself**. -### ✔️ Communication on the card: -- Share the agreed deadline before starting. -- Record deadline changes on the card itself. -- Explain blockers with enough context for another person to help. -- When opening the PR, share the link and list which validations were executed. +This keeps the workload fair, traceable and under control. -### ✔️ Branch and PR flow: -- Create the branch from `develop`. -- Use a prefix that matches the type of work: `feat`, `fix`, `docs`, `test`, `refactor`, `style` or `chore`. -- Make small and clear commits. -- Always open the Pull Request against `develop`. -- Link the PR to the issue with a closing keyword, for example `Fixes: #123`, when the PR completes the task. +### ✔️ Before you volunteer ---- +- Check your availability **before** committing to a task. +- Wait for the formal assignment before you start coding. +- Assigned task = responsibility accepted. +- If you realise you won't make the deadline, say so as early as you can. -## 🗂️ Rules and Organization +> 💡 **First contribution?** Look for issues labelled `good first issue`. They +> were picked because they're a safe place to start. -### ✔️ When showing interest in a task (card): -- Clearly state that you want to take on the task. -- Wait for formal assignment by a responsible person. -- Once assigned, respect the agreed deadline. -- Assess your availability before committing. +--- -### ✔️ Discipline: -- Task assigned = responsibility assumed. -- Don't leave tasks idle without updating. -- If you realize that you will not be able to meet the deadline, let us know as soon as possible via comment. +## 🚀 Getting started: from fork to running project -### ✔️ Constant feedback: -- If you have any doubts, ask. -- If someone asks for help, help. +Follow these in order. Each step depends on the previous one. ---- +### 1. Fork the project -## ⚙️ Local Environment Setup +Click **Fork** at the top of the repository page on GitHub. This creates a copy +of the project under your account. -Before starting, install dependencies with: +> Never worked with forks before? See the +> [official GitHub tutorial](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/working-with-forks/fork-a-repo). + +### 2. Clone your fork ```bash -npm run setup +git clone https://github.com/YOUR-USERNAME/trycatch.git +cd trycatch ``` -> This command is an alias for `npm ci`, which installs **exactly** what is in `package-lock.json` without modifying it. **Never use `npm install` just to set up your environment** — it may rewrite `package-lock.json` and generate unnecessary diffs in your PR. +Replace `YOUR-USERNAME` with your GitHub username. -**Node version:** use Node 18 or higher (CI uses Node 24). This guarantees the v3 lockfile format, which is cross-platform compatible (Windows, Linux, macOS). +> ⚠️ **On Windows:** don't put the project inside a synced folder (OneDrive, +> Google Drive, Dropbox). Sync locks files and git fails when switching +> branches. Prefer something like `C:\projects\trycatch`. -**If you need to add or update a package**, use `npm install ` normally — in that case it is expected that both `package.json` and `package-lock.json` will change. Commit both together: +### 3. Connect to the original repository + +This lets you pull updates from the main project into your fork: ```bash -git add package.json package-lock.json -git commit -m "chore(deps): add " +git remote add upstream https://github.com/TryCatch-ForMatch/trycatch.git ``` -**If `package-lock.json` appears modified after setup**, you accidentally ran `npm install`. Restore it with: +Check it with `git remote -v`. You should see both `origin` (your fork) and +`upstream` (the original project). + +### 4. Install dependencies ```bash -git checkout -- package-lock.json npm run setup ``` ---- +This runs `npm ci`, which installs **exactly** what's in `package-lock.json`. -## 🌿 Git Flow - Branches Pattern +> ⚠️ **Don't use `npm install` just to set up your environment.** It can rewrite +> `package-lock.json` and break continuous integration for everyone. Details in +> [Working with dependencies](#-working-with-dependencies). -### 🔥 Branch principal: -- `main`: stable version ready for production. +**Node version:** the project runs on **Node 24**, the same version used by CI +and production. If you use `nvm` or `fnm`, run `nvm use` in the project root. -### 🧪 Development branch: -- `develop`: where we integrate all the features before going to `main`. +> The Prisma Client is generated automatically by `postinstall`. You do **not** +> need to run `npx prisma generate` yourself. -### 🌱 Feature branches and fixes: -- `feat/feature-name`: new functionality (Ex: `feat/criar-login`) -- `fix/descricao-da-correcao`: bug fix (Ex: `fix/erro-no-formulario`) -- `docs/descricao`: change in documentation   -- `style/descricao`: formatting without code changes   -- `refactor/descricao`: refactoring without changing behavior   -- `test/description`: tests added or corrected   -- `chore/description`: maintenance (dependencies, configs, etc.) +### 5. Set up your environment variables ---- +Copy the template and fill it in: + +```bash +cp .env.example .env +``` -## 🔧 Before starting any task: +Every variable is documented inside the file. At a minimum you'll need +`DATABASE_URL`, `NEXTAUTH_SECRET` and `JWT_SECRET`. Ask on +[Discord](https://discord.gg/ZgUHkzf3r) if you're unsure about any of them. -1. Fork the project via GitHub. If you don't know how, see this [tutorial](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/working-with-forks/fork-a-repo). +> 🔒 Your `.env` **never** goes into the repository. It's already in +> `.gitignore` — don't force-add it under any circumstances. + +### 6. Run the project -2. Update the `develop` branch on your computer: ```bash -git checkout develop -git pull origin develop +npm run dev ``` -3. Create a new branch for your work: +Open . If the page loads, your environment is ready. 🎉 + +### 7. Check that everything works ```bash -git checkout -b feat/feature-name +npm test # tests +npm run lint # code standards +npx tsc --noEmit # type checking ``` -4. Work, make clear commits (use Husky for this) +> ℹ️ The project has **known type errors** that are being fixed gradually. If +> `npx tsc --noEmit` reports errors in files you didn't touch, they're not +> yours — move on and don't try to fix them. + +--- + +## 🤖 Using AI? Set it up before you start + +Plenty of people use an AI assistant in their editor, and that's **welcome +here**. The project ships its own instructions for those tools: they cover the +rules, the conventions and the workflow, and they adapt the level of explanation +to your experience. + +**You don't need AI to contribute.** If you'd rather work without it, skip this +section — the rest of the guide is enough on its own. + +### How it works + +The content lives in `docs/05 - contribuicao/`, and each tool automatically +reads an "entry point" file in the project root: -5. When finished: +| Tool | File it reads automatically | +|---|---| +| GitHub Copilot | `.github/copilot-instructions.md` | +| Claude Code | `CLAUDE.md` | +| Cursor | `.cursor/rules/trycatch.mdc` | + +In other words: **just open the project with the tool installed.** It finds the +instructions on its own and starts following the project's workflow. + +### Step by step + +**1. Pick and install a tool** + +| Tool | How to install | Cost | +|---|---|---| +| **GitHub Copilot** | *GitHub Copilot* extension in VS Code → sign in with your GitHub account | Free tier with a monthly limit; free for students and open source maintainers | +| **Claude Code** | VS Code extension, or from the terminal — see the [official docs](https://docs.claude.com/en/docs/claude-code/overview) | Free tier with a limit; paid plans available | +| **Cursor** | Standalone editor built on VS Code — [cursor.com](https://cursor.com) | Free tier with a limit; paid plans available | + +If you've never used any of them, **Copilot** is usually the easiest starting +point: it installs like any other VS Code extension and has a free tier. + +**2. Open the project in your tool** + +Nothing else to configure. When you open the project folder, the AI reads the +entry file and follows it to the full instructions. + +**3. Tell it what you want to do** + +Start with something simple, like: + +> I want to pick up issue #123. Where do I start? + +The AI will ask you two things: **which language you'd like to talk in** and +**how much experience** you have contributing to open source. From there it +adjusts how much it explains — more detail if you're starting out, straight to +the point if you already know the flow. + +> 🌍 **The project's documentation is in Portuguese, but you don't need to speak +> Portuguese to contribute.** The AI talks to you in your language and +> translates the documents as needed. Just write in English, Spanish or whatever +> you're comfortable with — it will follow. + +**4. (Optional) Save your preferences** + +So you don't answer the same questions every time: ```bash -git push origin feat/your-feature-name +cp "docs/05 - contribuicao/MINHAS-PREFERENCIAS.example.md" "docs/05 - contribuicao/MINHAS-PREFERENCIAS.md" ``` -6. Open a Pull Request (PR) to the `develop` branch of the organization's repository. +Then edit the file with your language, experience level, tool and how you prefer +to work. It stays **on your machine only** — it's in `.gitignore`, just like +`.env`. + +### What to expect from AI on this project + +- **It teaches before it does.** When you ask for something you'd learn by doing + — a git command, running a test, reading an error message — it shows you the + way and waits. If you insist, it does it and explains what it did. The point + here is for you to learn, not just for the code to get written. +- **`git commit`, `git push` and opening the PR are always yours.** The AI helps + draft the message, but you run the commands. +- **It warns you when something breaks the project's rules**, even if you asked + for it. When that happens, read the warning — it's usually about security or + real people's data. + +### Documents, if you want to dig deeper + +These are written in Portuguese. Your AI assistant can translate them for you, +or read them and explain in your language. + +| File | Contents | +|---|---| +| [`IA-REGRAS.md`](docs/05%20-%20contribuicao/IA-REGRAS.md) | Non-negotiable rules: security, authorisation, personal data, git flow | +| [`IA-GUIA.md`](docs/05%20-%20contribuicao/IA-GUIA.md) | The complete workflow, step by step | +| [`IA-NIVEIS.md`](docs/05%20-%20contribuicao/IA-NIVEIS.md) | How the AI adapts to your experience level and language | + +> 💡 If the AI does something different from what's documented, **the +> documentation wins**. Let us know on Discord or open an issue. --- -## 🤖 How to use the Smart Code Review Agent +## 🌿 The workflow: branch, commit and PR -To help maintain the quality of our code and give you quick feedback even before you submit your Pull Request, we use a Code Review robot powered by Gemini artificial intelligence! +This is the full cycle of a contribution, start to finish. -It will read the files you changed and generate a super organized report in the `docs/codereview_reports/` folder pointing out security, performance and best practices improvements. +### The project's branches -### Here is the step-by-step guide for you to configure and use this tool on your computer: +| Branch | What it's for | +|---|---| +| `main` | Stable, production version. **Never** work on it directly | +| `develop` | Where everything is integrated. **Your branch starts here, and your PR goes back here** | +| `feat/`, `fix/`, … | Your working branch | -1. Creating your API Key (Free) -Don't worry, you don't have to pay anything to use this artificial intelligence in your project! +Prefixes: + +| Prefix | When to use it | Example | +|---|---|---| +| `feat/` | new feature | `feat/criar-login` | +| `fix/` | bug fix | `fix/erro-no-formulario` | +| `docs/` | documentation | `docs/atualizar-readme` | +| `style/` | formatting, no behaviour change | `style/ajustar-espacamento` | +| `refactor/` | refactoring, no behaviour change | `refactor/extrair-service` | +| `test/` | tests | `test/cobertura-de-login` | +| `chore/` | maintenance, dependencies, config | `chore/atualizar-eslint` | + +### 1. Update develop before you start + +**Every time**, at the beginning of a task: + +```bash +git checkout develop +git pull upstream develop +git push origin develop +``` -- Access the [Google AI Studio] website (https://aistudio.google.com/api-keys). +`pull upstream` brings in changes from the original project; `push origin` +updates your fork. -- Log in using any regular Google (Gmail) account. +### 2. Create your working branch -- In the side or top menu, look for and click the "Get API key" button. +```bash +git checkout -b feat/your-feature-name +``` -- Click on "Create API Key" and then on "Create API key in new project". +`-b` creates the branch and switches to it. -- A large sequence of letters and numbers will appear. Click the button to copy this key and save it (do not close the page before copying!). +### 3. Work and commit +Use [Conventional Commits](https://www.conventionalcommits.org/) for your +messages: -2. Configuring your Environment Variables -The project needs to know what your key is to be able to talk to Gemini. +``` +feat: criar tela de cadastro de projeto +fix: corrigir bug no login +docs: atualizar guia de contribuição +``` -- Open your `.env.local` file (which you created following the [README](./README.md#-4-configure-o-arquivo-env) step by step). +> ℹ️ Commit messages in this project are usually written in Portuguese, matching +> the rest of the codebase. The **type prefix** (`feat`, `fix`, `docs`…) is +> always in English. If you're not comfortable writing in Portuguese, English is +> fine — just be consistent within your PR. -- Add the following line (replacing the code you copied from the Google website): +If you'd rather be guided step by step: +```bash +npm run commit ``` -GEMINI_API_KEY=Paste_Your_Key_Here_Without_Quotes + +That opens **Commitizen**, which builds the message with you. No need to +memorise the format. + +**Linking to an issue** — at the end of the message: + +- `Refs: #42` just references the issue; +- `Fixes: #42` closes it automatically when the PR is merged. + +### 4. Check before you push + +```bash +npm test +npm run lint +npx tsc --noEmit ``` -3. Running the Code Review -With everything configured, now it's easy! Whenever you want to review your code, open the terminal at the root of the project and type: +### 5. Push and open the pull request -```Bash -npm run review +```bash +git push origin feat/your-feature-name ``` -The terminal will give you 3 really cool options: +On GitHub, open the PR **from your branch to `develop`** on the organisation's +repository — never to `main`. -- [1] Only the changed files: Perfect to run before sending your code to us! It only reviews what you have changed and that has not yet been committed. +Fill in the template that shows up: what you did, the related issue, how to test +it. A good description speeds up review. -- [2] Choose a specific folder/module: Great for when you want to study or review an entire folder (like src/app or src/components). +### 6. Review -- [3] The entire project: It will read the entire project, dividing it into small batches so the AI doesn't crash. +Someone from the team reviews it and may ask for changes. **That's normal and +it's not personal criticism** — it's how the code gets better and how we all +learn. Reply to the comments, adjust and push a new commit. -Open the file generated in the `docs/codereview_reports/` folder to see tips from your virtual Senior Reviewer! 🚀 +Once approved, your PR is merged into `develop`. When everything is ready for +production, we merge `develop → main`. --- -## 🔥 Pull Request (PR) - Fluxo +## 📦 Working with dependencies -1. Create the branch → Work on it → Commit → Push -2. Open PR of your branch to `develop` -3. Describe what was done clearly -4. Someone does the proofreading -5. PR approved → merge to `develop` +This section matters even if you're not touching any package — because it's easy +to change `package-lock.json` by accident. -When everything is ready for production, we do `develop → main`. +### Just installing the project ---- +```bash +npm run setup +``` + +Never `npm install`. `npm ci` installs exactly what's in the lockfile without +rewriting it. -## 🏗️ Standard Commits (Conventional Commits) +### 🔴 `package-lock.json` can only be generated on Linux -We use standardized commit messages. Examples: +If you're on **Windows or macOS**, **do not run `npm install`** in this project. -- `feat: create project registration screen` -- `fix: fix login bug` -- `docs: update README` -- `style: format code with Prettier` -- `refactor: improve form structure` -- `test: add authentication tests` -- `chore: update dependencies` +**Why:** some dependencies ship platform-specific compiled builds. npm resolves +the dependency tree differently on each operating system, and the CI's `npm ci` +— which runs on Linux — rejects a lockfile generated elsewhere. This has already +taken the project's CI down for hours. -### 💡 How to create a commit correctly: +**So how do you add or update a package?** -Use the command: +| Situation | What to do | +|---|---| +| Bumping a package version | Let **Dependabot** handle it — it runs on Linux | +| Adding a new dependency | Use **GitHub Codespaces** (Linux, in the browser), WSL or Docker | +| Just installing to work | `npm run setup` — doesn't touch the lockfile | + +In Codespaces: ```bash -npm run commit +npm install +npm ci # validate on the same platform as CI +git add package.json package-lock.json ``` -This will open the **Commitizen**, which guides you step by step. -You don't need to memorize the patterns, the wizard helps with everything. +> ⚠️ **Talk to the team before adding any dependency.** Every new dependency is +> attack surface, bundle weight and future maintenance. + +### If `package-lock.json` shows up modified by accident + +If you **didn't touch any dependency** and it shows as changed, you ran +`npm install` by mistake. Restore it: + +```bash +git checkout -- package-lock.json +npm run setup +``` + +> ⚠️ **Only do this if the change really was accidental.** If you were fixing +> the lockfile on purpose, this command throws your work away. When in doubt, +> ask first. --- -## 🔗 Vincular commits a issues +## 🔍 AI code review agent + +Beyond the instructions for your editor assistant, the project has a **code +review bot** that analyses your changed files and writes a report to +`docs/codereview_reports/`, pointing out improvements in security, performance +and best practices. + +It's optional, free, and runs on your machine. + +### 1. Create your API key (free) -If the commit is related to an open issue, add at the end: +- Go to [Google AI Studio](https://aistudio.google.com/api-keys). +- Sign in with a regular Google account. +- Click **Get API key** → **Create API Key** → **Create API key in new project**. +- Copy the key that appears (don't close the page before copying!). -- For reference only: `Refs: #42` -- To close automatically: `Fixes: #42` +### 2. Set the environment variable -Example in long description: +Open your `.env` file (the one from step 5 of *Getting started*) and add: ``` -Update login button. Cool: #42 +GEMINI_API_KEY=paste_your_key_here_without_quotes ``` +> 🔒 The key is personal and yours. `.env` never goes into the repository — +> never share the key in an issue, a PR or a message. + +### 3. Run the review + +```bash +npm run review +``` + +The terminal offers three options: + +- **[1] Changed files only** — ideal right before opening your PR; +- **[2] A specific folder** — good for studying a module; +- **[3] The whole project** — in batches, to avoid overloading the model. + +Then open the generated report in `docs/codereview_reports/`. 🚀 + --- -## 🐶 Husky: why do we use? +## 🐶 Husky and Continuous Integration -**Husky** runs automatic checks before you `commit` or `push`, ensuring that: +### Husky: automatic checks before commits -- Your code is formatted correctly (with Prettier) -- Didn't break any tests (with Jest) -- The commit message follows the pattern (with Commitlint) +**Husky** runs automatic checks before `commit` and `push`: -This way, we prevent bugs or non-standard code from entering the database. +- formatting with Prettier; +- tests related to your changed files, with Jest; +- commit message format, with Commitlint; +- a guard against unintended `package-lock.json` changes. -**No need to worry**, everything runs automatically! +**Nothing to configure** — it works automatically after `npm run setup`. -If necessary, you can bypass the hooks with: +If a hook blocks your commit, **read the message**: it almost always tells you +what to do. There is an escape hatch: ```bash git commit --no-verify ``` +> ⚠️ Use it **only** when you know exactly why the hook is wrong, and explain +> your reasoning in the PR description. Skipping checks out of impatience +> usually just moves the problem onto someone else. + +### CI: what runs when you open a PR + +Automatically: **build**, **lint**, **tests**, **coverage**, **dependency +audit**, and then the **SonarCloud** analysis. + +Two things that commonly cause confusion: + +- **SonarCloud runs in a separate workflow**, triggered after CI. This is + necessary because PRs from forks don't receive secrets — without the split, it + would fail every time. +- The **dependency audit** job may show red because of vulnerabilities in + development tooling that have no published fix yet. If your PR didn't touch + dependencies, that's **not** your fault. + +Full details in +[`docs/04 - processo/ci-e-validacao.md`](docs/04%20-%20processo/ci-e-validacao.md) +(in Portuguese). + --- -## 🤖 Continuous Integration (CI) +## 🧭 Task tracking + +Once a task is assigned to you, keep the card up to date so the team knows the +real state of the work. -When you open a Pull Request, CI runs automatically: **build**, **lint**, -**tests**, **coverage**, **dependency audit**, and then the **SonarCloud** -analysis. +### Card status -Key points for contributors: +| Status | When to use it | +|---|---| +| **In progress** | when you start implementing or reviewing | +| **Blocked** | when you need a decision, access, scope change or technical help | +| **Done** | only after opening the PR, validating locally and leaving the link on the card | -- The **SonarCloud analysis runs in a separate workflow** (triggered after - CI). This is required because PRs from **forks** don't receive secrets — - without this split, Sonar would always fail. -- To install dependencies use `npm ci` (and **avoid `npm install` on - Windows** just to install, as it may rewrite `package-lock.json` and - break CI). -- The **Prisma Client** is generated automatically via `postinstall`; you - don't need to run `npx prisma generate` manually after installing. +### Communication -The full flow, the reasoning, and detailed guidance are in -[`docs/04 - processo/ci-e-validacao.md`](docs/04%20-%20processo/ci-e-validacao.md). +- State the agreed deadline before you start. +- Record any deadline change on the card itself. +- Explain blockers with enough context for someone else to help. +- When you open the PR, share the link and say which checks you ran. --- -## 💬 Where to ask for help? +## 💬 Where to ask for help + +- On our community [Discord](https://discord.gg/ZgUHkzf3r) +- By commenting on the issue itself +- By opening a new issue, if it's something that doesn't exist yet -- In the community group [Discord](https://discord.gg/ZgUHkzf3r) -- Opening an issue on GitHub +**Don't stay stuck on your own.** Asking early saves everyone's time, and nobody +here will think your question is silly. --- -## 💛 Golden Rules +## 💛 Golden rules - People > Technology -- Commitment > technical knowledge. -- No one walks alone: ask and help. -- Quality over quantity. -- Communication always. -- Responsibility with assumed deadlines. +- Commitment > technical knowledge +- Nobody walks alone: ask, and help +- Quality over quantity +- Always communicate +- Own the deadlines you accept --- -## 🧑u200d💻 Recognition of collaborators in the project +## 🧑‍💻 Contributor recognition -To ensure that all employees are recognized, follow these instructions: - -1. Comment on the issue or PR: +To make sure everyone gets credited, comment on the issue or PR: ``` -@all-contributors please add @usuario for code, doc +@all-contributors please add @username for code, doc ``` -> Replace `@user` with the contributor's GitHub username. -> You can add multiple contribution types, separated by commas (`code`, `doc`, `test`, etc.). +> Replace `@username` with the GitHub username. You can list several +> contribution types separated by commas (`code`, `doc`, `test`, etc.). + +The bot automatically updates: -3. The bot will automatically update: -- The file `CONTRIBUTORS.md` with the contributor -- The contributor count badge in the README +- the `CONTRIBUTORS.md` file; +- the contributor count badge in the README. -To see all the contribution emoji options, check out the [All Contributors emoji key](https://allcontributors.org/docs/en/emoji-key). +See all the types in the +[All Contributors emoji key](https://allcontributors.org/docs/en/emoji-key). --- + +**Thank you for contributing to TryCatch For Match!** 💛 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 9d5796da..804a7c58 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,335 +1,557 @@ # 🤝 Guia de Contribuição - TryCatch For Match --- -#### 🌐 **Languages / Idiomas:** [English](./README.en.md) | [Português](./README.md) +#### 🌐 **Languages / Idiomas:** [English](./CONTRIBUTING.en.md) | [Português](./CONTRIBUTING.md) --- -Seja muito bem-vindo(a)! 🚀   -Aqui estão as regras, padrões e combinados pra garantir que todo mundo consiga colaborar de forma organizada, leve e produtiva. +Seja muito bem-vindo(a)! 🚀 ---- +Este projeto existe para ajudar pessoas a **aprenderem a contribuir em open +source**. Não importa se é sua primeira contribuição ou se você já tem anos de +carreira — há espaço e tarefa para os dois. -## ✔️ Distribuição de tarefas +Este guia acompanha você do começo ao fim: pegar uma tarefa, preparar o +ambiente, trabalhar e abrir o pull request. -As tarefas são organizadas em cards/issues, que podem ser divididas em sub-issues, quando necessário, para melhor distribuição do trabalho. +> 💡 **Primeira vez contribuindo em open source?** Você não precisa saber tudo. +> Leia até o fim da seção *Começando* e peça ajuda no +> [Discord](https://discord.gg/ZgUHkzf3r) sempre que travar. Perguntar faz parte. -⚠️ **Importante:** -O interessado em contribuir não cria nem assume a issue/card por conta própria. +--- -### 📌 Fluxo correto de atribuição +## 📖 Índice -1. O colaborador comenta na issue/card existente, informando que tem interesse em assumir a tarefa. +1. [Como as tarefas são distribuídas](#-como-as-tarefas-são-distribuídas) +2. [Começando: do fork ao projeto rodando](#-começando-do-fork-ao-projeto-rodando) +3. [Vai usar IA? Configure antes de começar](#-vai-usar-ia-configure-antes-de-começar) +4. [O fluxo de trabalho: branch, commit e PR](#-o-fluxo-de-trabalho-branch-commit-e-pr) +5. [Trabalhando com dependências](#-trabalhando-com-dependências) +6. [Agente de code review com IA](#-agente-de-code-review-com-ia) +7. [Husky e Integração Contínua](#-husky-e-integração-contínua) +8. [Acompanhamento da tarefa](#-acompanhamento-da-tarefa) +9. [Onde pedir ajuda](#-onde-pedir-ajuda) +10. [Regras de ouro](#-regras-de-ouro) +11. [Reconhecimento de colaboradores](#-reconhecimento-de-colaboradores) -2. Um responsável pelo projeto irá: - - Avaliar o pedido - - Atribuir oficialmente o colaborador à issue/card - - Definir ou validar o prazo de entrega +--- -3. Caso necessário, o colaborador pode solicitar prorrogação de prazo, exclusivamente via comentário na própria issue/card. +## ✔️ Como as tarefas são distribuídas -Esse fluxo garante controle, equidade na distribuição e rastreabilidade das responsabilidades. +As tarefas são organizadas em **cards/issues** no GitHub Projects, que podem ser +divididas em sub-issues quando necessário. ---- +⚠️ **Importante:** você não cria nem assume a issue por conta própria. -## 🧭 Fluxo de acompanhamento da tarefa +### 📌 Fluxo correto de atribuição -Depois que a tarefa for atribuída, mantenha o card sempre atualizado para que a equipe saiba o estado real do trabalho. +1. Comente na issue/card informando que tem interesse em assumir a tarefa. +2. Um responsável pelo projeto irá: + - avaliar o pedido; + - atribuir oficialmente você à issue/card; + - definir ou validar o prazo de entrega. +3. Se precisar de mais tempo, peça prorrogação **na própria issue**. -### ✔️ Status do card: -- **Em andamento:** use quando começar a implementar ou revisar a tarefa. -- **Bloqueado:** use quando precisar de uma decisão, acesso, ajuste de escopo ou ajuda técnica para continuar. -- **Concluído:** use apenas depois de abrir o Pull Request, validar localmente e deixar o link do PR no card. +Esse fluxo garante controle, equidade na distribuição e rastreabilidade. -### ✔️ Comunicação no card: -- Informe o prazo combinado antes de iniciar. -- Registre mudanças de prazo no próprio card. -- Explique bloqueios com contexto suficiente para outra pessoa ajudar. -- Ao abrir o PR, informe o link e diga quais validações foram executadas. +### ✔️ Ao demonstrar interesse -### ✔️ Fluxo de branch e PR: -- Crie a branch a partir de `develop`. -- Use um prefixo coerente com o tipo de trabalho: `feat`, `fix`, `docs`, `test`, `refactor`, `style` ou `chore`. -- Faça commits pequenos e claros. -- Abra o Pull Request sempre apontando para `develop`. -- Relacione o PR com a issue usando uma palavra de fechamento, por exemplo `Fixes: #123`, quando o PR concluir a tarefa. +- Avalie sua disponibilidade **antes** de se comprometer. +- Aguarde a atribuição formal antes de começar a codar. +- Tarefa atribuída = responsabilidade assumida. +- Se perceber que não vai conseguir cumprir o prazo, avise o quanto antes. ---- +> 💡 **É sua primeira contribuição?** Procure issues marcadas como +> `good first issue`. Elas foram escolhidas por serem seguras para começar. -## 🗂️ Regras e Organização +--- -### ✔️ Ao demonstrar interesse em uma tarefa (card): -- Comente claramente que deseja assumir a tarefa. -- Aguarde a atribuição formal por um responsável. -- Após atribuído, respeite o prazo acordado. -- Avalie sua disponibilidade antes de se comprometer. +## 🚀 Começando: do fork ao projeto rodando -### ✔️ Disciplina: -- Tarefa atribuída = responsabilidade assumida. -- Não deixe tarefas paradas sem atualização. -- Se perceber que não conseguirá cumprir o prazo, avise o quanto antes via comentário. +Siga na ordem. Cada passo depende do anterior. -### ✔️ Feedback constante: -- Se tiver dúvida, pergunte. -- Se alguém pedir ajuda, ajude. +### 1. Faça um fork do projeto ---- +Clique em **Fork**, no topo da página do repositório no GitHub. Isso cria uma +cópia do projeto na sua conta. -## ⚙️ Configuração do Ambiente Local +> Nunca contribuiu com fork antes? Veja o +> [tutorial oficial do GitHub](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/working-with-forks/fork-a-repo). -Antes de começar, instale as dependências com: +### 2. Clone o seu fork para o computador ```bash -npm run setup +git clone https://github.com/SEU-USUARIO/trycatch.git +cd trycatch ``` -> Este comando é um alias para `npm ci`, que instala **exatamente** o que está no `package-lock.json` sem modificá-lo. **Nunca use `npm install` apenas para configurar o ambiente** — isso pode reescrever o `package-lock.json` e gerar diffs desnecessários no seu PR. +Troque `SEU-USUARIO` pelo seu nome de usuário no GitHub. + +> ⚠️ **No Windows:** não coloque o projeto dentro de pastas sincronizadas +> (OneDrive, Google Drive, Dropbox). A sincronização trava arquivos e o git +> falha ao trocar de branch. Prefira algo como `C:\projetos\trycatch`. -**Versão do Node:** use Node 18 ou superior (a CI usa Node 24). Isso garante o formato v3 do lockfile, que é compatível entre plataformas (Windows, Linux, macOS). +### 3. Conecte ao repositório original -**Se você precisar adicionar ou atualizar um pacote**, use `npm install ` normalmente — nesse caso é esperado que tanto `package.json` quanto `package-lock.json` sejam alterados. Faça commit dos dois juntos: +Assim você consegue trazer as novidades do projeto para o seu fork: ```bash -git add package.json package-lock.json -git commit -m "chore(deps): add " +git remote add upstream https://github.com/TryCatch-ForMatch/trycatch.git ``` -**Se o `package-lock.json` aparecer como modificado após o setup**, você acidentalmente rodou `npm install`. Restaure com: +Confira com `git remote -v`. Devem aparecer os dois: `origin` (seu fork) e +`upstream` (o projeto original). + +### 4. Instale as dependências ```bash -git checkout -- package-lock.json npm run setup ``` ---- +Esse comando roda `npm ci`, que instala **exatamente** o que está no +`package-lock.json`. -## 🌿 Git Flow - Padrão de Branches +> ⚠️ **Não use `npm install` para configurar o ambiente.** Ele pode reescrever o +> `package-lock.json` e quebrar a integração contínua para todo mundo. Os +> detalhes estão em [Trabalhando com dependências](#-trabalhando-com-dependências). -### 🔥 Branch principal: -- `main`: versão estável e pronta pra produção. +**Versão do Node:** o projeto usa **Node 24**, a mesma do CI e da produção. Se +você usa `nvm` ou `fnm`, rode `nvm use` na raiz do projeto. -### 🧪 Branch de desenvolvimento: -- `develop`: onde integramos todas as features antes de ir pra `main`. +> O Prisma Client é gerado automaticamente pelo `postinstall`. Você **não** +> precisa rodar `npx prisma generate` na mão. -### 🌱 Branches de funcionalidades e correções: -- `feat/nome-da-feature`: nova funcionalidade (Ex: `feat/criar-login`) -- `fix/descricao-da-correcao`: correção de bug (Ex: `fix/erro-no-formulario`) -- `docs/descricao`: alteração em documentação   -- `style/descricao`: formatação sem mudança de código   -- `refactor/descricao`: refatoração sem alterar comportamento   -- `test/descricao`: testes adicionados ou corrigidos   -- `chore/descricao`: manutenção (dependências, configs, etc.) +### 5. Configure as variáveis de ambiente ---- +O projeto precisa de um arquivo `.env` na raiz. Peça o modelo no +[Discord](https://discord.gg/ZgUHkzf3r) ou consulte a seção correspondente no +[README](./README.md). + +No mínimo você vai precisar de `DATABASE_URL`, `NEXTAUTH_SECRET` e `JWT_SECRET`. -## 🔧 Antes de começar qualquer tarefa: +> 🔒 O `.env` **nunca** vai para o repositório. Ele já está no `.gitignore` — +> não force a inclusão dele em nenhuma hipótese. -1. Faça um fork do projeto via GitHub. Caso não saiba como, veja este [tutorial](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/working-with-forks/fork-a-repo). +### 6. Rode o projeto -2. Atualize a branch `develop` no seu computador: ```bash -git checkout develop -git pull origin develop +npm run dev ``` -3. Crie uma nova branch para o seu trabalho: +Abra . Se a página carregar, seu ambiente está pronto. 🎉 + +### 7. Verifique que está tudo funcionando ```bash -git checkout -b feat/nome-da-sua-feature +npm test # testes +npm run lint # padrões de código +npx tsc --noEmit # checagem de tipos ``` -4. Trabalhe, faça commits claros (use o Husky para isso) +> ℹ️ O projeto tem **erros de tipo já conhecidos**, que estão sendo corrigidos +> aos poucos. Se `npx tsc --noEmit` acusar erros em arquivos que você não +> tocou, não são seus — siga em frente e não tente corrigi-los. + +--- + +## 🤖 Vai usar IA? Configure antes de começar + +Muita gente usa assistente de IA no editor, e isso é **bem-vindo** aqui. O +projeto tem instruções próprias para essas ferramentas: elas explicam as regras, +as convenções e o fluxo, e ajustam o nível de explicação à sua experiência. -5. Ao finalizar: +**Você não precisa usar IA para contribuir.** Se preferir trabalhar sem, pule +esta seção — o restante do guia é suficiente. + +### Como funciona + +O projeto guarda o conteúdo em `docs/05 - contribuicao/`, e cada ferramenta lê +automaticamente um arquivo de "porta de entrada" na raiz: + +| Ferramenta | Arquivo que ela lê sozinha | +|---|---| +| GitHub Copilot | `.github/copilot-instructions.md` | +| Claude Code | `CLAUDE.md` | +| Cursor | `.cursor/rules/trycatch.mdc` | + +Ou seja: **basta abrir o projeto com a ferramenta instalada.** Ela encontra as +instruções sozinha e passa a seguir o fluxo do projeto. + +### Passo a passo + +**1. Escolha e instale uma ferramenta** + +| Ferramenta | Como instalar | Custo | +|---|---|---| +| **GitHub Copilot** | Extensão *GitHub Copilot* no VS Code → entrar com a conta GitHub | Plano gratuito com limite mensal; grátis para estudantes e mantenedores de open source | +| **Claude Code** | Extensão no VS Code, ou pelo terminal — veja a [documentação oficial](https://docs.claude.com/en/docs/claude-code/overview) | Plano gratuito com limite; planos pagos | +| **Cursor** | Editor próprio, baseado no VS Code — [cursor.com](https://cursor.com) | Plano gratuito com limite; planos pagos | + +Se você nunca usou nenhuma, o **Copilot** costuma ser o caminho mais simples: +instala como extensão comum do VS Code e tem plano gratuito. + +**2. Abra o projeto na ferramenta** + +Não precisa configurar mais nada. Ao abrir a pasta do projeto, a IA lê o arquivo +de porta e é direcionada para as instruções completas. + +**3. Diga o que você quer fazer** + +Comece por algo simples, como: + +> Quero pegar a issue #123. Por onde começo? + +A IA vai perguntar duas coisas: **em qual idioma você prefere conversar** e +**qual é a sua experiência** com contribuição em open source. A partir daí ela +ajusta o nível de explicação — mais detalhada para quem está começando, mais +direta para quem já conhece o fluxo. + +> 🌍 **A documentação do projeto está em português, mas você não precisa +> falar português para contribuir.** A IA conversa com você no seu idioma e +> traduz o conteúdo dos documentos conforme necessário. Se preferir escrever em +> inglês, espanhol ou qualquer outro idioma, é só escrever — ela acompanha. + +**4. (Opcional) Registre suas preferências** + +Para não responder a mesma pergunta toda vez: ```bash -git push origin feat/nome-da-sua-feature +cp "docs/05 - contribuicao/MINHAS-PREFERENCIAS.example.md" "docs/05 - contribuicao/MINHAS-PREFERENCIAS.md" ``` -6. Abra um Pull Request (PR) para a branch `develop` do repositório da organização. +Depois edite o arquivo com seu nível, sua ferramenta e como prefere trabalhar. +Ele fica **só na sua máquina** — está no `.gitignore`, como o `.env`. + +### O que esperar da IA neste projeto + +- **Ela ensina antes de fazer.** Diante de algo que você aprenderia fazendo — um + comando de git, rodar um teste, ler uma mensagem de erro —, ela mostra o + caminho e espera. Se você insistir, ela faz e explica. O objetivo aqui é você + aprender, não só o código ficar pronto. +- **`git commit`, `git push` e abrir o PR são sempre seus.** A IA ajuda a montar + a mensagem, mas quem executa é você. +- **Ela avisa quando algo fere as regras do projeto**, mesmo que você peça. Se + isso acontecer, leia o alerta — em geral é sobre segurança ou dados de pessoas + reais. + +### Documentos, se quiser se aprofundar + +| Arquivo | Conteúdo | +|---|---| +| [`IA-REGRAS.md`](docs/05%20-%20contribuicao/IA-REGRAS.md) | Regras invioláveis: segurança, autorização, dados pessoais, fluxo de git | +| [`IA-GUIA.md`](docs/05%20-%20contribuicao/IA-GUIA.md) | O fluxo de trabalho completo, passo a passo | +| [`IA-NIVEIS.md`](docs/05%20-%20contribuicao/IA-NIVEIS.md) | Como a IA se ajusta ao seu nível de experiência | + +> 💡 Se a IA fizer algo diferente do que está documentado, **é a documentação +> que vale**. Avise no Discord ou abra uma issue. --- -## 🤖 Como usar o Agente de Code Review Inteligente +## 🌿 O fluxo de trabalho: branch, commit e PR + +Este é o ciclo completo de uma contribuição, do início ao fim. + +### As branches do projeto + +| Branch | Para que serve | +|---|---| +| `main` | Versão estável, em produção. **Nunca** trabalhe direto nela | +| `develop` | Onde tudo é integrado. **É daqui que sai a sua branch, e é para cá que vai o seu PR** | +| `feat/`, `fix/`, … | A sua branch de trabalho | -Para ajudar a manter a qualidade do nosso código e te dar feedbacks rápidos antes mesmo de você enviar o seu Pull Request, nós usamos um robô de Code Review alimentado pela inteligência artificial do Gemini! +Prefixos: -Ele vai ler os arquivos que você alterou e gerar um relatório super organizado na pasta `docs/codereview_reports/` apontando melhorias de segurança, performance e boas práticas. +| Prefixo | Quando usar | Exemplo | +|---|---|---| +| `feat/` | funcionalidade nova | `feat/criar-login` | +| `fix/` | correção de bug | `fix/erro-no-formulario` | +| `docs/` | documentação | `docs/atualizar-readme` | +| `style/` | formatação, sem mudar comportamento | `style/ajustar-espacamento` | +| `refactor/` | refatoração, sem mudar comportamento | `refactor/extrair-service` | +| `test/` | testes | `test/cobertura-de-login` | +| `chore/` | manutenção, dependências, configuração | `chore/atualizar-eslint` | -### Aqui está o passo a passo para você configurar e usar essa ferramenta no seu computador: +### 1. Atualize a develop antes de começar -1. Criando sua Chave de API (Gratuita) -Não se preocupe, você não precisa pagar nada para usar essa inteligência artificial no projeto! +**Sempre**, no início de cada tarefa: -- Acesse o site do [Google AI Studio](https://aistudio.google.com/api-keys). +```bash +git checkout develop +git pull upstream develop +git push origin develop +``` -- Faça login usando qualquer conta comum do Google (Gmail). +O `pull upstream` traz as novidades do projeto original; o `push origin` +atualiza o seu fork. -- No menu lateral ou no topo, procure e clique no botão "Get API key" (Obter chave de API). +### 2. Crie a branch de trabalho -- Clique em "Create API Key" (Criar chave de API) e depois em "Create API key in new project". +```bash +git checkout -b feat/nome-da-sua-feature +``` -- Uma sequência grande de letras e números vai aparecer. Clique no botão para copiar essa chave e guarde-a (não feche a página antes de copiar!). +O `-b` cria a branch e já muda para ela. +### 3. Trabalhe e faça commits -2. Configurando suas Variáveis de Ambiente -O projeto precisa saber qual é a sua chave para conseguir conversar com o Gemini. +Use mensagens no padrão [Conventional Commits](https://www.conventionalcommits.org/pt-br/): -- Abra o seu arquivo `.env.local` (que você criou seguindo o passo a passo do [README](./README.md#-4-configure-o-arquivo-env)). +``` +feat: criar tela de cadastro de projeto +fix: corrigir bug no login +docs: atualizar guia de contribuição +``` -- Adicione a seguinte linha (substituindo pelo código que você copiou lá no site do Google): +Se preferir ser guiado passo a passo: +```bash +npm run commit ``` -GEMINI_API_KEY=Cole_Sua_Chave_Aqui_Sem_Aspas + +Isso abre o **Commitizen**, que monta a mensagem com você. Não precisa decorar +os padrões. + +**Vinculando a uma issue** — no final da mensagem: + +- `Refs: #42` apenas referencia a issue; +- `Fixes: #42` fecha a issue automaticamente quando o PR for mergeado. + +### 4. Verifique antes de enviar + +```bash +npm test +npm run lint +npx tsc --noEmit ``` -3. Rodando o Code Review -Com tudo configurado, agora ficou fácil! Sempre que quiser revisar seu código, abra o terminal na raiz do projeto e digite: +### 5. Envie e abra o Pull Request -```Bash -npm run review +```bash +git push origin feat/nome-da-sua-feature ``` -O terminal vai te dar 3 opções muito legais: +No GitHub, abra o PR **da sua branch para a `develop`** do repositório da +organização — nunca para a `main`. -- [1] Apenas os arquivos alterados: Perfeito para rodar antes de enviar seu código para nós! Ele revisa só o que você mexeu e que ainda não foi commitado. +Preencha o template que aparece: o que foi feito, a issue relacionada, como +testar. Descrever bem acelera a revisão. -- [2] Escolher uma pasta/módulo específico: Ótimo para quando você quer estudar ou revisar uma pasta inteira (como a src/app ou src/components). +### 6. Revisão -- [3] Todo o projeto: Ele vai ler o projeto inteiro dividindo em pequenos lotes para a IA não travar. +Alguém do time revisa e pode pedir ajustes. **Isso é normal e não é crítica +pessoal** — é assim que o código melhora e que a gente aprende junto. Responda +aos comentários, ajuste e envie de novo com um novo commit. -Abra o arquivo gerado na pasta `docs/codereview_reports/` para ver as dicas do seu Revisor Sênior virtual! 🚀 +Aprovado o PR, ele é mergeado na `develop`. Quando tudo estiver pronto para +produção, fazemos `develop → main`. --- -## 🔥 Pull Request (PR) - Fluxo +## 📦 Trabalhando com dependências -1. Cria a branch → Trabalha nela → Commit → Push -2. Abre PR da sua branch para `develop` -3. Descreva o que foi feito de forma clara -4. Alguém faz a revisão -5. PR aprovado → merge para `develop` +Esta seção importa mesmo que você não vá mexer em pacote nenhum — porque é fácil +alterar o `package-lock.json` sem querer. -Quando tudo estiver pronto para produção, fazemos `develop → main`. +### Para apenas instalar o projeto ---- +```bash +npm run setup +``` + +Nunca `npm install`. O `npm ci` instala exatamente o que está no lockfile, sem +reescrevê-lo. -## 🏗️ Commits com padrão (Conventional Commits) +### 🔴 O `package-lock.json` só pode ser gerado em Linux -Usamos mensagens de commit padronizadas. Exemplos: +Se você usa **Windows ou macOS**, **não rode `npm install`** neste projeto. -- `feat: criar tela de cadastro de projeto` -- `fix: corrigir bug no login` -- `docs: atualizar README` -- `style: formatar código com Prettier` -- `refactor: melhorar estrutura do formulário` -- `test: adicionar testes de autenticação` -- `chore: atualizar dependências` +**Por quê:** algumas dependências trazem versões compiladas específicas por +sistema operacional. O npm monta a árvore de forma diferente em cada plataforma, +e o `npm ci` do CI — que roda em Linux — recusa um lockfile gerado em outro +sistema. Isso já derrubou a integração contínua do projeto por horas. -### 💡 Como criar um commit corretamente: +**Como adicionar ou atualizar um pacote, então:** -Use o comando: +| Situação | O que fazer | +|---|---| +| Atualizar versão de um pacote | Deixe o **Dependabot** — ele roda em Linux | +| Adicionar dependência nova | Use **GitHub Codespaces** (Linux, no navegador), WSL ou Docker | +| Só instalar para trabalhar | `npm run setup` — não altera o lockfile | + +No Codespaces: ```bash -npm run commit +npm install +npm ci # valida na mesma plataforma do CI +git add package.json package-lock.json ``` -Isso vai abrir o **Commitizen**, que guia passo a passo. -Não precisa decorar os padrões, o assistente ajuda com tudo. +> ⚠️ **Antes de adicionar qualquer dependência, combine com o time.** Toda +> dependência nova é superfície de ataque, peso no bundle e manutenção futura. + +### Se o `package-lock.json` aparecer modificado sem querer + +Se você **não mexeu em dependências** e ele aparece como alterado, foi um +`npm install` acidental. Restaure: + +```bash +git checkout -- package-lock.json +npm run setup +``` + +> ⚠️ **Só faça isso se a alteração foi mesmo acidental.** Se você estava +> corrigindo o lockfile de propósito, esse comando desfaz o seu trabalho. Na +> dúvida, pergunte antes. --- -## 🔗 Vincular commits a issues +## 🔍 Agente de code review com IA + +Além das instruções para o seu assistente no editor, o projeto tem um **robô de +code review** que analisa os arquivos alterados e gera um relatório em +`docs/codereview_reports/`, apontando melhorias de segurança, performance e boas +práticas. + +É opcional, gratuito e roda no seu computador. -Se o commit estiver relacionado a uma issue aberta, adicione no final: +### 1. Crie sua chave de API (gratuita) -- Para apenas referenciar: `Refs: #42` -- Para fechar automaticamente: `Fixes: #42` +- Acesse o [Google AI Studio](https://aistudio.google.com/api-keys). +- Faça login com uma conta Google comum. +- Clique em **Get API key** → **Create API Key** → **Create API key in new project**. +- Copie a chave que aparecer (não feche a página antes de copiar!). -Exemplo na descrição longa: +### 2. Configure a variável de ambiente + +Abra o seu arquivo `.env` (o mesmo do passo 5 de *Começando*) e adicione: ``` -Atualiza botão de login. Fixes: #42 +GEMINI_API_KEY=cole_sua_chave_aqui_sem_aspas ``` +> 🔒 A chave é sua e pessoal. O `.env` não vai para o repositório — nunca +> compartilhe a chave em issue, PR ou mensagem. + +### 3. Rode o review + +```bash +npm run review +``` + +O terminal oferece três opções: + +- **[1] Apenas os arquivos alterados** — ideal antes de abrir o PR; +- **[2] Uma pasta específica** — bom para estudar um módulo; +- **[3] Todo o projeto** — em lotes, para não sobrecarregar. + +Depois abra o relatório gerado em `docs/codereview_reports/`. 🚀 + --- -## 🐶 Husky: por que usamos? +## 🐶 Husky e Integração Contínua -O **Husky** roda verificações automáticas antes de você fazer `commit` ou `push`, garantindo que: +### Husky: verificações automáticas antes do commit -- Seu código esteja formatado corretamente (com Prettier) -- Não quebrou nenhum teste (com Jest) -- A mensagem do commit siga o padrão (com Commitlint) +O **Husky** roda checagens automáticas antes de `commit` e `push`: -Assim, evitamos bugs ou código fora do padrão de entrar na base. +- formatação com Prettier; +- testes relacionados aos arquivos alterados, com Jest; +- padrão da mensagem de commit, com Commitlint; +- verificação de alterações indevidas no `package-lock.json`. -**Não precisa se preocupar**, tudo roda automaticamente! +**Não precisa configurar nada** — funciona sozinho depois do `npm run setup`. -Se necessário, pode ignorar os hooks com: +Se um hook bloquear o seu commit, **leia a mensagem**: quase sempre ela diz o que +fazer. Existe a opção de ignorar as verificações: ```bash git commit --no-verify ``` ---- +> ⚠️ Use isso **só** quando souber exatamente por que o hook está errado, e +> explique o motivo na descrição do PR. Pular as verificações por pressa costuma +> transferir o problema para outra pessoa. -## 🤖 Integração Contínua (CI) +### CI: o que roda quando você abre um PR -Ao abrir um Pull Request, a CI roda automaticamente: **build**, **lint**, -**testes**, **cobertura**, **auditoria de dependências** e, em seguida, -a análise do **SonarCloud**. +Automaticamente: **build**, **lint**, **testes**, **cobertura**, **auditoria de +dependências** e, em seguida, a análise do **SonarCloud**. -Pontos importantes para contribuidores: +Pontos que costumam gerar dúvida: -- A análise do **SonarCloud roda em um workflow separado** (disparado - após a CI). Isso é necessário porque PRs vindos de **forks** não - recebem secrets — sem essa separação, o Sonar falharia sempre. -- Para instalar dependências use `npm ci` (e **evite `npm install` no - Windows** apenas para instalar, pois isso pode reescrever o - `package-lock.json` e quebrar a CI). -- O **Prisma Client** é gerado automaticamente via `postinstall`; não - precisa rodar `npx prisma generate` manualmente após instalar. +- O **SonarCloud roda num workflow separado**, disparado após a CI. É necessário + porque PRs vindos de forks não recebem secrets — sem isso, ele falharia sempre. +- O job de **auditoria de dependências** pode aparecer vermelho por + vulnerabilidades em ferramentas de desenvolvimento que ainda não têm correção + publicada. Se o seu PR não mexeu em dependências, isso **não** é culpa dele. -O fluxo completo, os motivos e as orientações detalhadas estão em +O detalhamento está em [`docs/04 - processo/ci-e-validacao.md`](docs/04%20-%20processo/ci-e-validacao.md). --- -## 💬 Onde pedir ajuda? +## 🧭 Acompanhamento da tarefa -- No grupo da comunidade [Discord](https://discord.gg/ZgUHkzf3r) -- Abrindo uma issue no GitHub +Depois que a tarefa for atribuída, mantenha o card atualizado para que o time +saiba o estado real do trabalho. + +### Status do card + +| Status | Quando usar | +|---|---| +| **Em andamento** | ao começar a implementar ou revisar | +| **Bloqueado** | quando precisar de decisão, acesso, ajuste de escopo ou ajuda técnica | +| **Concluído** | só depois de abrir o PR, validar localmente e deixar o link no card | + +### Comunicação + +- Informe o prazo combinado antes de iniciar. +- Registre mudanças de prazo no próprio card. +- Explique bloqueios com contexto suficiente para outra pessoa conseguir ajudar. +- Ao abrir o PR, informe o link e diga quais validações você executou. --- -## 💛 Regras de Ouro +## 💬 Onde pedir ajuda -- Pessoas > Tecnologia -- Comprometimento > conhecimento técnico. -- Ninguém caminha sozinho: pergunte e ajude. -- Qualidade acima de quantidade. -- Comunicação sempre. -- Responsabilidade com prazos assumidos. +- No grupo da comunidade no [Discord](https://discord.gg/ZgUHkzf3r) +- Comentando na própria issue +- Abrindo uma issue nova, se for algo que ainda não existe + +**Não fique travado sozinho.** Perguntar cedo economiza o tempo de todo mundo, e +ninguém aqui vai achar sua dúvida boba. --- -## 🧑‍💻 Reconhecimento de colaboradores no projeto +## 💛 Regras de ouro + +- Pessoas > Tecnologia +- Comprometimento > conhecimento técnico +- Ninguém caminha sozinho: pergunte e ajude +- Qualidade acima de quantidade +- Comunicação sempre +- Responsabilidade com prazos assumidos -Para garantir que todos os colaboradores sejam reconhecidos, siga estas instruções: +--- -1. AComente na issue ou PR: +## 🧑‍💻 Reconhecimento de colaboradores + +Para garantir que todo mundo seja reconhecido, comente na issue ou no PR: ``` @all-contributors please add @usuario for code, doc ``` -> Substitua `@usuario` pelo nome de usuário GitHub do colaborador. -> Você pode adicionar múltiplos tipos de contribuição, separados por vírgula (`code`, `doc`, `test`, etc.). +> Substitua `@usuario` pelo nome de usuário no GitHub. Você pode listar vários +> tipos de contribuição separados por vírgula (`code`, `doc`, `test`, etc.). + +O bot atualiza automaticamente: -3. O bot vai atualizar automaticamente: - - O arquivo `CONTRIBUTORS.md` com o colaborador - - O badge de contagem de contribuidores no README +- o arquivo `CONTRIBUTORS.md`; +- o badge de contagem de contribuidores no README. -Para ver todas as opções de emoji de contribuição, confira a [emoji key do All Contributors](https://allcontributors.org/docs/en/emoji-key). +Veja todos os tipos na +[emoji key do All Contributors](https://allcontributors.org/docs/en/emoji-key). --- + +**Obrigada por contribuir com o TryCatch For Match!** 💛 diff --git a/README.md b/README.md index 22776ee7..24e2e668 100644 Binary files a/README.md and b/README.md differ diff --git a/docs/05 - contribuicao/IA-GUIA.md b/docs/05 - contribuicao/IA-GUIA.md index 770eff00..b477ab60 100644 --- a/docs/05 - contribuicao/IA-GUIA.md +++ b/docs/05 - contribuicao/IA-GUIA.md @@ -15,16 +15,29 @@ entender o que fez** — e conseguir de novo na próxima, com menos ajuda. Se `MINHAS-PREFERENCIAS.md` **existir**, leia e siga o que está lá. -Se **não existir**, a primeira coisa é perguntar: +Se **não existir**, a primeira coisa é perguntar **duas coisas juntas**: -> Antes de começarmos: qual é a sua experiência com contribuição em projetos -> open source? +> Antes de começarmos, duas perguntas rápidas: > -> **1. Primeira vez** — nunca abri um PR, ou abri pouquíssimos -> **2. Já contribuí antes** — conheço o fluxo, mas não este projeto -> **3. Experiente** — quero direto ao ponto +> **1. Em qual idioma você prefere conversar?** A documentação do projeto está +> em português, mas eu posso falar com você em qualquer idioma. > -> Pode mudar a qualquer momento: é só dizer "explica mais" ou "vai direto". +> **2. Qual é a sua experiência com contribuição em projetos open source?** +> +> - **Primeira vez** — nunca abri um PR, ou abri pouquíssimos +> - **Já contribuí antes** — conheço o fluxo, mas não este projeto +> - **Experiente** — quero direto ao ponto +> +> Pode mudar as duas a qualquer momento: é só pedir. + +> 🌍 **Sobre o idioma:** se a pessoa responder em outro idioma que não o +> português, **passe a conversar nele imediatamente**, sem esperar resposta à +> pergunta 1. O projeto recebe contribuidores de vários países; a documentação +> estar em português não deve ser barreira. +> +> Ao citar trechos dos documentos, **traduza o sentido** em vez de colar o +> original em português. Nomes de arquivo, comandos e termos de git +> (`branch`, `commit`, `pull request`) permanecem como estão. Depois de responder, ofereça criar o arquivo de preferências: diff --git a/docs/05 - contribuicao/IA-NIVEIS.md b/docs/05 - contribuicao/IA-NIVEIS.md index fb5b91b1..c3e366e0 100644 --- a/docs/05 - contribuicao/IA-NIVEIS.md +++ b/docs/05 - contribuicao/IA-NIVEIS.md @@ -14,22 +14,60 @@ regras.** ## A pergunta de calibragem -Quando `MINHAS-PREFERENCIAS.md` não existir, pergunte logo no início: +Quando `MINHAS-PREFERENCIAS.md` não existir, pergunte logo no início — **idioma +e nível, juntos**: -> Antes de começarmos: qual é a sua experiência com contribuição em projetos -> open source? +> Antes de começarmos, duas perguntas rápidas: > -> **1. Primeira vez** — nunca abri um PR, ou abri pouquíssimos -> **2. Já contribuí antes** — conheço o fluxo, mas não este projeto -> **3. Experiente** — quero direto ao ponto +> **1. Em qual idioma você prefere conversar?** A documentação do projeto está +> em português, mas eu posso falar com você em qualquer idioma. > -> Pode mudar a qualquer momento: é só dizer "explica mais" ou "vai direto". +> **2. Qual é a sua experiência com contribuição em projetos open source?** +> +> - **Primeira vez** — nunca abri um PR, ou abri pouquíssimos +> - **Já contribuí antes** — conheço o fluxo, mas não este projeto +> - **Experiente** — quero direto ao ponto +> +> Pode mudar as duas a qualquer momento: é só pedir. Depois ofereça registrar em `MINHAS-PREFERENCIAS.md`, para não repetir a pergunta nas próximas sessões. -**Se a pessoa não responder ou não souber**, assuma o **nível 2**. É o meio-termo -que menos incomoda: não infantiliza quem sabe, e não abandona quem não sabe. +**Se a pessoa não responder ou não souber o nível**, assuma o **nível 2**. É o +meio-termo que menos incomoda: não infantiliza quem sabe, e não abandona quem +não sabe. + +--- + +## 🌍 Idioma + +O TryCatch é um projeto brasileiro e sua documentação está em português. Mas ele +recebe — e quer receber — contribuidores de outros países. + +**A documentação estar em português não pode ser barreira de entrada.** + +### Como proceder + +- **Se a pessoa escrever em outro idioma, responda nesse idioma imediatamente.** + Não espere ela responder à pergunta de calibragem, e não peça para ela falar + português. +- Ao citar os documentos do projeto, **traduza o sentido**. Não cole o trecho + original em português esperando que a pessoa se vire. +- **Não traduza:** nomes de arquivo, comandos de terminal, nomes de branch, + mensagens de commit (que seguem Conventional Commits em inglês) e termos + consagrados de git — `branch`, `commit`, `merge`, `pull request`, `issue`. +- **Traduza:** explicações, alertas, o raciocínio por trás das decisões e o + conteúdo das regras. + +### O que não muda com o idioma + +As mensagens de commit, os nomes de branch e o conteúdo do código seguem o +padrão do projeto, independentemente do idioma da conversa. Uma pessoa +conversando em inglês ainda escreve `feat: adiciona filtro de projetos` se essa +for a convenção adotada — oriente sobre isso quando for relevante. + +> 💡 Se a pessoa registrar o idioma em `MINHAS-PREFERENCIAS.md`, use-o desde a +> primeira mensagem das próximas sessões, sem perguntar de novo. --- diff --git a/docs/05 - contribuicao/MINHAS-PREFERENCIAS.example.md b/docs/05 - contribuicao/MINHAS-PREFERENCIAS.example.md index fd0aeac7..daa442b2 100644 --- a/docs/05 - contribuicao/MINHAS-PREFERENCIAS.example.md +++ b/docs/05 - contribuicao/MINHAS-PREFERENCIAS.example.md @@ -33,7 +33,14 @@ - [ ] Cursor - [ ] Outra: ______ -**Idioma:** português +**Idioma em que quero conversar:** + + +- [ ] Português +- [ ] English +- [ ] Español +- [ ] Outro: ______ ---