첫 커밋: 로컬 프로젝트 업로드

This commit is contained in:
송대일 committed 2026-06-10 15:51:34 +09:00
commit 6a8dbeb2e9
1211 files changed
+312864

No files matched your search

@@ -0,0 +1,62 @@
import { describe, expect, it } from "vitest";
import {
getHanmacFamilyTenantOrderRank,
orderHanmacFamilyChildren,
orderHanmacFamilyTenants,
} from "./hanmacFamilyOrder";
function tenant(name: string, slug: string) {
return { name, slug };
}
describe("hanmac family organization order", () => {
it("orders the top hanmac-family siblings by policy", () => {
const ordered = orderHanmacFamilyTenants([
tenant("한라산업개발", "halla"),
tenant("바론그룹", "baron-group"),
tenant("한맥기술", "hanmac"),
tenant("삼안", "saman"),
tenant("총괄기획&기술개발센터", "gpdtdc"),
]);
expect(ordered.map((item) => item.name)).toEqual([
"총괄기획&기술개발센터",
"삼안",
"한맥기술",
"바론그룹",
"한라산업개발",
]);
});
it("keeps hanmac-family as the root before ordered descendants", () => {
const family = tenant("한맥가족", "hanmac-family");
const children = orderHanmacFamilyChildren(family, [
tenant("바론그룹", "baron-group"),
tenant("총괄기획&기술개발센터", "gpdtdc"),
tenant("삼안", "saman"),
tenant("한라산업개발", "halla"),
tenant("한맥기술", "hanmac"),
]);
expect([family, ...children].map((item) => item.name)).toEqual([
"한맥가족",
"총괄기획&기술개발센터",
"삼안",
"한맥기술",
"바론그룹",
"한라산업개발",
]);
});
it("does not rank generic technical centers as GPDTDC", () => {
expect(
getHanmacFamilyTenantOrderRank(tenant("기술개발센터", "rnd-center")),
).toBe(Number.MAX_SAFE_INTEGER);
});
it("ranks Halla as the fifth hanmac-family company", () => {
expect(
getHanmacFamilyTenantOrderRank(tenant("한라산업개발", "halla")),
).toBe(4);
});
});
@@ -0,0 +1,67 @@
export type HanmacFamilyOrderTenant = {
name: string;
slug: string;
};
export const HANMAC_FAMILY_ROOT_SLUG = "hanmac-family";
export const HANMAC_FAMILY_TENANT_ORDER = [
"gpdtdc",
"saman",
"hanmac",
"baron-group",
"halla",
] as const;
function normalizedTenantText(tenant: HanmacFamilyOrderTenant) {
return `${tenant.slug} ${tenant.name}`.trim().toLowerCase();
}
export function isHanmacFamilyRootTenant(tenant: HanmacFamilyOrderTenant) {
return (
tenant.slug.toLowerCase() === HANMAC_FAMILY_ROOT_SLUG ||
tenant.name.includes("한맥가족")
);
}
export function getHanmacFamilyTenantOrderRank(
tenant: HanmacFamilyOrderTenant,
) {
const text = normalizedTenantText(tenant);
if (text.includes("gpdtdc") || text.includes("총괄기획")) return 0;
if (text.includes("saman") || text.includes("삼안")) return 1;
if (
(text.includes("hanmac") || text.includes("한맥기술")) &&
!isHanmacFamilyRootTenant(tenant)
) {
return 2;
}
if (text.includes("baron-group") || text.includes("바론그룹")) return 3;
if (text.includes("halla") || text.includes("한라산업개발")) return 4;
return Number.MAX_SAFE_INTEGER;
}
export function compareHanmacFamilyTenants<T extends HanmacFamilyOrderTenant>(
a: T,
b: T,
) {
const rankDiff =
getHanmacFamilyTenantOrderRank(a) - getHanmacFamilyTenantOrderRank(b);
if (rankDiff !== 0) return rankDiff;
return a.name.localeCompare(b.name);
}
export function orderHanmacFamilyTenants<T extends HanmacFamilyOrderTenant>(
tenants: readonly T[],
) {
return [...tenants].sort(compareHanmacFamilyTenants);
}
export function orderHanmacFamilyChildren<T extends HanmacFamilyOrderTenant>(
parent: HanmacFamilyOrderTenant,
children: readonly T[],
) {
return isHanmacFamilyRootTenant(parent)
? orderHanmacFamilyTenants(children)
: [...children];
}
@@ -0,0 +1,189 @@
import { describe, expect, it } from "vitest";
import type { TenantSummary, UserSummary } from "../../lib/adminApi";
import { buildOrgPickerTree } from "./pickerTree";
function tenant(
id: string,
type: string,
name: string,
slug: string,
parentId?: string,
): TenantSummary {
return {
id,
type,
name,
slug,
description: "",
status: "active",
parentId,
memberCount: 0,
createdAt: "2026-05-11T00:00:00.000Z",
updatedAt: "2026-05-11T00:00:00.000Z",
};
}
describe("buildOrgPickerTree", () => {
it("uses the hanmac-family company-group as the default picker root", () => {
const tenants = [
tenant("wrong-group", "COMPANY_GROUP", "Wrong Group", "wrong-group"),
tenant(
"wrong-company",
"COMPANY",
"Wrong Company",
"wrong-company",
"wrong-group",
),
tenant("hanmac-family-id", "COMPANY_GROUP", "한맥가족", "hanmac-family"),
tenant("saman-id", "COMPANY", "삼안", "saman", "hanmac-family-id"),
];
const tree = buildOrgPickerTree({
tenants,
users: [] satisfies UserSummary[],
});
expect(tree.companyGroupId).toBe("hanmac-family-id");
expect(tree.roots).toHaveLength(1);
expect(tree.roots[0]?.id).toBe("hanmac-family-id");
expect(tree.roots[0]?.children.map((node) => node.id)).toEqual([
"saman-id",
]);
});
it("orders hanmac-family children by the shared organization policy", () => {
const tenants = [
tenant("hanmac-family-id", "COMPANY_GROUP", "한맥가족", "hanmac-family"),
tenant(
"baron-group-id",
"COMPANY_GROUP",
"바론그룹",
"baron-group",
"hanmac-family-id",
),
tenant("hanmac-id", "COMPANY", "한맥기술", "hanmac", "hanmac-family-id"),
tenant(
"halla-id",
"COMPANY",
"한라산업개발",
"halla",
"hanmac-family-id",
),
tenant("saman-id", "COMPANY", "삼안", "saman", "hanmac-family-id"),
tenant(
"gpdtdc-id",
"ORGANIZATION",
"총괄기획&기술개발센터",
"gpdtdc",
"hanmac-family-id",
),
];
const tree = buildOrgPickerTree({
tenants,
users: [] satisfies UserSummary[],
});
expect(tree.roots[0]?.children.map((node) => node.name)).toEqual([
"총괄기획&기술개발센터",
"삼안",
"한맥기술",
"바론그룹",
"한라산업개발",
]);
});
it("scopes descendant filtering by tenant slug", () => {
const tenants = [
tenant("hanmac-family-id", "COMPANY_GROUP", "한맥가족", "hanmac-family"),
tenant("saman-id", "COMPANY", "삼안", "saman", "hanmac-family-id"),
tenant("planning-id", "ORGANIZATION", "기획팀", "planning", "saman-id"),
tenant("hanmac-id", "COMPANY", "한맥기술", "hanmac", "hanmac-family-id"),
];
const tree = buildOrgPickerTree({
tenants,
users: [] satisfies UserSummary[],
tenantId: "saman",
});
expect(tree.roots).toHaveLength(1);
expect(tree.roots[0]?.id).toBe("saman-id");
expect(tree.roots[0]?.children.map((node) => node.id)).toEqual([
"planning-id",
]);
});
it("excludes internal and private tenants from picker choices by default", () => {
const tenants = [
tenant("hanmac-family-id", "COMPANY_GROUP", "한맥가족", "hanmac-family"),
tenant("saman-id", "COMPANY", "삼안", "saman", "hanmac-family-id"),
{
...tenant(
"internal-id",
"ORGANIZATION",
"내부 조직",
"internal",
"saman-id",
),
config: { visibility: "internal" },
},
{
...tenant(
"secret-id",
"ORGANIZATION",
"비공개 조직",
"secret",
"saman-id",
),
config: { visibility: "private" },
},
tenant(
"secret-child-id",
"USER_GROUP",
"비공개 하위",
"secret-child",
"secret-id",
),
tenant("open-id", "ORGANIZATION", "공개 조직", "open", "saman-id"),
];
const tree = buildOrgPickerTree({
tenants,
users: [] satisfies UserSummary[],
tenantId: "saman",
});
expect(tree.roots[0]?.children.map((node) => node.id)).toEqual(["open-id"]);
});
it("includes internal tenants when explicitly requested", () => {
const tenants = [
tenant("hanmac-family-id", "COMPANY_GROUP", "한맥가족", "hanmac-family"),
tenant("saman-id", "COMPANY", "삼안", "saman", "hanmac-family-id"),
{
...tenant(
"internal-id",
"ORGANIZATION",
"내부 조직",
"internal",
"saman-id",
),
config: { visibility: "internal" },
},
tenant("open-id", "ORGANIZATION", "공개 조직", "open", "saman-id"),
];
const tree = buildOrgPickerTree({
includeInternal: true,
tenants,
users: [] satisfies UserSummary[],
tenantId: "saman",
});
expect(tree.roots[0]?.children.map((node) => node.id)).toEqual([
"internal-id",
"open-id",
]);
});
});
@@ -0,0 +1,188 @@
import type { TenantSummary, UserSummary } from "../../lib/adminApi";
import { buildTenantFullTree, type TenantNode } from "../../lib/tenantTree";
import { orderHanmacFamilyChildren } from "./hanmacFamilyOrder";
import type { OrgPickerTreeNode } from "./pickerTypes";
import { filterTenantsByVisibility } from "./tenantVisibility";
import { getOrgChartUserDisplayName } from "./userDisplay";
function getUserTenantSlug(user: UserSummary) {
return user.tenantSlug?.toLowerCase() || "";
}
function isOrgFrontTenantType(tenant: TenantSummary) {
return ["COMPANY_GROUP", "COMPANY", "ORGANIZATION", "USER_GROUP"].includes(
tenant.type.toUpperCase(),
);
}
function getCompanyGroupId(node: TenantNode, allTenants: TenantSummary[]) {
let cursor: TenantSummary | undefined = node;
const byId = new Map(allTenants.map((tenant) => [tenant.id, tenant]));
while (cursor?.parentId) {
const parent = byId.get(cursor.parentId);
if (!parent) break;
cursor = parent;
}
return cursor?.type === "COMPANY_GROUP" ? cursor.id : node.id;
}
function isHanmacFamilyCompanyGroup(tenant: TenantSummary) {
return (
tenant.type.toUpperCase() === "COMPANY_GROUP" &&
tenant.slug.toLowerCase() === "hanmac-family"
);
}
function findTenantByRef(tenants: TenantSummary[], ref?: string) {
const normalizedRef = ref?.trim().toLowerCase();
if (!normalizedRef) return undefined;
return (
tenants.find((tenant) => tenant.slug.toLowerCase() === normalizedRef) ??
tenants.find((tenant) => tenant.id === ref)
);
}
function tenantToPickerNode(
tenant: TenantNode,
usersBySlug: Map<string, UserSummary[]>,
): OrgPickerTreeNode {
const tenantChildren = orderHanmacFamilyChildren(tenant, tenant.children).map(
(child) => tenantToPickerNode(child, usersBySlug),
);
const userChildren = (usersBySlug.get(tenant.slug.toLowerCase()) || []).map(
(user) => ({
type: "user" as const,
id: user.id,
name: getOrgChartUserDisplayName(user, tenant),
parentId: tenant.id,
user,
children: [],
}),
);
return {
type: "tenant",
id: tenant.id,
name: tenant.name,
parentId: tenant.parentId ?? null,
tenant,
children: [...userChildren, ...tenantChildren],
};
}
function findTenantNode(
roots: TenantNode[],
tenantRef: string,
): TenantNode | undefined {
const findBySlug = (node: TenantNode): TenantNode | undefined => {
if (node.slug.toLowerCase() === tenantRef.trim().toLowerCase()) {
return node;
}
for (const child of node.children) {
const match = findBySlug(child);
if (match) return match;
}
return undefined;
};
const findById = (node: TenantNode): TenantNode | undefined => {
if (node.id === tenantRef) return node;
for (const child of node.children) {
const match = findById(child);
if (match) return match;
}
return undefined;
};
for (const root of roots) {
const slugMatch = findBySlug(root);
if (slugMatch) return slugMatch;
}
for (const root of roots) {
const idMatch = findById(root);
if (idMatch) return idMatch;
}
return undefined;
}
export function buildOrgPickerTree({
includeInternal = false,
tenants,
users,
rootTenantId,
tenantId,
}: {
includeInternal?: boolean;
tenants: TenantSummary[];
users: UserSummary[];
rootTenantId?: string;
tenantId?: string;
}) {
const visibleTenants = filterTenantsByVisibility(
tenants.filter(isOrgFrontTenantType),
includeInternal ? "internal" : "public",
);
const usersBySlug = new Map<string, UserSummary[]>();
for (const user of users) {
if (user.status !== "active") continue;
const slug = getUserTenantSlug(user);
if (!slug) continue;
const list = usersBySlug.get(slug) || [];
list.push(user);
usersBySlug.set(slug, list);
}
const companyGroup =
findTenantByRef(visibleTenants, rootTenantId) ??
visibleTenants.find(isHanmacFamilyCompanyGroup) ??
visibleTenants.find((tenant) => tenant.type === "COMPANY_GROUP") ??
visibleTenants.find((tenant) => !tenant.parentId);
if (!companyGroup) return { roots: [], companies: [], companyGroupId: "" };
const { currentBase } = buildTenantFullTree(visibleTenants, companyGroup.id);
const groupNode =
currentBase ??
buildTenantFullTree(visibleTenants).subTree.find(
(node) => node.id === companyGroup.id,
);
if (!groupNode) return { roots: [], companies: [], companyGroupId: "" };
const companies = orderHanmacFamilyChildren(
groupNode,
groupNode.children,
).filter((node) => node.type === "COMPANY");
const scopedRoot = tenantId
? findTenantNode([groupNode], tenantId)
: groupNode;
const filteredRoots = scopedRoot ? [scopedRoot] : [];
const roots = filteredRoots.map((node) =>
tenantToPickerNode(node, usersBySlug),
);
return {
roots,
companies: companies.map((company) => ({
id: company.id,
name: company.name,
companyGroupTenantId: getCompanyGroupId(company, tenants),
})),
companyGroupId: companyGroup.id,
};
}
export function flattenDescendants(node: OrgPickerTreeNode) {
const descendants: OrgPickerTreeNode[] = [];
const walk = (current: OrgPickerTreeNode) => {
for (const child of current.children) {
descendants.push(child);
walk(child);
}
};
walk(node);
return descendants;
}
@@ -0,0 +1,56 @@
import { describe, expect, it } from "vitest";
import {
buildOrgPickerEmbedSrc,
parseOrgPickerEmbedOptions,
} from "./pickerTypes";
describe("org picker embed options", () => {
it("builds slug-based tenant scope urls", () => {
expect(
buildOrgPickerEmbedSrc({
includeInternal: false,
mode: "single",
select: "tenant",
includeDescendants: true,
showDescendantToggle: true,
tenantId: "saman",
width: 400,
height: 600,
}),
).toBe(
"/embed/picker?mode=single&select=tenant&width=400&height=600&tenantSlug=saman",
);
});
it("builds and parses internal visibility flag only when requested", () => {
const src = buildOrgPickerEmbedSrc({
includeInternal: true,
mode: "single",
select: "tenant",
includeDescendants: true,
showDescendantToggle: true,
tenantId: "",
width: 400,
height: 600,
});
expect(src).toBe(
"/embed/picker?mode=single&select=tenant&width=400&height=600&includeInternal=true",
);
expect(parseOrgPickerEmbedOptions(src).includeInternal).toBe(true);
expect(parseOrgPickerEmbedOptions("?mode=single").includeInternal).toBe(
false,
);
});
it("parses tenantSlug first and keeps legacy tenantId compatibility", () => {
expect(
parseOrgPickerEmbedOptions(
"?tenantId=legacy-id&tenantSlug=saman&companyTenantId=legacy-company",
).tenantId,
).toBe("saman");
expect(parseOrgPickerEmbedOptions("?tenantId=legacy-id").tenantId).toBe(
"legacy-id",
);
});
});
@@ -0,0 +1,107 @@
import type { TenantSummary, UserSummary } from "../../lib/adminApi";
export type OrgPickerMode = "single" | "multiple";
export type OrgPickerSelectableType = "tenant" | "user" | "both";
export type OrgPickerObjectType = "tenant" | "user";
export type OrgPickerSelection = {
type: OrgPickerObjectType;
id: string;
name: string;
};
export type OrgPickerResult = {
mode: OrgPickerMode;
selections: OrgPickerSelection[];
};
export type OrgPickerEmbedOptions = {
includeInternal: boolean;
mode: OrgPickerMode;
select: OrgPickerSelectableType;
includeDescendants: boolean;
showDescendantToggle: boolean;
tenantId: string;
width: number;
height: number;
};
export type OrgPickerTreeNode = {
type: OrgPickerObjectType;
id: string;
name: string;
parentId: string | null;
tenant?: TenantSummary;
user?: UserSummary;
children: OrgPickerTreeNode[];
};
export function nodeKey(node: Pick<OrgPickerTreeNode, "type" | "id">) {
return `${node.type}:${node.id}`;
}
export function selectionKey(selection: OrgPickerSelection) {
return `${selection.type}:${selection.id}`;
}
export function parseOrgPickerMode(value: string | null): OrgPickerMode {
return value === "multiple" ? "multiple" : "single";
}
export function parseOrgPickerSelectableType(
value: string | null,
): OrgPickerSelectableType {
if (value === "tenant" || value === "user") return value;
return "both";
}
function parseEmbedDimension(value: string | null, fallback: number) {
const parsed = Number.parseInt(value ?? "", 10);
if (!Number.isFinite(parsed)) return fallback;
return Math.min(1600, Math.max(240, parsed));
}
export function parseOrgPickerEmbedOptions(search: string) {
const params = new URLSearchParams(search);
return {
mode:
params.get("mode") === "single"
? ("single" as const)
: ("multiple" as const),
select: parseOrgPickerSelectableType(params.get("select")),
includeInternal: params.get("includeInternal") === "true",
includeDescendants: params.get("includeDescendants") !== "false",
showDescendantToggle: params.get("showDescendantToggle") !== "false",
tenantId:
params.get("tenantSlug") ??
params.get("tenantId") ??
params.get("companyTenantId") ??
"",
width: parseEmbedDimension(params.get("width"), 400),
height: parseEmbedDimension(params.get("height"), 600),
};
}
export function buildOrgPickerEmbedSrc(options: OrgPickerEmbedOptions) {
const params = new URLSearchParams({
mode: options.mode,
select: options.select,
width: String(options.width),
height: String(options.height),
});
if (options.includeInternal) {
params.set("includeInternal", "true");
}
const tenantSlug = options.tenantId.trim();
if (tenantSlug) {
params.set("tenantSlug", tenantSlug);
}
if (options.mode === "multiple") {
params.set("includeDescendants", String(options.includeDescendants));
params.set("showDescendantToggle", String(options.showDescendantToggle));
}
return `/embed/picker?${params.toString()}`;
}
@@ -0,0 +1,42 @@
import { describe, expect, it } from "vitest";
import {
compareOrgRanks,
getOrgRankDisplayName,
getOrgRankWeight,
} from "./rankPriority";
describe("org chart rank priority", () => {
it("normalizes long rank aliases to short display labels", () => {
expect(getOrgRankDisplayName("전무이사")).toBe("전무");
expect(getOrgRankDisplayName("상무이사")).toBe("상무");
expect(getOrgRankDisplayName("수석연구원")).toBe("수석");
expect(getOrgRankDisplayName("책임연구원")).toBe("책임");
expect(getOrgRankDisplayName("선임연구원")).toBe("선임");
});
it("orders executive and research ranks with shared priority weights", () => {
expect(getOrgRankWeight("사장")).toBeLessThan(getOrgRankWeight("부사장"));
expect(getOrgRankWeight("전무이사")).toBeLessThan(getOrgRankWeight("상무"));
expect(getOrgRankWeight("수석연구원")).toBeLessThan(
getOrgRankWeight("책임"),
);
expect(getOrgRankWeight("책임연구원")).toBeLessThan(
getOrgRankWeight("선임"),
);
expect(compareOrgRanks("부장", "차장")).toBeLessThan(0);
});
it("orders top executive ranks before the existing vice president and lower ranks", () => {
const ranks = ["부사장", "고문", "부회장", "사장", "회장"];
expect(ranks.toSorted(compareOrgRanks)).toEqual([
"회장",
"사장",
"부회장",
"고문",
"부사장",
]);
expect(getOrgRankWeight("부사장")).toBe(10);
expect(getOrgRankWeight("전무")).toBe(20);
});
});
@@ -0,0 +1,57 @@
export type OrgRankDefinition = {
aliases: string[];
label: string;
weight: number;
};
export const ORG_RANK_DEFINITIONS: OrgRankDefinition[] = [
{ label: "회장", weight: -10, aliases: ["회장"] },
{ label: "사장", weight: 0, aliases: ["사장"] },
{ label: "부회장", weight: 2, aliases: ["부회장"] },
{ label: "고문", weight: 5, aliases: ["고문"] },
{ label: "부사장", weight: 10, aliases: ["부사장"] },
{ label: "전무", weight: 20, aliases: ["전무", "전무이사"] },
{ label: "상무", weight: 30, aliases: ["상무", "상무이사"] },
{ label: "이사", weight: 40, aliases: ["이사"] },
{ label: "부장", weight: 50, aliases: ["부장"] },
{ label: "수석", weight: 50, aliases: ["수석", "수석연구원"] },
{ label: "차장", weight: 60, aliases: ["차장"] },
{ label: "과장", weight: 70, aliases: ["과장"] },
{ label: "책임", weight: 70, aliases: ["책임", "책임연구원"] },
{ label: "대리", weight: 80, aliases: ["대리"] },
{ label: "선임", weight: 80, aliases: ["선임", "선임연구원"] },
{ label: "연구원", weight: 90, aliases: ["연구원"] },
{ label: "사원", weight: 90, aliases: ["사원"] },
];
const UNKNOWN_RANK_WEIGHT = 999;
function normalizeRankText(value: unknown) {
return typeof value === "string" ? value.trim().replace(/\s+/g, "") : "";
}
export function getOrgRankDefinition(rank: unknown) {
const normalizedRank = normalizeRankText(rank);
if (!normalizedRank) return undefined;
return ORG_RANK_DEFINITIONS.find((definition) =>
definition.aliases.some(
(alias) => normalizeRankText(alias) === normalizedRank,
),
);
}
export function getOrgRankDisplayName(rank: unknown) {
return (
getOrgRankDefinition(rank)?.label ??
(typeof rank === "string" ? rank.trim() : "")
);
}
export function getOrgRankWeight(rank: unknown) {
return getOrgRankDefinition(rank)?.weight ?? UNKNOWN_RANK_WEIGHT;
}
export function compareOrgRanks(a: unknown, b: unknown) {
return getOrgRankWeight(a) - getOrgRankWeight(b);
}
@@ -0,0 +1,660 @@
import { describe, expect, it } from "vitest";
import {
buildOrgSelectionOptions,
buildUsersMap,
clampScale,
filterSystemGlobalTenants,
getMemberGridMetrics,
getOrgNodeHeaderFill,
getSemanticZoomMode,
layoutForest,
resolveOrgChartFamilyRoot,
type OrgNode,
} from "./OrgChartPage";
function orgNode(id: string, children: OrgNode[] = [], level = 0): OrgNode {
return {
id,
name: id,
level,
members: [],
children,
totalCount: 0,
totalMemberIds: new Set<string>(),
companyCode: id,
type: level === 0 ? "COMPANY" : "USER_GROUP",
};
}
function member(id: string) {
return {
id,
email: `${id}@example.com`,
name: id,
role: "user",
status: "active",
companyCode: "root",
grade: "사원",
createdAt: "2026-05-11T00:00:00.000Z",
updatedAt: "2026-05-11T00:00:00.000Z",
};
}
function tenantNode(
id: string,
type: string,
name: string,
slug: string,
children = [],
) {
return {
id,
type,
name,
slug,
children,
description: "",
status: "active",
memberCount: 0,
recursiveMemberCount: 0,
createdAt: "2026-05-11T00:00:00.000Z",
updatedAt: "2026-05-11T00:00:00.000Z",
};
}
function getNodeBoundsAspectRatio(
nodes: ReturnType<typeof layoutForest>["nodes"],
) {
const minX = Math.min(...nodes.map((node) => node.x));
const maxX = Math.max(...nodes.map((node) => node.x + node.width));
const minY = Math.min(...nodes.map((node) => node.y));
const maxY = Math.max(...nodes.map((node) => node.y + node.height));
return (maxX - minX) / (maxY - minY);
}
describe("org chart layout", () => {
it("keeps small sibling groups horizontal in automatic mode", () => {
const children = Array.from({ length: 4 }, (_, index) =>
orgNode(`child-${index + 1}`, [], 1),
);
const layout = layoutForest([orgNode("root", children)], new Set());
const childNodes = layout.nodes.filter((node) =>
node.node.id.startsWith("child-"),
);
expect(new Set(childNodes.map((node) => node.y)).size).toBe(1);
});
it("uses member columns in node bounds when the rendered node aspect ratio needs them", () => {
const compactMembers = Array.from({ length: 10 }, (_, index) =>
member(`member-${index + 1}`),
);
const node = {
...orgNode("root"),
members: compactMembers,
totalCount: compactMembers.length,
totalMemberIds: new Set(compactMembers.map((item) => item.id)),
};
const layout = layoutForest([node], new Set());
const rootNode = layout.nodes.find((item) => item.node.id === "root");
expect(rootNode).toBeDefined();
expect(rootNode?.width).toBeGreaterThan(240);
expect(rootNode?.height).toBeLessThan(42 + 24 + 10 * 24);
expect(layout.width).toBeGreaterThan((rootNode?.width ?? 0) + 72 * 2 - 1);
});
it("sizes member cards from an eight-character baseline and expands for long display names", () => {
const shortMembers = Array.from({ length: 6 }, (_, index) => ({
...member(`short-${index + 1}`),
name: `홍길${index + 1}`,
grade: "책임",
}));
const longMembers = shortMembers.map((item, index) => ({
...item,
id: `long-${index + 1}`,
name: `매우긴사용자이름${index + 1}`,
}));
const shortLayout = layoutForest(
[
{
...orgNode("short"),
members: shortMembers,
totalCount: shortMembers.length,
totalMemberIds: new Set(shortMembers.map((item) => item.id)),
},
],
new Set(),
);
const longLayout = layoutForest(
[
{
...orgNode("long"),
members: longMembers,
totalCount: longMembers.length,
totalMemberIds: new Set(longMembers.map((item) => item.id)),
},
],
new Set(),
);
const shortNode = shortLayout.nodes.find(
(item) => item.node.id === "short",
);
const longNode = longLayout.nodes.find((item) => item.node.id === "long");
expect(shortNode?.width).toBeLessThan(320);
expect(longNode?.width).toBeGreaterThan(shortNode?.width ?? 0);
});
it("uses compact member columns when another column improves the rendered ratio", () => {
const tenMembers = Array.from({ length: 10 }, (_, index) =>
member(`member-${index + 1}`),
);
const sixMembers = tenMembers.slice(0, 6);
const sixLayout = layoutForest(
[
{
...orgNode("six"),
members: sixMembers,
totalCount: sixMembers.length,
totalMemberIds: new Set(sixMembers.map((item) => item.id)),
},
],
new Set(),
);
const tenLayout = layoutForest(
[
{
...orgNode("ten"),
members: tenMembers,
totalCount: tenMembers.length,
totalMemberIds: new Set(tenMembers.map((item) => item.id)),
},
],
new Set(),
);
const sixNode = sixLayout.nodes.find((item) => item.node.id === "six");
const tenNode = tenLayout.nodes.find((item) => item.node.id === "ten");
expect(sixNode?.width).toBeGreaterThan(240);
expect(tenNode?.width).toBe(sixNode?.width);
expect(sixNode?.height).toBeLessThan(42 + 24 + 6 * 24);
expect(tenNode?.height).toBeLessThan(42 + 24 + 10 * 24);
});
it("chooses member columns from the rendered node aspect ratio instead of fixed five-member buckets", () => {
expect(getMemberGridMetrics(6)).toEqual({ columnCount: 2, rowCount: 3 });
expect(getMemberGridMetrics(10)).toEqual({ columnCount: 2, rowCount: 5 });
expect(getMemberGridMetrics(25)).toEqual({ columnCount: 4, rowCount: 7 });
});
it("sorts members by normalized rank inside the same organization", () => {
const members = [
{ ...member("staff"), name: "사원", grade: "사원" },
{ ...member("principal"), name: "수석", grade: "수석연구원" },
{ ...member("director"), name: "전무", grade: "전무이사" },
{ ...member("lead"), name: "책임", grade: "책임" },
];
const layout = layoutForest(
[
{
...orgNode("root"),
members,
totalCount: members.length,
totalMemberIds: new Set(members.map((item) => item.id)),
},
],
new Set(),
);
const rootNode = layout.nodes.find((item) => item.node.id === "root");
expect(rootNode?.members.map((item) => item.id)).toEqual([
"director",
"principal",
"lead",
"staff",
]);
});
it("uses multi-column layout by default when sibling width crosses the threshold", () => {
const children = Array.from({ length: 13 }, (_, index) =>
orgNode(`child-${index + 1}`, [], 1),
);
const layout = layoutForest([orgNode("root", children)], new Set());
const childNodes = layout.nodes.filter((node) =>
node.node.id.startsWith("child-"),
);
const uniqueChildRows = new Set(childNodes.map((node) => node.y));
const childSpan =
Math.max(...childNodes.map((node) => node.x + node.width)) -
Math.min(...childNodes.map((node) => node.x));
const aspectRatio = getNodeBoundsAspectRatio(layout.nodes);
expect(childNodes).toHaveLength(13);
expect(uniqueChildRows.size).toBeGreaterThan(1);
expect(aspectRatio).toBeGreaterThanOrEqual(1.41);
expect(aspectRatio).toBeLessThanOrEqual(1.61);
expect(childSpan).toBeLessThan(13 * 240 + 12 * 80);
expect(
layout.edges.filter((edge) => edge.key.startsWith("root->")),
).toHaveLength(13);
expect(
layout.edges.filter(
(edge) => edge.key.startsWith("root->") && edge.visibleByDefault,
),
).toHaveLength(new Set(childNodes.map((node) => node.x)).size);
});
it("tunes column and row gaps after column selection to keep auto layout near the target aspect ratio", () => {
const children = Array.from({ length: 5 }, (_, index) =>
orgNode(`child-${index + 1}`, [], 1),
);
const layout = layoutForest([orgNode("root", children)], new Set());
const childNodes = layout.nodes.filter((node) =>
node.node.id.startsWith("child-"),
);
const aspectRatio = getNodeBoundsAspectRatio(layout.nodes);
expect(new Set(childNodes.map((node) => node.x)).size).toBe(4);
expect(aspectRatio).toBeGreaterThanOrEqual(1.41);
expect(aspectRatio).toBeLessThanOrEqual(1.61);
});
it("keeps direct siblings on one level in top-down mode", () => {
const children = Array.from({ length: 13 }, (_, index) =>
orgNode(`child-${index + 1}`, [], 1),
);
const layout = layoutForest([orgNode("root", children)], new Set(), {
childLayoutMode: "topDown",
});
const childNodes = layout.nodes.filter((node) =>
node.node.id.startsWith("child-"),
);
const uniqueChildRows = new Set(childNodes.map((node) => node.y));
expect(childNodes).toHaveLength(13);
expect(uniqueChildRows.size).toBe(1);
});
it("places children in three fixed columns with centered parent edges", () => {
const children = Array.from({ length: 10 }, (_, index) =>
orgNode(`child-${index + 1}`, [], 1),
);
const layout = layoutForest([orgNode("root", children)], new Set(), {
childLayoutMode: "threeColumn",
});
const childNodes = layout.nodes.filter((node) =>
node.node.id.startsWith("child-"),
);
const uniqueChildColumns = new Set(childNodes.map((node) => node.x));
const uniqueChildRows = new Set(childNodes.map((node) => node.y));
const rootEdges = layout.edges.filter((edge) =>
edge.key.startsWith("root->"),
);
expect(uniqueChildColumns.size).toBe(3);
expect(uniqueChildRows.size).toBe(4);
expect(rootEdges).toHaveLength(10);
expect(rootEdges.filter((edge) => edge.visibleByDefault)).toHaveLength(3);
});
it("places the deepest child subtree in the first multi-column section", () => {
const children = [
orgNode("shallow-1", [], 1),
orgNode("shallow-2", [], 1),
orgNode("shallow-3", [], 1),
orgNode(
"deep",
[
orgNode(
"deep-branch",
[orgNode("deep-leaf", [orgNode("deep-tail", [], 4)], 3)],
2,
),
],
1,
),
orgNode("shallow-4", [], 1),
orgNode("shallow-5", [], 1),
];
const layout = layoutForest([orgNode("root", children)], new Set(), {
childLayoutMode: "threeColumn",
});
const rootEdges = layout.edges.filter((edge) =>
edge.key.startsWith("root->"),
);
expect(rootEdges.map((edge) => edge.key)).toContain("root->deep");
});
it("centers a parent over the full child span in multi-column mode", () => {
const children = [
orgNode(
"deep",
[
orgNode(
"deep-branch",
[orgNode("deep-leaf", [orgNode("deep-tail", [], 4)], 3)],
2,
),
],
1,
),
...Array.from({ length: 9 }, (_, index) =>
orgNode(`shallow-${index + 1}`, [], 1),
),
];
const layout = layoutForest([orgNode("root", children)], new Set(), {
childLayoutMode: "threeColumn",
});
const rootNode = layout.nodes.find((node) => node.node.id === "root");
const directChildren = layout.nodes.filter((node) => node.node.level === 1);
const childSpanCenter =
(Math.min(...directChildren.map((node) => node.x + node.width / 2)) +
Math.max(...directChildren.map((node) => node.x + node.width / 2))) /
2;
const rootCenter = rootNode ? rootNode.x + rootNode.width / 2 : 0;
expect(rootNode).toBeDefined();
expect(rootCenter).toBeCloseTo(childSpanCenter, 5);
});
it("centers parents above the tidy child span", () => {
const children = [
orgNode("left", [orgNode("left-a", [], 2), orgNode("left-b", [], 2)], 1),
orgNode("middle", [], 1),
orgNode(
"right",
[orgNode("right-a", [], 2), orgNode("right-b", [], 2)],
1,
),
];
const layout = layoutForest([orgNode("root", children)], new Set(), {
childLayoutMode: "topDown",
});
const rootNode = layout.nodes.find((node) => node.node.id === "root");
const directChildren = layout.nodes.filter((node) =>
["left", "middle", "right"].includes(node.node.id),
);
const childSpanCenter =
(Math.min(...directChildren.map((node) => node.x + node.width / 2)) +
Math.max(...directChildren.map((node) => node.x + node.width / 2))) /
2;
const rootCenter = rootNode ? rootNode.x + rootNode.width / 2 : 0;
expect(rootNode).toBeDefined();
expect(rootCenter).toBeCloseTo(childSpanCenter, 5);
});
it("keeps compressed subtrees from overlapping on shared vertical bands", () => {
const layout = layoutForest(
[
orgNode("root", [
orgNode(
"left",
[orgNode("left-a", [], 2), orgNode("left-b", [], 2)],
1,
),
orgNode(
"right",
[orgNode("right-a", [], 2), orgNode("right-b", [], 2)],
1,
),
]),
],
new Set(),
);
for (const node of layout.nodes) {
for (const other of layout.nodes) {
if (node.node.id >= other.node.id) continue;
const verticalOverlap =
node.y < other.y + other.height && other.y < node.y + node.height;
const horizontalOverlap =
node.x < other.x + other.width && other.x < node.x + node.width;
expect(
verticalOverlap && horizontalOverlap,
`${node.node.id} overlaps ${other.node.id}`,
).toBe(false);
}
}
});
it("keeps zoom limits wide enough for large SVG organization charts", () => {
expect(clampScale(0.08)).toBe(0.08);
expect(clampScale(32)).toBe(32);
expect(clampScale(64)).toBe(32);
});
it("switches semantic zoom modes from overview to detail", () => {
expect(getSemanticZoomMode(0.12)).toBe("overview");
expect(getSemanticZoomMode(0.4)).toBe("compact");
expect(getSemanticZoomMode(0.8)).toBe("detail");
});
it("uses distinct header fills by organization depth", () => {
expect(getOrgNodeHeaderFill(0, "family")).toBe("#000000");
expect(getOrgNodeHeaderFill(0, "saman")).toBe("#f58220");
expect(getOrgNodeHeaderFill(0, "hanmac")).toBe("#1e489d");
expect(getOrgNodeHeaderFill(0, "gpdtdc")).toBe("#4b746d");
expect(getOrgNodeHeaderFill(0, "baron")).toBe("#004cbf");
expect(getOrgNodeHeaderFill(1, "saman")).not.toBe(
getOrgNodeHeaderFill(0, "saman"),
);
expect(getOrgNodeHeaderFill(2, "saman")).not.toBe(
getOrgNodeHeaderFill(1, "saman"),
);
});
it("orders top organization choices by the hanmac family policy", () => {
const familyRoot = tenantNode(
"family",
"COMPANY_GROUP",
"한맥가족",
"hanmac-family",
[
tenantNode("saman", "COMPANY", "삼안", "saman"),
tenantNode("baron", "COMPANY_GROUP", "바론그룹", "baron-group"),
tenantNode("hanmac", "COMPANY", "한맥기술", "hanmac"),
tenantNode("gpdtdc", "ORGANIZATION", "총괄기획&기술개발센터", "gpdtdc"),
],
);
expect(
buildOrgSelectionOptions(familyRoot).map((option) => option.label),
).toEqual(["총괄기획&기술개발센터", "삼안", "한맥기술", "바론그룹"]);
});
it("selects hanmac family as the default root even when public sector group is listed first", () => {
const publicSector = tenantNode(
"public-sector",
"COMPANY_GROUP",
"공공기관",
"public-sector",
);
const familyRoot = tenantNode(
"family",
"COMPANY_GROUP",
"한맥가족",
"hanmac-family",
[tenantNode("saman", "COMPANY", "삼안", "saman")],
);
expect(resolveOrgChartFamilyRoot([publicSector, familyRoot])?.id).toBe(
"family",
);
});
it("hides internal organizations by default and includes them for internal mode", () => {
const visibleParent = tenantNode(
"visible-parent",
"COMPANY",
"공개 회사",
"visible-parent",
);
const internalOrg = {
...tenantNode(
"internal-org",
"ORGANIZATION",
"내부 조직",
"internal-org",
),
parentId: "visible-parent",
config: { visibility: "internal" },
};
const internalChild = {
...tenantNode(
"internal-child",
"ORGANIZATION",
"내부 하위",
"internal-child",
),
parentId: "internal-org",
};
const privateOrg = {
...tenantNode(
"private-org",
"ORGANIZATION",
"비공개 조직",
"private-org",
),
parentId: "visible-parent",
config: { visibility: "private" },
};
const publicOrg = {
...tenantNode("public-org", "ORGANIZATION", "공개 조직", "public-org"),
parentId: "visible-parent",
};
const tenants = [
visibleParent,
internalOrg,
internalChild,
privateOrg,
publicOrg,
];
expect(
filterSystemGlobalTenants(tenants, "public").map((tenant) => tenant.id),
).toEqual(["visible-parent", "public-org"]);
expect(
filterSystemGlobalTenants(tenants, "internal").map((tenant) => tenant.id),
).toEqual([
"visible-parent",
"internal-org",
"internal-child",
"public-org",
]);
});
it("maps legacy companyCode users to matching tenant slugs", () => {
const usersMap = buildUsersMap(
[
{
...member("engineering-user"),
companyCode: "engineering",
tenantSlug: undefined,
tenant: undefined,
joinedTenants: undefined,
},
],
[tenantNode("engineering", "ORGANIZATION", "Engineering", "engineering")],
{ activeOnly: true },
);
expect(usersMap.get("engineering")?.map((user) => user.id)).toEqual([
"engineering-user",
]);
});
it("maps GPDTDC representative users to their visible leaf appointment", () => {
const gpdtdc = tenantNode("gpdtdc", "COMPANY", "GPDTDC", "gpdtdc");
const tdc = {
...tenantNode("tdc", "ORGANIZATION", "기술개발센터", "tdc"),
parentId: "gpdtdc",
};
const leaf = {
...tenantNode("tdc-leaf", "USER_GROUP", "기술개발센터 1팀", "tdc-leaf"),
parentId: "tdc",
};
const rootNode = {
...gpdtdc,
children: [{ ...tdc, children: [leaf] }],
};
const usersMap = buildUsersMap(
[
{
...member("gpdtdc-user"),
companyCode: undefined,
tenantSlug: "gpdtdc",
metadata: {
additionalAppointments: [
{
tenantSlug: "internal-planning",
isPrimary: true,
},
{
tenantSlug: "tdc-leaf",
isPrimary: false,
grade: "책임",
position: "팀장",
},
],
},
joinedTenants: undefined,
},
],
[rootNode],
{ activeOnly: true },
);
expect(usersMap.get("gpdtdc")).toBeUndefined();
expect(usersMap.get("internal-planning")).toBeUndefined();
expect(usersMap.get("tdc-leaf")?.map((user) => user.id)).toEqual([
"gpdtdc-user",
]);
});
it("does not fall back to a visible parent for hidden leaf memberships", () => {
const gpdtdc = tenantNode("gpdtdc", "COMPANY", "GPDTDC", "gpdtdc");
const internalLeaf = {
...tenantNode(
"internal-leaf",
"USER_GROUP",
"내부 구성 조직",
"internal-leaf",
),
parentId: "gpdtdc",
};
const usersMap = buildUsersMap(
[
{
...member("hidden-only-user"),
companyCode: undefined,
tenantSlug: "gpdtdc",
metadata: {
additionalAppointments: [
{
tenantSlug: "internal-leaf",
isPrimary: true,
},
],
},
joinedTenants: undefined,
},
],
[gpdtdc],
{
activeOnly: true,
membershipRootNodes: [{ ...gpdtdc, children: [internalLeaf] }],
},
);
expect(usersMap.get("gpdtdc")).toBeUndefined();
expect(usersMap.get("internal-leaf")).toBeUndefined();
});
});
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,68 @@
import { GitBranch, Network, PanelTop } from "lucide-react";
import { NavLink, Outlet, useLocation } from "react-router-dom";
const navItems = [
{ to: "/chart", label: "조직도", icon: Network },
{ to: "/picker", label: "조직 선택기", icon: GitBranch },
{ to: "/embed-preview", label: "임베딩 검증", icon: PanelTop },
];
export function OrgFrontLayout() {
const location = useLocation();
const isChartRoute =
location.pathname === "/chart" || location.pathname.startsWith("/chart/");
return (
<div
className={
isChartRoute
? "flex h-screen flex-col overflow-hidden bg-background text-foreground"
: "min-h-screen bg-background text-foreground"
}
>
<header
className="sticky top-0 z-30 shrink-0 border-b border-border bg-background/95 backdrop-blur"
data-testid="orgfront-topbar"
>
<div className="mx-auto flex max-w-7xl flex-col gap-3 px-4 py-4 md:flex-row md:items-center md:justify-between">
<div>
<p className="text-xs font-semibold uppercase tracking-[0.18em] text-muted-foreground">
Baron Orgfront
</p>
<h1 className="text-xl font-semibold">조직도 서비스</h1>
</div>
<nav className="flex flex-wrap gap-2" aria-label="주요 메뉴">
{navItems.map(({ to, label, icon: Icon }) => (
<NavLink
key={to}
to={to}
className={({ isActive }) =>
[
"inline-flex h-10 items-center gap-2 rounded-md border px-3 text-sm font-semibold transition",
isActive
? "border-primary bg-primary text-primary-foreground"
: "border-border bg-card text-muted-foreground hover:text-foreground",
].join(" ")
}
>
<Icon size={16} />
{label}
</NavLink>
))}
</nav>
</div>
</header>
<main
className={
isChartRoute
? "min-h-0 flex-1 overflow-hidden"
: "mx-auto max-w-7xl px-4 py-5"
}
data-testid="orgfront-main"
>
<Outlet />
</main>
</div>
);
}
@@ -0,0 +1,236 @@
import * as React from "react";
import { useLocation } from "react-router-dom";
import {
buildOrgPickerEmbedSrc,
type OrgPickerEmbedOptions,
type OrgPickerMode,
type OrgPickerSelectableType,
parseOrgPickerEmbedOptions,
} from "../pickerTypes";
type PickerMessage = {
type: string;
payload?: unknown;
error?: string;
};
function PickerScenarioControls({
options,
onChange,
}: {
options: OrgPickerEmbedOptions;
onChange: (options: OrgPickerEmbedOptions) => void;
}) {
return (
<div className="grid gap-3 rounded-md border border-border bg-card p-4 md:grid-cols-2 lg:grid-cols-[1fr,1fr,1fr,auto,auto,auto,auto,auto] lg:items-end">
<label className="space-y-1 text-sm font-medium">
<span className="block text-muted-foreground">선택 모드</span>
<select
className="h-10 w-full rounded-md border border-input bg-background px-3"
value={options.mode}
onChange={(event) =>
onChange({
...options,
mode: event.target.value as OrgPickerMode,
})
}
>
<option value="multiple">복수 선택</option>
<option value="single">단일 선택</option>
</select>
</label>
<label className="space-y-1 text-sm font-medium">
<span className="block text-muted-foreground">선택 대상</span>
<select
className="h-10 w-full rounded-md border border-input bg-background px-3"
value={options.select}
onChange={(event) =>
onChange({
...options,
select: event.target.value as OrgPickerSelectableType,
})
}
>
<option value="both">조직&구성원</option>
<option value="tenant">조직</option>
<option value="user">구성원</option>
</select>
</label>
<label className="space-y-1 text-sm font-medium">
<span className="block text-muted-foreground">tenant slug</span>
<input
className="h-10 w-full rounded-md border border-input bg-background px-3"
onChange={(event) =>
onChange({
...options,
tenantId: event.target.value,
})
}
placeholder="saman"
type="text"
value={options.tenantId}
/>
</label>
<label className="flex h-10 items-center gap-2 rounded-md border border-border bg-background px-3 text-sm">
<input
checked={options.includeDescendants}
disabled={options.mode === "single"}
onChange={(event) =>
onChange({
...options,
includeDescendants: event.target.checked,
})
}
type="checkbox"
/>
<span>하위 포함</span>
</label>
<label className="flex h-10 items-center gap-2 rounded-md border border-border bg-background px-3 text-sm">
<input
checked={options.showDescendantToggle}
disabled={options.mode === "single"}
onChange={(event) =>
onChange({
...options,
showDescendantToggle: event.target.checked,
})
}
type="checkbox"
/>
<span>하위 선택 스위치 표시</span>
</label>
<label className="flex h-10 items-center gap-2 rounded-md border border-border bg-background px-3 text-sm">
<input
checked={options.includeInternal}
onChange={(event) =>
onChange({
...options,
includeInternal: event.target.checked,
})
}
type="checkbox"
/>
<span>internal 표시</span>
</label>
<label className="space-y-1 text-sm font-medium">
<span className="block text-muted-foreground">임베딩 너비</span>
<input
className="h-10 w-full rounded-md border border-input bg-background px-3"
min={240}
max={1600}
onChange={(event) =>
onChange({
...options,
width: Number.parseInt(event.target.value || "400", 10),
})
}
type="number"
value={options.width}
/>
</label>
<label className="space-y-1 text-sm font-medium">
<span className="block text-muted-foreground">임베딩 높이</span>
<input
className="h-10 w-full rounded-md border border-input bg-background px-3"
min={240}
max={1600}
onChange={(event) =>
onChange({
...options,
height: Number.parseInt(event.target.value || "600", 10),
})
}
type="number"
value={options.height}
/>
</label>
</div>
);
}
export function OrgPickerEmbedPreviewPage() {
const location = useLocation();
const shareToken = new URLSearchParams(location.search).get("token");
const [options, setOptions] = React.useState<OrgPickerEmbedOptions>(() =>
parseOrgPickerEmbedOptions(location.search),
);
const [lastMessage, setLastMessage] = React.useState<PickerMessage | null>(
null,
);
const pickerSrcBase = buildOrgPickerEmbedSrc(options);
const pickerSrc = shareToken
? `${pickerSrcBase}&token=${encodeURIComponent(shareToken)}`
: pickerSrcBase;
React.useEffect(() => {
const handleMessage = (event: MessageEvent<PickerMessage>) => {
if (!event.data?.type?.startsWith("orgfront:picker:")) return;
setLastMessage(event.data);
};
window.addEventListener("message", handleMessage);
return () => window.removeEventListener("message", handleMessage);
}, []);
return (
<div className="space-y-5">
<header className="space-y-3">
<div>
<p className="text-xs font-semibold uppercase tracking-[0.18em] text-muted-foreground">
Embed Preview
</p>
<h1 className="text-2xl font-semibold">임베딩 검증</h1>
</div>
<div
className="min-h-16 w-full overflow-x-auto rounded-md border border-border bg-card px-4 py-3 font-mono text-sm leading-6 text-foreground"
data-testid="embed-preview-src"
>
{pickerSrc}
</div>
</header>
<PickerScenarioControls options={options} onChange={setOptions} />
<section className="grid gap-4 lg:grid-cols-[1fr,360px]">
<div
className="max-w-full resize overflow-auto rounded-md border border-border bg-card"
data-testid="embed-preview-frame-shell"
style={{
width: options.width,
height: options.height,
}}
>
<iframe
className="h-full w-full bg-background"
src={pickerSrc}
title="조직 선택기 임베딩 검증"
/>
</div>
<aside className="space-y-3 rounded-md border border-border bg-card p-4">
<div>
<p className="text-xs font-semibold uppercase tracking-[0.18em] text-muted-foreground">
postMessage
</p>
<h2 className="text-lg font-semibold">수신 결과</h2>
</div>
<pre
className="min-h-[280px] overflow-auto rounded-md border border-border bg-background p-3 text-xs"
data-testid="embed-preview-output"
>
{lastMessage
? JSON.stringify(lastMessage, null, 2)
: "아직 수신된 메시지가 없습니다."}
</pre>
</aside>
</section>
</div>
);
}
@@ -0,0 +1,737 @@
import { useQuery } from "@tanstack/react-query";
import { Check, ChevronDown, ChevronRight, Search, X } from "lucide-react";
import * as React from "react";
import { useLocation } from "react-router-dom";
import { Button } from "../../../components/ui/button";
import { fetchAllTenants, fetchUsers } from "../../../lib/adminApi";
import { buildOrgPickerTree, flattenDescendants } from "../pickerTree";
import {
buildOrgPickerEmbedSrc,
nodeKey,
type OrgPickerEmbedOptions,
type OrgPickerMode,
type OrgPickerResult,
type OrgPickerSelectableType,
type OrgPickerSelection,
type OrgPickerTreeNode,
parseOrgPickerEmbedOptions,
parseOrgPickerMode,
parseOrgPickerSelectableType,
} from "../pickerTypes";
function canSelectNode(
node: OrgPickerTreeNode,
select: OrgPickerSelectableType,
) {
return select === "both" || select === node.type;
}
function toSelection(node: OrgPickerTreeNode): OrgPickerSelection {
return {
type: node.type,
id: node.id,
name: node.name,
};
}
function collectSelectedNodes({
roots,
selectedKeys,
includeDescendants,
select,
}: {
roots: OrgPickerTreeNode[];
selectedKeys: Set<string>;
includeDescendants: boolean;
select: OrgPickerSelectableType;
}) {
const selected = new Map<string, OrgPickerTreeNode>();
const visit = (node: OrgPickerTreeNode) => {
const key = nodeKey(node);
if (selectedKeys.has(key) && canSelectNode(node, select)) {
selected.set(key, node);
if (includeDescendants && node.type === "tenant") {
for (const descendant of flattenDescendants(node)) {
if (canSelectNode(descendant, select)) {
selected.set(nodeKey(descendant), descendant);
}
}
}
}
for (const child of node.children) visit(child);
};
for (const root of roots) visit(root);
return Array.from(selected.values()).map(toSelection);
}
function collectCheckedKeys({
roots,
selectedKeys,
includeDescendants,
select,
}: {
roots: OrgPickerTreeNode[];
selectedKeys: Set<string>;
includeDescendants: boolean;
select: OrgPickerSelectableType;
}) {
const checkedKeys = new Set(selectedKeys);
if (!includeDescendants) return checkedKeys;
const visit = (node: OrgPickerTreeNode) => {
const key = nodeKey(node);
if (selectedKeys.has(key) && node.type === "tenant") {
for (const descendant of flattenDescendants(node)) {
if (canSelectNode(descendant, select)) {
checkedKeys.add(nodeKey(descendant));
}
}
}
for (const child of node.children) visit(child);
};
for (const root of roots) visit(root);
return checkedKeys;
}
function postPickerMessage(message: unknown) {
window.parent.postMessage(message, "*");
}
function collectSearchValues(value: unknown, depth = 0): string[] {
if (value == null || depth > 4) return [];
if (
typeof value === "string" ||
typeof value === "number" ||
typeof value === "boolean"
) {
return [String(value)];
}
if (Array.isArray(value)) {
return value.flatMap((item) => collectSearchValues(item, depth + 1));
}
if (typeof value === "object") {
return Object.entries(value as Record<string, unknown>).flatMap(
([key, item]) => [key, ...collectSearchValues(item, depth + 1)],
);
}
return [];
}
function getNodeSearchValues(node: OrgPickerTreeNode) {
const tenantSearchValues = node.tenant
? collectSearchValues({
id: node.tenant.id,
type: node.tenant.type,
name: node.tenant.name,
slug: node.tenant.slug,
description: node.tenant.description,
status: node.tenant.status,
domains: node.tenant.domains,
parentId: node.tenant.parentId,
config: node.tenant.config,
memberCount: node.tenant.memberCount,
createdAt: node.tenant.createdAt,
updatedAt: node.tenant.updatedAt,
})
: [];
return [
node.type,
node.id,
node.name,
node.parentId ?? "",
...tenantSearchValues,
...collectSearchValues(node.user),
].map((value) => value.toLowerCase());
}
function nodeMatchesSearch(node: OrgPickerTreeNode, query: string) {
return getNodeSearchValues(node).some((value) => value.includes(query));
}
function filterPickerTree(
roots: OrgPickerTreeNode[],
rawQuery: string,
): OrgPickerTreeNode[] {
const query = rawQuery.trim().toLowerCase();
if (!query) return roots;
const filterNode = (node: OrgPickerTreeNode): OrgPickerTreeNode | null => {
const filteredChildren = node.children
.map(filterNode)
.filter((child): child is OrgPickerTreeNode => Boolean(child));
if (nodeMatchesSearch(node, query) || filteredChildren.length > 0) {
return {
...node,
children: filteredChildren,
};
}
return null;
};
return roots
.map(filterNode)
.filter((node): node is OrgPickerTreeNode => Boolean(node));
}
function OrgPickerTree({
roots,
mode,
select,
selectedKeys,
onSingleSelect,
onToggle,
}: {
roots: OrgPickerTreeNode[];
mode: OrgPickerMode;
select: OrgPickerSelectableType;
selectedKeys: Set<string>;
onSingleSelect: (node: OrgPickerTreeNode) => void;
onToggle: (node: OrgPickerTreeNode, checked: boolean) => void;
}) {
return (
<div className="space-y-1" data-testid="org-picker-tree">
{roots.map((node) => (
<OrgPickerTreeItem
key={nodeKey(node)}
mode={mode}
node={node}
onSingleSelect={onSingleSelect}
onToggle={onToggle}
select={select}
selectedKeys={selectedKeys}
/>
))}
</div>
);
}
function OrgPickerTreeItem({
node,
mode,
select,
selectedKeys,
onSingleSelect,
onToggle,
depth = 0,
}: {
node: OrgPickerTreeNode;
mode: OrgPickerMode;
select: OrgPickerSelectableType;
selectedKeys: Set<string>;
onSingleSelect: (node: OrgPickerTreeNode) => void;
onToggle: (node: OrgPickerTreeNode, checked: boolean) => void;
depth?: number;
}) {
const [isOpen, setIsOpen] = React.useState(true);
const selectable = canSelectNode(node, select);
const hasChildren = node.children.length > 0;
const key = nodeKey(node);
const checked = selectedKeys.has(key);
const label = `${node.name} 선택`;
const email = node.type === "user" ? node.user?.email : undefined;
const nameTestId =
node.type === "tenant"
? "org-picker-node-name-tenant"
: "org-picker-node-name-user";
const content = (
<span className="flex min-w-0 flex-col">
<span
className={`truncate font-semibold leading-5 ${
node.type === "tenant" ? "text-[#0a2114]" : ""
}`}
data-testid={nameTestId}
>
{node.name}
</span>
{email ? (
<span className="truncate text-xs leading-5 text-muted-foreground">
{email}
</span>
) : null}
</span>
);
return (
<div className="relative">
<div
className={`group flex min-h-7 items-center gap-1.5 rounded-sm py-0.5 pr-1.5 transition ${
mode === "single" && checked
? "bg-primary/15 text-foreground ring-2 ring-primary/60 shadow-sm"
: "hover:bg-secondary/50"
} ${depth > 0 ? "pl-4" : "pl-1"}`}
data-selected={mode === "single" && checked ? "true" : undefined}
>
{hasChildren ? (
<button
type="button"
className="grid h-6 w-6 shrink-0 place-items-center rounded-sm text-muted-foreground transition hover:bg-secondary"
onClick={() => setIsOpen((current) => !current)}
aria-label={`${node.name} ${isOpen ? "접기" : "펼치기"}`}
>
{isOpen ? <ChevronDown size={16} /> : <ChevronRight size={16} />}
</button>
) : (
<span className="h-6 w-6 shrink-0" aria-hidden="true" />
)}
{mode === "multiple" && selectable ? (
<input
aria-label={label}
checked={checked}
className="h-3.5 w-3.5 rounded border-border"
onChange={(event) => onToggle(node, event.target.checked)}
type="checkbox"
/>
) : null}
{mode === "single" && selectable ? (
<button
type="button"
aria-pressed={checked}
className={`min-w-0 flex-1 rounded-sm px-1 text-left outline-none transition focus-visible:ring-2 focus-visible:ring-ring ${
checked ? "text-primary" : ""
}`}
data-selected={checked ? "true" : undefined}
onClick={() => onSingleSelect(node)}
>
{content}
</button>
) : (
<div className="min-w-0 flex-1">{content}</div>
)}
</div>
{isOpen && hasChildren ? (
<div className="ml-4">
{node.children.map((child) => (
<OrgPickerTreeItem
depth={depth + 1}
key={nodeKey(child)}
mode={mode}
node={child}
onSingleSelect={onSingleSelect}
onToggle={onToggle}
select={select}
selectedKeys={selectedKeys}
/>
))}
</div>
) : null}
</div>
);
}
export function OrgPickerEmbedPage() {
const location = useLocation();
const searchParams = new URLSearchParams(location.search);
const mode = parseOrgPickerMode(searchParams.get("mode"));
const select = parseOrgPickerSelectableType(searchParams.get("select"));
const rootTenantId = searchParams.get("rootTenantId") || undefined;
const includeInternal = searchParams.get("includeInternal") === "true";
const tenantId =
searchParams.get("tenantSlug") ||
searchParams.get("tenantId") ||
searchParams.get("companyTenantId") ||
undefined;
const [includeDescendants, setIncludeDescendants] = React.useState(
searchParams.get("includeDescendants") !== "false",
);
const showDescendantToggle =
searchParams.get("showDescendantToggle") !== "false";
const [searchQuery, setSearchQuery] = React.useState("");
const [selectedKeys, setSelectedKeys] = React.useState<Set<string>>(
() => new Set(),
);
const tenantsQuery = useQuery({
queryKey: ["org-picker-tenants"],
queryFn: () => fetchAllTenants(),
});
const usersQuery = useQuery({
queryKey: ["org-picker-users"],
queryFn: () => fetchUsers(5000, 0),
});
React.useEffect(() => {
postPickerMessage({ type: "orgfront:picker:ready" });
}, []);
const tree = React.useMemo(() => {
return buildOrgPickerTree({
includeInternal,
tenants: tenantsQuery.data?.items ?? [],
users: select === "tenant" ? [] : (usersQuery.data?.items ?? []),
rootTenantId,
tenantId,
});
}, [
includeInternal,
rootTenantId,
select,
tenantId,
tenantsQuery.data,
usersQuery.data,
]);
const selectedItems = React.useMemo(
() =>
collectSelectedNodes({
roots: tree.roots,
selectedKeys,
includeDescendants: mode === "multiple" && includeDescendants,
select,
}),
[includeDescendants, mode, select, selectedKeys, tree.roots],
);
const checkedKeys = React.useMemo(
() =>
collectCheckedKeys({
roots: tree.roots,
selectedKeys,
includeDescendants: mode === "multiple" && includeDescendants,
select,
}),
[includeDescendants, mode, select, selectedKeys, tree.roots],
);
const filteredRoots = React.useMemo(
() => filterPickerTree(tree.roots, searchQuery),
[searchQuery, tree.roots],
);
const handleSingleSelect = (node: OrgPickerTreeNode) => {
setSelectedKeys(new Set([nodeKey(node)]));
};
const handleToggle = (node: OrgPickerTreeNode, checked: boolean) => {
setSelectedKeys((current) => {
const next = new Set(current);
const key = nodeKey(node);
if (checked) next.add(key);
else next.delete(key);
return next;
});
};
const confirmSelection = () => {
const payload: OrgPickerResult = {
mode,
selections: selectedItems,
};
postPickerMessage({ type: "orgfront:picker:confirm", payload });
};
const cancelSelection = () => {
postPickerMessage({ type: "orgfront:picker:cancel" });
};
const isLoading = tenantsQuery.isLoading || usersQuery.isLoading;
const isError = tenantsQuery.isError || usersQuery.isError;
React.useEffect(() => {
const htmlOverflow = document.documentElement.style.overflow;
const bodyOverflow = document.body.style.overflow;
document.documentElement.style.overflow = "hidden";
document.body.style.overflow = "hidden";
return () => {
document.documentElement.style.overflow = htmlOverflow;
document.body.style.overflow = bodyOverflow;
};
}, []);
React.useEffect(() => {
if (!isError) return;
postPickerMessage({
type: "orgfront:picker:error",
error: "org_picker_load_failed",
});
}, [isError]);
if (isLoading) {
return (
<div className="grid min-h-screen place-items-center bg-background p-6 text-muted-foreground">
조직 선택기를 불러오는 중...
</div>
);
}
if (isError) {
return (
<div className="grid min-h-screen place-items-center bg-background p-6 text-destructive">
조직 선택기를 불러올 수 없습니다.
</div>
);
}
return (
<div className="flex h-screen flex-col overflow-hidden bg-background text-foreground">
<main className="flex min-h-0 flex-1 flex-col">
<div
className="shrink-0 border-b border-border bg-background p-2"
data-testid="org-picker-search-section"
>
<div className="grid grid-cols-[minmax(0,1fr),auto] items-end gap-2">
<div>
<label className="sr-only" htmlFor="org-picker-search">
조직/구성원 검색
</label>
<div className="relative">
<Search
aria-hidden="true"
className="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"
size={16}
/>
<input
id="org-picker-search"
className="h-9 w-full rounded-md border border-input bg-background pl-9 pr-3 text-sm"
onChange={(event) => setSearchQuery(event.target.value)}
placeholder="ID, 이름, 이메일, 메타데이터"
type="search"
value={searchQuery}
/>
</div>
</div>
{mode === "multiple" && showDescendantToggle ? (
<label
className="inline-flex h-9 items-center gap-2 whitespace-nowrap text-sm"
data-testid="org-picker-descendant-toggle"
>
<input
checked={includeDescendants}
className="h-3.5 w-3.5"
onChange={(event) =>
setIncludeDescendants(event.target.checked)
}
type="checkbox"
/>
<span>하위 선택</span>
</label>
) : null}
</div>
</div>
<div
className="min-h-0 flex-1 overflow-y-auto p-3"
data-testid="org-picker-tree-scroll"
>
{filteredRoots.length > 0 ? (
<OrgPickerTree
mode={mode}
onSingleSelect={handleSingleSelect}
onToggle={handleToggle}
roots={filteredRoots}
select={select}
selectedKeys={checkedKeys}
/>
) : (
<div className="grid min-h-40 place-items-center rounded-md border border-dashed border-border bg-background p-6 text-center text-sm text-muted-foreground">
검색 결과가 없습니다.
</div>
)}
</div>
</main>
<footer className="flex shrink-0 items-center justify-between gap-3 border-t border-border bg-background px-3 py-2">
<div className="min-w-0 text-sm text-muted-foreground">
{selectedItems.length > 0
? `${selectedItems.length}개 항목 선택됨`
: "선택된 항목이 없습니다."}
</div>
<div className="flex items-center gap-2">
<Button onClick={cancelSelection} type="button" variant="outline">
<X size={16} />
취소
</Button>
<Button
disabled={selectedItems.length === 0}
onClick={confirmSelection}
type="button"
>
<Check size={16} />
선택 완료
</Button>
</div>
</footer>
</div>
);
}
export function OrgPickerPage() {
const location = useLocation();
const shareToken = new URLSearchParams(location.search).get("token");
const [options, setOptions] = React.useState<OrgPickerEmbedOptions>(() =>
parseOrgPickerEmbedOptions(location.search),
);
const pickerSrcBase = buildOrgPickerEmbedSrc(options);
const pickerSrc = shareToken
? `${pickerSrcBase}&token=${encodeURIComponent(shareToken)}`
: pickerSrcBase;
return (
<div className="space-y-4">
<header className="flex flex-col gap-2 md:flex-row md:items-end md:justify-between">
<div>
<p className="text-xs font-semibold uppercase tracking-[0.18em] text-muted-foreground">
Picker Workbench
</p>
<h1 className="text-2xl font-semibold">조직 선택기</h1>
</div>
<div className="rounded-md border border-border bg-card px-3 py-2 text-sm text-muted-foreground">
{pickerSrc}
</div>
</header>
<section className="grid gap-3 rounded-md border border-border bg-card p-4 md:grid-cols-2 lg:grid-cols-[1fr,1fr,1fr,auto,auto,auto,auto,auto] lg:items-end">
<label className="space-y-1 text-sm font-medium">
<span className="block text-muted-foreground">선택 모드</span>
<select
className="h-10 w-full rounded-md border border-input bg-background px-3"
value={options.mode}
onChange={(event) =>
setOptions((current) => ({
...current,
mode: event.target.value as OrgPickerMode,
}))
}
>
<option value="multiple">복수 선택</option>
<option value="single">단일 선택</option>
</select>
</label>
<label className="space-y-1 text-sm font-medium">
<span className="block text-muted-foreground">선택 대상</span>
<select
className="h-10 w-full rounded-md border border-input bg-background px-3"
value={options.select}
onChange={(event) =>
setOptions((current) => ({
...current,
select: event.target.value as OrgPickerSelectableType,
}))
}
>
<option value="both">조직&구성원</option>
<option value="tenant">조직</option>
<option value="user">구성원</option>
</select>
</label>
<label className="space-y-1 text-sm font-medium">
<span className="block text-muted-foreground">tenant slug</span>
<input
className="h-10 w-full rounded-md border border-input bg-background px-3"
onChange={(event) =>
setOptions((current) => ({
...current,
tenantId: event.target.value,
}))
}
placeholder="saman"
type="text"
value={options.tenantId}
/>
</label>
<label className="flex h-10 items-center gap-2 rounded-md border border-border bg-background px-3 text-sm">
<input
checked={options.includeDescendants}
disabled={options.mode === "single"}
onChange={(event) =>
setOptions((current) => ({
...current,
includeDescendants: event.target.checked,
}))
}
type="checkbox"
/>
<span>하위 포함</span>
</label>
<label className="flex h-10 items-center gap-2 rounded-md border border-border bg-background px-3 text-sm">
<input
checked={options.showDescendantToggle}
disabled={options.mode === "single"}
onChange={(event) =>
setOptions((current) => ({
...current,
showDescendantToggle: event.target.checked,
}))
}
type="checkbox"
/>
<span>하위 선택 스위치 표시</span>
</label>
<label className="flex h-10 items-center gap-2 rounded-md border border-border bg-background px-3 text-sm">
<input
checked={options.includeInternal}
onChange={(event) =>
setOptions((current) => ({
...current,
includeInternal: event.target.checked,
}))
}
type="checkbox"
/>
<span>internal 표시</span>
</label>
<label className="space-y-1 text-sm font-medium">
<span className="block text-muted-foreground">임베딩 너비</span>
<input
className="h-10 w-full rounded-md border border-input bg-background px-3"
max={1600}
min={240}
onChange={(event) =>
setOptions((current) => ({
...current,
width: Number.parseInt(event.target.value || "400", 10),
}))
}
type="number"
value={options.width}
/>
</label>
<label className="space-y-1 text-sm font-medium">
<span className="block text-muted-foreground">임베딩 높이</span>
<input
className="h-10 w-full rounded-md border border-input bg-background px-3"
max={1600}
min={240}
onChange={(event) =>
setOptions((current) => ({
...current,
height: Number.parseInt(event.target.value || "600", 10),
}))
}
type="number"
value={options.height}
/>
</label>
</section>
<div
className="max-w-full resize overflow-auto rounded-md border border-border bg-card"
style={{
width: options.width,
height: options.height,
}}
>
<iframe
className="h-full w-full bg-background"
src={pickerSrc}
title="조직 선택기 테스트"
/>
</div>
</div>
);
}
@@ -0,0 +1,45 @@
import type { TenantSummary } from "../../lib/adminApi";
export function getTenantVisibility(tenant: Pick<TenantSummary, "config">) {
const raw = String(tenant.config?.visibility ?? "public").toLowerCase();
if (raw === "internal" || raw === "private") return raw;
return "public";
}
export function filterTenantsByVisibility(
tenants: TenantSummary[],
mode: "internal" | "public",
) {
const excludedIds = new Set<string>();
for (const tenant of tenants) {
const visibility = getTenantVisibility(tenant);
if (
visibility === "private" ||
(mode === "public" && visibility === "internal")
) {
excludedIds.add(tenant.id);
}
}
let changed = true;
while (changed) {
changed = false;
for (const tenant of tenants) {
if (
tenant.parentId &&
excludedIds.has(tenant.parentId) &&
!excludedIds.has(tenant.id)
) {
excludedIds.add(tenant.id);
changed = true;
}
}
}
return tenants.filter((tenant) => !excludedIds.has(tenant.id));
}
export function getOrgUnitType(config: Record<string, unknown> | undefined) {
const value = config?.orgUnitType;
return typeof value === "string" ? value.trim() : "";
}
@@ -0,0 +1,167 @@
import { describe, expect, it } from "vitest";
import type { UserSummary } from "../../lib/adminApi";
import { getOrgChartUserDisplayName, getUserOrgProfile } from "./userDisplay";
function user(overrides: Partial<UserSummary>): UserSummary {
return {
id: "user-1",
email: "user@example.com",
name: "홍길동",
role: "user",
status: "active",
createdAt: "",
updatedAt: "",
...overrides,
};
}
describe("getOrgChartUserDisplayName", () => {
it("renders name with grade and without job details", () => {
expect(
getOrgChartUserDisplayName(
user({
grade: "수석",
position: "팀장",
jobTitle: "구조",
}),
),
).toBe("홍길동 수석");
});
it("uses tenant appointment grade before the user grade", () => {
expect(
getOrgChartUserDisplayName(
user({
grade: "책임",
metadata: {
additionalAppointments: [
{
tenantSlug: "hanmac",
grade: "수석",
position: "센터장",
},
],
},
}),
{ id: "tenant-1", slug: "hanmac" },
),
).toBe("홍길동 수석");
});
it("uses short grade aliases in the display name", () => {
expect(
getOrgChartUserDisplayName(
user({
grade: "책임연구원",
jobTitle: "구조",
}),
),
).toBe("홍길동 책임");
});
it("does not add leader text to the display name", () => {
expect(
getOrgChartUserDisplayName(
user({
grade: "책임",
metadata: {
additionalAppointments: [
{
tenantSlug: "hanmac",
isOwner: true,
grade: "수석",
position: "센터장",
},
],
},
}),
{ id: "tenant-1", slug: "hanmac" },
),
).toBe("홍길동 수석");
});
it("does not leak an owner appointment flag into another tenant display", () => {
expect(
getOrgChartUserDisplayName(
user({
grade: "책임",
position: "팀원",
metadata: {
additionalAppointments: [
{
tenantSlug: "hanmac",
isOwner: true,
grade: "수석",
position: "센터장",
},
],
},
}),
{ id: "tenant-2", slug: "baron" },
),
).toBe("홍길동 책임");
});
});
describe("getUserOrgProfile", () => {
it("marks owner, manager, and admin flags as highlighted profiles", () => {
expect(
getUserOrgProfile(
user({
metadata: {
additionalAppointments: [
{
tenantSlug: "owner",
isOwner: true,
},
{
tenantSlug: "manager",
isManager: true,
},
{
tenantSlug: "admin",
isAdmin: true,
},
],
},
}),
{ id: "tenant-1", slug: "owner" },
).isHighlighted,
).toBe(true);
expect(
getUserOrgProfile(
user({
metadata: {
additionalAppointments: [{ tenantSlug: "leader", isLeader: true }],
},
}),
{ id: "tenant-2", slug: "leader" },
).isHighlighted,
).toBe(false);
expect(
getUserOrgProfile(
user({
metadata: {
additionalAppointments: [
{ tenantSlug: "manager", isManager: true },
],
},
}),
{ id: "tenant-2", slug: "manager" },
).isHighlighted,
).toBe(true);
expect(
getUserOrgProfile(
user({
metadata: {
additionalAppointments: [{ tenantSlug: "admin", isAdmin: true }],
},
}),
{ id: "tenant-3", slug: "admin" },
).isHighlighted,
).toBe(true);
expect(getUserOrgProfile(user({ grade: "책임" })).isHighlighted).toBe(
false,
);
});
});
@@ -0,0 +1,77 @@
import type { TenantSummary, UserSummary } from "../../lib/adminApi";
import { getOrgRankDisplayName } from "./rankPriority";
type UserAppointment = {
tenantId?: string;
tenantSlug?: string;
isAdmin?: boolean;
isManager?: boolean;
isOwner?: boolean;
grade?: string;
jobTitle?: string;
position?: string;
};
type TenantIdentity = Pick<TenantSummary, "id" | "slug">;
function normalizeText(value: unknown) {
return typeof value === "string" ? value.trim() : "";
}
function getUserAppointments(user: UserSummary): UserAppointment[] {
const rawAppointments = user.metadata?.additionalAppointments;
if (!Array.isArray(rawAppointments)) return [];
return rawAppointments
.filter(
(item): item is Record<string, unknown> =>
typeof item === "object" && item !== null,
)
.map((item) => ({
tenantId: normalizeText(item.tenantId),
tenantSlug: normalizeText(item.tenantSlug),
isAdmin: item.isAdmin === true,
isManager: item.isManager === true,
isOwner: item.isOwner === true,
grade: normalizeText(item.grade),
jobTitle: normalizeText(item.jobTitle),
position: normalizeText(item.position),
}));
}
export function getUserOrgProfile(user: UserSummary, tenant?: TenantIdentity) {
const appointment = getUserAppointments(user).find((item) => {
if (tenant?.id && item.tenantId === tenant.id) return true;
if (
tenant?.slug &&
item.tenantSlug &&
item.tenantSlug.toLowerCase() === tenant.slug.toLowerCase()
) {
return true;
}
return false;
});
return {
grade: appointment?.grade || normalizeText(user.grade),
isHighlighted:
appointment?.isAdmin === true ||
appointment?.isManager === true ||
appointment?.isOwner === true,
jobTitle: appointment?.jobTitle || normalizeText(user.jobTitle),
position: appointment?.position || normalizeText(user.position),
};
}
export function getOrgChartUserDisplayName(
user: UserSummary,
tenant?: TenantIdentity,
) {
const { grade } = getUserOrgProfile(user, tenant);
const baseName = user.name.trim();
const displayGrade = getOrgRankDisplayName(grade);
let displayName = baseName;
if (displayGrade) displayName = `${baseName} ${displayGrade}`;
return displayName;
}