forjajs 5.0.0 → 5.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (171) hide show
  1. package/CHANGELOG.md +68 -2
  2. package/README.md +4 -2
  3. package/README.pt-BR.md +4 -1
  4. package/boilerplates/02-saas-starter/README.md +58 -293
  5. package/boilerplates/02-saas-starter/backend/.env.example +13 -0
  6. package/boilerplates/02-saas-starter/backend/.oxlintrc.json +8 -0
  7. package/boilerplates/02-saas-starter/backend/nest-cli.json +6 -0
  8. package/boilerplates/02-saas-starter/backend/package.json +32 -73
  9. package/boilerplates/02-saas-starter/backend/src/app.module.ts +16 -16
  10. package/boilerplates/02-saas-starter/backend/src/billing/adapters/http/billing.controller.ts +55 -0
  11. package/boilerplates/02-saas-starter/backend/src/billing/adapters/persistence/orm-entities.ts +28 -0
  12. package/boilerplates/02-saas-starter/backend/src/billing/adapters/persistence/typeorm-billing.repository.ts +46 -0
  13. package/boilerplates/02-saas-starter/backend/src/billing/application/billing.service.spec.ts +58 -0
  14. package/boilerplates/02-saas-starter/backend/src/billing/application/billing.service.ts +68 -0
  15. package/boilerplates/02-saas-starter/backend/src/billing/billing.module.ts +11 -0
  16. package/boilerplates/02-saas-starter/backend/src/billing/domain/plan.spec.ts +23 -0
  17. package/boilerplates/02-saas-starter/backend/src/billing/domain/plan.ts +36 -0
  18. package/boilerplates/02-saas-starter/backend/src/billing/domain/ports.ts +27 -0
  19. package/boilerplates/02-saas-starter/backend/src/billing/domain/subscription.spec.ts +28 -0
  20. package/boilerplates/02-saas-starter/backend/src/billing/domain/subscription.ts +47 -0
  21. package/boilerplates/02-saas-starter/backend/src/identity/adapters/http/auth.dto.ts +22 -0
  22. package/boilerplates/02-saas-starter/backend/src/identity/adapters/http/identity.controller.ts +59 -0
  23. package/boilerplates/02-saas-starter/backend/src/identity/adapters/persistence/orm-entities.ts +25 -0
  24. package/boilerplates/02-saas-starter/backend/src/identity/adapters/persistence/typeorm-identity.repository.ts +47 -0
  25. package/boilerplates/02-saas-starter/backend/src/identity/application/auth.service.spec.ts +72 -0
  26. package/boilerplates/02-saas-starter/backend/src/identity/application/auth.service.ts +63 -0
  27. package/boilerplates/02-saas-starter/backend/src/identity/domain/model.spec.ts +19 -0
  28. package/boilerplates/02-saas-starter/backend/src/identity/domain/model.ts +42 -0
  29. package/boilerplates/02-saas-starter/backend/src/identity/domain/password.spec.ts +17 -0
  30. package/boilerplates/02-saas-starter/backend/src/identity/domain/password.ts +26 -0
  31. package/boilerplates/02-saas-starter/backend/src/identity/identity.module.ts +12 -0
  32. package/boilerplates/02-saas-starter/backend/src/main.ts +19 -19
  33. package/boilerplates/02-saas-starter/backend/src/platform/auth/jwt-auth.guard.ts +17 -0
  34. package/boilerplates/02-saas-starter/backend/src/platform/auth/principal.ts +22 -0
  35. package/boilerplates/02-saas-starter/backend/src/platform/auth/roles.guard.spec.ts +23 -0
  36. package/boilerplates/02-saas-starter/backend/src/platform/auth/roles.guard.ts +20 -0
  37. package/boilerplates/02-saas-starter/backend/src/platform/auth/token.service.ts +54 -0
  38. package/boilerplates/02-saas-starter/backend/src/platform/config.spec.ts +18 -0
  39. package/boilerplates/02-saas-starter/backend/src/platform/config.ts +33 -0
  40. package/boilerplates/02-saas-starter/backend/src/platform/platform.module.ts +14 -0
  41. package/boilerplates/02-saas-starter/backend/tsconfig.build.json +6 -0
  42. package/boilerplates/02-saas-starter/backend/tsconfig.json +16 -21
  43. package/boilerplates/02-saas-starter/backend/vitest.config.ts +7 -0
  44. package/boilerplates/02-saas-starter/boilerplate.manifest.json +19 -14
  45. package/boilerplates/02-saas-starter/docker-compose.yml +10 -24
  46. package/boilerplates/02-saas-starter/memory/30-domains/billing/context.md +15 -132
  47. package/boilerplates/02-saas-starter/memory/30-domains/identity/context.md +20 -0
  48. package/boilerplates/README.md +9 -10
  49. package/dist/bin/create-memory-nest-kit.js +0 -0
  50. package/dist/bin/forja.js +0 -0
  51. package/dist/bin/init-project.js +1 -0
  52. package/dist/lib/core/journey.js +10 -0
  53. package/dist/lib/generators/memory-generator.d.ts +0 -11
  54. package/dist/lib/generators/memory-generator.js +5 -161
  55. package/dist/lib/generators/readme-generator.js +1 -1
  56. package/dist/lib/llm/json-output.d.ts +14 -0
  57. package/dist/lib/llm/json-output.js +77 -0
  58. package/dist/lib/project-upgrade.d.ts +0 -4
  59. package/dist/lib/project-upgrade.js +19 -1
  60. package/dist/lib/project-wiring.d.ts +8 -0
  61. package/dist/lib/project-wiring.js +74 -2
  62. package/dist/lib/validators/structure-validator.js +0 -1
  63. package/dist/packages/llm/src/index.js +12 -2
  64. package/dist/scripts/llm-fit.js +23 -1
  65. package/dist/scripts/project-upgrade.js +9 -6
  66. package/docs/init-project.md +1 -1
  67. package/docs/llm-fit-loop.md +16 -0
  68. package/memory/90-decisions/0086-projeto-conectado-e-jornada-como-gate.md +1 -1
  69. package/memory/90-decisions/0088-templates-validados.md +3 -0
  70. package/memory/90-decisions/0089-skills-do-projeto.md +51 -0
  71. package/memory/90-decisions/0090-adapters-de-agente-somente-leitura.md +47 -0
  72. package/package.json +2 -2
  73. package/specs/skills-do-projeto/plan.md +40 -0
  74. package/specs/skills-do-projeto/spec.md +63 -0
  75. package/specs/skills-do-projeto/tasks.md +27 -0
  76. package/templates/project/AGENTS.md +9 -0
  77. package/templates/project/agents/context-engineer.md +3 -0
  78. package/templates/project/agents/governance.md +3 -0
  79. package/templates/project/agents/marketing.md +3 -0
  80. package/templates/project/agents/orchestrator.md +3 -0
  81. package/templates/project/agents/product.md +3 -0
  82. package/templates/project/agents/sdd-architect.md +3 -0
  83. package/templates/project/skills/README.md +14 -0
  84. package/templates/project/skills/accessibility-review/SKILL.md +89 -0
  85. package/templates/project/skills/api-design/SKILL.md +77 -0
  86. package/templates/project/skills/architecture-decision-record/SKILL.md +92 -0
  87. package/templates/project/skills/backlog-slicing/SKILL.md +82 -0
  88. package/templates/project/skills/bounded-context-mapping/SKILL.md +88 -0
  89. package/templates/project/skills/ci-pipeline-review/SKILL.md +83 -0
  90. package/templates/project/skills/commit-message/SKILL.md +143 -0
  91. package/templates/project/skills/data-migrations/SKILL.md +88 -0
  92. package/templates/project/skills/dependency-upgrade/SKILL.md +75 -0
  93. package/templates/project/skills/docker-compose-review/SKILL.md +85 -0
  94. package/templates/project/skills/domain-modeling/SKILL.md +120 -0
  95. package/templates/project/skills/event-storming/SKILL.md +95 -0
  96. package/templates/project/skills/executive-writing/SKILL.md +99 -0
  97. package/templates/project/skills/frontend-architecture/SKILL.md +97 -0
  98. package/templates/project/skills/incident-postmortem/SKILL.md +93 -0
  99. package/templates/project/skills/lgpd-compliance/SKILL.md +108 -0
  100. package/templates/project/skills/llm-provider-routing/SKILL.md +18 -0
  101. package/templates/project/skills/observability/SKILL.md +93 -0
  102. package/templates/project/skills/product-evaluation/SKILL.md +130 -0
  103. package/templates/project/skills/prompt-spec/SKILL.md +83 -0
  104. package/templates/project/skills/pull-request/SKILL.md +101 -0
  105. package/templates/project/skills/query-performance/SKILL.md +83 -0
  106. package/templates/project/skills/release-checklist/SKILL.md +106 -0
  107. package/templates/project/skills/release-notes/SKILL.md +87 -0
  108. package/templates/project/skills/requirements-elicitation/SKILL.md +127 -0
  109. package/templates/project/skills/requirements-gathering/SKILL.md +134 -0
  110. package/templates/project/skills/technical-spike/SKILL.md +101 -0
  111. package/templates/project/skills/testing/SKILL.md +109 -0
  112. package/templates/project/skills/threat-modeling/SKILL.md +87 -0
  113. package/templates/project/skills/ts-async-patterns/SKILL.md +101 -0
  114. package/templates/project/skills/ts-code-review/SKILL.md +121 -0
  115. package/templates/project/skills/ts-module-layout/SKILL.md +104 -0
  116. package/templates/project/skills/ts-testing/SKILL.md +89 -0
  117. package/templates/project/skills/web-performance/SKILL.md +72 -0
  118. package/boilerplates/02-saas-starter/.env.example +0 -25
  119. package/boilerplates/02-saas-starter/CHECKLIST-CRIACAO.md +0 -190
  120. package/boilerplates/02-saas-starter/INFO.md +0 -252
  121. package/boilerplates/02-saas-starter/QUICK_START.md +0 -194
  122. package/boilerplates/02-saas-starter/START-HERE.md +0 -259
  123. package/boilerplates/02-saas-starter/backend/src/common/decorators/roles.decorator.ts +0 -3
  124. package/boilerplates/02-saas-starter/backend/src/common/decorators/tenant.decorator.ts +0 -6
  125. package/boilerplates/02-saas-starter/backend/src/common/middleware/roles.guard.ts +0 -23
  126. package/boilerplates/02-saas-starter/backend/src/config/database.ts +0 -26
  127. package/boilerplates/02-saas-starter/backend/src/modules/auth/auth.controller.ts +0 -46
  128. package/boilerplates/02-saas-starter/backend/src/modules/auth/auth.module.ts +0 -25
  129. package/boilerplates/02-saas-starter/backend/src/modules/auth/auth.service.ts +0 -145
  130. package/boilerplates/02-saas-starter/backend/src/modules/auth/dto/auth.dto.ts +0 -30
  131. package/boilerplates/02-saas-starter/backend/src/modules/auth/strategies/jwt.strategy.ts +0 -24
  132. package/boilerplates/02-saas-starter/backend/src/modules/auth/strategies/local.strategy.ts +0 -19
  133. package/boilerplates/02-saas-starter/backend/src/modules/billing/billing.controller.ts +0 -42
  134. package/boilerplates/02-saas-starter/backend/src/modules/billing/billing.module.ts +0 -13
  135. package/boilerplates/02-saas-starter/backend/src/modules/billing/billing.service.ts +0 -67
  136. package/boilerplates/02-saas-starter/backend/src/modules/billing/entities/invoice.entity.ts +0 -52
  137. package/boilerplates/02-saas-starter/backend/src/modules/organizations/entities/organization.entity.ts +0 -36
  138. package/boilerplates/02-saas-starter/backend/src/modules/organizations/organizations.controller.ts +0 -16
  139. package/boilerplates/02-saas-starter/backend/src/modules/organizations/organizations.module.ts +0 -13
  140. package/boilerplates/02-saas-starter/backend/src/modules/organizations/organizations.service.ts +0 -34
  141. package/boilerplates/02-saas-starter/backend/src/modules/subscriptions/entities/subscription.entity.ts +0 -40
  142. package/boilerplates/02-saas-starter/backend/src/modules/subscriptions/subscriptions.controller.ts +0 -36
  143. package/boilerplates/02-saas-starter/backend/src/modules/subscriptions/subscriptions.module.ts +0 -13
  144. package/boilerplates/02-saas-starter/backend/src/modules/subscriptions/subscriptions.service.ts +0 -91
  145. package/boilerplates/02-saas-starter/backend/src/modules/users/entities/user.entity.ts +0 -42
  146. package/boilerplates/02-saas-starter/backend/src/modules/users/users.controller.ts +0 -14
  147. package/boilerplates/02-saas-starter/backend/src/modules/users/users.module.ts +0 -13
  148. package/boilerplates/02-saas-starter/backend/src/modules/users/users.service.ts +0 -48
  149. package/boilerplates/02-saas-starter/memory/00-global/agent-contract.md +0 -227
  150. package/boilerplates/02-saas-starter/memory/00-global/context-policy.md +0 -141
  151. package/boilerplates/02-saas-starter/memory/00-global/index.md +0 -133
  152. package/boilerplates/02-saas-starter/memory/00-global/mission.md +0 -45
  153. package/boilerplates/02-saas-starter/memory/00-global/patterns.md +0 -223
  154. package/boilerplates/02-saas-starter/memory/10-product/business-rules.md +0 -240
  155. package/boilerplates/02-saas-starter/memory/10-product/nfrs.md +0 -239
  156. package/boilerplates/02-saas-starter/memory/10-product/personas.md +0 -195
  157. package/boilerplates/02-saas-starter/memory/10-product/vision.md +0 -63
  158. package/boilerplates/02-saas-starter/memory/20-architecture/overview.md +0 -232
  159. package/boilerplates/02-saas-starter/memory/30-domains/auth/api.md +0 -186
  160. package/boilerplates/02-saas-starter/memory/30-domains/auth/context.md +0 -85
  161. package/boilerplates/02-saas-starter/memory/30-domains/billing/api.md +0 -262
  162. package/boilerplates/02-saas-starter/memory/30-domains/subscriptions/api.md +0 -176
  163. package/boilerplates/02-saas-starter/memory/30-domains/subscriptions/context.md +0 -100
  164. package/boilerplates/02-saas-starter/memory/40-delivery/backlog.md +0 -81
  165. package/boilerplates/02-saas-starter/memory/40-delivery/roadmap.md +0 -97
  166. package/boilerplates/02-saas-starter/memory/40-delivery/sprint-atual.md +0 -57
  167. package/boilerplates/02-saas-starter/memory/50-orchestration/topology.md +0 -90
  168. package/boilerplates/02-saas-starter/memory/60-runs/index.md +0 -54
  169. package/boilerplates/02-saas-starter/memory/70-summaries/global.md +0 -50
  170. package/boilerplates/02-saas-starter/memory/80-data/schema.md +0 -185
  171. package/boilerplates/02-saas-starter/memory/90-decisions/adr-template.md +0 -75
