ceo-api/src/organizations/organizations.service.ts
valentinbvro eb652446f6 feat: Sprint 1 -- Projection Kernel (read models pentru dashboard)
Repara criteriul de acceptare "dashboardurile citesc read models, nu
interogheaza haotic toate modulele".

- projection_processed_events (unique: name+version+event_id) = garantia de
  idempotency. Checkpointul e doar optimizare de scanare, nu corectitudine:
  rescanam cu un safety lag de 60s si sarim ce s-a aplicat deja, ca sa nu
  pierdem evenimente comise dupa unul cu created_at mai mare.
- ProjectionRegistry cu ProjectionDefinition (name, version, subscribedEvents,
  rebuildStrategy, apply, rebuildTenant).
- executive_dashboard foloseste rebuildStrategy 'canonical-tables':
  recalculeaza contorii din tabelele canonice, nu incrementeaza. Contorii
  incrementali pot deriva daca un eveniment se pierde sau se dubleaza;
  recalcularea e corecta prin constructie si idempotenta natural. Costul e o
  interogare per eveniment relevant -- ok la volumul actual.
- GET /v1/dashboard/executive citeste proiectia. Cand proiectia inca n-a rulat
  pentru workspace, intoarce status 'building' explicit, NU zerouri care ar
  parea date reale.
- POST /v1/dashboard/executive/rebuild -- owner/admin, auditat.
- Serviciile de taskuri/organizatii/segmente emit acum evenimente in outbox
  (in aceeasi tranzactie cu scrierea). Fara ele proiectia era cod mort.
- Campurile din spec care depind de module neconstruite (documents,
  transactions, approvals) raman 0 explicit, nu inventate.
2026-07-29 12:03:34 +02:00

138 lines
4.7 KiB
TypeScript

import { Injectable, NotFoundException } from '@nestjs/common';
import { and, desc, eq, isNull, sql } from 'drizzle-orm';
import { db } from '../db/client';
import { organizations } from '../db/schema';
import { AuditService } from '../audit/audit.service';
import { OutboxService } from '../events/outbox.service';
import type { AuthenticatedSession } from '../auth/tenant.guard';
import type { CreateOrganizationDto, UpdateOrganizationDto } from './dto';
/** Domeniile se normalizeaza la stocare (blueprint 11.6): lowercase, fara schema/path. */
function normalizeDomain(domain: string | undefined): string | undefined {
if (!domain) {
return undefined;
}
return domain
.trim()
.toLowerCase()
.replace(/^https?:\/\//, '')
.replace(/\/.*$/, '');
}
@Injectable()
export class OrganizationsService {
constructor(
private readonly outbox: OutboxService,
private readonly audit: AuditService,
) {}
async list(session: AuthenticatedSession) {
return db.query.organizations.findMany({
where: and(eq(organizations.tenantId, session.tenantId), isNull(organizations.deletedAt)),
orderBy: desc(organizations.createdAt),
});
}
async getById(session: AuthenticatedSession, id: string) {
const row = await db.query.organizations.findFirst({
where: and(
eq(organizations.id, id),
eq(organizations.tenantId, session.tenantId),
isNull(organizations.deletedAt),
),
});
if (!row) {
throw new NotFoundException('Organization not found');
}
return row;
}
async create(session: AuthenticatedSession, dto: CreateOrganizationDto) {
return this.outbox.withTransaction(async (tx) => {
const [row] = await tx
.insert(organizations)
.values({
tenantId: session.tenantId,
name: dto.name,
legalName: dto.legalName,
country: dto.country,
registryId: dto.registryId,
domain: normalizeDomain(dto.domain),
externalIds: dto.externalIds ?? {},
})
.returning();
await this.audit.record(tx, {
tenantId: session.tenantId,
actorId: session.userId,
action: 'organization.created',
resource: `organization:${row.id}`,
});
await this.outbox.record(tx, {
tenantId: session.tenantId,
workspaceId: session.workspaceId,
actorId: session.userId,
aggregateType: 'organization',
correlationId: session.correlationId,
eventType: 'organization.created',
subjectId: row.id,
payload: { name: row.name, country: row.country },
});
return row;
});
}
async update(session: AuthenticatedSession, id: string, dto: UpdateOrganizationDto) {
await this.getById(session, id);
return this.outbox.withTransaction(async (tx) => {
const [row] = await tx
.update(organizations)
.set({
...(dto.name !== undefined ? { name: dto.name } : {}),
...(dto.legalName !== undefined ? { legalName: dto.legalName } : {}),
...(dto.country !== undefined ? { country: dto.country } : {}),
...(dto.registryId !== undefined ? { registryId: dto.registryId } : {}),
...(dto.domain !== undefined ? { domain: normalizeDomain(dto.domain) } : {}),
...(dto.externalIds !== undefined ? { externalIds: dto.externalIds } : {}),
updatedAt: new Date(),
version: sql`${organizations.version} + 1`,
})
.where(and(eq(organizations.id, id), eq(organizations.tenantId, session.tenantId)))
.returning();
await this.audit.record(tx, {
tenantId: session.tenantId,
actorId: session.userId,
action: 'organization.updated',
resource: `organization:${id}`,
});
return row;
});
}
/** Soft delete (blueprint 12.1); hard delete doar prin workflow controlat, nu prin API. */
async softDelete(session: AuthenticatedSession, id: string) {
await this.getById(session, id);
await this.outbox.withTransaction(async (tx) => {
await tx
.update(organizations)
.set({ deletedAt: new Date() })
.where(and(eq(organizations.id, id), eq(organizations.tenantId, session.tenantId)));
await this.audit.record(tx, {
tenantId: session.tenantId,
actorId: session.userId,
action: 'organization.deleted',
resource: `organization:${id}`,
});
await this.outbox.record(tx, {
tenantId: session.tenantId,
workspaceId: session.workspaceId,
actorId: session.userId,
eventType: 'organization.deleted',
aggregateType: 'organization',
subjectId: id,
correlationId: session.correlationId,
payload: {},
});
});
return { deleted: true };
}
}