acc_invoices: роль admin и переключатель роли CFO/accountant/employee; Keycloak: фирменный стиль KH Build
All checks were successful
ci / test (push) Successful in 55s
ci / deploy (push) Successful in 3m13s

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-04 14:36:45 +03:00
parent d79ebfda10
commit b878aa72bb
9 changed files with 126 additions and 15 deletions

View File

@@ -32,3 +32,20 @@
100% { box-shadow: 0 0 0 0 rgba(66, 133, 244, 0); } 100% { box-shadow: 0 0 0 0 rgba(66, 133, 244, 0); }
} }
@media (prefers-reduced-motion: reduce) { #social-google { animation: none; box-shadow: 0 0 0 4px rgba(66, 133, 244, .4); } } @media (prefers-reduced-motion: reduce) { #social-google { animation: none; box-shadow: 0 0 0 4px rgba(66, 133, 244, .4); } }
/* Фирменный стиль KH Build: тёмный фон, золотой акцент (цвета сайта khbuild.pro), логотип над формой */
:root { --khb-gold: #a98146; --khb-gold-light: #e9c79a; --khb-dark: #151005; }
body#keycloak-bg, .pf-v5-c-login { background: radial-gradient(ellipse at top, #2e2210 0%, var(--khb-dark) 70%) !important; }
.pf-v5-c-login__main { border-top: 4px solid var(--khb-gold); border-radius: 8px; }
#kc-header-wrapper {
display: flex; flex-direction: column; align-items: center; gap: .75rem;
color: var(--khb-gold-light); font-size: 2rem; font-weight: 700; letter-spacing: .35em; text-transform: uppercase;
}
#kc-header-wrapper::before {
content: ""; width: 96px; height: 96px; border-radius: 18px; background: #fff url("../img/logo.svg") center / 72px no-repeat;
box-shadow: 0 0 0 3px var(--khb-gold);
}
#kc-header-wrapper::after { content: "Services"; font-size: .9rem; letter-spacing: .5em; color: var(--khb-gold); }
.pf-v5-c-title { color: var(--khb-dark); }
.pf-v5-c-button.pf-m-primary { background-color: var(--khb-gold); color: #fff; }
.pf-v5-c-button.pf-m-primary:hover, .pf-v5-c-button.pf-m-primary:focus { background-color: #8c6a37; }

View File

@@ -0,0 +1,37 @@
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<defs>
<linearGradient id="light" x1="13.5833" y1="3.4498" x2="4.02803" y2="13.1927" gradientUnits="userSpaceOnUse">
<stop stop-color="#151005"/>
<stop offset="0.1" stop-color="#180E04"/>
<stop offset="0.2" stop-color="#170E05"/>
<stop offset="0.3" stop-color="#150903"/>
<stop offset="0.4" stop-color="#110801"/>
<stop offset="0.5" stop-color="#110801"/>
<stop offset="0.6" stop-color="#110801"/>
<stop offset="0.7" stop-color="#150903"/>
<stop offset="0.8" stop-color="#170E05"/>
<stop offset="0.9" stop-color="#180E04"/>
<stop offset="1" stop-color="#151005"/>
</linearGradient>
<linearGradient id="dark" x1="13.5833" y1="3.4498" x2="4.02803" y2="13.1927" gradientUnits="userSpaceOnUse">
<stop stop-color="#E9C79A"/>
<stop offset="0.1" stop-color="#CEAA77"/>
<stop offset="0.2" stop-color="#B8925A"/>
<stop offset="0.3" stop-color="#A98146"/>
<stop offset="0.4" stop-color="#9F7639"/>
<stop offset="0.5" stop-color="#9C7335"/>
<stop offset="0.6" stop-color="#9F7738"/>
<stop offset="0.7" stop-color="#A88442"/>
<stop offset="0.8" stop-color="#B79853"/>
<stop offset="0.9" stop-color="#CBB569"/>
<stop offset="1" stop-color="#E4D885"/>
</linearGradient>
<style>
.icon { fill: url(#light); }
@media (prefers-color-scheme: dark) {
.icon { fill: url(#dark); }
}
</style>
</defs>
<path class="icon" d="M9.70634 7.85438L12.5879 5.93932V2.47551L8.85572 0L2 4.52017V11.2056L9.17272 15.9595L9.23348 16L13 13.502V10.0382L9.70634 7.85438ZM9.27786 12.1524L6.25523 10.1477L9.24246 8.16263L12.2677 10.1693L9.27786 12.1524ZM9.49606 15.2129V12.6243L12.469 10.6522V13.2413L9.49606 15.2129ZM8.96297 12.5607V15.2054L2.53521 10.9429V8.29774L8.96297 12.5607ZM5.75543 6.65591L2.73386 4.65428L8.85466 0.616L11.8609 2.60912L5.75543 6.65591ZM2.53256 7.68074V5.13667L5.47012 7.08475V9.63132L2.53256 7.68074ZM6.00322 9.69638V7.10627L12.0522 3.09451V5.67811L6.00322 9.69638Z"/>
</svg>

After

Width:  |  Height:  |  Size: 2.1 KiB

View File

@@ -0,0 +1,19 @@
import { describe, expect, it } from "vitest";
import { effectiveRoles } from "./auth.js";
describe("effectiveRoles", () => {
it("CFO по умолчанию CFO и может переключаться", () => {
expect(effectiveRoles(["cfo"])).toEqual({ roles: ["cfo"], canSwitch: true, acting: "cfo" });
expect(effectiveRoles(["cfo"], "employee")).toEqual({ roles: [], canSwitch: true, acting: "employee" });
expect(effectiveRoles(["cfo"], "accountant").roles).toEqual(["accountant"]);
});
it("admin по умолчанию employee и может стать кем угодно", () => {
expect(effectiveRoles(["admin"])).toEqual({ roles: [], canSwitch: true, acting: "employee" });
expect(effectiveRoles(["admin"], "cfo").roles).toEqual(["cfo"]);
expect(effectiveRoles(["admin"], "bogus").acting).toBe("employee");
});
it("бухгалтер и сотрудник переключаться не могут", () => {
expect(effectiveRoles(["accountant"], "cfo")).toEqual({ roles: ["accountant"], canSwitch: false, acting: "accountant" });
expect(effectiveRoles([], "cfo")).toEqual({ roles: [], canSwitch: false, acting: "employee" });
});
});

View File

@@ -10,10 +10,19 @@ export class AuthError extends Error {
} }
export type Role = "accountant" | "cfo"; export type Role = "accountant" | "cfo";
/** Роль для переключателя в интерфейсе (employee - без прав бухгалтерии). */
export type ActingRole = Role | "employee";
export const ACTING_ROLES: ActingRole[] = ["cfo", "accountant", "employee"];
export interface Actor { export interface Actor {
personId: string; personId: string;
displayName: string; displayName: string;
/** Действующие роли (с учётом выбранной роли у admin и CFO). */
roles: Role[]; roles: Role[];
/** Настоящие роли человека из user_roles (admin, accountant, cfo). */
realRoles: string[];
/** admin и CFO могут переключать роль (отладка и тестирование). */
canSwitch: boolean;
acting: ActingRole;
} }
const safeEqual = (a: string, b: string): boolean => { const safeEqual = (a: string, b: string): boolean => {
@@ -38,30 +47,41 @@ export function keycloakVerifier(issuer: string): JwtVerifier {
} }
/** Роли человека: таблица user_roles, а если записей нет - person.role_code (accountant, cfo). */ /** Роли человека: таблица user_roles, а если записей нет - person.role_code (accountant, cfo). */
export async function loadRoles(pool: Pool, personId: string): Promise<Role[]> { export async function loadRoles(pool: Pool, personId: string): Promise<string[]> {
const r = await pool.query("select role from user_roles where person_id = $1", [personId]); const r = await pool.query("select role from user_roles where person_id = $1", [personId]);
const roles = new Set<Role>(r.rows.map((x) => x.role as Role)); const roles = new Set<string>(r.rows.map((x) => String(x.role)));
if (!roles.size) { if (![...roles].some((x) => x !== "admin")) {
const p = (await pool.query("select role_code from person where id = $1", [personId])).rows[0]; const p = (await pool.query("select role_code from person where id = $1", [personId])).rows[0];
if (p?.role_code === "accountant" || p?.role_code === "cfo") roles.add(p.role_code); if (p?.role_code === "accountant" || p?.role_code === "cfo") roles.add(p.role_code);
} }
return [...roles]; return [...roles];
} }
async function actorOf(pool: Pool, personId: string): Promise<Actor> { /** Действующая роль: admin и CFO выбирают сами (по умолчанию CFO у CFO, employee у admin); остальным выбор недоступен. */
export function effectiveRoles(real: string[], requested?: string): { roles: Role[]; canSwitch: boolean; acting: ActingRole } {
const base = real.filter((x): x is Role => x === "accountant" || x === "cfo");
const canSwitch = real.includes("admin") || real.includes("cfo");
if (!canSwitch) return { roles: base, canSwitch, acting: base[0] ?? "employee" };
const def: ActingRole = real.includes("cfo") ? "cfo" : "employee";
const acting = (ACTING_ROLES as string[]).includes(requested ?? "") ? (requested as ActingRole) : def;
return { roles: acting === "employee" ? [] : [acting], canSwitch, acting };
}
async function actorOf(pool: Pool, personId: string, requested?: string): Promise<Actor> {
const p = (await pool.query("select id, display_name from person where id = $1 and is_active", [personId])).rows[0]; const p = (await pool.query("select id, display_name from person where id = $1 and is_active", [personId])).rows[0];
if (!p) throw new AuthError("человек не найден или неактивен", 403); if (!p) throw new AuthError("человек не найден или неактивен", 403);
return { personId: String(p.id), displayName: String(p.display_name), roles: await loadRoles(pool, personId) }; const realRoles = await loadRoles(pool, personId);
return { personId: String(p.id), displayName: String(p.display_name), realRoles, ...effectiveRoles(realRoles, requested) };
} }
/** «Заголовок Authorization -> Actor». Статический токен, затем JWT Keycloak (person по email). */ /** «Заголовок Authorization -> Actor». Статический токен, затем JWT Keycloak (person по email). */
export function createAuth(pool: Pool, settings: Pick<AccInvoicesSettings, "auth">, verifyJwt?: JwtVerifier): (authorization: string | undefined) => Promise<Actor> { export function createAuth(pool: Pool, settings: Pick<AccInvoicesSettings, "auth">, verifyJwt?: JwtVerifier): (authorization: string | undefined, actingRole?: string) => Promise<Actor> {
const verify = verifyJwt ?? (settings.auth.issuer ? keycloakVerifier(settings.auth.issuer) : undefined); const verify = verifyJwt ?? (settings.auth.issuer ? keycloakVerifier(settings.auth.issuer) : undefined);
return async (authorization) => { return async (authorization, actingRole) => {
const t = bearerToken(authorization); const t = bearerToken(authorization);
if (!t) throw new AuthError("нужен заголовок Authorization: Bearer <токен>", 401); if (!t) throw new AuthError("нужен заголовок Authorization: Bearer <токен>", 401);
const st = settings.auth.staticTokens.find((x) => safeEqual(t, x.token)); const st = settings.auth.staticTokens.find((x) => safeEqual(t, x.token));
if (st) return actorOf(pool, st.personId); if (st) return actorOf(pool, st.personId, actingRole);
if (!verify) throw new AuthError("токен не принят", 401); if (!verify) throw new AuthError("токен не принят", 401);
let email: string | undefined; let email: string | undefined;
try { try {
@@ -84,6 +104,6 @@ export function createAuth(pool: Pool, settings: Pick<AccInvoicesSettings, "auth
) )
).rows[0]; ).rows[0];
if (!p) throw new AuthError(`для ${email} нет активного person: доступ запрещён`, 403); if (!p) throw new AuthError(`для ${email} нет активного person: доступ запрещён`, 403);
return actorOf(pool, String(p.id)); return actorOf(pool, String(p.id), actingRole);
}; };
} }

View File

@@ -90,7 +90,7 @@ export function buildApi(deps: ApiDeps): FastifyInstance {
return reply.code(500).send({ error: "внутренняя ошибка" }); return reply.code(500).send({ error: "внутренняя ошибка" });
}); });
const need = async (req: FastifyRequest): Promise<Actor> => authenticate(req.headers.authorization); const need = async (req: FastifyRequest): Promise<Actor> => authenticate(req.headers.authorization, typeof req.headers["x-acting-role"] === "string" ? req.headers["x-acting-role"] : undefined);
const fail = (reply: FastifyReply, status: number, error: string) => reply.code(status).send({ error }); const fail = (reply: FastifyReply, status: number, error: string) => reply.code(status).send({ error });
/** Загружает инвойс и проверяет, что он виден этому человеку (чужой выглядит как несуществующий). */ /** Загружает инвойс и проверяет, что он виден этому человеку (чужой выглядит как несуществующий). */
@@ -106,7 +106,7 @@ export function buildApi(deps: ApiDeps): FastifyInstance {
app.get("/api/me", async (req) => { app.get("/api/me", async (req) => {
const a = await need(req); const a = await need(req);
return { person_id: a.personId, name: a.displayName, roles: a.roles, is_staff: isStaff(a), filters: QUICK_FILTERS }; return { person_id: a.personId, name: a.displayName, roles: a.roles, real_roles: a.realRoles, can_switch: a.canSwitch, acting_role: a.acting, is_staff: isStaff(a), filters: QUICK_FILTERS };
}); });
app.get("/api/lookups", async (req) => { app.get("/api/lookups", async (req) => {

View File

@@ -1,6 +1,6 @@
import * as Ariakit from "@ariakit/react"; import * as Ariakit from "@ariakit/react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { ApiError, api, getToken, type Detail, type Line, type Lookups, type Me, type Row } from "./api.js"; import { ApiError, api, getActing, getToken, setActing, type Detail, type Line, type Lookups, type Me, type Row } from "./api.js";
import { FormDialog } from "./FormDialog.js"; import { FormDialog } from "./FormDialog.js";
import { Login } from "./Login.js"; import { Login } from "./Login.js";
import { finishLogin, logout, relogin } from "./oidc.js"; import { finishLogin, logout, relogin } from "./oidc.js";
@@ -105,7 +105,15 @@ function Main({ me, onLogout }: { me: Me; onLogout: () => void }) {
</Ariakit.TabList> </Ariakit.TabList>
<input className="search" type="search" placeholder="Поиск: вендор, номер, проект, сумма" value={q} onChange={(e) => setQ(e.target.value)} aria-label="Поиск" /> <input className="search" type="search" placeholder="Поиск: вендор, номер, проект, сумма" value={q} onChange={(e) => setQ(e.target.value)} aria-label="Поиск" />
<span className="spacer" /> <span className="spacer" />
<span className="who" title={me.roles.join(", ") || "сотрудник"}>{me.name}</span> <span className="who" title={"роли: " + (me.real_roles.join(", ") || "сотрудник")}>{me.name}</span>
{me.can_switch && (
<select className="role-switch" aria-label="Роль для отладки и тестирования" title="Роль (отладка и тестирование)" value={me.acting_role}
onChange={(e) => { setActing(e.target.value); location.reload(); }}>
<option value="cfo">CFO</option>
<option value="accountant">accountant</option>
<option value="employee">employee</option>
</select>
)}
<button className="btn" onClick={onLogout}>Выйти</button> <button className="btn" onClick={onLogout}>Выйти</button>
<button className="btn primary" disabled={!lookups} onClick={() => openForm(null, [])}>Create</button> <button className="btn primary" disabled={!lookups} onClick={() => openForm(null, [])}>Create</button>
</Ariakit.Toolbar> </Ariakit.Toolbar>

View File

@@ -1,4 +1,4 @@
export interface Me { person_id: string; name: string; roles: string[]; is_staff: boolean; filters: { key: string; label: string }[] } export interface Me { person_id: string; name: string; roles: string[]; real_roles: string[]; can_switch: boolean; acting_role: string; is_staff: boolean; filters: { key: string; label: string }[] }
export interface Row { export interface Row {
id: string; invoice_number: string | null; vendor_name: string; vendor_qbo_id: string | null; invoice_date: string | null; amount: number; id: string; invoice_number: string | null; vendor_name: string; vendor_qbo_id: string | null; invoice_date: string | null; amount: number;
project_customer_id: string | null; project_name: string | null; contract_id: string | null; pay_method: string | null; project_customer_id: string | null; project_name: string | null; contract_id: string | null; pay_method: string | null;
@@ -20,6 +20,9 @@ export interface Lookups { projects: Named[]; vendors: Named[]; people: Named[];
import { freshToken, hasSession } from "./oidc.js"; import { freshToken, hasSession } from "./oidc.js";
export const getToken = (): string => (hasSession() ? "1" : ""); export const getToken = (): string => (hasSession() ? "1" : "");
const AK = "acc_invoices_acting_role";
export const getActing = (): string => { try { return sessionStorage.getItem(AK) ?? ""; } catch { return ""; } };
export const setActing = (r: string): void => { try { sessionStorage.setItem(AK, r); } catch { /* ignore */ } };
export class ApiError extends Error { export class ApiError extends Error {
constructor(message: string, readonly status: number, readonly problems?: string[]) { super(message); } constructor(message: string, readonly status: number, readonly problems?: string[]) { super(message); }
@@ -29,7 +32,7 @@ export class ApiError extends Error {
export async function api<T = unknown>(path: string, init: { method?: string; body?: unknown } = {}): Promise<T> { export async function api<T = unknown>(path: string, init: { method?: string; body?: unknown } = {}): Promise<T> {
const r = await fetch(`api/${path}`, { const r = await fetch(`api/${path}`, {
method: init.method ?? "GET", method: init.method ?? "GET",
headers: { Authorization: `Bearer ${await freshToken()}`, ...(init.body !== undefined ? { "content-type": "application/json" } : {}) }, headers: { Authorization: `Bearer ${await freshToken()}`, ...(getActing() ? { "x-acting-role": getActing() } : {}), ...(init.body !== undefined ? { "content-type": "application/json" } : {}) },
body: init.body !== undefined ? JSON.stringify(init.body) : undefined, body: init.body !== undefined ? JSON.stringify(init.body) : undefined,
}); });
const text = await r.text(); const text = await r.text();

View File

@@ -23,6 +23,7 @@ body { margin: 0; background: var(--bg); color: var(--text); font: 14px/1.4 syst
.search { min-width: 240px; padding: 6px 10px; border: 1px solid var(--line); border-radius: 8px; background: var(--panel); color: var(--text); } .search { min-width: 240px; padding: 6px 10px; border: 1px solid var(--line); border-radius: 8px; background: var(--panel); color: var(--text); }
.spacer { flex: 1; } .spacer { flex: 1; }
.who { color: var(--muted); } .who { color: var(--muted); }
.role-switch { padding: 5px 8px; border: 1px solid var(--accent); border-radius: 8px; background: var(--panel); color: var(--text); font: inherit; }
.btn { border: 1px solid var(--line); background: var(--panel); color: var(--text); padding: 6px 14px; border-radius: 8px; cursor: pointer; font: inherit; text-decoration: none; display: inline-block; } .btn { border: 1px solid var(--line); background: var(--panel); color: var(--text); padding: 6px 14px; border-radius: 8px; cursor: pointer; font: inherit; text-decoration: none; display: inline-block; }
.btn:hover:not(:disabled) { border-color: var(--accent); } .btn:hover:not(:disabled) { border-color: var(--accent); }

View File

@@ -0,0 +1,6 @@
-- acc_invoices: роль admin (отладка и тестирование: может переключаться между CFO, accountant и employee)
alter table user_roles drop constraint if exists user_roles_role_check;
alter table user_roles add constraint user_roles_role_check check (role in ('accountant', 'cfo', 'admin'));
insert into user_roles (person_id, role)
select id, 'admin' from person where lower(email) in ('yuri@khbuild.pro', 'dmitry@khbuild.pro')
on conflict do nothing;