@@ -1,133 +0,0 @@
1
- # Índice de Memória - SaaS Starter
2
-
3
- ## Navegação Rápida
4
-
5
- ### 00-Global (Políticas & Princípios)
6
- - **[mission.md](./mission.md)** — Visão, objetivos, papéis de agentes
7
- - **[patterns.md](./patterns.md)** — Code patterns, conventions, testing
8
- - **[context-policy.md](./context-policy.md)** — Gestão de níveis, freshness, limpeza
9
- - **[agent-contract.md](./agent-contract.md)** — Ciclo de vida, responsabilidades, handoffs
10
- - **[index.md](./index.md)** — Este arquivo
11
-
12
- ### 10-Product (Visão & Regras)
13
- - **vision.md** — Proposta de valor, diferencial
14
- - **personas.md** — Buyer persona, user scenarios
15
- - **business-rules.md** — Rules engine, compliance
16
- - **nfrs.md** — Performance, scalability, security requirements
17
-
18
- ### 20-Architecture (Decisões Técnicas)
19
- - **overview.md** — Diagrama de arquitetura, stack
20
- - **frontend.md** — Stack frontend, componentes, state
21
- - **backend.md** — NestJS, modules, database strategy
22
- - **data.md** — PostgreSQL schema, indexing strategy
23
- - **security.md** — JWT, RBAC, encryption, PII
24
- - **observability.md** — Logging, metrics, tracing
25
-
26
- ### 30-Domains (Domínios de Negócio)
27
- - **auth/context.md** — O que é auth aqui, fluxo
28
- - **auth/api.md** — Endpoints, contratos, errors
29
- - **subscriptions/context.md** — Planos, transições, regras
30
- - **subscriptions/api.md** — Endpoints de subscriptions
31
- - **billing/context.md** — Pagamentos, invoices, refunds
32
- - **billing/api.md** — Endpoints de billing
33
-
34
- ### 40-Delivery (Roadmap & Sprints)
35
- - **roadmap.md** — 6+ months vision
36
- - **sprint-atual.md** — Sprint atual, tasks, burndown
37
- - **backlog.md** — Product backlog, priorização
38
-
39
- ### 50-Orchestration (Topologia de Agents)
40
- - **topology.md** — Quais agents, quando, em que ordem
41
- - **routing.md** — Como agentes se descobrem
42
- - **handoff-protocol.md** — Formato, timing, escalation
43
- - **playbook-paralelo.md** — Como executar 2+ agents em paralelo
44
- - **handoffs/ directory** — Histórico de handoffs
45
-
46
- ### 60-Runs (Logs de Execução)
47
- - **index.md** — Lista de todas as runs
48
- - **YYYY-MM-DD-agent-task.md** — Run log individual
49
- - **YYYY-MM-DD-ERROR.md** — Logs de erro
50
-
51
- ### 70-Summaries (Sínteses Executivas)
52
- - **global.md** — Status geral, funcionalidades implementadas, bloqueadores
53
- - **auth.md** — Status módulo auth, endpoints ready
54
- - **subscriptions.md** — Status subscriptions, issues
55
- - **billing.md** — Status billing, payment gateway
56
-
57
- ### 80-Data (Schemas & Migrations)
58
- - **schema.md** — Entidades PostgreSQL, relationships
59
- - **migrations/ directory** — Histórico de migrations
60
- - **seeds/ directory** — Seed data
61
-
62
- ### 90-Decisions (ADRs - Architecture Decision Records)
63
- - **adr-template.md** — Template para novas decisões
64
- - **adr-YYYYMMDD-*.md** — Decisões arquiteturais
65
- - **index.md** — Índice de ADRs
66
- - **conflicts.md** — Conflitos e resoluções
67
-
68
- ## Fluxo de Leitura por Cenário
69
-
70
- ### Cenário 1: Novo agente começa tarefa
71
- 1. Ler level 30 (domain específico)
72
- 2. Ler level 20 (architecture)
73
- 3. Ler level 00 (patterns)
74
- 4. Verificar 40-delivery para status
75
- 5. Executar tarefa
76
- 6. Documentar em 60-runs
77
-
78
- ### Cenário 2: Debug de issue
79
- 1. Procurar em 60-runs (problema similar?)
80
- 2. Verificar ADR em 90-decisions (decisão relevante?)
81
- 3. Consultar domain context em 30-domains
82
- 4. Criar ADR se nova decisão necessária
83
-
84
- ### Cenário 3: Atualizar visão de produto
85
- 1. Editar 10-product/
86
- 2. Criar ADR em 90-decisions
87
- 3. Registrar em 70-summaries/global.md
88
-
89
- ### Cenário 4: Escalação de bloqueador
90
- 1. Documentar issue em 60-runs/ERROR.md
91
- 2. Registrar dependência em 40-delivery/backlog.md
92
- 3. Criar ADR se decisão necessária
93
- 4. Notificar responsável
94
-
95
- ## Queries Rápidas
96
-
97
- **"Qual é o status do auth module?"**
98
- → Ler `70-summaries/auth.md`
99
-
100
- **"Como implementar novo endpoint?"**
101
- → Ler `00-global/patterns.md` + `20-architecture/backend.md`
102
-
103
- **"Qual é o próximo agente?"**
104
- → Ler `40-delivery/sprint-atual.md` + `50-orchestration/topology.md`
105
-
106
- **"Por que escolhemos PostgreSQL?"**
107
- → Buscar ADR em `90-decisions/`
108
-
109
- **"O que significa tenant isolation?"**
110
- → Ler `20-architecture/security.md` + `30-domains/auth/context.md`
111
-
112
- **"Como fazer handoff?"**
113
- → Ler `50-orchestration/handoff-protocol.md` (template em `agent-contract.md`)
114
-
115
- ## Atualização Frequência
116
-
117
- | Nível | Frequência | Responsável |
118
- |-------|-----------|-------------|
119
- | 00 | Trimestral | Tech lead |
120
- | 10 | Mensal | Product |
121
- | 20 | Conforme necessário | Tech lead |
122
- | 30 | Cada agente concluindo | Agentes |
123
- | 40 | Semanal | Scrum master |
124
- | 50 | Cada handoff | Agente completando |
125
- | 60 | Cada execução | Agente executando |
126
- | 70 | Diário | Summary agent |
127
- | 80 | Com migrations | Data agent |
128
- | 90 | Decisões imutáveis | Tech lead |
129
-
130
- ## Last Updated
131
- - **Date**: 2024-01-15
132
- - **By**: SaaS Starter Scaffold
133
- - **Next Review**: 2024-02-15
@@ -1,45 +0,0 @@
1
- # Missão do Projeto SaaS Starter
2
-
3
- ## Visão Geral
4
-
5
- Fornecer uma plataforma SaaS multi-tenant, escalável e pronta para produção que:
6
-
7
- 1. **Autenticação & Autorização**: JWT-based com RBAC (roles: owner, admin, member)
8
- 2. **Subscription Management**: Planos (free, pro, enterprise) com gerenciamento automático
9
- 3. **Billing & Payments**: Integração mock com sistemas de pagamento (Stripe-like)
10
- 4. **Multi-Tenancy**: Isolamento seguro de dados por organização
11
- 5. **Observabilidade**: Logs estruturados e métricas para decisões operacionais
12
-
13
- ## Princípios Fundamentais
14
-
15
- | Princípio | Descrição |
16
- |-----------|-----------|
17
- | **Multi-Tenant First** | Cada organização é isolada em camada de data e contexto |
18
- | **Security by Default** | JWT + Rate limiting + Input validation em todas as rotas |
19
- | **Scalability Ready** | Arquitetura preparada para PostgreSQL + Redis |
20
- | **Developer Experience** | NestJS + TypeScript com tipagem forte e injeção de dependências |
21
- | **Testabilidade** | Testes E2E para fluxos críticos (auth, subscriptions, billing) |
22
-
23
- ## Objetivos Imediatos
24
-
25
- 1. Gerar scaffold completo com módulos SaaS funcionais
26
- 2. Fornecer exemplos de endpoints para Auth, Subscriptions e Billing
27
- 3. Documentar fluxos de signup, subscription upgrade, e pagamento
28
- 4. Incluir testes E2E para os fluxos críticos
29
- 5. Docker-compose com PostgreSQL + Redis preconfigurado
30
-
31
- ## Papéis de Agentes
32
-
33
- | Agente | Responsabilidade |
34
- |--------|-----------------|
35
- | **Setup Agent** | Inicializar projeto, criar schemas, seedar dados |
36
- | **Auth Agent** | Validar JWT, gerenciar permissões RBAC |
37
- | **Subscription Agent** | Gerenciar planos e upgrades |
38
- | **Billing Agent** | Processar pagamentos (mock) e gerar invoices |
39
- | **Analytics Agent** | Rastrear eventos de negócio e métricas |
40
-
41
- ## Status
42
-
43
- - ✅ Estrutura de memória criada
44
- - ✅ Backend NestJS inicializado
45
- - 🚀 Pronto para integração de agents
@@ -1,223 +0,0 @@
1
- # Padrões & Convenções do Projeto SaaS Starter
2
-
3
- ## Code Patterns
4
-
5
- ### 1. Estrutura de Módulo
6
-
7
- Cada módulo segue este padrão:
8
-
9
- ```
10
- modules/
11
- ├── domain-name/
12
- ├── entities/
13
- │ └── domain.entity.ts # Typeorm entity
14
- ├── dto/
15
- │ ├── create-domain.dto.ts
16
- │ └── update-domain.dto.ts
17
- ├── domain.service.ts # Lógica de negócio
18
- ├── domain.controller.ts # Endpoints HTTP
19
- └── domain.module.ts # Module definition
20
- ```
21
-
22
- ### 2. Service Pattern
23
-
24
- ```typescript
25
- @Injectable()
26
- export class DomainService {
27
- constructor(
28
- @InjectRepository(DomainEntity)
29
- private readonly repo: Repository<DomainEntity>,
30
- private readonly tenantContext: TenantContextService,
31
- ) {}
32
-
33
- async create(dto: CreateDomainDto): Promise<DomainEntity> {
34
- const tenantId = this.tenantContext.getTenantId();
35
- return this.repo.save({
36
- ...dto,
37
- tenantId,
38
- });
39
- }
40
- }
41
- ```
42
-
43
- ### 3. Controller Pattern
44
-
45
- ```typescript
46
- @Controller('api/domains')
47
- @UseGuards(JwtAuthGuard, RolesGuard)
48
- export class DomainController {
49
- constructor(private readonly service: DomainService) {}
50
-
51
- @Post()
52
- @Roles('admin', 'owner')
53
- create(@Body() dto: CreateDomainDto) {
54
- return this.service.create(dto);
55
- }
56
- }
57
- ```
58
-
59
- ### 4. Tenant Context
60
-
61
- - Injetado via middleware no request
62
- - Validado no JwtStrategy
63
- - Isolado por request usando Async Local Storage
64
- - Sempre incluído em queries do banco
65
-
66
- ### 5. RBAC (Role-Based Access Control)
67
-
68
- **Roles:**
69
- - `owner` — full access, billing, team management
70
- - `admin` — module management, user invites
71
- - `member` — read + limited operations
72
-
73
- **Decorator:**
74
- ```typescript
75
- @Roles('owner', 'admin')
76
- async update(@Param('id') id: string) { }
77
- ```
78
-
79
- ### 6. Error Handling
80
-
81
- ```typescript
82
- throw new BadRequestException('Invalid subscription plan');
83
- throw new ForbiddenException('Only organization owners can manage billing');
84
- throw new UnauthorizedException('Invalid credentials');
85
- ```
86
-
87
- ### 7. Validation
88
-
89
- - Class-validator para DTOs
90
- - Custom validators para regras de negócio
91
- - Pipes no controller
92
-
93
- ## Database Patterns
94
-
95
- ### 1. Tenant Isolation
96
-
97
- Todas as entidades têm `tenantId`:
98
- ```typescript
99
- @Entity()
100
- export class Organization {
101
- @PrimaryGeneratedColumn('uuid')
102
- id: string;
103
-
104
- @Column({ type: 'uuid' })
105
- tenantId: string;
106
-
107
- // ...
108
- }
109
- ```
110
-
111
- ### 2. Soft Deletes
112
-
113
- Entidades com dados sensíveis usam soft delete:
114
- ```typescript
115
- @DeleteDateColumn()
116
- deletedAt?: Date;
117
- ```
118
-
119
- ### 3. Indexes
120
-
121
- ```typescript
122
- @Index(['tenantId', 'email'])
123
- @Index(['tenantId', 'status'])
124
- ```
125
-
126
- ## API Conventions
127
-
128
- ### 1. Response Format
129
-
130
- ```json
131
- {
132
- "data": { /* resource */ },
133
- "meta": {
134
- "timestamp": "2024-01-15T10:30:00Z",
135
- "version": "1.0"
136
- }
137
- }
138
- ```
139
-
140
- ### 2. Error Response
141
-
142
- ```json
143
- {
144
- "error": "RESOURCE_NOT_FOUND",
145
- "message": "Organization not found",
146
- "statusCode": 404,
147
- "timestamp": "2024-01-15T10:30:00Z"
148
- }
149
- ```
150
-
151
- ### 3. List Response
152
-
153
- ```json
154
- {
155
- "data": [ /* items */ ],
156
- "pagination": {
157
- "page": 1,
158
- "limit": 20,
159
- "total": 150,
160
- "pages": 8
161
- }
162
- }
163
- ```
164
-
165
- ## Testing Conventions
166
-
167
- ### 1. Unit Tests
168
-
169
- - Usar `jest` com `@testing-library/nestjs`
170
- - Mock services com `jest.Mock`
171
- - Testar apenas a unidade, não integração
172
-
173
- ### 2. E2E Tests
174
-
175
- ```typescript
176
- describe('Auth (e2e)', () => {
177
- let app: INestApplication;
178
-
179
- beforeAll(async () => {
180
- // Setup
181
- });
182
-
183
- it('should signup user', async () => {
184
- const response = await request(app.getHttpServer())
185
- .post('/api/auth/signup')
186
- .send({ email, password });
187
-
188
- expect(response.status).toBe(201);
189
- expect(response.body.data.accessToken).toBeDefined();
190
- });
191
- });
192
- ```
193
-
194
- ## Naming Conventions
195
-
196
- - **Services**: `PascalCase + Service` (AuthService, SubscriptionService)
197
- - **Controllers**: `PascalCase + Controller` (AuthController)
198
- - **Entities**: `PascalCase + Entity` (UserEntity)
199
- - **DTOs**: `PascalCase + Dto` (CreateUserDto)
200
- - **Routes**: kebab-case (/api/auth/sign-up)
201
- - **Fields**: camelCase (firstName, tenantId, createdAt)
202
-
203
- ## Commit Message Format
204
-
205
- ```
206
- feat: add subscription upgrade endpoint
207
-
208
- - Add POST /api/subscriptions/:id/upgrade
209
- - Validate plan compatibility
210
- - Record billing event
211
- - Send confirmation email
212
-
213
- Closes #123
214
- ```
215
-
216
- ## Documentation Requirements
217
-
218
- Every module must have:
219
- 1. README.md with module purpose
220
- 2. Context document in memory/30-domains/
221
- 3. API documentation (Swagger/OpenAPI)
222
- 4. Example curl requests
223
- 5. Error codes and meanings
@@ -1,240 +0,0 @@
1
- # Regras de Negócio
2
-
3
- ## 1. Subscription Plans
4
-
5
- ### Planos Padrão
6
-
7
- | Plan | Price/mo | Users | API Calls | Storage | Support |
8
- |------|----------|-------|-----------|---------|---------|
9
- | **Free** | $0 | 1 | 1k/mo | 1GB | Community |
10
- | **Pro** | $99 | 5 | 100k/mo | 100GB | Email |
11
- | **Enterprise** | Custom | Unlimited | Unlimited | Unlimited | Dedicated |
12
-
13
- ### Regras de Transição
14
-
15
- **Upgrade:**
16
- - Free → Pro: Imediato, prorated charge
17
- - Pro → Enterprise: Requer aprovação
18
- - Any → Any: Sem penalty
19
-
20
- **Downgrade:**
21
- - Pro → Free: Imediato, credit note
22
- - Downgrade gera refund pro-rata
23
- - Cannot downgrade mid-commitment (annual plans)
24
-
25
- **Effective Date:**
26
- - Upgrade: Imediato
27
- - Downgrade: Fim da billing cycle
28
- - Já-paid: Pro-rata adjustment
29
-
30
- ### Limits & Quotas
31
-
32
- - Free: 1k API calls/mo (soft), 1GB storage (hard)
33
- - Pro: 100k API calls/mo (soft), 100GB storage (hard)
34
- - Enterprise: Unlimited
35
- - Rate limiting: 100 req/sec per tenant
36
-
37
- **What happens at limit?**
38
- - Soft limit: Warning email, continue working
39
- - Hard limit: 429 Too Many Requests, suggest upgrade
40
-
41
- ---
42
-
43
- ## 2. Billing
44
-
45
- ### Invoice Schedule
46
-
47
- - Monthly subscription: Charge first day of month
48
- - Annual subscription: Charge on anniversary
49
- - Pro-rata charges: Immediate
50
- - Failed charge: Retry 3x over 14 days, then cancel
51
-
52
- ### Payment Terms
53
-
54
- - Credit card: Charge immediately
55
- - Annual discount: 20% (e.g., Pro $1188/year = $99/mo)
56
- - No long-term contracts (SaaS, not enterprise software)
57
- - Money-back guarantee: 14 days
58
-
59
- ### Refund Policy
60
-
61
- - Within 14 days: Full refund
62
- - After 14 days: Pro-rata refund (unused balance)
63
- - Chargeback: Suspend account immediately
64
- - Refund issued within 5-7 business days
65
-
66
- ### Tax
67
-
68
- - US: Sales tax calculated by state (Stripe does this)
69
- - EU: VAT applied, reverse charge for B2B
70
- - Exempt: Non-profits (certificate required)
71
-
72
- ---
73
-
74
- ## 3. Users & Roles
75
-
76
- ### RBAC Matrix
77
-
78
- | Action | Owner | Admin | Member |
79
- |--------|-------|-------|--------|
80
- | Create org | ✅ | ❌ | ❌ |
81
- | Delete org | ✅ | ❌ | ❌ |
82
- | Change plan | ✅ | ❌ | ❌ |
83
- | Invite user | ✅ | ✅ | ❌ |
84
- | Remove user | ✅ | ✅ | ❌ |
85
- | Change role | ✅ | ❌ | ❌ |
86
- | View billing | ✅ | ✅ | ❌ |
87
- | Use API | ✅ | ✅ | ✅ |
88
-
89
- ### User Lifecycle
90
-
91
- ```
92
- Invite → Pending → Accepted → Active → Removed/Suspended
93
- ```
94
-
95
- **Rules:**
96
- - Owner is permanent, cannot be removed
97
- - Min 1 owner per org, max 3 (governance)
98
- - Invitation expires in 7 days
99
- - Removed user: Access revoked immediately, no refund
100
- - Suspended user: Access disabled, but data retained
101
-
102
- ### Seat Usage
103
-
104
- - Free: 1 user
105
- - Pro: 5 seats included, $10 per additional
106
- - Enterprise: Unlimited
107
-
108
- **Calculation:**
109
- ```
110
- Monthly bill = Subscription + (Overage seats × $10)
111
- ```
112
-
113
- ---
114
-
115
- ## 4. Multi-Tenancy
116
-
117
- ### Organization Isolation
118
-
119
- Every request must include:
120
- - `Authorization: Bearer {jwt}`
121
- - JWT contains `tenantId`
122
- - Query filters by `tenantId` automatically
123
- - Cross-tenant queries: FORBIDDEN
124
-
125
- ### Tenant Context Rules
126
-
127
- 1. **Mandatory**: Every endpoint must validate tenant
128
- 2. **Implicit**: Service methods receive tenantId via middleware
129
- 3. **Defensive**: Never trust client-provided tenantId
130
- 4. **Logged**: All tenant access in audit log
131
-
132
- ### Data Segregation
133
-
134
- - Separate database per tenant: NO (security/ops complexity)
135
- - Row-level security: YES (tenant_id on every table)
136
- - Index on tenant_id: MANDATORY
137
- - Soft-deletes: YES (audit + recovery)
138
-
139
- ---
140
-
141
- ## 5. Security
142
-
143
- ### Password Rules
144
-
145
- - Minimum 12 characters
146
- - At least: uppercase + lowercase + number + symbol
147
- - Cannot contain username or email
148
- - Expire: Never (stateless auth)
149
- - History: Not enforced (JWT, not sessions)
150
-
151
- ### JWT Strategy
152
-
153
- - Algorithm: HS256
154
- - Access token: 15 min expiry
155
- - Refresh token: 7 days expiry
156
- - Signing secret: From env, rotated quarterly
157
- - No sensitive data in payload (only id, tenantId, roles)
158
-
159
- ### Session Handling
160
-
161
- - Stateless (no session store)
162
- - Token blacklisting on logout: Cache in Redis, TTL 7 days
163
- - Concurrent sessions: Unlimited per user
164
- - Device limit: Not enforced (SaaS, not mobile app)
165
-
166
- ### IP Whitelisting
167
-
168
- - Enterprise only
169
- - Configure in org settings
170
- - Bypass: Fail-open (if misconfigured, not fail-closed)
171
-
172
- ---
173
-
174
- ## 6. Compliance & Data Protection
175
-
176
- ### GDPR
177
-
178
- - Right to access: Export user data in 24h
179
- - Right to delete: Hard-delete after 30 day retention
180
- - Right to portability: JSON export of all data
181
- - Consent: Recorded at signup, audit logged
182
- - DPA required: For EU customers
183
-
184
- ### Data Retention
185
-
186
- - Active org: Keep indefinitely
187
- - Deleted org: Soft-delete, purge after 1 year
188
- - Logs: 90 days (audit), 7 days (debug)
189
- - Backups: 30 day retention
190
-
191
- ### PII Handling
192
-
193
- - Never log passwords, API keys, tokens
194
- - Redact in error messages (e.g., "invalid ***")
195
- - Encrypt at rest: Not mandatory (assume secure infrastructure)
196
- - Encrypt in transit: TLS 1.3, mandatory
197
- - No personal data in CDN
198
-
199
- ---
200
-
201
- ## 7. Cancellation & Churn Prevention
202
-
203
- ### Cancellation Policy
204
-
205
- - Self-service: Cancel anytime, effective end of billing cycle
206
- - Data: Accessible for 30 days, then deleted
207
- - Reactivation: Can reactivate within 30 days (restore data)
208
- - Appeal: No manual intervention
209
-
210
- ### Churn Prevention
211
-
212
- - 7 days before expiry: Reminder email
213
- - Failed payment: Retry 3x, then notification
214
- - Downgrade trigger: Send "Why?" survey
215
- - Win-back: No special offers (preserve pricing integrity)
216
-
217
- ---
218
-
219
- ## 8. Terms & Policies
220
-
221
- ### Service Level Agreement (SLA)
222
-
223
- - Uptime: 99.9% (monitoring by Pingdom)
224
- - Support: Max 24h response time (Pro tier)
225
- - Incident: Public status page
226
- - Breach: Service credit 10% of monthly fee
227
-
228
- ### Acceptable Use Policy
229
-
230
- - Prohibited: Spam, malware, illegal content, scraping
231
- - Enforcement: Suspension without notice
232
- - Appeal: Customer support, 48h review period
233
- - Serious breach: Permanent termination
234
-
235
- ### Change Management
236
-
237
- - Price changes: 30 days notice
238
- - Feature deprecation: 6 months notice
239
- - Service terms: 30 days notice
240
- - Backwards compatibility: Guaranteed for API v1