forjajs 5.0.1 → 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 (164) hide show
  1. package/CHANGELOG.md +38 -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/init-project.js +1 -0
  50. package/dist/lib/core/journey.js +10 -0
  51. package/dist/lib/generators/memory-generator.d.ts +0 -11
  52. package/dist/lib/generators/memory-generator.js +5 -161
  53. package/dist/lib/generators/readme-generator.js +1 -1
  54. package/dist/lib/llm/json-output.d.ts +14 -0
  55. package/dist/lib/llm/json-output.js +77 -0
  56. package/dist/lib/project-wiring.d.ts +8 -0
  57. package/dist/lib/project-wiring.js +74 -2
  58. package/dist/lib/validators/structure-validator.js +0 -1
  59. package/dist/packages/llm/src/index.js +12 -2
  60. package/dist/scripts/llm-fit.js +23 -1
  61. package/docs/llm-fit-loop.md +16 -0
  62. package/memory/90-decisions/0088-templates-validados.md +3 -0
  63. package/memory/90-decisions/0089-skills-do-projeto.md +51 -0
  64. package/memory/90-decisions/0090-adapters-de-agente-somente-leitura.md +47 -0
  65. package/package.json +1 -1
  66. package/specs/skills-do-projeto/plan.md +40 -0
  67. package/specs/skills-do-projeto/spec.md +63 -0
  68. package/specs/skills-do-projeto/tasks.md +27 -0
  69. package/templates/project/AGENTS.md +9 -0
  70. package/templates/project/agents/context-engineer.md +3 -0
  71. package/templates/project/agents/governance.md +3 -0
  72. package/templates/project/agents/marketing.md +3 -0
  73. package/templates/project/agents/orchestrator.md +3 -0
  74. package/templates/project/agents/product.md +3 -0
  75. package/templates/project/agents/sdd-architect.md +3 -0
  76. package/templates/project/skills/README.md +14 -0
  77. package/templates/project/skills/accessibility-review/SKILL.md +89 -0
  78. package/templates/project/skills/api-design/SKILL.md +77 -0
  79. package/templates/project/skills/architecture-decision-record/SKILL.md +92 -0
  80. package/templates/project/skills/backlog-slicing/SKILL.md +82 -0
  81. package/templates/project/skills/bounded-context-mapping/SKILL.md +88 -0
  82. package/templates/project/skills/ci-pipeline-review/SKILL.md +83 -0
  83. package/templates/project/skills/commit-message/SKILL.md +143 -0
  84. package/templates/project/skills/data-migrations/SKILL.md +88 -0
  85. package/templates/project/skills/dependency-upgrade/SKILL.md +75 -0
  86. package/templates/project/skills/docker-compose-review/SKILL.md +85 -0
  87. package/templates/project/skills/domain-modeling/SKILL.md +120 -0
  88. package/templates/project/skills/event-storming/SKILL.md +95 -0
  89. package/templates/project/skills/executive-writing/SKILL.md +99 -0
  90. package/templates/project/skills/frontend-architecture/SKILL.md +97 -0
  91. package/templates/project/skills/incident-postmortem/SKILL.md +93 -0
  92. package/templates/project/skills/lgpd-compliance/SKILL.md +108 -0
  93. package/templates/project/skills/llm-provider-routing/SKILL.md +18 -0
  94. package/templates/project/skills/observability/SKILL.md +93 -0
  95. package/templates/project/skills/product-evaluation/SKILL.md +130 -0
  96. package/templates/project/skills/prompt-spec/SKILL.md +83 -0
  97. package/templates/project/skills/pull-request/SKILL.md +101 -0
  98. package/templates/project/skills/query-performance/SKILL.md +83 -0
  99. package/templates/project/skills/release-checklist/SKILL.md +106 -0
  100. package/templates/project/skills/release-notes/SKILL.md +87 -0
  101. package/templates/project/skills/requirements-elicitation/SKILL.md +127 -0
  102. package/templates/project/skills/requirements-gathering/SKILL.md +134 -0
  103. package/templates/project/skills/technical-spike/SKILL.md +101 -0
  104. package/templates/project/skills/testing/SKILL.md +109 -0
  105. package/templates/project/skills/threat-modeling/SKILL.md +87 -0
  106. package/templates/project/skills/ts-async-patterns/SKILL.md +101 -0
  107. package/templates/project/skills/ts-code-review/SKILL.md +121 -0
  108. package/templates/project/skills/ts-module-layout/SKILL.md +104 -0
  109. package/templates/project/skills/ts-testing/SKILL.md +89 -0
  110. package/templates/project/skills/web-performance/SKILL.md +72 -0
  111. package/boilerplates/02-saas-starter/.env.example +0 -25
  112. package/boilerplates/02-saas-starter/CHECKLIST-CRIACAO.md +0 -190
  113. package/boilerplates/02-saas-starter/INFO.md +0 -252
  114. package/boilerplates/02-saas-starter/QUICK_START.md +0 -194
  115. package/boilerplates/02-saas-starter/START-HERE.md +0 -259
  116. package/boilerplates/02-saas-starter/backend/src/common/decorators/roles.decorator.ts +0 -3
  117. package/boilerplates/02-saas-starter/backend/src/common/decorators/tenant.decorator.ts +0 -6
  118. package/boilerplates/02-saas-starter/backend/src/common/middleware/roles.guard.ts +0 -23
  119. package/boilerplates/02-saas-starter/backend/src/config/database.ts +0 -26
  120. package/boilerplates/02-saas-starter/backend/src/modules/auth/auth.controller.ts +0 -46
  121. package/boilerplates/02-saas-starter/backend/src/modules/auth/auth.module.ts +0 -25
  122. package/boilerplates/02-saas-starter/backend/src/modules/auth/auth.service.ts +0 -145
  123. package/boilerplates/02-saas-starter/backend/src/modules/auth/dto/auth.dto.ts +0 -30
  124. package/boilerplates/02-saas-starter/backend/src/modules/auth/strategies/jwt.strategy.ts +0 -24
  125. package/boilerplates/02-saas-starter/backend/src/modules/auth/strategies/local.strategy.ts +0 -19
  126. package/boilerplates/02-saas-starter/backend/src/modules/billing/billing.controller.ts +0 -42
  127. package/boilerplates/02-saas-starter/backend/src/modules/billing/billing.module.ts +0 -13
  128. package/boilerplates/02-saas-starter/backend/src/modules/billing/billing.service.ts +0 -67
  129. package/boilerplates/02-saas-starter/backend/src/modules/billing/entities/invoice.entity.ts +0 -52
  130. package/boilerplates/02-saas-starter/backend/src/modules/organizations/entities/organization.entity.ts +0 -36
  131. package/boilerplates/02-saas-starter/backend/src/modules/organizations/organizations.controller.ts +0 -16
  132. package/boilerplates/02-saas-starter/backend/src/modules/organizations/organizations.module.ts +0 -13
  133. package/boilerplates/02-saas-starter/backend/src/modules/organizations/organizations.service.ts +0 -34
  134. package/boilerplates/02-saas-starter/backend/src/modules/subscriptions/entities/subscription.entity.ts +0 -40
  135. package/boilerplates/02-saas-starter/backend/src/modules/subscriptions/subscriptions.controller.ts +0 -36
  136. package/boilerplates/02-saas-starter/backend/src/modules/subscriptions/subscriptions.module.ts +0 -13
  137. package/boilerplates/02-saas-starter/backend/src/modules/subscriptions/subscriptions.service.ts +0 -91
  138. package/boilerplates/02-saas-starter/backend/src/modules/users/entities/user.entity.ts +0 -42
  139. package/boilerplates/02-saas-starter/backend/src/modules/users/users.controller.ts +0 -14
  140. package/boilerplates/02-saas-starter/backend/src/modules/users/users.module.ts +0 -13
  141. package/boilerplates/02-saas-starter/backend/src/modules/users/users.service.ts +0 -48
  142. package/boilerplates/02-saas-starter/memory/00-global/agent-contract.md +0 -227
  143. package/boilerplates/02-saas-starter/memory/00-global/context-policy.md +0 -141
  144. package/boilerplates/02-saas-starter/memory/00-global/index.md +0 -133
  145. package/boilerplates/02-saas-starter/memory/00-global/mission.md +0 -45
  146. package/boilerplates/02-saas-starter/memory/00-global/patterns.md +0 -223
  147. package/boilerplates/02-saas-starter/memory/10-product/business-rules.md +0 -240
  148. package/boilerplates/02-saas-starter/memory/10-product/nfrs.md +0 -239
  149. package/boilerplates/02-saas-starter/memory/10-product/personas.md +0 -195
  150. package/boilerplates/02-saas-starter/memory/10-product/vision.md +0 -63
  151. package/boilerplates/02-saas-starter/memory/20-architecture/overview.md +0 -232
  152. package/boilerplates/02-saas-starter/memory/30-domains/auth/api.md +0 -186
  153. package/boilerplates/02-saas-starter/memory/30-domains/auth/context.md +0 -85
  154. package/boilerplates/02-saas-starter/memory/30-domains/billing/api.md +0 -262
  155. package/boilerplates/02-saas-starter/memory/30-domains/subscriptions/api.md +0 -176
  156. package/boilerplates/02-saas-starter/memory/30-domains/subscriptions/context.md +0 -100
  157. package/boilerplates/02-saas-starter/memory/40-delivery/backlog.md +0 -81
  158. package/boilerplates/02-saas-starter/memory/40-delivery/roadmap.md +0 -97
  159. package/boilerplates/02-saas-starter/memory/40-delivery/sprint-atual.md +0 -57
  160. package/boilerplates/02-saas-starter/memory/50-orchestration/topology.md +0 -90
  161. package/boilerplates/02-saas-starter/memory/60-runs/index.md +0 -54
  162. package/boilerplates/02-saas-starter/memory/70-summaries/global.md +0 -50
  163. package/boilerplates/02-saas-starter/memory/80-data/schema.md +0 -185
  164. package/boilerplates/02-saas-starter/memory/90-decisions/adr-template.md +0 -75
