Initial commit
This commit is contained in:
@@ -0,0 +1,217 @@
|
||||
# Plano de Responsividade Mobile + Reutilizacao de Codigo
|
||||
|
||||
## Breakpoints alvo
|
||||
|
||||
| Nome | Largura | Dispositivo |
|
||||
|-------|---------|--------------------------------|
|
||||
| xs | < 640px | iPhone SE, pequenos |
|
||||
| sm | 640px+ | Smartphones grandes |
|
||||
| md | 768px+ | Tablets retrato |
|
||||
| lg | 1024px+ | Tablets paisagem / laptops |
|
||||
|
||||
---
|
||||
|
||||
## Fase 0: Extrair componentes base (reutilizacao)
|
||||
|
||||
Antes de aplicar responsividade, consolidar codigo duplicado.
|
||||
|
||||
### 0.1 Componentes novos a criar
|
||||
|
||||
| Componente | Substitui | Arquivos afetados |
|
||||
|----------------------|------------------------------------------------|-------------------|
|
||||
| `Modal` | 11 copias do overlay `fixed inset-0 bg-black/50` | 11 arquivos |
|
||||
| `TableWrapper` | 9 wrappers identicos de tabela admin | 9 arquivos |
|
||||
| `MaterialsList` | Listagem de materiais nos 3 ClassDetail | 3 arquivos |
|
||||
| `ClassHistoryList` | 3 versoes (teacher/student/guardian) | 3 arquivos |
|
||||
| `PaymentForm` unificado | 2 PaymentForms 98% identicos | 2 arquivos |
|
||||
| `FormField` | Padrao label+input+helper repetido em 4 forms | 4 arquivos |
|
||||
| `Spinner` | SVG de loading copiado em 2+ arquivos | 2+ arquivos |
|
||||
|
||||
### 0.2 Componentes existentes nao utilizados
|
||||
|
||||
| Componente existente | Redefinido inline em | Acao |
|
||||
|---------------------------------------------------|-------------------------------------|---------------------------|
|
||||
| `Card` (`dashboard/components/Card.jsx`) | 20 ocorrencias em 10 arquivos | Importar em vez de inline |
|
||||
| `Stat` (`dashboard/components/Stat.jsx`) | Redefinido localmente em 2 arquivos | Importar |
|
||||
| `Row` (`dashboard/components/Row.jsx`) | Redefinido em `StudentClassDetail` | Importar |
|
||||
| `Button` (`shared/Button.jsx`) | Redefinido em `StudentClassDetail` | Importar |
|
||||
| `DashboardLayout` | Existe mas zero paginas usam | Adotar ou remover |
|
||||
| `dateUtils.js` | `formatDateBR` redefinido em 12 arquivos (22 instancias) | Importar |
|
||||
|
||||
### 0.3 Funcoes utilitarias a centralizar
|
||||
|
||||
| Funcao | Onde centralizar | Redefinida em |
|
||||
|--------------------|------------------------------------|---------------------|
|
||||
| `formatDateBR` | `@/app/lib/utils/dateUtils.js` | 12 arquivos |
|
||||
| `formatTime` | `@/app/lib/utils/dateUtils.js` | 2 ExamResults |
|
||||
| `normalizeStatus` | `@/app/lib/utils/statusPatterns.js`| 5 arquivos |
|
||||
|
||||
---
|
||||
|
||||
## Fase 1: Layout responsivo global
|
||||
|
||||
### 1.1 Admin Sidebar -- Drawer off-canvas
|
||||
|
||||
**Arquivos**: `SideBarNav.jsx:7`, `admin/layout.jsx:22-28`
|
||||
|
||||
**Problema**: Sidebar fixa `w-64` (256px) visivel em todas as telas. Em celulares de 375px, sobram ~119px para conteudo.
|
||||
|
||||
**Solucao**:
|
||||
- Criar `MobileSidebarToggle` (hamburger button) visivel apenas em `md:hidden`
|
||||
- Sidebar: `hidden md:flex` + state para abrir/fechar no mobile com overlay
|
||||
- Usar `@headlessui/react` (ja no projeto) para o Dialog/Drawer
|
||||
- Drawer aberto: largura `w-72` + overlay escuro
|
||||
- Animação de slide-in/slide-out
|
||||
|
||||
### 1.2 Page container padronizado
|
||||
|
||||
**Problema**: 14+ paginas com container `max-w-6xl mx-auto p-6` hardcoded de formas inconsistentes.
|
||||
|
||||
**Solucao**: Padronizar usando `MainSection` ou `DashboardLayout` com padding responsivo:
|
||||
```
|
||||
px-4 sm:px-6 lg:px-8 py-4 sm:py-6
|
||||
```
|
||||
|
||||
| Pagina | Container atual | Correcao |
|
||||
|----------------------------|----------------------------------|----------------------------|
|
||||
| `student/StudentClassDetail` | `max-w-6xl p-6` (sem mx-auto) | Adicionar `mx-auto` |
|
||||
| `guardian/GuardianClassDetail` | `w-full p-6` | `max-w-6xl mx-auto p-4 sm:p-6` |
|
||||
| `guardian/GuardianClassHistoryList` | `w-full` sem padding | Adicionar `px-4 sm:px-6` |
|
||||
| Todas as outras | Variacoes de `max-w-6xl mx-auto p-6` | Padronizar via `MainSection` |
|
||||
|
||||
### 1.3 `PageHeader` -- actions com wrap
|
||||
|
||||
**Arquivo**: `shared/PageHeader.jsx:29`
|
||||
|
||||
**Correcao**: Adicionar `flex-wrap` no div de actions. Resolve ~9 paginas de uma vez.
|
||||
|
||||
---
|
||||
|
||||
## Fase 2: Componentes responsivos (1 correcao aplica-se a N paginas)
|
||||
|
||||
### 2.1 `Modal` (novo componente)
|
||||
|
||||
```
|
||||
max-w-[95vw] sm:max-w-2xl md:max-w-4xl
|
||||
```
|
||||
+ padding responsivo `p-4 sm:p-6`
|
||||
|
||||
**Afeta**: 11 modais
|
||||
|
||||
### 2.2 `TableWrapper` (novo componente)
|
||||
|
||||
- `overflow-x-auto` por padrao
|
||||
- Borda e estilo consistentes
|
||||
|
||||
**Afeta**: 9 tabelas admin
|
||||
|
||||
### 2.3 `MainSection` -- padding responsivo
|
||||
|
||||
```
|
||||
p-4 sm:p-6
|
||||
```
|
||||
|
||||
**Afeta**: todas as paginas que usam `MainSection`
|
||||
|
||||
---
|
||||
|
||||
## Fase 3: Ajustes por componente
|
||||
|
||||
### 3.1 Grids sem breakpoint responsivo
|
||||
|
||||
| Arquivo | Linha | Atual | Correcao |
|
||||
|------------------------------------------|-------|-------------------|---------------------------------|
|
||||
| `teacher/ExamResults.jsx` | 140 | `grid-cols-3` | `grid-cols-1 sm:grid-cols-3` |
|
||||
| `teacher/ExamResults.jsx` | 251 | `grid-cols-2` | `grid-cols-1 sm:grid-cols-2` |
|
||||
| `exam-templates/TemplateForm.jsx` | 485 | `grid-cols-2` | `grid-cols-1 sm:grid-cols-2` |
|
||||
| `exam-templates/AssignmentForm.jsx` | 485 | `grid-cols-2` | `grid-cols-1 sm:grid-cols-2` |
|
||||
|
||||
### 3.2 Tabela com overflow-hidden
|
||||
|
||||
| Arquivo | Linha | Atual | Correcao |
|
||||
|----------------------------|-------|-------------------|-------------------|
|
||||
| `teacher/ClassDetail.jsx` | 304 | `overflow-hidden` | `overflow-x-auto` |
|
||||
|
||||
### 3.3 Flex layouts que transbordam
|
||||
|
||||
| Arquivo | Linha | Correcao |
|
||||
|----------------------------------|----------|---------------------------------------------|
|
||||
| `student/TakeExam.jsx` | 211 | `flex-wrap` + `gap-2` |
|
||||
| `dashboard/student/page.jsx` | 29 | `flex-wrap` nos botoes |
|
||||
| `teacher/ExamResults.jsx` | 169 | `flex-wrap` nos metadados |
|
||||
| `student/ExamResults.jsx` | 269 | `flex-wrap gap-4` no resumo |
|
||||
| `lessons/LessonForm.jsx` | 372-376 | `flex-col sm:flex-row` |
|
||||
| `teacher/AssignmentList.jsx` | 127 | `flex-wrap gap-2` |
|
||||
| `exam-templates/TemplateList.jsx`| 153 | `flex-wrap` nos botoes |
|
||||
| `student/AvailableExams.jsx` | 187, 231 | `flex-col sm:flex-row` |
|
||||
|
||||
### 3.4 Texto longo sem quebra
|
||||
|
||||
| Arquivo | Linha | Correcao |
|
||||
|----------------------------------------|-------|---------------------|
|
||||
| `guardian/GuardianClassDetail.jsx` | 40 | `break-words` |
|
||||
| `teacher/class/[id]/page.jsx` | 212 | Truncar no mobile |
|
||||
|
||||
### 3.5 Tabelas com muitas colunas -- ocultar no mobile
|
||||
|
||||
| Arquivo | Colunas | Correcao |
|
||||
|--------------------------------|---------|---------------------------------------|
|
||||
| `teacher/ExamStatistics.jsx` | 7 | `hidden sm:table-cell` nas colunas menos importantes |
|
||||
| `guardian/payments/page.jsx` | 6 | Ocultar "Comprovante" no mobile |
|
||||
|
||||
### 3.6 Botoes que podem empilhar
|
||||
|
||||
| Arquivo | Linha | Correcao |
|
||||
|------------------|-------|-------------------------|
|
||||
| `PaymentForm.jsx`| 193 | `flex-col sm:flex-row` |
|
||||
| `RegisterForm.jsx`| 253 | `flex-col sm:flex-row` |
|
||||
|
||||
---
|
||||
|
||||
## Header mobile -- ja parcialmente implementado
|
||||
|
||||
O `Header.jsx` ja tem navegacao mobile (`md:hidden` com scroll horizontal). Pontos de melhoria:
|
||||
- Chips de navegacao mobile (linhas 147-162) poderiam usar icones maiores e mais touch-friendly
|
||||
- Considerar colapsar os chips em menu hamburger quando ha mais de 4 items (admin tem 6 links)
|
||||
|
||||
---
|
||||
|
||||
## Resumo de prioridade de execucao
|
||||
|
||||
1. **Fase 0** -- Extrair componentes base (maior esforco, maior ganho em manutenibilidade)
|
||||
2. **Fase 1** -- Layout global responsivo (sidebar + containers + page header)
|
||||
3. **Fase 2** -- Componentes responsivos reutilizaveis (Modal + TableWrapper)
|
||||
4. **Fase 3** -- Ajustes pontuais por componente (grids, flex, tabelas)
|
||||
|
||||
---
|
||||
|
||||
## Metricas estimadas
|
||||
|
||||
| Metricica | Valor |
|
||||
|------------------------------------|----------------------|
|
||||
| Arquivos alterados | ~18 |
|
||||
| Linhas removidas (duplicacao) | ~800-1000 |
|
||||
| Componentes novos reutilizaveis | 7 |
|
||||
| Componentes importados (ja existiam)| 6 |
|
||||
| Correcoes de responsividade | ~26 |
|
||||
| Modais afetados por 1 componente | 11 |
|
||||
| Tabelas afetadas por 1 componente | 9 |
|
||||
|
||||
---
|
||||
|
||||
## Componentes que NAO precisam de correcao de responsividade
|
||||
|
||||
Ja estao corretos:
|
||||
- `page.jsx` (landing page) -- bem estruturado com breakpoints
|
||||
- `LoginForm.jsx` -- formulario centralizado simples
|
||||
- `ClassCard.jsx` -- card layout responsivo
|
||||
- `ClassCardsComponent.jsx` -- `grid-cols-1 sm:grid-cols-2`
|
||||
- `WardClassCardComponent.jsx` -- `grid-cols-1 sm:grid-cols-2 lg:grid-cols-3`
|
||||
- `DashboardCard.jsx` -- card layout
|
||||
- `AdminDashboard.jsx` -- `grid-cols-1 sm:grid-cols-2`
|
||||
- `RoleDispatcher.jsx` -- `grid-cols-1 sm:grid-cols-2`
|
||||
- `ProfileForm.jsx` -- `grid-cols-1 md:grid-cols-2`
|
||||
- `PasswordUpdateForm.jsx` -- `grid-cols-1 md:grid-cols-2`
|
||||
- `AffiliateProductsSection.jsx` -- `grid-cols-1 sm:grid-cols-2 lg:grid-cols-3`
|
||||
- `ToggleTheme.jsx` -- botao de tamanho fixo
|
||||
- `UserMenu.jsx` -- esconde nome em telas pequenas com `hidden sm:inline`
|
||||
@@ -0,0 +1,102 @@
|
||||
# Dashboard Design System - Standardization Plan
|
||||
|
||||
## Problem Analysis
|
||||
|
||||
Current dashboards have **inconsistent layouts** causing width and spacing issues:
|
||||
|
||||
| Dashboard | Width Constraint | Padding | Layout Component |
|
||||
|-----------|------------------|---------|------------------|
|
||||
| Admin | `max-w-6xl mx-auto p-6` | 1.5rem | Page-level wrapper |
|
||||
| Teacher | None (uses MainSection) | 2rem (p-8) | MainSection with no max-width |
|
||||
| Student | `max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6` | Variable | Page-level wrapper |
|
||||
| Guardian | `max-w-5xl mx-auto` | 2rem (p-8) | MainSection + inner wrapper |
|
||||
|
||||
### Additional Issues:
|
||||
1. **Global CSS** (lines 451-459) adds underline to all links on hover
|
||||
2. **ClassCardsComponent** has `lg:grid-cols-3` causing 3 cards per row on large screens
|
||||
3. **ClassCard** links have default underline on hover
|
||||
|
||||
## Proposed Solution
|
||||
|
||||
### 1. Update MainSection Component
|
||||
Add width constraint to standardize all dashboards using it:
|
||||
```jsx
|
||||
// Current
|
||||
<main className={`flex-1 p-8 overflow-y-auto ${className}`}>
|
||||
|
||||
// Proposed
|
||||
<main className={`flex-1 p-6 overflow-y-auto ${className}`}>
|
||||
<div className="max-w-7xl mx-auto">
|
||||
{children}
|
||||
</div>
|
||||
</main>
|
||||
```
|
||||
|
||||
### 2. Remove Global Link Underline
|
||||
Remove hover underline from globals.css (lines 457-459):
|
||||
```css
|
||||
/* Remove these lines */
|
||||
a:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
```
|
||||
|
||||
### 3. Standardize ClassCardsComponent Grid
|
||||
Change from 3 columns to max 2 columns:
|
||||
```jsx
|
||||
// Current
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
|
||||
// Proposed
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||
```
|
||||
|
||||
### 4. Ensure ClassCard Has No Underline
|
||||
Keep the `no-underline` class on Link:
|
||||
```jsx
|
||||
<Link href={link} className="block no-underline">
|
||||
```
|
||||
|
||||
### 5. Standard Dashboard Page Pattern
|
||||
All dashboard pages should follow this structure:
|
||||
```jsx
|
||||
<MainSection>
|
||||
<div className="max-w-6xl mx-auto">
|
||||
<PageTitle title="..." subTitle="..."/>
|
||||
{/* Content */}
|
||||
</div>
|
||||
</MainSection>
|
||||
```
|
||||
|
||||
### 6. Create Shared DashboardLayout Component (Optional)
|
||||
For future consistency, create a reusable component:
|
||||
```jsx
|
||||
// src/app/(protected)/components/DashboardLayout.jsx
|
||||
export function DashboardLayout({ title, subtitle, children }) {
|
||||
return (
|
||||
<MainSection>
|
||||
<div className="max-w-6xl mx-auto">
|
||||
<PageTitle title={title} subTitle={subtitle}/>
|
||||
{children}
|
||||
</div>
|
||||
</MainSection>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
## Files to Modify
|
||||
|
||||
1. [`src/app/(protected)/components/shared/Main.jsx`](src/app/\(protected\)/components/shared/Main.jsx) - Add max-width wrapper
|
||||
2. [`src/app/globals.css`](src/app/globals.css) - Remove link hover underline
|
||||
3. [`src/app/(protected)/components/shared/ClassCardsComponent.jsx`](src/app/\(protected\)/components/shared/ClassCardsComponent.jsx) - Standardize grid
|
||||
4. [`src/app/(protected)/components/shared/ClassCard.jsx`](src/app/\(protected\)/components/shared/ClassCard.jsx) - Ensure no-underline
|
||||
5. [`src/app/(protected)/dashboard/teacher/page.jsx`](src/app/\(protected\)/dashboard/teacher/page.jsx) - Remove redundant wrapper
|
||||
6. (Optional) [`src/app/(protected)/components/DashboardLayout.jsx`](src/app/\(protected\)/components/DashboardLayout.jsx) - Create reusable component
|
||||
|
||||
## After Changes
|
||||
|
||||
All dashboards will:
|
||||
- Have consistent max-width (`max-w-6xl` ≈ 72rem / 1152px)
|
||||
- Use consistent padding (`p-6` ≈ 1.5rem)
|
||||
- Display max 2 cards per row
|
||||
- No underline on link hover
|
||||
@@ -0,0 +1,177 @@
|
||||
# Payment Registration System Architecture
|
||||
|
||||
## Overview
|
||||
A payment registration system that allows guardians/students to register payments for classes and enables admins to track payment status.
|
||||
|
||||
## Requirements
|
||||
- **Users**: Guardians/students can register payments, admins can view payment status
|
||||
- **Payment Information**: Value, date/time, optional receipt image
|
||||
- **Access Control**: Only admins can view payment details; guardians/students can only register their own payments
|
||||
|
||||
## Database Schema Design
|
||||
|
||||
### Payment Model
|
||||
```javascript
|
||||
{
|
||||
_id: ObjectId,
|
||||
classId: ObjectId (ref: Class),
|
||||
userId: ObjectId (ref: User),
|
||||
amount: Number,
|
||||
paymentDate: Date,
|
||||
paymentMethod: String (e.g., "pix", "bank_transfer", "cash"),
|
||||
status: String (enum: ["pending", "verified", "rejected"]),
|
||||
receiptUrl: String (optional, from file upload),
|
||||
notes: String (optional),
|
||||
createdAt: Date,
|
||||
updatedAt: Date
|
||||
}
|
||||
```
|
||||
|
||||
### Key Features
|
||||
- **One-to-Many**: A class can have multiple payments (partial payments)
|
||||
- **Many-to-One**: A user can make multiple payments across different classes
|
||||
- **Status Tracking**: Pending → Verified/Rejected workflow
|
||||
|
||||
## API Routes Structure
|
||||
|
||||
### 1. Payment API Routes
|
||||
```
|
||||
/api/payments
|
||||
GET - List all payments (admin only)
|
||||
POST - Create new payment (guardian/student only)
|
||||
GET/:id - Get single payment (admin only)
|
||||
PUT/:id - Update payment status (admin only)
|
||||
DELETE/:id - Delete payment (admin only)
|
||||
|
||||
/api/payments/class/:classId
|
||||
GET - Get all payments for a specific class (admin only)
|
||||
|
||||
/api/payments/user/:userId
|
||||
GET - Get all payments for a specific user (guardian/student only)
|
||||
```
|
||||
|
||||
### 2. File Upload Integration
|
||||
- Use existing `/api/files` routes
|
||||
- Set `relatedToType` = "payment"
|
||||
- Set `relatedToId` = payment ID
|
||||
- Store receipt image URL in payment record
|
||||
|
||||
## UI Components Structure
|
||||
|
||||
### Admin Dashboard
|
||||
```
|
||||
/app/(protected)/admin/dashboard/payments/
|
||||
page.jsx - Main payments dashboard
|
||||
components/
|
||||
PaymentsTable.jsx - Table showing all payments
|
||||
PaymentDetail.jsx - Modal showing payment details
|
||||
PaymentStats.jsx - Statistics cards
|
||||
VerifyPaymentButton.jsx - Button to verify/reject payments
|
||||
```
|
||||
|
||||
### Guardian Dashboard
|
||||
```
|
||||
/app/(protected)/dashboard/guardian/payments/
|
||||
page.jsx - List of registered payments
|
||||
register/
|
||||
page.jsx - Payment registration form
|
||||
components/
|
||||
PaymentForm.jsx - Form to register payment
|
||||
ReceiptUpload.jsx - File upload component
|
||||
|
||||
/app/(protected)/dashboard/guardian/class/[id]/payments/
|
||||
page.jsx - Payments for specific class
|
||||
```
|
||||
|
||||
### Student Dashboard
|
||||
```
|
||||
/app/(protected)/dashboard/student/payments/
|
||||
page.jsx - List of registered payments
|
||||
register/
|
||||
page.jsx - Payment registration form
|
||||
```
|
||||
|
||||
## Payment Flow Diagram
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant G as Guardian/Student
|
||||
participant UI as UI Component
|
||||
participant API as API Route
|
||||
participant DB as Database
|
||||
participant FS as File Storage
|
||||
|
||||
G->>UI: Submit payment form (amount, date, receipt)
|
||||
UI->>API: POST /api/payments
|
||||
API->>DB: Create payment record (status: pending)
|
||||
API->>FS: Upload receipt image
|
||||
API->>DB: Update payment with receipt URL
|
||||
API-->>UI: Return payment confirmation
|
||||
UI-->>G: Show success message
|
||||
|
||||
Note over Admin: Admin views dashboard
|
||||
Admin->>UI: View payments dashboard
|
||||
UI->>API: GET /api/payments
|
||||
API-->>UI: Return all payments
|
||||
UI-->>Admin: Display payment table with status
|
||||
```
|
||||
|
||||
## Class View Integration
|
||||
|
||||
### Guardian Class Detail Page
|
||||
- Add payment status indicator
|
||||
- Show "Register Payment" button if not paid
|
||||
- Show payment history for the class
|
||||
|
||||
### Admin Class View
|
||||
- Show payment status for all students
|
||||
- Filter by payment status
|
||||
- Quick actions to verify/reject payments
|
||||
|
||||
## Implementation Steps
|
||||
|
||||
### Phase 1: Database & API
|
||||
1. Create Payment model
|
||||
2. Create API routes for payment CRUD operations
|
||||
3. Integrate with existing file upload system
|
||||
|
||||
### Phase 2: Admin Dashboard
|
||||
1. Create payments dashboard page
|
||||
2. Build payments table with filtering
|
||||
3. Add payment detail modal
|
||||
4. Implement verify/reject functionality
|
||||
|
||||
### Phase 3: Guardian/Student Interface
|
||||
1. Create payment registration form
|
||||
2. Build payment history view
|
||||
3. Integrate receipt upload
|
||||
4. Add payment status indicators
|
||||
|
||||
### Phase 4: Integration
|
||||
1. Update class detail pages
|
||||
2. Add payment status to class cards
|
||||
3. Add payment reminders (optional)
|
||||
|
||||
## Security Considerations
|
||||
- **Role-Based Access Control**: Only admins can view payment details
|
||||
- **Data Validation**: Validate payment amounts and dates
|
||||
- **File Upload Security**: Validate receipt images before storing
|
||||
- **User Authorization**: Users can only register payments for their own classes
|
||||
|
||||
## Data Validation Rules
|
||||
- Amount: Must be positive number
|
||||
- Payment Date: Must be in the past or present
|
||||
- Receipt: Max file size, allowed image formats only
|
||||
- Payment Method: Must be from predefined list
|
||||
|
||||
## Status Workflow
|
||||
```
|
||||
Pending (default) → Verified (admin approves) → Rejected (admin rejects)
|
||||
```
|
||||
|
||||
## Future Enhancements
|
||||
- Payment reminders for pending payments
|
||||
- Payment history export
|
||||
- Bulk payment verification
|
||||
- Payment analytics and reports
|
||||
- Integration with payment gateways (optional)
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,139 @@
|
||||
# Payment Registration System - Summary
|
||||
|
||||
## Overview
|
||||
A complete payment registration system for your course platform that allows guardians/students to register payments and enables admins to track payment status.
|
||||
|
||||
## What You'll Get
|
||||
|
||||
### 1. **Database Model**
|
||||
- New [`Payment`](src/app/models/Payment.js) model with fields:
|
||||
- `classId` - Reference to the class
|
||||
- `userId` - Reference to the user (guardian/student)
|
||||
- `amount` - Payment value
|
||||
- `paymentDate` - Date and time of payment
|
||||
- `paymentMethod` - Method (PIX, bank transfer, cash, etc.)
|
||||
- `status` - Pending, Verified, or Rejected
|
||||
- `receiptUrl` - Optional receipt image
|
||||
- `notes` - Optional notes
|
||||
|
||||
### 2. **API Routes**
|
||||
- [`/api/payments`](src/app/api/payments/route.js) - Create and list payments
|
||||
- [`/api/payments/[id]`](src/app/api/payments/[id]/route.js) - Get, update, delete single payment
|
||||
- [`/api/payments/class/[classId]`](src/app/api/payments/class/[classId]/route.js) - Get all payments for a class
|
||||
- [`/api/payments/user/[userId]`](src/app/api/payments/user/[userId]/route.js) - Get all payments for a user
|
||||
|
||||
### 3. **Admin Dashboard**
|
||||
- [`/admin/dashboard/payments`](src/app/(protected)/admin/dashboard/payments/page.jsx) - Main dashboard
|
||||
- **Features**:
|
||||
- View all payments in a table
|
||||
- Filter by status (all, pending, verified, rejected)
|
||||
- See payment statistics (total, verified, pending, rejected)
|
||||
- Verify or reject payments
|
||||
- View payment details
|
||||
|
||||
### 4. **Guardian/Student Interface**
|
||||
- **Payment Registration**:
|
||||
- Form to register payments with amount, date, method
|
||||
- Optional receipt image upload
|
||||
- Notes field for additional information
|
||||
- **Payment History**:
|
||||
- View all registered payments
|
||||
- See payment status for each class
|
||||
|
||||
### 5. **Payment Status Indicators**
|
||||
- Reusable [`PaymentStatusBadge`](src/app/(protected)/components/shared/PaymentStatusBadge.jsx) component
|
||||
- Shows status: Not Paid, Pending, Paid, or Rejected
|
||||
- Color-coded badges for easy identification
|
||||
|
||||
## How It Works
|
||||
|
||||
### For Guardians/Students:
|
||||
1. Navigate to a class they're enrolled in or their ward is enrolled in
|
||||
2. Click "Registrar Pagamento" (Register Payment)
|
||||
3. Fill in payment details:
|
||||
- Amount (R$)
|
||||
- Payment date
|
||||
- Payment method (PIX, bank transfer, cash, etc.)
|
||||
- Optional: Upload receipt image
|
||||
- Optional: Add notes
|
||||
4. Submit the form
|
||||
5. Payment status becomes "Pending" (waiting for admin verification)
|
||||
|
||||
### For Admins:
|
||||
1. Navigate to Admin Dashboard → Payments
|
||||
2. View all payments in a table
|
||||
3. See payment statistics at the top
|
||||
4. Filter payments by status
|
||||
5. Click on a payment to see details
|
||||
6. Verify or reject the payment
|
||||
7. Payment status updates accordingly
|
||||
|
||||
## File Structure
|
||||
|
||||
```
|
||||
src/
|
||||
├── app/
|
||||
│ ├── api/payments/ # API routes
|
||||
│ ├── (protected)/
|
||||
│ │ ├── admin/dashboard/payments/ # Admin dashboard
|
||||
│ │ ├── dashboard/guardian/payments/ # Guardian interface
|
||||
│ │ └── dashboard/student/payments/ # Student interface
|
||||
│ └── components/shared/PaymentStatusBadge.jsx # Reusable component
|
||||
├── models/Payment.js # Payment model
|
||||
└── lib/utils/payments.js # Helper functions
|
||||
```
|
||||
|
||||
## Security Features
|
||||
|
||||
- **Role-Based Access Control**:
|
||||
- Only admins can view payment details
|
||||
- Guardians can only register payments for their wards
|
||||
- Students can only register payments for their enrolled classes
|
||||
- **Data Validation**:
|
||||
- Amount must be positive
|
||||
- Payment date must be valid
|
||||
- File uploads are validated
|
||||
- **Data Integrity**:
|
||||
- All payments are tracked with timestamps
|
||||
- Payment status workflow is enforced
|
||||
|
||||
## Integration with Existing System
|
||||
|
||||
- Uses existing file upload infrastructure
|
||||
- Integrates with existing User and Class models
|
||||
- Follows existing API patterns
|
||||
- Uses existing UI components
|
||||
- Compatible with current role-based authentication
|
||||
|
||||
## Next Steps
|
||||
|
||||
1. **Review the plans**:
|
||||
- [`payment-system-architecture.md`](plans/payment-system-architecture.md) - High-level architecture
|
||||
- [`payment-system-implementation.md`](plans/payment-system-implementation.md) - Detailed implementation guide
|
||||
|
||||
2. **Implementation order**:
|
||||
- Create Payment model
|
||||
- Create API routes
|
||||
- Create admin dashboard
|
||||
- Create guardian/student interface
|
||||
- Integrate with class views
|
||||
- Test the complete flow
|
||||
|
||||
3. **Testing checklist**:
|
||||
- Create payment with guardian account
|
||||
- Verify payment with admin account
|
||||
- Test file upload for receipts
|
||||
- Verify role-based access control
|
||||
- Test payment status indicators
|
||||
|
||||
## Questions?
|
||||
|
||||
The detailed implementation guide includes:
|
||||
- Complete code for all components
|
||||
- API route implementations
|
||||
- Database schema definitions
|
||||
- UI component code
|
||||
- Integration points
|
||||
- Testing checklist
|
||||
|
||||
Would you like me to proceed with implementing this system? I can start by creating the Payment model and API routes.
|
||||
@@ -0,0 +1,283 @@
|
||||
# Plano de Refatoracao por Fases
|
||||
|
||||
Este documento organiza a correcao do projeto em fases pequenas, verificaveis e sem ruptura grande.
|
||||
|
||||
Objetivo principal:
|
||||
- estabilizar build e seguranca
|
||||
- migrar gradualmente de API Routes para Server Actions
|
||||
- eliminar conflitos de CSS global (sem `!important`)
|
||||
- aproximar o frontend de um estilo tipo shadcn (componentes reutilizaveis + tokens consistentes)
|
||||
|
||||
---
|
||||
|
||||
## Visao Geral das Fases
|
||||
|
||||
1. Fase 0 - Baseline e congelamento
|
||||
2. Fase 1 - Build, auth e seguranca minima
|
||||
3. Fase 2 - Migracao API -> Server Actions
|
||||
4. Fase 3 - Reset de CSS global e fim de conflitos
|
||||
5. Fase 4 - Base de design system estilo shadcn
|
||||
6. Fase 5 - Refino visual da plataforma de ingles
|
||||
7. Fase 6 - Limpeza final e hardening
|
||||
|
||||
Cada fase tem: escopo, tarefas, definicao de pronto e risco.
|
||||
|
||||
### Status consolidado (fev/2026)
|
||||
- Fase 1: concluida.
|
||||
- Fase 2: concluida nos dominios planejados para fluxo interno (APIs legadas mantidas como fallback temporario).
|
||||
- Fase 3: concluida no objetivo principal (globals enxuto, sem `!important`, sem overrides globais agressivos).
|
||||
- Fase 4: concluida no escopo principal (base `ui` ativa + login/register + dashboards principais migrados).
|
||||
- Fase 5: pendente (refino visual mais amplo ainda nao iniciado de forma sistematica).
|
||||
- Fase 6: em andamento parcial (melhorias de feedback ao usuario e tratamento de erros em fluxos criticos).
|
||||
|
||||
---
|
||||
|
||||
## Fase 0 - Baseline e congelamento
|
||||
|
||||
### Escopo
|
||||
Criar um ponto de partida confiavel antes de alterar arquitetura.
|
||||
|
||||
### Tarefas
|
||||
- [ ] Registrar o estado atual (erros conhecidos, rotas criticas, telas criticas).
|
||||
- [ ] Salvar relatorio de build/lint/testes E2E atuais.
|
||||
- [ ] Definir branch de refatoracao (ex.: `refactor/phases`).
|
||||
- [ ] Congelar novas features ate concluir Fase 2.
|
||||
|
||||
### Definicao de pronto
|
||||
- Baseline documentado e reproduzivel.
|
||||
- Time alinhado sobre prioridades e ordem de execucao.
|
||||
|
||||
### Risco
|
||||
- Baixo. Sem mudanca de codigo de negocio.
|
||||
|
||||
---
|
||||
|
||||
## Fase 1 - Build, auth e seguranca minima
|
||||
|
||||
### Escopo
|
||||
Resolver problemas que quebram producao/deploy e vazamentos de autorizacao.
|
||||
|
||||
### Tarefas
|
||||
- [x] Corrigir middleware para nao importar auth/db de runtime Edge.
|
||||
- Opcao recomendada: middleware apenas para roteamento simples.
|
||||
- Verificacao de permissao real fica no server (Server Components/Server Actions).
|
||||
- [x] Revisar matcher do middleware para incluir rotas protegidas reais (`/admin/*`, `/dashboard/*`).
|
||||
- [x] Garantir bloqueio de acesso nas paginas sensiveis antes de carregar dados.
|
||||
- [x] Corrigir verificacao de role inconsistente (`role` vs `roles`).
|
||||
- [x] Revisar regra de arquivos legados: negar por padrao quando nao houver metadado de permissao.
|
||||
- [x] Remover/encerrar fluxo duplicado de auth (uma unica fonte de verdade do NextAuth).
|
||||
- [x] Padronizar variavel de ambiente do Mongo (`MONGODB_URI` ou `MONGO_URI`) e alinhar docs.
|
||||
|
||||
### Definicao de pronto
|
||||
- `npm run build` passa sem erro.
|
||||
- Rotas protegidas retornam 401/403 corretamente.
|
||||
- Fluxo de login/logout unico e consistente.
|
||||
|
||||
### Risco
|
||||
- Medio. Pode impactar acesso de usuarios se a regra de permissao nao for validada com cuidado.
|
||||
|
||||
---
|
||||
|
||||
## Fase 2 - Migracao API -> Server Actions
|
||||
|
||||
### Escopo
|
||||
Migrar gradualmente endpoints de API para Server Actions, priorizando fluxo interno do app.
|
||||
|
||||
### Principios
|
||||
- Evitar big-bang. Migrar por dominio funcional.
|
||||
- Manter API somente quando houver necessidade real externa (webhook, integracao de terceiros, upload streaming, callback externo).
|
||||
- Toda Action deve validar sessao e permissao no servidor.
|
||||
|
||||
### Ordem recomendada de migracao
|
||||
1. **Pagamentos**
|
||||
2. **Turmas e atribuicoes/provas**
|
||||
3. **Arquivos e categorias**
|
||||
4. **Usuarios/guardian/wards**
|
||||
|
||||
### Tarefas por dominio (template)
|
||||
- [ ] Criar `actions/` por dominio com funcoes server-only.
|
||||
- [ ] Mover validacoes de auth/autorizacao para as Actions.
|
||||
- [ ] Substituir chamadas `fetch('/api/...')` por invocacao direta de Action.
|
||||
- [ ] Padronizar retorno `{ success, data, message, fieldErrors }`.
|
||||
- [ ] Revalidar cache (`revalidatePath`/`revalidateTag`) quando necessario.
|
||||
- [ ] Manter fallback temporario para rotas antigas e remover ao final da fase.
|
||||
|
||||
### Progresso atual (dominio: Pagamentos)
|
||||
- [x] Criadas Server Actions de pagamentos e dependentes.
|
||||
- [x] Auth/autorizacao centralizadas nas Actions de pagamentos.
|
||||
- [x] Telas de pagamentos de aluno/responsavel migradas de `fetch('/api/...')` para Actions.
|
||||
- [x] Formularios de registro de pagamento migrados para Actions.
|
||||
- [x] Retorno padronizado nas novas Actions (`success`, `data`, `message`, `fieldErrors`).
|
||||
- [x] Revalidacao aplicada para dashboards de pagamento apos envio.
|
||||
- [x] Fluxo admin de pagamentos migrado para Actions (criacao de obrigacao, aprovacao/rejeicao, consulta por obrigacao).
|
||||
- [x] Fallback temporario mantido: APIs antigas continuam disponiveis por compatibilidade e remocao gradual.
|
||||
|
||||
### Progresso atual (dominio: Turmas e atribuicoes/provas)
|
||||
- [x] Criadas Server Actions para fluxo operacional de provas (listar atribuicoes por turma, iniciar tentativa, listar tentativas, detalhar tentativa, corrigir resposta).
|
||||
- [x] Componentes de aluno migrados para Actions (`AvailableExams`, `TakeExam`) sem dependencia de `/api/classes/*` e `/api/assignments/*` nesses fluxos.
|
||||
- [x] Componente de resultados para professor/admin migrado para Actions (`ExamResults`) sem dependencia de `/api/attempts/*`.
|
||||
- [x] Mantido fallback temporario: rotas API de provas continuam existentes para compatibilidade durante transicao.
|
||||
|
||||
### Progresso atual (dominio: Arquivos e categorias)
|
||||
- [x] Criada Server Action para carregamento de categorias com migracao de `colorIndex` quando necessario.
|
||||
- [x] Formulario de upload de arquivos do admin migrado para Action de categorias, removendo dependencia de `/api/categories` no cliente.
|
||||
- [x] Ajuste de navegacao pos-upload para `router.push` em componentes cliente de upload (evitando uso indevido de `redirect`).
|
||||
- [x] Eliminadas chamadas `fetch('/api/...')` no frontend protegido; fluxo interno agora opera via Server Actions.
|
||||
|
||||
### Progresso atual (dominio: Usuarios/guardian/wards)
|
||||
- [x] Criadas Server Actions de usuarios para dependentes (`getWardsAction`) e listagem admin (`getUsersForAdminAction`).
|
||||
- [x] Fluxo de pagamentos do responsavel desacoplado do dominio de pagamentos para usar Action de usuarios no carregamento de dependentes.
|
||||
- [x] Painel admin de usuarios passou a consumir Action de usuarios (sem dependencia de rota API interna).
|
||||
- [x] Harden de cadastro de estudante por responsavel: validacao de sessao/role, vinculo seguro de guardian e verificacao de unicidade (email/username).
|
||||
|
||||
### Definicao de pronto
|
||||
- Fluxos internos principais sem dependencia de API Route.
|
||||
- Reducao significativa de codigo duplicado entre page/API.
|
||||
- Permissoes centralizadas em camada server.
|
||||
|
||||
### Risco
|
||||
- Medio/alto. Erros de cache e invalidacao podem causar dados desatualizados.
|
||||
|
||||
---
|
||||
|
||||
## Fase 3 - Reset de CSS global e fim de conflitos
|
||||
|
||||
### Escopo
|
||||
Reduzir `globals.css` ao minimo necessario e eliminar conflitos causados por regras globais.
|
||||
|
||||
### Regras obrigatorias
|
||||
- Sem `!important`.
|
||||
- Sem redefinir utilitarios Tailwind manualmente (`.bg-*`, `.text-*`, etc.).
|
||||
- Sem estilos globais agressivos para `button`, `a`, `table`, `input` que mudem componentes inteiros.
|
||||
|
||||
### Tarefas
|
||||
- [x] Criar backup do `globals.css` atual.
|
||||
- [x] Reescrever `globals.css` em blocos minimos:
|
||||
- tokens CSS (`:root`, `.dark`)
|
||||
- reset basico
|
||||
- utilitarios realmente necessarios
|
||||
- [x] Extrair classes de componentes para componentes reais (Button, Input, Badge, Card, Alert).
|
||||
- [x] Remover gradualmente classes legadas utilitarias customizadas.
|
||||
- [x] Garantir fonte definida no layout e aplicada de forma unica.
|
||||
- [x] Revisar contraste, foco e estados disabled/hover.
|
||||
|
||||
### Progresso atual (Fase 3)
|
||||
- [x] `globals.css` reduzido e sem `!important`.
|
||||
- [x] Removidos overrides manuais de utilitarios Tailwind (`.bg-*`, `.text-*`, `.border-*`).
|
||||
- [x] `Label` e `RoleCheckbox` migrados para variantes no componente (sem classes de tema globais acopladas).
|
||||
- [x] Continuar extracao para componentes de base (Button/Input/Badge/Card/Alert) e reduzir classes globais remanescentes.
|
||||
|
||||
### Definicao de pronto
|
||||
- Arquivo global enxuto e previsivel.
|
||||
- Sem conflitos visuais entre telas por efeito colateral global.
|
||||
- Nenhum `!important` no codigo do app.
|
||||
|
||||
### Risco
|
||||
- Medio. Pode quebrar aparencia de telas antigas sem componentes padronizados.
|
||||
|
||||
---
|
||||
|
||||
## Fase 4 - Base de design system estilo shadcn
|
||||
|
||||
### Escopo
|
||||
Padronizar UI com componentes reutilizaveis, variantes e tokens.
|
||||
|
||||
### Tarefas
|
||||
- [x] Criar base `components/ui` (Button, Input, Select, Textarea, Badge, Card, Dialog, Table).
|
||||
- [x] Adotar utilitario `cn` para composicao de classes.
|
||||
- [x] Adotar estrategia de variantes (ex.: cva) para reduzir classes repetidas.
|
||||
- [x] Padronizar espacamento, raio, sombras, tipografia e cores semanticas.
|
||||
- [x] Migrar telas mais usadas primeiro (login, register, dashboard admin/teacher/student).
|
||||
|
||||
### Progresso atual (Fase 4)
|
||||
- [x] Estrutura inicial criada em `src/components/ui` com componentes base (Button, Input, Select, Textarea, Badge, Card, Alert).
|
||||
- [x] Utilitario `cn` criado e aplicado na base dos componentes UI.
|
||||
- [x] Primeira migracao pratica feita em formularios criticos (registro de estudante e pagamento aluno/responsavel).
|
||||
- [x] Migracao aplicada em login/register com padrao `components/ui` (Card/Input/Button/Alert) e layout alinhado.
|
||||
- [x] Dashboards principais ajustados para consistencia de componentes e estilos-base (admin/teacher/student/guardian).
|
||||
|
||||
### Definicao de pronto
|
||||
- Componentes principais usados pela maioria das telas.
|
||||
- Queda relevante de duplicacao de classes Tailwind.
|
||||
- Visual consistente entre areas publicas e protegidas.
|
||||
|
||||
### Risco
|
||||
- Medio. Requer disciplina para evitar voltar ao estilo ad-hoc por pagina.
|
||||
|
||||
---
|
||||
|
||||
## Fase 5 - Refino visual da plataforma de ingles
|
||||
|
||||
### Escopo
|
||||
Dar identidade visual propria da escola, sem perder legibilidade e performance.
|
||||
|
||||
### Tarefas
|
||||
- [ ] Definir direcao visual unica (paleta, tipografia, acentos, ilustracoes/fotos).
|
||||
- [ ] Revisar landing page e fluxo de autenticacao com hierarquia visual clara.
|
||||
- [ ] Melhorar componentes de conteudo educacional (cards de nivel, progresso, tarefas, feedback).
|
||||
- [ ] Garantir responsividade real (mobile-first) nas paginas criticas.
|
||||
- [ ] Revisar acessibilidade (foco visivel, contraste, labels, erros de formulario).
|
||||
|
||||
### Definicao de pronto
|
||||
- Interface coerente com proposta de plataforma de ingles.
|
||||
- Melhor legibilidade e consistencia de interacao.
|
||||
|
||||
### Risco
|
||||
- Baixo/medio. Principal risco e retrabalho visual sem criterios definidos.
|
||||
|
||||
---
|
||||
|
||||
## Fase 6 - Limpeza final e hardening
|
||||
|
||||
### Escopo
|
||||
Fechamento tecnico para estabilidade de longo prazo.
|
||||
|
||||
### Tarefas
|
||||
- [ ] Remover codigo morto (rotas API legadas, helpers nao usados, estilos antigos).
|
||||
- [~] Reduzir logs de debug e padronizar logger por ambiente.
|
||||
- [~] Revisar tratamento de erros (mensagem para usuario vs log tecnico).
|
||||
- [ ] Atualizar README e documentacao de arquitetura nova (Server Actions-first).
|
||||
- [ ] Validar testes E2E por papel (admin/teacher/student/guardian).
|
||||
- [ ] Revisar seguranca de upload/acesso a arquivos.
|
||||
|
||||
### Progresso atual (Fase 6)
|
||||
- [x] Melhorado feedback de permissao no registro/edicao de aula (403 com mensagem clara no UI).
|
||||
- [x] Reduzido ruido de console no cliente para erros esperados (4xx) em `LessonForm`.
|
||||
- [x] Ajustados fluxos de navegacao que causavam 404 silencioso (links de upload/historico/resultados entre contextos admin/teacher).
|
||||
- [ ] Consolidar padrao unico de erros para todos os formularios com Server Actions e APIs legadas restantes.
|
||||
|
||||
### Definicao de pronto
|
||||
- Build estavel, testes principais passando e documentacao atualizada.
|
||||
- Arquitetura mais simples para manutencao.
|
||||
|
||||
### Risco
|
||||
- Baixo.
|
||||
|
||||
---
|
||||
|
||||
## Criterios tecnicos transversais (todas as fases)
|
||||
|
||||
- Nao quebrar fluxo de login, registro e dispatcher.
|
||||
- Toda regra de permissao deve existir no servidor.
|
||||
- Alteracoes pequenas por PR, com escopo fechado.
|
||||
- Sempre validar com build + fluxo manual das telas afetadas.
|
||||
|
||||
---
|
||||
|
||||
## Checklist de execucao por fase
|
||||
|
||||
Use este mini-checklist ao iniciar cada fase:
|
||||
|
||||
1. Definir escopo exato da fase (o que entra e o que nao entra).
|
||||
2. Criar tarefas tecnicas pequenas (max 1-2 dias cada).
|
||||
3. Implementar em branch dedicada.
|
||||
4. Rodar `npm run lint` e `npm run build`.
|
||||
5. Validar fluxo funcional manual.
|
||||
6. Atualizar este documento marcando itens concluidos.
|
||||
|
||||
---
|
||||
|
||||
## Proxima acao recomendada
|
||||
|
||||
Fechar a **Fase 4** (migracao de login/register/dashboards para componentes `ui` + padrao visual),
|
||||
e em seguida executar um passe objetivo da **Fase 6** para remover logs legados e fallbacks de API nao utilizados.
|
||||
Reference in New Issue
Block a user