import type { Pool } from "khb_common"; /** Вызывающий и его права. admin - внутренний вызов без person (все todo); person - агент или человек. */ export interface Caller { kind: "admin" | "person"; name: string; personId?: string; all: boolean; jobIds: ReadonlySet; membershipId: string | null; } export const ADMIN: Caller = { kind: "admin", name: "service", all: true, jobIds: new Set(), membershipId: null }; export class AccessError extends Error { constructor(message: string, readonly status = 403) { super(message); } } /** Права по person: CEO видит и меняет всё, менеджер - todo своих проектов (assistant_project) и назначенные ему. */ export async function resolveCaller(pool: Pool, personId: string): Promise { const { rows } = await pool.query( `select p.id, p.display_name, p.jt_membership_id, cm.chat_kind from person p left join construction_manager cm on cm.person_id = p.id where p.id = $1 and p.is_active`, [personId], ); const p = rows[0]; if (!p) throw new AccessError("неизвестный или неактивный person", 401); if (p.chat_kind === "ceo") return { kind: "person", name: p.display_name, personId, all: true, jobIds: new Set(), membershipId: p.jt_membership_id ?? null }; const jobs = await pool.query("select jt_job_id from assistant_project where manager_person_id = $1 and is_enabled", [personId]); return { kind: "person", name: p.display_name, personId, all: false, jobIds: new Set(jobs.rows.map((r) => String(r.jt_job_id))), membershipId: p.jt_membership_id ?? null, }; } /** Видит ли вызывающий todo (проект или назначение). */ export function canRead(c: Caller, t: { jobId: string | null; assigneeIds: string[] }): boolean { if (c.all) return true; if (t.jobId && c.jobIds.has(t.jobId)) return true; return !!c.membershipId && t.assigneeIds.includes(c.membershipId); } /** Условие SQL для списков: возвращает фрагмент и добавляет параметры. */ export function scopeSql(c: Caller, params: unknown[], alias = "i"): string { if (c.all) return "true"; params.push([...c.jobIds]); const jobs = `${alias}.job_id = any($${params.length}::text[])`; if (!c.membershipId) return `(${jobs})`; params.push(c.membershipId); return `(${jobs} or $${params.length} = any(${alias}.assignee_ids))`; }