@@ -1,26 +1,26 @@
1
1
  import { Module } from '@nestjs/common';
2
- import { ConfigModule } from '@nestjs/config';
3
2
  import { TypeOrmModule } from '@nestjs/typeorm';
4
- import { AuthModule } from './modules/auth/auth.module';
5
- import { UsersModule } from './modules/users/users.module';
6
- import { OrganizationsModule } from './modules/organizations/organizations.module';
7
- import { SubscriptionsModule } from './modules/subscriptions/subscriptions.module';
8
- import { BillingModule } from './modules/billing/billing.module';
9
- import { TypeOrmConfigService } from './config/database';
3
+ import { APP_CONFIG, type AppConfig } from './platform/config.js';
4
+ import { PlatformModule } from './platform/platform.module.js';
5
+ import { IdentityModule } from './identity/identity.module.js';
6
+ import { BillingModule } from './billing/billing.module.js';
7
+ import { OrganizationOrm, UserOrm } from './identity/adapters/persistence/orm-entities.js';
8
+ import { InvoiceOrm, SubscriptionOrm } from './billing/adapters/persistence/orm-entities.js';
10
9
 
11
10
  @Module({
12
11
  imports: [
13
- ConfigModule.forRoot({
14
- isGlobal: true,
15
- envFilePath: ['.env.local', '.env'],
16
- }),
12
+ PlatformModule,
17
13
  TypeOrmModule.forRootAsync({
18
- useClass: TypeOrmConfigService,
14
+ inject: [APP_CONFIG],
15
+ useFactory: (config: AppConfig) => ({
16
+ type: 'postgres',
17
+ url: config.databaseUrl,
18
+ entities: [OrganizationOrm, UserOrm, SubscriptionOrm, InvoiceOrm],
19
+ // Em produção o esquema muda por migração (skill data-migrations), nunca por synchronize.
20
+ synchronize: !config.production,
21
+ }),
19
22
  }),
20
- AuthModule,
21
- UsersModule,
22
- OrganizationsModule,
23
- SubscriptionsModule,
23
+ IdentityModule,
24
24
  BillingModule,
25
25
  ],
26
26
  })
