Integra módulo de Resellers (agente eden-commercial)
Resolve conflitos de merge (users.ts, audit.ts, br-documents.ts, pnpm-lock/workspace.yaml — o worktree partiu de uma base anterior à existência do módulo de auth/companies, então recriou versões próprias de arquivos que já existiam no main; mantido o conteúdo do main, incorporando só a função nova assignUserToReseller). Adiciona resellersRepo ao barrel @eden/database e ResellersModule ao app.module.ts. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
59
packages/database/migrations/1788439142825_resellers.cjs
Normal file
59
packages/database/migrations/1788439142825_resellers.cjs
Normal file
@@ -0,0 +1,59 @@
|
||||
/**
|
||||
* Commercial bounded context, first slice: `resellers` — the operational
|
||||
* reseller/partner registry (eden.md §1.7). Pre-dates the "Programa de
|
||||
* Canais" approval workflow with public tokens described in eden.md §6 —
|
||||
* that workflow (client_registrations/reseller_registrations, public
|
||||
* approval tokens) is explicitly out of scope for this migration and
|
||||
* lands in its own later phase. This is just the simple operational CRUD
|
||||
* table eden.md §1.7 describes, already referenced by `quotes.reseller_id`
|
||||
* conceptually (quotes themselves aren't modeled yet either — Commercial
|
||||
* phase lands module by module).
|
||||
*
|
||||
* Also adds `users.reseller_id` (nullable) — how a user gets scoped to a
|
||||
* reseller, per eden.md §7 and the `scope=reseller` permission model
|
||||
* (docs/adr/0004-permission-model.md). Lives in this migration rather
|
||||
* than a separate one so the FK to `resellers(id)` can be added in the
|
||||
* same statement the table is created in, without a two-step migration.
|
||||
*/
|
||||
|
||||
exports.shorthands = undefined;
|
||||
|
||||
exports.up = (pgm) => {
|
||||
pgm.sql(`
|
||||
CREATE TABLE resellers (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
created_by UUID REFERENCES users(id),
|
||||
name TEXT NOT NULL,
|
||||
document TEXT,
|
||||
contact_email TEXT,
|
||||
active BOOLEAN NOT NULL DEFAULT true
|
||||
);
|
||||
COMMENT ON TABLE resellers IS
|
||||
'Cadastro operacional de revenda — eden.md §1.7. document é CPF/CNPJ livre (sem CHECK de dígito no banco, validado na camada de aplicação, igual companies.cnpj). Leitura aberta a qualquer autenticado (usado em seletores, ex. Orçamentos); escrita restrita à permissão resellers:edit.';
|
||||
|
||||
CREATE TRIGGER trg_resellers_updated_at BEFORE UPDATE ON resellers
|
||||
FOR EACH ROW EXECUTE FUNCTION set_updated_at();
|
||||
|
||||
CREATE INDEX idx_resellers_active ON resellers(active);
|
||||
|
||||
-- =====================================================================
|
||||
-- users.reseller_id — scopes a user to a reseller (eden.md §7,
|
||||
-- docs/adr/0004-permission-model.md scope=reseller)
|
||||
-- =====================================================================
|
||||
ALTER TABLE users ADD COLUMN reseller_id UUID REFERENCES resellers(id);
|
||||
COMMENT ON COLUMN users.reseller_id IS
|
||||
'Nullable — vincula o usuário a uma revenda (vendedor de revenda), escopando o que ele vê (eden.md §7). Atribuído via PATCH /v1/resellers/:id/assign-user, nunca aceito de campo vindo do cliente para decisão de autorização (docs/architecture.md, ADR-0004).';
|
||||
|
||||
CREATE INDEX idx_users_reseller ON users(reseller_id);
|
||||
`);
|
||||
};
|
||||
|
||||
exports.down = (pgm) => {
|
||||
pgm.sql(`
|
||||
DROP INDEX IF EXISTS idx_users_reseller;
|
||||
ALTER TABLE users DROP COLUMN IF EXISTS reseller_id;
|
||||
DROP TABLE IF EXISTS resellers;
|
||||
`);
|
||||
};
|
||||
@@ -5,6 +5,8 @@ export * as sessionsRepo from "./repositories/sessions.js";
|
||||
export * as auditRepo from "./repositories/audit.js";
|
||||
export * as companiesRepo from "./repositories/companies.js";
|
||||
export * as productsRepo from "./repositories/products.js";
|
||||
export * as resellersRepo from "./repositories/resellers.js";
|
||||
export type * from "./repositories/types.js";
|
||||
export type { Company } from "./repositories/companies.js";
|
||||
export type { Product, CreateProductInput, UpdateProductInput } from "./repositories/products.js";
|
||||
export type { Reseller, CreateResellerInput, UpdateResellerInput } from "./repositories/resellers.js";
|
||||
|
||||
@@ -20,12 +20,13 @@ function canonicalJson(value: unknown): string {
|
||||
}
|
||||
|
||||
/**
|
||||
* Appends one event to the audit_log hash chain. Never call this inside a
|
||||
* larger transaction that might roll back for unrelated reasons without
|
||||
* considering that the chain must stay contiguous — a rolled-back event
|
||||
* never happened, which is fine (nothing was recorded), but a *committed*
|
||||
* event must never be skipped when computing previous_event_hash for the
|
||||
* next one. See .claude/skills/eden-security/references/audit.md.
|
||||
* Appends one event to the audit_log hash chain (see baseline-schema
|
||||
* migration and .claude/skills/eden-security/references/audit.md). Never
|
||||
* call this inside a larger transaction that might roll back for
|
||||
* unrelated reasons without considering that the chain must stay
|
||||
* contiguous — a rolled-back event never happened (fine, nothing was
|
||||
* recorded), but a *committed* event must never be skipped when
|
||||
* computing previous_event_hash for the next one.
|
||||
*/
|
||||
export async function appendAuditEvent(input: AuditEventInput): Promise<void> {
|
||||
const { rows } = await query<{ event_hash: string }>(
|
||||
|
||||
71
packages/database/src/repositories/resellers.ts
Normal file
71
packages/database/src/repositories/resellers.ts
Normal file
@@ -0,0 +1,71 @@
|
||||
import { query } from "../pool.js";
|
||||
|
||||
export interface Reseller {
|
||||
id: string;
|
||||
created_at: Date;
|
||||
updated_at: Date;
|
||||
created_by: string | null;
|
||||
name: string;
|
||||
document: string | null;
|
||||
contact_email: string | null;
|
||||
active: boolean;
|
||||
}
|
||||
|
||||
export async function listResellers(includeInactive = false): Promise<Reseller[]> {
|
||||
const { rows } = await query<Reseller>(
|
||||
includeInactive
|
||||
? "SELECT * FROM resellers ORDER BY created_at ASC"
|
||||
: "SELECT * FROM resellers WHERE active = true ORDER BY created_at ASC",
|
||||
);
|
||||
return rows;
|
||||
}
|
||||
|
||||
export async function getResellerById(id: string): Promise<Reseller | null> {
|
||||
const { rows } = await query<Reseller>("SELECT * FROM resellers WHERE id = $1", [id]);
|
||||
return rows[0] ?? null;
|
||||
}
|
||||
|
||||
export interface CreateResellerInput {
|
||||
name: string;
|
||||
document?: string | null;
|
||||
contactEmail?: string | null;
|
||||
active?: boolean;
|
||||
createdBy?: string | null;
|
||||
}
|
||||
|
||||
export async function createReseller(input: CreateResellerInput): Promise<Reseller> {
|
||||
const { rows } = await query<Reseller>(
|
||||
`INSERT INTO resellers (name, document, contact_email, active, created_by)
|
||||
VALUES ($1, $2, $3, COALESCE($4, true), $5)
|
||||
RETURNING *`,
|
||||
[
|
||||
input.name,
|
||||
input.document ?? null,
|
||||
input.contactEmail ?? null,
|
||||
input.active ?? null,
|
||||
input.createdBy ?? null,
|
||||
],
|
||||
);
|
||||
const reseller = rows[0];
|
||||
if (!reseller) throw new Error("failed to create reseller");
|
||||
return reseller;
|
||||
}
|
||||
|
||||
export type UpdateResellerInput = Partial<Omit<CreateResellerInput, "createdBy">>;
|
||||
|
||||
export async function updateReseller(
|
||||
id: string,
|
||||
input: UpdateResellerInput,
|
||||
): Promise<Reseller | null> {
|
||||
const { rows } = await query<Reseller>(
|
||||
`UPDATE resellers SET
|
||||
name = COALESCE($2, name),
|
||||
document = COALESCE($3, document),
|
||||
contact_email = COALESCE($4, contact_email),
|
||||
active = COALESCE($5, active)
|
||||
WHERE id = $1
|
||||
RETURNING *`,
|
||||
[id, input.name ?? null, input.document ?? null, input.contactEmail ?? null, input.active ?? null],
|
||||
);
|
||||
return rows[0] ?? null;
|
||||
}
|
||||
@@ -124,3 +124,21 @@ export async function updateUserProfile(
|
||||
);
|
||||
return rows[0] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reseller-scoping: sets or clears which reseller a user belongs to
|
||||
* (`users.reseller_id`, nullable — eden.md §1.7, §7). Resolved and
|
||||
* enforced server-side only; callers must never accept `reseller_id`
|
||||
* from client input for authorization decisions (docs/adr/0004,
|
||||
* docs/architecture.md).
|
||||
*/
|
||||
export async function assignUserToReseller(
|
||||
userId: string,
|
||||
resellerId: string | null,
|
||||
): Promise<boolean> {
|
||||
const { rowCount } = await query("UPDATE users SET reseller_id = $2 WHERE id = $1", [
|
||||
userId,
|
||||
resellerId,
|
||||
]);
|
||||
return (rowCount ?? 0) > 0;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user