inogen/app/contexts/deployment-profile-context.tsx

162 lines
6.2 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import React, { createContext, useContext, useEffect, useMemo, useState } from "react";
import { Navigate, useLocation } from "react-router";
import { API_BASE_URL } from "~/lib/api";
import { resolveDeploymentAsset } from "~/lib/deployment-assets";
export interface DeploymentUnit {
dataKey: string;
title: string;
imageAssetKey: string;
imageColumn: number;
imageRow: number;
infoColumn: number;
infoRow: number;
metrics: string[];
}
export interface DeploymentProfile {
isConfigured: boolean;
profileVersion: string;
company: { displayName: string; shortName: string; englishName?: string };
branding: {
dashboardLoginLogoAssetKey: string;
adminLoginLogoAssetKey: string;
ecosystemCenterLogoSource: "dashboard" | "admin";
applicationTitle: string;
adminTitle: string;
loginTitle: string;
loginSubtitle: string;
loginDescription?: string;
footerText?: string;
};
theme: { primaryColor: string; secondaryColor: string; accentColor: string };
dashboard: {
layout: string;
units: DeploymentUnit[];
visibleMetrics: string[];
showRevenueSeries: boolean;
costSeriesLabel: string;
ecosystemCenter: {
label: string;
imageAssetKey: string;
width: number;
height: number;
};
};
features: {
showAdminLink: boolean;
reportingModules: string[];
adminModules: string[];
};
}
interface DeploymentContextValue {
profile: DeploymentProfile;
assetUrl: (key?: string) => string;
}
const safeDefault: DeploymentProfile = {
isConfigured: false,
profileVersion: "unavailable",
company: { displayName: "سازمان", shortName: "سازمان" },
branding: {
dashboardLoginLogoAssetKey: "",
adminLoginLogoAssetKey: "",
ecosystemCenterLogoSource: "dashboard",
applicationTitle: "سامانه مدیریت فناوری و نوآوری",
adminTitle: "پنل راهبر",
loginTitle: "سامانه مدیریت فناوری و نوآوری",
loginSubtitle: "ورود",
},
theme: { primaryColor: "#3AEA83", secondaryColor: "#69C8EA", accentColor: "#F76276" },
dashboard: {
layout: "unit-grid",
units: [],
visibleMetrics: ["incomeIncrease", "innovationCostReduction", "productionCapacityIncrease"],
showRevenueSeries: true,
costSeriesLabel: "کاهش هزینه",
ecosystemCenter: { label: "سازمان", imageAssetKey: "", width: 180, height: 80 },
},
features: { showAdminLink: false, reportingModules: [], adminModules: [] },
};
const DeploymentContext = createContext<DeploymentContextValue | null>(null);
export function DeploymentProfileProvider({ children }: { children: React.ReactNode }) {
const location = useLocation();
const [profile, setProfile] = useState<DeploymentProfile>(safeDefault);
const [state, setState] = useState<"loading" | "ready" | "error">("loading");
useEffect(() => {
const controller = new AbortController();
fetch(`${API_BASE_URL}/deployment/profile`, {
credentials: "include",
headers: { Accept: "application/json" },
signal: controller.signal,
})
.then(async (response) => {
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return response.json() as Promise<DeploymentProfile>;
})
.then((value) => {
setProfile(value);
setState("ready");
})
.catch((error) => {
if (error instanceof DOMException && error.name === "AbortError") return;
console.error("Deployment profile could not be loaded.");
setState("error");
});
return () => controller.abort();
}, []);
const assetUrl = useMemo(
() => (key?: string) => resolveDeploymentAsset(API_BASE_URL, key),
[],
);
useEffect(() => {
if (state !== "ready") return;
document.documentElement.style.setProperty("--deployment-primary", profile.theme.primaryColor);
document.documentElement.style.setProperty("--deployment-secondary", profile.theme.secondaryColor);
document.documentElement.style.setProperty("--deployment-accent", profile.theme.accentColor);
document.documentElement.style.setProperty("--color-green", profile.theme.primaryColor);
document.documentElement.style.setProperty("--color-pr-green", profile.theme.primaryColor);
document.documentElement.style.setProperty("--primary", profile.theme.primaryColor);
document.documentElement.style.setProperty("--color-blue", profile.theme.secondaryColor);
document.documentElement.style.setProperty("--color-pr-blue", profile.theme.secondaryColor);
document.documentElement.style.setProperty("--color-red", profile.theme.accentColor);
document.documentElement.style.setProperty("--color-pr-red", profile.theme.accentColor);
document.documentElement.dataset.deploymentProfile = profile.profileVersion;
document.title = `${profile.branding.applicationTitle} - ${profile.company.shortName}`;
{
let link = document.querySelector<HTMLLinkElement>('link[data-deployment-favicon="true"]');
if (!link) {
link = document.createElement("link");
link.rel = "icon";
link.dataset.deploymentFavicon = "true";
document.head.appendChild(link);
}
link.href = "/product-logo.svg";
}
}, [assetUrl, profile, state]);
if (state === "loading") {
return <div className="min-h-screen grid place-items-center bg-slate-950 text-white">در حال دریافت تنظیمات استقرار…</div>;
}
if (state === "error") {
return <div className="min-h-screen grid place-items-center bg-slate-950 text-white text-center p-6">
<div><h1 className="text-lg font-bold mb-2">تنظیمات استقرار در دسترس نیست</h1><p>اتصال API را بررسی و صفحه را دوباره بارگذاری کنید.</p></div>
</div>;
}
if (!profile.isConfigured && !location.pathname.startsWith("/admin"))
return <Navigate to="/admin/deployment-settings" replace/>;
return <DeploymentContext.Provider value={{ profile, assetUrl }}>{children}</DeploymentContext.Provider>;
}
export function useDeploymentProfile() {
const value = useContext(DeploymentContext);
if (!value) throw new Error("useDeploymentProfile must be used inside DeploymentProfileProvider.");
return value;
}