@@ -0,0 +1,55 @@
1
+ import { Body, Controller, Get, HttpCode, Param, ParseUUIDPipe, Post, Put, UseGuards } from '@nestjs/common';
2
+ import { ApiBearerAuth, ApiProperty, ApiTags } from '@nestjs/swagger';
3
+ import { IsIn } from 'class-validator';
4
+ import { CurrentPrincipal, type Principal } from '../../../platform/auth/principal.js';
5
+ import { JwtAuthGuard } from '../../../platform/auth/jwt-auth.guard.js';
6
+ import { RequireRoles, RolesGuard } from '../../../platform/auth/roles.guard.js';
7
+ import { BillingService } from '../../application/billing.service.js';
8
+ import { PLAN_IDS, PLANS } from '../../domain/plan.js';
9
+
10
+ class ChangePlanDto {
11
+ @ApiProperty({ enum: PLAN_IDS }) @IsIn([...PLAN_IDS]) plan: string;
12
+ }
13
+
14
+ @ApiTags('billing')
15
+ @ApiBearerAuth()
16
+ @Controller('billing')
17
+ @UseGuards(JwtAuthGuard, RolesGuard)
18
+ export class BillingController {
19
+ constructor(private readonly billing: BillingService) {}
20
+
21
+ @Get('plans')
22
+ plans() {
23
+ return Object.values(PLANS);
24
+ }
25
+
26
+ @Get('subscription')
27
+ subscription(@CurrentPrincipal() p: Principal) {
28
+ return this.billing.subscription(p.tenantId);
29
+ }
30
+
31
+ @Put('subscription/plan')
32
+ @RequireRoles('owner')
33
+ changePlan(@CurrentPrincipal() p: Principal, @Body() dto: ChangePlanDto) {
34
+ return this.billing.changePlan(p.tenantId, dto.plan);
35
+ }
36
+
37
+ @Post('invoices/current')
38
+ @HttpCode(200)
39
+ @RequireRoles('owner', 'admin')
40
+ issue(@CurrentPrincipal() p: Principal) {
41
+ return this.billing.issueCurrentInvoice(p.tenantId);
42
+ }
43
+
44
+ @Get('invoices')
45
+ @RequireRoles('owner', 'admin')
46
+ invoices(@CurrentPrincipal() p: Principal) {
47
+ return this.billing.listInvoices(p.tenantId);
48
+ }
49
+
50
+ @Get('invoices/:id')
51
+ @RequireRoles('owner', 'admin')
52
+ invoice(@CurrentPrincipal() p: Principal, @Param('id', new ParseUUIDPipe()) id: string) {
53
+ return this.billing.invoice(id, p.tenantId);
54
+ }
55
+ }
@@ -0,0 +1,28 @@
1
+ import { Column, CreateDateColumn, Entity, Index, PrimaryColumn, UpdateDateColumn } from 'typeorm';
2
+
3
+ @Entity('subscriptions')
4
+ export class SubscriptionOrm {
5
+ @PrimaryColumn('uuid') id: string;
6
+ @Column('uuid', { unique: true }) tenantId: string;
7
+ @Column('varchar', { length: 20 }) plan: string;
8
+ @Column('timestamptz') periodStart: Date;
9
+ @Column('timestamptz') periodEnd: Date;
10
+ @CreateDateColumn({ type: 'timestamptz' }) createdAt: Date;
11
+ @UpdateDateColumn({ type: 'timestamptz' }) updatedAt: Date;
12
+ }
13
+
14
+ @Entity('invoices')
15
+ @Index(['tenantId', 'periodStart'], { unique: true })
16
+ export class InvoiceOrm {
17
+ @PrimaryColumn('uuid') id: string;
18
+ @Column('uuid') tenantId: string;
19
+ @Column('varchar', { length: 40, unique: true }) number: string;
20
+ @Column('varchar', { length: 20 }) plan: string;
21
+ /** Centavos, inteiro. */
22
+ @Column('integer') amountCents: number;
23
+ @Column('char', { length: 3 }) currency: string;
24
+ @Column('timestamptz') periodStart: Date;
25
+ @Column('timestamptz') periodEnd: Date;
26
+ @Column('varchar', { length: 10 }) status: 'open' | 'paid' | 'void';
27
+ @Column('timestamptz') issuedAt: Date;
28
+ }
@@ -0,0 +1,46 @@
1
+ import { Injectable } from '@nestjs/common';
2
+ import { InjectDataSource } from '@nestjs/typeorm';
3
+ import { DataSource } from 'typeorm';
4
+ import { isPlanId } from '../../domain/plan.js';
5
+ import type { SubscriptionState } from '../../domain/subscription.js';
6
+ import type { BillingRepository, Invoice } from '../../domain/ports.js';
7
+ import { InvoiceOrm, SubscriptionOrm } from './orm-entities.js';
8
+
9
+ const toInvoice = (r: InvoiceOrm): Invoice => ({
10
+ id: r.id, tenantId: r.tenantId, number: r.number, plan: r.plan, amountCents: r.amountCents, currency: r.currency,
11
+ periodStart: r.periodStart, periodEnd: r.periodEnd, status: r.status, issuedAt: r.issuedAt,
12
+ });
13
+
14
+ @Injectable()
15
+ export class TypeOrmBillingRepository implements BillingRepository {
16
+ constructor(@InjectDataSource() private readonly ds: DataSource) {}
17
+
18
+ async findSubscription(tenantId: string): Promise<SubscriptionState | null> {
19
+ const r = await this.ds.getRepository(SubscriptionOrm).findOneBy({ tenantId });
20
+ if (!r) return null;
21
+ if (!isPlanId(r.plan)) throw new Error(`Plano inválido no banco: ${r.plan}`);
22
+ return { id: r.id, tenantId: r.tenantId, plan: r.plan, periodStart: r.periodStart, periodEnd: r.periodEnd };
23
+ }
24
+
25
+ async saveSubscription(state: SubscriptionState): Promise<void> {
26
+ await this.ds.getRepository(SubscriptionOrm).save({ ...state });
27
+ }
28
+
29
+ async findInvoiceForPeriod(tenantId: string, periodStart: Date): Promise<Invoice | null> {
30
+ const r = await this.ds.getRepository(InvoiceOrm).findOneBy({ tenantId, periodStart });
31
+ return r ? toInvoice(r) : null;
32
+ }
33
+
34
+ async insertInvoice(invoice: Invoice): Promise<void> {
35
+ await this.ds.getRepository(InvoiceOrm).insert({ ...invoice });
36
+ }
37
+
38
+ async listInvoices(tenantId: string): Promise<Invoice[]> {
39
+ return (await this.ds.getRepository(InvoiceOrm).find({ where: { tenantId }, order: { periodStart: 'DESC' } })).map(toInvoice);
40
+ }
41
+
42
+ async findInvoice(id: string, tenantId: string): Promise<Invoice | null> {
43
+ const r = await this.ds.getRepository(InvoiceOrm).findOneBy({ id, tenantId });
44
+ return r ? toInvoice(r) : null;
45
+ }
46
+ }
@@ -0,0 +1,58 @@
1
+ import { BadRequestException, NotFoundException, UnprocessableEntityException } from '@nestjs/common';
2
+ import type { SubscriptionState } from '../domain/subscription.js';
3
+ import type { BillingRepository, Invoice } from '../domain/ports.js';
4
+ import { BillingService } from './billing.service.js';
5
+
6
+ class InMemoryBilling implements BillingRepository {
7
+ subs = new Map<string, SubscriptionState>();
8
+ invoices: Invoice[] = [];
9
+ async findSubscription(t: string) { return this.subs.get(t) ?? null; }
10
+ async saveSubscription(s: SubscriptionState) { this.subs.set(s.tenantId, s); }
11
+ async findInvoiceForPeriod(t: string, start: Date) { return this.invoices.find((i) => i.tenantId === t && i.periodStart.getTime() === start.getTime()) ?? null; }
12
+ async insertInvoice(i: Invoice) { this.invoices.push(i); }
13
+ async listInvoices(t: string) { return this.invoices.filter((i) => i.tenantId === t); }
14
+ async findInvoice(id: string, t: string) { return this.invoices.find((i) => i.id === id && i.tenantId === t) ?? null; }
15
+ }
16
+
17
+ const setup = (at = new Date('2026-05-10T12:00:00Z')) => {
18
+ const repo = new InMemoryBilling();
19
+ return { repo, billing: new BillingService(repo, () => at, { currency: 'BRL' }) };
20
+ };
21
+
22
+ describe('BillingService', () => {
23
+ it('cria a assinatura free na primeira consulta e devolve a mesma depois', async () => {
24
+ const { billing } = setup();
25
+ const a = await billing.subscription('t1');
26
+ expect(a.plan).toBe('free');
27
+ expect((await billing.subscription('t1')).id).toBe(a.id);
28
+ });
29
+
30
+ it('plano desconhecido → 400; transição proibida → 422', async () => {
31
+ const { billing } = setup();
32
+ await expect(billing.changePlan('t1', 'gold')).rejects.toBeInstanceOf(BadRequestException);
33
+ await billing.changePlan('t1', 'enterprise');
34
+ await expect(billing.changePlan('t1', 'free')).rejects.toBeInstanceOf(UnprocessableEntityException);
35
+ });
36
+
37
+ it('fatura usa o preço do plano em centavos e é idempotente no período', async () => {
38
+ const { billing, repo } = setup();
39
+ await billing.changePlan('t1', 'pro');
40
+ const first = await billing.issueCurrentInvoice('t1');
41
+ const again = await billing.issueCurrentInvoice('t1');
42
+ expect(first).toMatchObject({ amountCents: 9900, currency: 'BRL', status: 'open', plan: 'pro' });
43
+ expect(again.id).toBe(first.id);
44
+ expect(repo.invoices).toHaveLength(1);
45
+ });
46
+
47
+ it('fatura do plano free nasce paga, com valor zero', async () => {
48
+ const { billing } = setup();
49
+ expect(await billing.issueCurrentInvoice('t1')).toMatchObject({ amountCents: 0, status: 'paid' });
50
+ });
51
+
52
+ it('isolamento: fatura de outro tenant responde 404 e não aparece na lista', async () => {
53
+ const { billing } = setup();
54
+ const inv = await billing.issueCurrentInvoice('t1');
55
+ await expect(billing.invoice(inv.id, 't2')).rejects.toBeInstanceOf(NotFoundException);
56
+ expect(await billing.listInvoices('t2')).toEqual([]);
57
+ });
58
+ });
@@ -0,0 +1,68 @@
1
+ import { BadRequestException, Inject, Injectable, NotFoundException, UnprocessableEntityException } from '@nestjs/common';
2
+ import { randomUUID } from 'node:crypto';
3
+ import { APP_CONFIG, type AppConfig } from '../../platform/config.js';
4
+ import { isPlanId, PLANS } from '../domain/plan.js';
5
+ import { InvalidPlanChange, Subscription, monthlyPeriod, type SubscriptionState } from '../domain/subscription.js';
6
+ import { BILLING_REPOSITORY, CLOCK, type BillingRepository, type Clock, type Invoice } from '../domain/ports.js';
7
+
8
+ @Injectable()
9
+ export class BillingService {
10
+ constructor(
11
+ @Inject(BILLING_REPOSITORY) private readonly repo: BillingRepository,
12
+ @Inject(CLOCK) private readonly now: Clock,
13
+ @Inject(APP_CONFIG) private readonly config: Pick<AppConfig, 'currency'>,
14
+ ) {}
15
+
16
+ /** A assinatura do tenant; criada no plano free na primeira consulta. */
17
+ async subscription(tenantId: string): Promise<SubscriptionState> {
18
+ const existing = await this.repo.findSubscription(tenantId);
19
+ if (existing) return existing;
20
+ const created = Subscription.start(randomUUID(), tenantId, this.now()).snapshot;
21
+ await this.repo.saveSubscription(created);
22
+ return created;
23
+ }
24
+
25
+ async changePlan(tenantId: string, plan: string): Promise<SubscriptionState> {
26
+ if (!isPlanId(plan)) throw new BadRequestException(`Plano desconhecido: ${plan}`);
27
+ const sub = Subscription.restore(await this.subscription(tenantId));
28
+ try {
29
+ sub.changePlan(plan);
30
+ } catch (error) {
31
+ if (error instanceof InvalidPlanChange) throw new UnprocessableEntityException(error.message);
32
+ throw error;
33
+ }
34
+ await this.repo.saveSubscription(sub.snapshot);
35
+ return sub.snapshot;
36
+ }
37
+
38
+ /**
39
+ * Emite a fatura do período atual a partir do plano. Idempotente por período: chamar de novo devolve
40
+ * a mesma fatura. O valor vem da tabela de planos, nunca do cliente.
41
+ */
42
+ async issueCurrentInvoice(tenantId: string): Promise<Invoice> {
43
+ const sub = await this.subscription(tenantId);
44
+ const { start, end } = monthlyPeriod(this.now());
45
+ const existing = await this.repo.findInvoiceForPeriod(tenantId, start);
46
+ if (existing) return existing;
47
+ const plan = PLANS[sub.plan];
48
+ const issuedAt = this.now();
49
+ const invoice: Invoice = {
50
+ id: randomUUID(), tenantId, plan: plan.id, amountCents: plan.monthlyPriceCents, currency: this.config.currency,
51
+ number: `INV-${start.toISOString().slice(0, 7)}-${tenantId.slice(0, 8)}`,
52
+ periodStart: start, periodEnd: end, status: plan.monthlyPriceCents === 0 ? 'paid' : 'open', issuedAt,
53
+ };
54
+ await this.repo.insertInvoice(invoice);
55
+ return invoice;
56
+ }
57
+
58
+ listInvoices(tenantId: string): Promise<Invoice[]> {
59
+ return this.repo.listInvoices(tenantId);
60
+ }
61
+
62
+ /** Fatura de outro tenant responde 404, como se não existisse. */
63
+ async invoice(id: string, tenantId: string): Promise<Invoice> {
64
+ const found = await this.repo.findInvoice(id, tenantId);
65
+ if (!found) throw new NotFoundException('Fatura não encontrada');
66
+ return found;
67
+ }
68
+ }
@@ -0,0 +1,11 @@
1
+ import { Module } from '@nestjs/common';
2
+ import { BillingService } from './application/billing.service.js';
3
+ import { BILLING_REPOSITORY, CLOCK } from './domain/ports.js';
4
+ import { TypeOrmBillingRepository } from './adapters/persistence/typeorm-billing.repository.js';
5
+ import { BillingController } from './adapters/http/billing.controller.js';
6
+
7
+ @Module({
8
+ controllers: [BillingController],
9
+ providers: [BillingService, { provide: BILLING_REPOSITORY, useClass: TypeOrmBillingRepository }, { provide: CLOCK, useValue: () => new Date() }],
10
+ })
11
+ export class BillingModule {}
@@ -0,0 +1,23 @@
1
+ import { canChangePlan, isPlanId, PLANS } from './plan.js';
2
+
3
+ describe('política de planos', () => {
4
+ it.each([
5
+ { from: 'free', to: 'pro', ok: true },
6
+ { from: 'free', to: 'enterprise', ok: true },
7
+ { from: 'pro', to: 'free', ok: true },
8
+ { from: 'pro', to: 'enterprise', ok: true },
9
+ { from: 'enterprise', to: 'pro', ok: false },
10
+ { from: 'enterprise', to: 'free', ok: false },
11
+ ] as const)('$from → $to: $ok', ({ from, to, ok }) => {
12
+ expect(canChangePlan(from, to)).toBe(ok);
13
+ });
14
+
15
+ it('preços são centavos inteiros', () => {
16
+ for (const plan of Object.values(PLANS)) expect(Number.isSafeInteger(plan.monthlyPriceCents)).toBe(true);
17
+ });
18
+
19
+ it('reconhece só os planos da tabela', () => {
20
+ expect(isPlanId('pro')).toBe(true);
21
+ expect(isPlanId('gold')).toBe(false);
22
+ });
23
+ });
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Política de planos: preço em centavos (inteiro, nunca float), limites e transições permitidas.
3
+ * Mudar um preço ou uma regra de transição é mudar este arquivo, e os testes dizem o que quebrou.
4
+ */
5
+ export const PLAN_IDS = ['free', 'pro', 'enterprise'] as const;
6
+ export type PlanId = (typeof PLAN_IDS)[number];
7
+
8
+ export interface Plan {
9
+ readonly id: PlanId;
10
+ readonly monthlyPriceCents: number;
11
+ /** null = sem limite. */
12
+ readonly apiCallsPerMonth: number | null;
13
+ readonly seats: number | null;
14
+ }
15
+
16
+ export const PLANS: Readonly<Record<PlanId, Plan>> = {
17
+ free: { id: 'free', monthlyPriceCents: 0, apiCallsPerMonth: 1_000, seats: 3 },
18
+ pro: { id: 'pro', monthlyPriceCents: 9_900, apiCallsPerMonth: 100_000, seats: 25 },
19
+ // Enterprise é negociado: preço por contrato, não por tabela.
20
+ enterprise: { id: 'enterprise', monthlyPriceCents: 0, apiCallsPerMonth: null, seats: null },
21
+ };
22
+
23
+ const TRANSITIONS: Readonly<Record<PlanId, readonly PlanId[]>> = {
24
+ free: ['pro', 'enterprise'],
25
+ pro: ['free', 'enterprise'],
26
+ // Sair do enterprise passa por contrato, não por autoatendimento.
27
+ enterprise: [],
28
+ };
29
+
30
+ export function isPlanId(value: string): value is PlanId {
31
+ return (PLAN_IDS as readonly string[]).includes(value);
32
+ }
33
+
34
+ export function canChangePlan(from: PlanId, to: PlanId): boolean {
35
+ return TRANSITIONS[from].includes(to);
36
+ }
@@ -0,0 +1,27 @@
1
+ import type { SubscriptionState } from './subscription.js';
2
+
3
+ export interface Invoice {
4
+ readonly id: string;
5
+ readonly tenantId: string;
6
+ readonly number: string;
7
+ readonly plan: string;
8
+ readonly amountCents: number;
9
+ readonly currency: string;
10
+ readonly periodStart: Date;
11
+ readonly periodEnd: Date;
12
+ readonly status: 'open' | 'paid' | 'void';
13
+ readonly issuedAt: Date;
14
+ }
15
+
16
+ export interface BillingRepository {
17
+ findSubscription(tenantId: string): Promise<SubscriptionState | null>;
18
+ saveSubscription(state: SubscriptionState): Promise<void>;
19
+ findInvoiceForPeriod(tenantId: string, periodStart: Date): Promise<Invoice | null>;
20
+ insertInvoice(invoice: Invoice): Promise<void>;
21
+ listInvoices(tenantId: string): Promise<Invoice[]>;
22
+ findInvoice(id: string, tenantId: string): Promise<Invoice | null>;
23
+ }
24
+
25
+ export const BILLING_REPOSITORY = Symbol('BILLING_REPOSITORY');
26
+ export const CLOCK = Symbol('CLOCK');
27
+ export type Clock = () => Date;
@@ -0,0 +1,28 @@
1
+ import { InvalidPlanChange, monthlyPeriod, Subscription } from './subscription.js';
2
+
3
+ describe('Assinatura', () => {
4
+ it('começa no plano free, no período mensal em UTC do momento', () => {
5
+ const s = Subscription.start('s1', 't1', new Date('2026-03-15T23:30:00-03:00')).snapshot;
6
+ expect(s.plan).toBe('free');
7
+ expect(s.periodStart.toISOString()).toBe('2026-03-01T00:00:00.000Z');
8
+ expect(s.periodEnd.toISOString()).toBe('2026-04-01T00:00:00.000Z');
9
+ });
10
+
11
+ it('virada de ano no período mensal', () => {
12
+ const { start, end } = monthlyPeriod(new Date('2026-12-31T12:00:00Z'));
13
+ expect([start.toISOString(), end.toISOString()]).toEqual(['2026-12-01T00:00:00.000Z', '2027-01-01T00:00:00.000Z']);
14
+ });
15
+
16
+ it('transição inválida lança e deixa a assinatura como estava', () => {
17
+ const sub = Subscription.start('s1', 't1', new Date());
18
+ sub.changePlan('enterprise');
19
+ expect(() => sub.changePlan('free')).toThrow(InvalidPlanChange);
20
+ expect(sub.snapshot.plan).toBe('enterprise');
21
+ });
22
+
23
+ it('mudar para o mesmo plano não é erro', () => {
24
+ const sub = Subscription.start('s1', 't1', new Date());
25
+ sub.changePlan('free');
26
+ expect(sub.snapshot.plan).toBe('free');
27
+ });
28
+ });
@@ -0,0 +1,47 @@
1
+ import { canChangePlan, type PlanId } from './plan.js';
2
+
3
+ export class InvalidPlanChange extends Error {
4
+ constructor(readonly from: PlanId, readonly to: PlanId) {
5
+ super(`Mudança de plano não permitida: ${from} → ${to}`);
6
+ this.name = 'InvalidPlanChange';
7
+ }
8
+ }
9
+
10
+ export interface SubscriptionState {
11
+ readonly id: string;
12
+ readonly tenantId: string;
13
+ readonly plan: PlanId;
14
+ readonly periodStart: Date;
15
+ readonly periodEnd: Date;
16
+ }
17
+
18
+ /** Período mensal em UTC que contém `at`: [primeiro dia do mês, primeiro dia do mês seguinte). */
19
+ export function monthlyPeriod(at: Date): { start: Date; end: Date } {
20
+ const start = new Date(Date.UTC(at.getUTCFullYear(), at.getUTCMonth(), 1));
21
+ const end = new Date(Date.UTC(at.getUTCFullYear(), at.getUTCMonth() + 1, 1));
22
+ return { start, end };
23
+ }
24
+
25
+ /** Agregado Assinatura: um por tenant; a mudança de plano respeita a política de transições. */
26
+ export class Subscription {
27
+ private constructor(private state: SubscriptionState) {}
28
+
29
+ static start(id: string, tenantId: string, at: Date): Subscription {
30
+ const { start, end } = monthlyPeriod(at);
31
+ return new Subscription({ id, tenantId, plan: 'free', periodStart: start, periodEnd: end });
32
+ }
33
+
34
+ static restore(state: SubscriptionState): Subscription {
35
+ return new Subscription(state);
36
+ }
37
+
38
+ get snapshot(): SubscriptionState {
39
+ return this.state;
40
+ }
41
+
42
+ changePlan(to: PlanId): void {
43
+ if (to === this.state.plan) return;
44
+ if (!canChangePlan(this.state.plan, to)) throw new InvalidPlanChange(this.state.plan, to);
45
+ this.state = { ...this.state, plan: to };
46
+ }
47
+ }
@@ -0,0 +1,22 @@
1
+ import { ApiProperty } from '@nestjs/swagger';
2
+ import { IsEmail, IsNotEmpty, IsString, Matches, MaxLength, MinLength } from 'class-validator';
3
+
4
+ export class SignupDto {
5
+ @ApiProperty() @IsEmail() @MaxLength(254) email: string;
6
+
7
+ @ApiProperty({ minLength: 12 })
8
+ @IsString() @MinLength(12) @MaxLength(128)
9
+ @Matches(/(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/, { message: 'A senha precisa ter minúscula, maiúscula e número' })
10
+ password: string;
11
+
12
+ @ApiProperty() @IsString() @IsNotEmpty() @MaxLength(120) organizationName: string;
13
+ }
14
+
15
+ export class LoginDto {
16
+ @ApiProperty() @IsEmail() email: string;
17
+ @ApiProperty() @IsString() @IsNotEmpty() @MaxLength(128) password: string;
18
+ }
19
+
20
+ export class RefreshDto {
21
+ @ApiProperty() @IsString() @IsNotEmpty() refreshToken: string;
22
+ }
@@ -0,0 +1,59 @@
1
+ import { Body, Controller, Get, HttpCode, Inject, NotFoundException, Post, UseGuards } from '@nestjs/common';
2
+ import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
3
+ import { CurrentPrincipal, type Principal } from '../../../platform/auth/principal.js';
4
+ import { JwtAuthGuard } from '../../../platform/auth/jwt-auth.guard.js';
5
+ import { RequireRoles, RolesGuard } from '../../../platform/auth/roles.guard.js';
6
+ import { AuthService } from '../../application/auth.service.js';
7
+ import { IDENTITY_REPOSITORY, type IdentityRepository } from '../../domain/model.js';
8
+ import { LoginDto, RefreshDto, SignupDto } from './auth.dto.js';
9
+
10
+ @ApiTags('auth')
11
+ @Controller('auth')
12
+ export class AuthController {
13
+ constructor(private readonly auth: AuthService) {}
14
+
15
+ @Post('signup')
16
+ signup(@Body() dto: SignupDto) {
17
+ return this.auth.signup(dto);
18
+ }
19
+
20
+ @Post('login')
21
+ @HttpCode(200)
22
+ login(@Body() dto: LoginDto) {
23
+ return this.auth.login(dto.email, dto.password);
24
+ }
25
+
26
+ @Post('refresh')
27
+ @HttpCode(200)
28
+ refresh(@Body() dto: RefreshDto) {
29
+ return this.auth.refresh(dto.refreshToken);
30
+ }
31
+ }
32
+
33
+ @ApiTags('identity')
34
+ @ApiBearerAuth()
35
+ @Controller()
36
+ @UseGuards(JwtAuthGuard, RolesGuard)
37
+ export class IdentityController {
38
+ constructor(@Inject(IDENTITY_REPOSITORY) private readonly repo: IdentityRepository) {}
39
+
40
+ @Get('me')
41
+ async me(@CurrentPrincipal() principal: Principal) {
42
+ const user = await this.repo.findUserById(principal.userId, principal.tenantId);
43
+ if (!user) throw new NotFoundException();
44
+ return { id: user.id, email: user.email, roles: user.roles };
45
+ }
46
+
47
+ @Get('organization')
48
+ async organization(@CurrentPrincipal() principal: Principal) {
49
+ const org = await this.repo.findOrganization(principal.tenantId);
50
+ if (!org) throw new NotFoundException();
51
+ return org;
52
+ }
53
+
54
+ @Get('users')
55
+ @RequireRoles('owner', 'admin')
56
+ async users(@CurrentPrincipal() principal: Principal) {
57
+ return (await this.repo.listUsers(principal.tenantId)).map((u) => ({ id: u.id, email: u.email, roles: u.roles, active: u.active }));
58
+ }
59
+ }
@@ -0,0 +1,25 @@
1
+ import { Column, CreateDateColumn, Entity, Index, PrimaryColumn, UpdateDateColumn } from 'typeorm';
2
+
3
+ @Entity('organizations')
4
+ export class OrganizationOrm {
5
+ @PrimaryColumn('uuid') id: string;
6
+ @Column('uuid', { unique: true }) tenantId: string;
7
+ @Column('varchar', { length: 120 }) name: string;
8
+ @Column('varchar', { length: 64, unique: true }) slug: string;
9
+ @Column('uuid') ownerId: string;
10
+ @CreateDateColumn({ type: 'timestamptz' }) createdAt: Date;
11
+ @UpdateDateColumn({ type: 'timestamptz' }) updatedAt: Date;
12
+ }
13
+
14
+ @Entity('users')
15
+ @Index(['tenantId'])
16
+ export class UserOrm {
17
+ @PrimaryColumn('uuid') id: string;
18
+ @Column('uuid') tenantId: string;
19
+ @Column('varchar', { length: 254, unique: true }) email: string;
20
+ @Column('varchar', { length: 255 }) passwordHash: string;
21
+ @Column('simple-array') roles: string[];
22
+ @Column('boolean', { default: true }) active: boolean;
23
+ @CreateDateColumn({ type: 'timestamptz' }) createdAt: Date;
24
+ @UpdateDateColumn({ type: 'timestamptz' }) updatedAt: Date;
25
+ }
@@ -0,0 +1,47 @@
1
+ import { Injectable } from '@nestjs/common';
2
+ import { InjectDataSource } from '@nestjs/typeorm';
3
+ import { DataSource } from 'typeorm';
4
+ import { ROLES, type Role } from '../../../platform/auth/principal.js';
5
+ import type { IdentityRepository, Organization, User } from '../../domain/model.js';
6
+ import { OrganizationOrm, UserOrm } from './orm-entities.js';
7
+
8
+ const toUser = (row: UserOrm): User => ({
9
+ id: row.id, tenantId: row.tenantId, email: row.email, passwordHash: row.passwordHash, active: row.active,
10
+ roles: row.roles.filter((r): r is Role => (ROLES as readonly string[]).includes(r)),
11
+ });
12
+ const toOrg = (row: OrganizationOrm): Organization => ({ id: row.id, tenantId: row.tenantId, name: row.name, slug: row.slug, ownerId: row.ownerId });
13
+
14
+ @Injectable()
15
+ export class TypeOrmIdentityRepository implements IdentityRepository {
16
+ constructor(@InjectDataSource() private readonly ds: DataSource) {}
17
+
18
+ async findUserByEmail(email: string): Promise<User | null> {
19
+ const row = await this.ds.getRepository(UserOrm).findOneBy({ email });
20
+ return row ? toUser(row) : null;
21
+ }
22
+
23
+ async findUserById(id: string, tenantId: string): Promise<User | null> {
24
+ const row = await this.ds.getRepository(UserOrm).findOneBy({ id, tenantId });
25
+ return row ? toUser(row) : null;
26
+ }
27
+
28
+ async listUsers(tenantId: string): Promise<User[]> {
29
+ return (await this.ds.getRepository(UserOrm).find({ where: { tenantId }, order: { createdAt: 'ASC' } })).map(toUser);
30
+ }
31
+
32
+ async findOrganization(tenantId: string): Promise<Organization | null> {
33
+ const row = await this.ds.getRepository(OrganizationOrm).findOneBy({ tenantId });
34
+ return row ? toOrg(row) : null;
35
+ }
36
+
37
+ async slugTaken(slug: string): Promise<boolean> {
38
+ return (await this.ds.getRepository(OrganizationOrm).countBy({ slug })) > 0;
39
+ }
40
+
41
+ async createTenant(org: Organization, owner: User): Promise<void> {
42
+ await this.ds.transaction(async (tx) => {
43
+ await tx.getRepository(OrganizationOrm).insert({ ...org });
44
+ await tx.getRepository(UserOrm).insert({ ...owner, roles: [...owner.roles] });
45
+ });
46
+ }
47
+ }