diff --git a/deploy/infra/keycloak-theme-khb/login/resources/css/khb.css b/deploy/infra/keycloak-theme-khb/login/resources/css/khb.css index 8dea039..1b9aa7f 100644 --- a/deploy/infra/keycloak-theme-khb/login/resources/css/khb.css +++ b/deploy/infra/keycloak-theme-khb/login/resources/css/khb.css @@ -32,3 +32,20 @@ 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); } } + +/* Фирменный стиль 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; } diff --git a/deploy/infra/keycloak-theme-khb/login/resources/img/logo.svg b/deploy/infra/keycloak-theme-khb/login/resources/img/logo.svg new file mode 100644 index 0000000..e4389de --- /dev/null +++ b/deploy/infra/keycloak-theme-khb/login/resources/img/logo.svg @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/packages/acc_invoices/src/auth.test.ts b/packages/acc_invoices/src/auth.test.ts new file mode 100644 index 0000000..550bac2 --- /dev/null +++ b/packages/acc_invoices/src/auth.test.ts @@ -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" }); + }); +}); diff --git a/packages/acc_invoices/src/auth.ts b/packages/acc_invoices/src/auth.ts index 49add3b..2e265cc 100644 --- a/packages/acc_invoices/src/auth.ts +++ b/packages/acc_invoices/src/auth.ts @@ -10,10 +10,19 @@ export class AuthError extends Error { } export type Role = "accountant" | "cfo"; +/** Роль для переключателя в интерфейсе (employee - без прав бухгалтерии). */ +export type ActingRole = Role | "employee"; +export const ACTING_ROLES: ActingRole[] = ["cfo", "accountant", "employee"]; export interface Actor { personId: string; displayName: string; + /** Действующие роли (с учётом выбранной роли у admin и CFO). */ roles: Role[]; + /** Настоящие роли человека из user_roles (admin, accountant, cfo). */ + realRoles: string[]; + /** admin и CFO могут переключать роль (отладка и тестирование). */ + canSwitch: boolean; + acting: ActingRole; } const safeEqual = (a: string, b: string): boolean => { @@ -38,30 +47,41 @@ export function keycloakVerifier(issuer: string): JwtVerifier { } /** Роли человека: таблица user_roles, а если записей нет - person.role_code (accountant, cfo). */ -export async function loadRoles(pool: Pool, personId: string): Promise { +export async function loadRoles(pool: Pool, personId: string): Promise { const r = await pool.query("select role from user_roles where person_id = $1", [personId]); - const roles = new Set(r.rows.map((x) => x.role as Role)); - if (!roles.size) { + const roles = new Set(r.rows.map((x) => String(x.role))); + if (![...roles].some((x) => x !== "admin")) { 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); } return [...roles]; } -async function actorOf(pool: Pool, personId: string): Promise { +/** Действующая роль: 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 { 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); - 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). */ -export function createAuth(pool: Pool, settings: Pick, verifyJwt?: JwtVerifier): (authorization: string | undefined) => Promise { +export function createAuth(pool: Pool, settings: Pick, verifyJwt?: JwtVerifier): (authorization: string | undefined, actingRole?: string) => Promise { const verify = verifyJwt ?? (settings.auth.issuer ? keycloakVerifier(settings.auth.issuer) : undefined); - return async (authorization) => { + return async (authorization, actingRole) => { const t = bearerToken(authorization); if (!t) throw new AuthError("нужен заголовок Authorization: Bearer <токен>", 401); 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); let email: string | undefined; try { @@ -84,6 +104,6 @@ export function createAuth(pool: Pool, settings: Pick => authenticate(req.headers.authorization); + const need = async (req: FastifyRequest): Promise => 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 }); /** Загружает инвойс и проверяет, что он виден этому человеку (чужой выглядит как несуществующий). */ @@ -106,7 +106,7 @@ export function buildApi(deps: ApiDeps): FastifyInstance { app.get("/api/me", async (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) => { diff --git a/packages/acc_invoices/web/src/App.tsx b/packages/acc_invoices/web/src/App.tsx index fd5541d..ca309e3 100644 --- a/packages/acc_invoices/web/src/App.tsx +++ b/packages/acc_invoices/web/src/App.tsx @@ -1,6 +1,6 @@ import * as Ariakit from "@ariakit/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 { Login } from "./Login.js"; import { finishLogin, logout, relogin } from "./oidc.js"; @@ -105,7 +105,15 @@ function Main({ me, onLogout }: { me: Me; onLogout: () => void }) { setQ(e.target.value)} aria-label="Поиск" /> - {me.name} + {me.name} + {me.can_switch && ( + + )} diff --git a/packages/acc_invoices/web/src/api.ts b/packages/acc_invoices/web/src/api.ts index a087a6a..327e90f 100644 --- a/packages/acc_invoices/web/src/api.ts +++ b/packages/acc_invoices/web/src/api.ts @@ -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 { 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; @@ -20,6 +20,9 @@ export interface Lookups { projects: Named[]; vendors: Named[]; people: Named[]; import { freshToken, hasSession } from "./oidc.js"; 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 { constructor(message: string, readonly status: number, readonly problems?: string[]) { super(message); } @@ -29,7 +32,7 @@ export class ApiError extends Error { export async function api(path: string, init: { method?: string; body?: unknown } = {}): Promise { const r = await fetch(`api/${path}`, { 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, }); const text = await r.text(); diff --git a/packages/acc_invoices/web/src/styles.css b/packages/acc_invoices/web/src/styles.css index 8f592b1..74f14b0 100644 --- a/packages/acc_invoices/web/src/styles.css +++ b/packages/acc_invoices/web/src/styles.css @@ -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); } .spacer { flex: 1; } .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:hover:not(:disabled) { border-color: var(--accent); } diff --git a/packages/khb_common/migrations/083_acc_invoices_admin.sql b/packages/khb_common/migrations/083_acc_invoices_admin.sql new file mode 100644 index 0000000..dd69104 --- /dev/null +++ b/packages/khb_common/migrations/083_acc_invoices_admin.sql @@ -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;