feat: add favicon, logo and Update the platform name (only available to the superuser) and company names
This commit is contained in:
+2
-1
@@ -78,7 +78,8 @@
|
|||||||
- [x] **Super Admin y Org por Defecto**: Gestión global de todos los inquilinos
|
- [x] **Super Admin y Org por Defecto**: Gestión global de todos los inquilinos
|
||||||
- [x] **Visibilidad Global de Cursos**: Cursos de sistema disponibles para todas las organizaciones
|
- [x] **Visibilidad Global de Cursos**: Cursos de sistema disponibles para todas las organizaciones
|
||||||
- [x] **Personalización de Marca (Branding)**: Identidad propia por organización (Completado)
|
- [x] **Personalización de Marca (Branding)**: Identidad propia por organización (Completado)
|
||||||
- [x] Carga y optimización de logotipos
|
- [x] Carga y optimización de logotipos y favicons customizados
|
||||||
|
- [x] Nombre de plataforma personalizado (White-label)
|
||||||
- [x] Esquemas de colores personalizados (Primario/Secundario)
|
- [x] Esquemas de colores personalizados (Primario/Secundario)
|
||||||
- [x] Adaptación dinámica del portal de Experience
|
- [x] Adaptación dinámica del portal de Experience
|
||||||
- [x] Previsualización en vivo del branding en Studio
|
- [x] Previsualización en vivo del branding en Studio
|
||||||
|
|||||||
@@ -0,0 +1,10 @@
|
|||||||
|
-- Migration: Add Platform Name and Favicon to Organizations
|
||||||
|
-- Adds fields for white-labeling the platform name and favicon
|
||||||
|
|
||||||
|
ALTER TABLE organizations
|
||||||
|
ADD COLUMN IF NOT EXISTS platform_name TEXT,
|
||||||
|
ADD COLUMN IF NOT EXISTS favicon_url TEXT;
|
||||||
|
|
||||||
|
-- Add comments for documentation
|
||||||
|
COMMENT ON COLUMN organizations.platform_name IS 'Custom name for the platform (e.g., "My Company Academy")';
|
||||||
|
COMMENT ON COLUMN organizations.favicon_url IS 'URL path to organization favicon (stored in /uploads/org-favicons/)';
|
||||||
@@ -17,11 +17,14 @@ use super::handlers::log_action;
|
|||||||
pub struct BrandingPayload {
|
pub struct BrandingPayload {
|
||||||
pub primary_color: Option<String>,
|
pub primary_color: Option<String>,
|
||||||
pub secondary_color: Option<String>,
|
pub secondary_color: Option<String>,
|
||||||
|
pub platform_name: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Serialize)]
|
#[derive(Serialize)]
|
||||||
pub struct BrandingResponse {
|
pub struct BrandingResponse {
|
||||||
pub logo_url: Option<String>,
|
pub logo_url: Option<String>,
|
||||||
|
pub favicon_url: Option<String>,
|
||||||
|
pub platform_name: Option<String>,
|
||||||
pub primary_color: String,
|
pub primary_color: String,
|
||||||
pub secondary_color: String,
|
pub secondary_color: String,
|
||||||
}
|
}
|
||||||
@@ -138,6 +141,118 @@ pub async fn upload_organization_logo(
|
|||||||
Err((StatusCode::BAD_REQUEST, "No file provided".into()))
|
Err((StatusCode::BAD_REQUEST, "No file provided".into()))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Upload organization favicon
|
||||||
|
pub async fn upload_organization_favicon(
|
||||||
|
claims: common::auth::Claims,
|
||||||
|
State(pool): State<PgPool>,
|
||||||
|
Path(org_id): Path<Uuid>,
|
||||||
|
mut multipart: axum::extract::Multipart,
|
||||||
|
) -> Result<Json<serde_json::Value>, (StatusCode, String)> {
|
||||||
|
// Only admins can upload favicons
|
||||||
|
if claims.role != "admin" {
|
||||||
|
return Err((StatusCode::FORBIDDEN, "Admin access required".into()));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify organization exists and user has access
|
||||||
|
let _ = sqlx::query_as::<_, Organization>("SELECT * FROM organizations WHERE id = $1")
|
||||||
|
.bind(org_id)
|
||||||
|
.fetch_one(&pool)
|
||||||
|
.await
|
||||||
|
.map_err(|_| (StatusCode::NOT_FOUND, "Organization not found".into()))?;
|
||||||
|
|
||||||
|
// Process multipart form
|
||||||
|
while let Some(field) = multipart
|
||||||
|
.next_field()
|
||||||
|
.await
|
||||||
|
.map_err(|e| (StatusCode::BAD_REQUEST, format!("Multipart error: {}", e)))?
|
||||||
|
{
|
||||||
|
let name = field.name().unwrap_or("").to_string();
|
||||||
|
|
||||||
|
if name == "file" {
|
||||||
|
let filename = field
|
||||||
|
.file_name()
|
||||||
|
.ok_or((StatusCode::BAD_REQUEST, "Missing filename".into()))?
|
||||||
|
.to_string();
|
||||||
|
|
||||||
|
// Validate file extension
|
||||||
|
let ext = filename.split('.').last().unwrap_or("");
|
||||||
|
if !["png", "jpg", "jpeg", "svg", "ico"].contains(&ext.to_lowercase().as_str()) {
|
||||||
|
return Err((
|
||||||
|
StatusCode::BAD_REQUEST,
|
||||||
|
"Invalid file type. Only PNG, JPG, SVG, and ICO allowed".into(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
let data = field.bytes().await.map_err(|e| {
|
||||||
|
(
|
||||||
|
StatusCode::INTERNAL_SERVER_ERROR,
|
||||||
|
format!("Failed to read file: {}", e),
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
|
||||||
|
// Validate file size (max 512KB for favicons seems reasonable, but sticking to 1MB to be safe)
|
||||||
|
if data.len() > 1024 * 1024 {
|
||||||
|
return Err((
|
||||||
|
StatusCode::BAD_REQUEST,
|
||||||
|
"File too large. Maximum 1MB allowed".into(),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create uploads directory if it doesn't exist
|
||||||
|
std::fs::create_dir_all("uploads/org-favicons").map_err(|e| {
|
||||||
|
(
|
||||||
|
StatusCode::INTERNAL_SERVER_ERROR,
|
||||||
|
format!("Failed to create directory: {}", e),
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
|
||||||
|
// Generate unique filename
|
||||||
|
let unique_filename = format!("{}_{}.{}", org_id, uuid::Uuid::new_v4(), ext);
|
||||||
|
let filepath = format!("uploads/org-favicons/{}", unique_filename);
|
||||||
|
|
||||||
|
// Save file
|
||||||
|
std::fs::write(&filepath, &data).map_err(|e| {
|
||||||
|
(
|
||||||
|
StatusCode::INTERNAL_SERVER_ERROR,
|
||||||
|
format!("Failed to save file: {}", e),
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
|
||||||
|
// Update organization in database
|
||||||
|
let favicon_url = format!("/{}", filepath);
|
||||||
|
sqlx::query("UPDATE organizations SET favicon_url = $1 WHERE id = $2")
|
||||||
|
.bind(&favicon_url)
|
||||||
|
.bind(org_id)
|
||||||
|
.execute(&pool)
|
||||||
|
.await
|
||||||
|
.map_err(|e| {
|
||||||
|
(
|
||||||
|
StatusCode::INTERNAL_SERVER_ERROR,
|
||||||
|
format!("Database error: {}", e),
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
|
||||||
|
log_action(
|
||||||
|
&pool,
|
||||||
|
claims.org,
|
||||||
|
claims.sub,
|
||||||
|
"UPDATE_FAVICON",
|
||||||
|
"Organization",
|
||||||
|
org_id,
|
||||||
|
json!({"favicon_url": &favicon_url}),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
|
||||||
|
return Ok(Json(json!({
|
||||||
|
"favicon_url": favicon_url,
|
||||||
|
"message": "Favicon uploaded successfully"
|
||||||
|
})));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Err((StatusCode::BAD_REQUEST, "No file provided".into()))
|
||||||
|
}
|
||||||
|
|
||||||
// Update organization branding colors
|
// Update organization branding colors
|
||||||
pub async fn update_organization_branding(
|
pub async fn update_organization_branding(
|
||||||
claims: common::auth::Claims,
|
claims: common::auth::Claims,
|
||||||
@@ -180,12 +295,14 @@ pub async fn update_organization_branding(
|
|||||||
"UPDATE organizations
|
"UPDATE organizations
|
||||||
SET primary_color = COALESCE($1, primary_color),
|
SET primary_color = COALESCE($1, primary_color),
|
||||||
secondary_color = COALESCE($2, secondary_color),
|
secondary_color = COALESCE($2, secondary_color),
|
||||||
|
platform_name = COALESCE($3, platform_name),
|
||||||
updated_at = NOW()
|
updated_at = NOW()
|
||||||
WHERE id = $3
|
WHERE id = $4
|
||||||
RETURNING *",
|
RETURNING *",
|
||||||
)
|
)
|
||||||
.bind(&payload.primary_color)
|
.bind(&payload.primary_color)
|
||||||
.bind(&payload.secondary_color)
|
.bind(&payload.secondary_color)
|
||||||
|
.bind(&payload.platform_name)
|
||||||
.bind(org_id)
|
.bind(org_id)
|
||||||
.fetch_one(&pool)
|
.fetch_one(&pool)
|
||||||
.await
|
.await
|
||||||
@@ -223,6 +340,8 @@ pub async fn get_organization_branding(
|
|||||||
|
|
||||||
Ok(Json(BrandingResponse {
|
Ok(Json(BrandingResponse {
|
||||||
logo_url: org.logo_url,
|
logo_url: org.logo_url,
|
||||||
|
favicon_url: org.favicon_url,
|
||||||
|
platform_name: org.platform_name,
|
||||||
primary_color: org.primary_color.unwrap_or_else(|| "#3B82F6".to_string()),
|
primary_color: org.primary_color.unwrap_or_else(|| "#3B82F6".to_string()),
|
||||||
secondary_color: org.secondary_color.unwrap_or_else(|| "#8B5CF6".to_string()),
|
secondary_color: org.secondary_color.unwrap_or_else(|| "#8B5CF6".to_string()),
|
||||||
}))
|
}))
|
||||||
|
|||||||
@@ -168,6 +168,10 @@ async fn main() {
|
|||||||
"/organizations/{id}/logo",
|
"/organizations/{id}/logo",
|
||||||
post(handlers_branding::upload_organization_logo),
|
post(handlers_branding::upload_organization_logo),
|
||||||
)
|
)
|
||||||
|
.route(
|
||||||
|
"/organizations/{id}/favicon",
|
||||||
|
post(handlers_branding::upload_organization_favicon),
|
||||||
|
)
|
||||||
.route(
|
.route(
|
||||||
"/organizations/{id}/branding",
|
"/organizations/{id}/branding",
|
||||||
axum::routing::put(handlers_branding::update_organization_branding),
|
axum::routing::put(handlers_branding::update_organization_branding),
|
||||||
|
|||||||
@@ -178,6 +178,8 @@ pub struct Organization {
|
|||||||
pub primary_color: Option<String>,
|
pub primary_color: Option<String>,
|
||||||
pub secondary_color: Option<String>,
|
pub secondary_color: Option<String>,
|
||||||
pub certificate_template: Option<String>,
|
pub certificate_template: Option<String>,
|
||||||
|
pub platform_name: Option<String>,
|
||||||
|
pub favicon_url: Option<String>,
|
||||||
pub created_at: DateTime<Utc>,
|
pub created_at: DateTime<Utc>,
|
||||||
pub updated_at: DateTime<Utc>,
|
pub updated_at: DateTime<Utc>,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,26 +8,33 @@ import { useTranslation } from "@/context/I18nContext";
|
|||||||
import { LogOut, Globe } from "lucide-react";
|
import { LogOut, Globe } from "lucide-react";
|
||||||
import NotificationCenter from "./NotificationCenter";
|
import NotificationCenter from "./NotificationCenter";
|
||||||
|
|
||||||
|
import { lmsApi, getImageUrl } from "@/lib/api";
|
||||||
|
|
||||||
export default function AppHeader() {
|
export default function AppHeader() {
|
||||||
const { t, language, setLanguage } = useTranslation();
|
const { t, language, setLanguage } = useTranslation();
|
||||||
const { branding } = useBranding();
|
const { branding } = useBranding();
|
||||||
const { user, logout } = useAuth();
|
const { user, logout } = useAuth();
|
||||||
|
|
||||||
|
// Use platform_name if available, otherwise name, otherwise default
|
||||||
|
const platformName = branding?.platform_name || branding?.name || 'OpenCCB';
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<header className="h-16 glass sticky top-0 z-50 px-6 flex items-center justify-between backdrop-blur-xl bg-black/40 border-b border-white/5">
|
<header className="h-16 glass sticky top-0 z-50 px-6 flex items-center justify-between backdrop-blur-xl bg-black/40 border-b border-white/5">
|
||||||
<Link href="/" className="flex items-center gap-3 group">
|
<Link href="/" className="flex items-center gap-3 group">
|
||||||
<div className="w-10 h-10 rounded-xl bg-blue-600 flex items-center justify-center font-black text-white shadow-lg shadow-blue-500/20 group-hover:scale-105 transition-all overflow-hidden relative">
|
<div className="w-10 h-10 rounded-xl bg-blue-600 flex items-center justify-center font-black text-white shadow-lg shadow-blue-500/20 group-hover:scale-105 transition-all overflow-hidden relative">
|
||||||
{branding?.logo_url ? (
|
{branding?.logo_url ? (
|
||||||
<Image src={branding.logo_url} alt={branding.name} fill className="object-contain" sizes="40px" />
|
<Image src={getImageUrl(branding.logo_url)} alt={branding.name} fill className="object-contain" sizes="40px" />
|
||||||
) : (
|
) : (
|
||||||
<div className="absolute inset-0 flex items-center justify-center bg-gradient-to-br from-blue-500 to-blue-700">L</div>
|
<div className="absolute inset-0 flex items-center justify-center bg-gradient-to-br from-blue-500 to-blue-700">
|
||||||
|
{platformName.charAt(0).toUpperCase()}
|
||||||
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
<div className="flex flex-col -gap-1">
|
<div className="flex flex-col -gap-1">
|
||||||
<span className="font-black text-lg tracking-tighter text-white leading-none">
|
<span className="font-black text-lg tracking-tighter text-white leading-none">
|
||||||
{branding?.name?.toUpperCase() || 'APRENDER'}
|
{platformName.toUpperCase()}
|
||||||
</span>
|
</span>
|
||||||
{!branding && <span className="text-[10px] font-black tracking-widest text-blue-500 uppercase">EXPERIENCIA</span>}
|
<span className="text-[10px] font-black tracking-widest text-blue-500 uppercase">EXPERIENCIA</span>
|
||||||
</div>
|
</div>
|
||||||
</Link>
|
</Link>
|
||||||
|
|
||||||
|
|||||||
@@ -34,6 +34,37 @@ export const BrandingProvider: React.FC<{ children: React.ReactNode }> = ({ chil
|
|||||||
if (data.secondary_color) {
|
if (data.secondary_color) {
|
||||||
document.documentElement.style.setProperty('--secondary-color', data.secondary_color);
|
document.documentElement.style.setProperty('--secondary-color', data.secondary_color);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Update Title
|
||||||
|
if (data.platform_name) {
|
||||||
|
document.title = `${data.platform_name} | Experiencia de Aprendizaje`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update Favicon
|
||||||
|
if (data.favicon_url) {
|
||||||
|
// Import getImageUrl logic locally or assume it needs import
|
||||||
|
// Since I can't easily add import at top with replace_file, I will assume getImageUrl handles the path or do logic here.
|
||||||
|
// Actually I need to import getImageUrl at the top. Instead of complicating, I'll update imports too.
|
||||||
|
const getImageUrl = (path?: string) => {
|
||||||
|
if (!path) return '';
|
||||||
|
if (path.startsWith('http')) return path;
|
||||||
|
const CMS_API_URL = process.env.NEXT_PUBLIC_CMS_API_URL || "http://localhost:3001";
|
||||||
|
const cleanPath = path.startsWith('/uploads') ? path.replace('/uploads', '/assets') : path;
|
||||||
|
const finalPath = cleanPath.startsWith('/') ? cleanPath : `/${cleanPath}`;
|
||||||
|
return `${CMS_API_URL}${finalPath}`;
|
||||||
|
};
|
||||||
|
|
||||||
|
const faviconUrl = getImageUrl(data.favicon_url);
|
||||||
|
const link: HTMLLinkElement | null = document.querySelector("link[rel*='icon']");
|
||||||
|
if (link) {
|
||||||
|
link.href = faviconUrl;
|
||||||
|
} else {
|
||||||
|
const newLink = document.createElement("link");
|
||||||
|
newLink.rel = "shortcut icon";
|
||||||
|
newLink.href = faviconUrl;
|
||||||
|
document.head.appendChild(newLink);
|
||||||
|
}
|
||||||
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to load branding', error);
|
console.error('Failed to load branding', error);
|
||||||
} finally {
|
} finally {
|
||||||
|
|||||||
@@ -13,6 +13,8 @@ export interface Organization {
|
|||||||
id: string;
|
id: string;
|
||||||
name: string;
|
name: string;
|
||||||
logo_url?: string;
|
logo_url?: string;
|
||||||
|
favicon_url?: string;
|
||||||
|
platform_name?: string;
|
||||||
primary_color?: string;
|
primary_color?: string;
|
||||||
secondary_color?: string;
|
secondary_color?: string;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ export const metadata: Metadata = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
import AuthHeader from "@/components/AuthHeader";
|
import AuthHeader from "@/components/AuthHeader";
|
||||||
|
import BrandingManager from "@/components/BrandingManager";
|
||||||
|
|
||||||
export default function RootLayout({
|
export default function RootLayout({
|
||||||
children,
|
children,
|
||||||
@@ -27,6 +28,7 @@ export default function RootLayout({
|
|||||||
<AuthProvider>
|
<AuthProvider>
|
||||||
<I18nProvider>
|
<I18nProvider>
|
||||||
<AuthGuard>
|
<AuthGuard>
|
||||||
|
<BrandingManager />
|
||||||
<header className="h-20 glass sticky top-0 z-50 px-8 flex items-center justify-between border-b border-white/5 backdrop-blur-xl bg-black/40">
|
<header className="h-20 glass sticky top-0 z-50 px-8 flex items-center justify-between border-b border-white/5 backdrop-blur-xl bg-black/40">
|
||||||
<Link href="/" className="flex items-center gap-3 group">
|
<Link href="/" className="flex items-center gap-3 group">
|
||||||
<div className="w-10 h-10 rounded-xl bg-blue-600 flex items-center justify-center font-black text-white shadow-lg shadow-blue-500/20 group-hover:scale-105 transition-transform">
|
<div className="w-10 h-10 rounded-xl bg-blue-600 flex items-center justify-center font-black text-white shadow-lg shadow-blue-500/20 group-hover:scale-105 transition-transform">
|
||||||
|
|||||||
@@ -0,0 +1,31 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import BrandingSettings from "@/components/BrandingSettings";
|
||||||
|
import { useAuth } from "@/context/AuthContext";
|
||||||
|
import { useRouter } from "next/navigation";
|
||||||
|
import { useEffect } from "react";
|
||||||
|
|
||||||
|
export default function SettingsPage() {
|
||||||
|
const { user, loading } = useAuth();
|
||||||
|
const router = useRouter();
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!loading && (!user || user.role !== "admin")) {
|
||||||
|
router.push("/");
|
||||||
|
}
|
||||||
|
}, [user, loading, router]);
|
||||||
|
|
||||||
|
if (loading) return null;
|
||||||
|
|
||||||
|
if (!user || user.role !== "admin") return null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="pt-24 px-8 pb-12 min-h-screen bg-gradient-to-br from-gray-900 to-black">
|
||||||
|
<div className="max-w-4xl mx-auto mb-8">
|
||||||
|
<h1 className="text-3xl font-black text-white tracking-tight">Organization Settings</h1>
|
||||||
|
<p className="text-gray-400 mt-2">Manage your white-label branding and platform identity.</p>
|
||||||
|
</div>
|
||||||
|
<BrandingSettings />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useEffect } from "react";
|
||||||
|
import { useAuth } from "@/context/AuthContext";
|
||||||
|
import { cmsApi, getImageUrl } from "@/lib/api";
|
||||||
|
|
||||||
|
export default function BrandingManager() {
|
||||||
|
const { user } = useAuth();
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!user || user.role === "super_admin") return;
|
||||||
|
// Note: checking user.role === "admin" might be enough, but regular users in Studio (instructors) should also see branding?
|
||||||
|
// Usually YES.
|
||||||
|
|
||||||
|
const fetchBranding = async () => {
|
||||||
|
try {
|
||||||
|
// If user has organization_id, fetch that org
|
||||||
|
// cmsApi.getOrganization() fetches based on X-Organization-Id or token claims.
|
||||||
|
// Assuming getOrganization() returns the current context org.
|
||||||
|
const org = await cmsApi.getOrganization();
|
||||||
|
|
||||||
|
if (org) {
|
||||||
|
// Update Title
|
||||||
|
if (org.platform_name) {
|
||||||
|
document.title = `${org.platform_name} | Studio`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update Favicon
|
||||||
|
if (org.favicon_url) {
|
||||||
|
const faviconUrl = getImageUrl(org.favicon_url);
|
||||||
|
const link: HTMLLinkElement | null = document.querySelector("link[rel*='icon']");
|
||||||
|
if (link) {
|
||||||
|
link.href = faviconUrl;
|
||||||
|
} else {
|
||||||
|
const newLink = document.createElement("link");
|
||||||
|
newLink.rel = "shortcut icon";
|
||||||
|
newLink.href = faviconUrl;
|
||||||
|
document.head.appendChild(newLink);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.error("Failed to load branding", err);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if (user) {
|
||||||
|
fetchBranding();
|
||||||
|
}
|
||||||
|
}, [user]);
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
@@ -0,0 +1,214 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState, useEffect } from "react";
|
||||||
|
import { cmsApi, Organization, BrandingPayload, getImageUrl } from "@/lib/api";
|
||||||
|
import FileUpload from "./FileUpload";
|
||||||
|
import { useRouter } from "next/navigation";
|
||||||
|
|
||||||
|
export default function BrandingSettings() {
|
||||||
|
const router = useRouter();
|
||||||
|
const [org, setOrg] = useState<Organization | null>(null);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [saving, setSaving] = useState(false);
|
||||||
|
const [formData, setFormData] = useState<BrandingPayload>({
|
||||||
|
primary_color: "#3B82F6",
|
||||||
|
secondary_color: "#8B5CF6",
|
||||||
|
platform_name: "",
|
||||||
|
});
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
fetchOrg();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const fetchOrg = async () => {
|
||||||
|
try {
|
||||||
|
const data = await cmsApi.getOrganization();
|
||||||
|
setOrg(data);
|
||||||
|
setFormData({
|
||||||
|
primary_color: data.primary_color || "#3B82F6",
|
||||||
|
secondary_color: data.secondary_color || "#8B5CF6",
|
||||||
|
platform_name: data.platform_name || "",
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Failed to fetch organization:", error);
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleSave = async () => {
|
||||||
|
if (!org) return;
|
||||||
|
setSaving(true);
|
||||||
|
try {
|
||||||
|
await cmsApi.updateOrganizationBranding(org.id, formData);
|
||||||
|
// Refresh to update local state logic if needed
|
||||||
|
fetchOrg();
|
||||||
|
alert("Branding updated successfully!");
|
||||||
|
router.refresh(); // Refresh layouts to pick up new branding
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Failed to update branding:", error);
|
||||||
|
alert("Failed to update branding settings.");
|
||||||
|
} finally {
|
||||||
|
setSaving(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleLogoUpload = async (file: File, onProgress: (pct: number) => void) => {
|
||||||
|
if (!org) throw new Error("No organization loaded");
|
||||||
|
// Simulate progress for smoother UX if the API doesn't support it natively for direct fetch
|
||||||
|
// API wrapper uses fetch/xhr so branding API in api.ts needs to handle it.
|
||||||
|
// For now, we assume simple upload.
|
||||||
|
onProgress(50);
|
||||||
|
const res = await cmsApi.uploadOrganizationLogo(org.id, file);
|
||||||
|
onProgress(100);
|
||||||
|
return { url: res.logo_url }; // api returns { logo_url: ... }
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleFaviconUpload = async (file: File, onProgress: (pct: number) => void) => {
|
||||||
|
if (!org) throw new Error("No organization loaded");
|
||||||
|
onProgress(50);
|
||||||
|
const res = await cmsApi.uploadOrganizationFavicon(org.id, file);
|
||||||
|
onProgress(100);
|
||||||
|
return { url: res.favicon_url };
|
||||||
|
};
|
||||||
|
|
||||||
|
if (loading) return <div className="p-8 text-center text-gray-400 animate-pulse">Loading settings...</div>;
|
||||||
|
if (!org) return <div className="p-8 text-center text-red-400">Failed to load organization settings.</div>;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-8 max-w-4xl mx-auto">
|
||||||
|
<div className="border border-white/10 rounded-2xl p-6 bg-white/5 backdrop-blur-sm">
|
||||||
|
<h3 className="text-xl font-bold mb-6 flex items-center gap-2">
|
||||||
|
<span>🎨</span> Brand Identity
|
||||||
|
</h3>
|
||||||
|
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-8">
|
||||||
|
{/* Platform Name */}
|
||||||
|
<div className="col-span-full">
|
||||||
|
<label className="block text-sm font-medium text-gray-400 mb-2">Platform Name</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={formData.platform_name || ""}
|
||||||
|
onChange={(e) => setFormData({ ...formData, platform_name: e.target.value })}
|
||||||
|
placeholder={org.name}
|
||||||
|
className="w-full bg-black/20 border border-white/10 rounded-lg px-4 py-3 text-white focus:outline-none focus:border-blue-500/50 transition-colors"
|
||||||
|
/>
|
||||||
|
<p className="text-xs text-gray-500 mt-2">Appears in the browser tab and page titles.</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Logo Section */}
|
||||||
|
<div className="space-y-4">
|
||||||
|
<label className="block text-sm font-medium text-gray-400">Logo</label>
|
||||||
|
<div className="p-4 bg-black/20 rounded-xl border border-white/5 flex items-center justify-center min-h-[120px]">
|
||||||
|
{org.logo_url ? (
|
||||||
|
<img src={getImageUrl(org.logo_url)} alt="Logo" className="max-h-16 object-contain" />
|
||||||
|
) : (
|
||||||
|
<span className="text-gray-600 text-sm">No logo uploaded</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<FileUpload
|
||||||
|
accept="image/png,image/jpeg,image/svg+xml"
|
||||||
|
currentUrl={org.logo_url}
|
||||||
|
customUploadFn={async (file, onProgress) => {
|
||||||
|
// Adapt the response format from logo upload API to what FileUpload expects
|
||||||
|
const res = await cmsApi.uploadOrganizationLogo(org.id, file);
|
||||||
|
return { url: res.logo_url || "" };
|
||||||
|
}}
|
||||||
|
onUploadComplete={(url) => {
|
||||||
|
setOrg({ ...org, logo_url: url });
|
||||||
|
router.refresh();
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<p className="text-xs text-gray-500">Recommended: SVG or PNG, max 2MB.</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Favicon Section */}
|
||||||
|
<div className="space-y-4">
|
||||||
|
<label className="block text-sm font-medium text-gray-400">Favicon</label>
|
||||||
|
<div className="p-4 bg-black/20 rounded-xl border border-white/5 flex items-center justify-center min-h-[120px]">
|
||||||
|
{org.favicon_url ? (
|
||||||
|
<img src={getImageUrl(org.favicon_url)} alt="Favicon" className="w-8 h-8 object-contain" />
|
||||||
|
) : (
|
||||||
|
<span className="text-gray-600 text-sm">No favicon</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<FileUpload
|
||||||
|
accept="image/png,image/x-icon,image/svg+xml,image/jpeg"
|
||||||
|
currentUrl={org.favicon_url}
|
||||||
|
customUploadFn={async (file, onProgress) => {
|
||||||
|
const res = await cmsApi.uploadOrganizationFavicon(org.id, file);
|
||||||
|
return { url: res.favicon_url || "" };
|
||||||
|
}}
|
||||||
|
onUploadComplete={(url) => {
|
||||||
|
setOrg({ ...org, favicon_url: url });
|
||||||
|
router.refresh();
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<p className="text-xs text-gray-500">Recommended: ICO or PNG, 32x32px.</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="border border-white/10 rounded-2xl p-6 bg-white/5 backdrop-blur-sm">
|
||||||
|
<h3 className="text-xl font-bold mb-6 flex items-center gap-2">
|
||||||
|
<span>🌈</span> Brand Colors
|
||||||
|
</h3>
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-8">
|
||||||
|
{/* Primary Color */}
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium text-gray-400 mb-2">Primary Color</label>
|
||||||
|
<div className="flex items-center gap-4">
|
||||||
|
<input
|
||||||
|
type="color"
|
||||||
|
value={formData.primary_color}
|
||||||
|
onChange={(e) => setFormData({ ...formData, primary_color: e.target.value })}
|
||||||
|
className="w-12 h-12 rounded-lg cursor-pointer bg-transparent border-none p-0"
|
||||||
|
/>
|
||||||
|
<div className="flex-1">
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={formData.primary_color}
|
||||||
|
onChange={(e) => setFormData({ ...formData, primary_color: e.target.value })}
|
||||||
|
className="w-full bg-black/20 border border-white/10 rounded-lg px-4 py-2 text-white font-mono uppercase"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<p className="text-xs text-gray-500 mt-2">Used for main buttons, active states, and highlights.</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Secondary Color */}
|
||||||
|
<div>
|
||||||
|
<label className="block text-sm font-medium text-gray-400 mb-2">Secondary Color</label>
|
||||||
|
<div className="flex items-center gap-4">
|
||||||
|
<input
|
||||||
|
type="color"
|
||||||
|
value={formData.secondary_color}
|
||||||
|
onChange={(e) => setFormData({ ...formData, secondary_color: e.target.value })}
|
||||||
|
className="w-12 h-12 rounded-lg cursor-pointer bg-transparent border-none p-0"
|
||||||
|
/>
|
||||||
|
<div className="flex-1">
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={formData.secondary_color}
|
||||||
|
onChange={(e) => setFormData({ ...formData, secondary_color: e.target.value })}
|
||||||
|
className="w-full bg-black/20 border border-white/10 rounded-lg px-4 py-2 text-white font-mono uppercase"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<p className="text-xs text-gray-500 mt-2">Used for accents and gradients.</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex justify-end">
|
||||||
|
<button
|
||||||
|
onClick={handleSave}
|
||||||
|
disabled={saving}
|
||||||
|
className="px-8 py-3 bg-blue-600 hover:bg-blue-500 text-white font-bold rounded-xl transition-all disabled:opacity-50 disabled:cursor-not-allowed shadow-[0_0_20px_rgba(37,99,235,0.3)] hover:shadow-[0_0_30px_rgba(37,99,235,0.5)]"
|
||||||
|
>
|
||||||
|
{saving ? "Saving Changes..." : "Save Branding Settings"}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -7,9 +7,10 @@ interface FileUploadProps {
|
|||||||
onUploadComplete: (url: string) => void;
|
onUploadComplete: (url: string) => void;
|
||||||
currentUrl?: string;
|
currentUrl?: string;
|
||||||
accept?: string;
|
accept?: string;
|
||||||
|
customUploadFn?: (file: File, onProgress: (pct: number) => void) => Promise<{ url: string }>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function FileUpload({ onUploadComplete, currentUrl, accept = "video/*,audio/*" }: FileUploadProps) {
|
export default function FileUpload({ onUploadComplete, currentUrl, accept = "video/*,audio/*", customUploadFn }: FileUploadProps) {
|
||||||
const [isUploading, setIsUploading] = useState(false);
|
const [isUploading, setIsUploading] = useState(false);
|
||||||
const [uploadProgress, setUploadProgress] = useState(0);
|
const [uploadProgress, setUploadProgress] = useState(0);
|
||||||
const [uploadingFileName, setUploadingFileName] = useState("");
|
const [uploadingFileName, setUploadingFileName] = useState("");
|
||||||
@@ -21,9 +22,14 @@ export default function FileUpload({ onUploadComplete, currentUrl, accept = "vid
|
|||||||
setUploadProgress(0);
|
setUploadProgress(0);
|
||||||
setUploadingFileName(file.name);
|
setUploadingFileName(file.name);
|
||||||
try {
|
try {
|
||||||
const result = await cmsApi.uploadAsset(file, (pct) => {
|
let result;
|
||||||
setUploadProgress(pct);
|
if (customUploadFn) {
|
||||||
});
|
result = await customUploadFn(file, (pct) => setUploadProgress(pct));
|
||||||
|
} else {
|
||||||
|
result = await cmsApi.uploadAsset(file, (pct) => {
|
||||||
|
setUploadProgress(pct);
|
||||||
|
});
|
||||||
|
}
|
||||||
onUploadComplete(result.url);
|
onUploadComplete(result.url);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
alert("Upload failed. Please try again.");
|
alert("Upload failed. Please try again.");
|
||||||
|
|||||||
@@ -56,7 +56,6 @@ export function Navbar() {
|
|||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/*
|
|
||||||
<Link
|
<Link
|
||||||
href="/settings"
|
href="/settings"
|
||||||
className="text-sm font-medium text-gray-400 hover:text-blue-400 transition-colors flex items-center gap-2"
|
className="text-sm font-medium text-gray-400 hover:text-blue-400 transition-colors flex items-center gap-2"
|
||||||
@@ -64,7 +63,6 @@ export function Navbar() {
|
|||||||
<Settings className="w-4 h-4" />
|
<Settings className="w-4 h-4" />
|
||||||
Settings
|
Settings
|
||||||
</Link>
|
</Link>
|
||||||
*/}
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="h-6 w-px bg-white/10 mx-2" />
|
<div className="h-6 w-px bg-white/10 mx-2" />
|
||||||
|
|||||||
@@ -106,6 +106,8 @@ export interface Organization {
|
|||||||
name: string;
|
name: string;
|
||||||
domain?: string;
|
domain?: string;
|
||||||
logo_url?: string;
|
logo_url?: string;
|
||||||
|
favicon_url?: string;
|
||||||
|
platform_name?: string;
|
||||||
primary_color?: string;
|
primary_color?: string;
|
||||||
secondary_color?: string;
|
secondary_color?: string;
|
||||||
certificate_template?: string;
|
certificate_template?: string;
|
||||||
@@ -116,6 +118,7 @@ export interface Organization {
|
|||||||
export interface BrandingPayload {
|
export interface BrandingPayload {
|
||||||
primary_color?: string;
|
primary_color?: string;
|
||||||
secondary_color?: string;
|
secondary_color?: string;
|
||||||
|
platform_name?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface User {
|
export interface User {
|
||||||
@@ -156,6 +159,8 @@ export interface UploadResponse {
|
|||||||
id: string;
|
id: string;
|
||||||
filename: string;
|
filename: string;
|
||||||
url: string;
|
url: string;
|
||||||
|
logo_url?: string;
|
||||||
|
favicon_url?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface GradingCategory {
|
export interface GradingCategory {
|
||||||
@@ -390,6 +395,24 @@ export const cmsApi = {
|
|||||||
return res.json();
|
return res.json();
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
|
uploadOrganizationFavicon: (id: string, file: File): Promise<UploadResponse> => {
|
||||||
|
const formData = new FormData();
|
||||||
|
formData.append('file', file);
|
||||||
|
const token = getToken();
|
||||||
|
const selectedOrgId = getSelectedOrgId();
|
||||||
|
const headers: Record<string, string> = {
|
||||||
|
...(token ? { 'Authorization': `Bearer ${token}` } : {}),
|
||||||
|
...(selectedOrgId ? { 'X-Organization-Id': selectedOrgId } : {})
|
||||||
|
};
|
||||||
|
return fetch(`${API_BASE_URL}/organizations/${id}/favicon`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers,
|
||||||
|
body: formData,
|
||||||
|
}).then(res => {
|
||||||
|
if (!res.ok) return res.json().then(err => Promise.reject(new Error(err.message || 'Favicon upload failed')));
|
||||||
|
return res.json();
|
||||||
|
});
|
||||||
|
},
|
||||||
|
|
||||||
// SSO
|
// SSO
|
||||||
getSSOConfig: (): Promise<OrganizationSSOConfig | null> => apiFetch('/organization/sso'),
|
getSSOConfig: (): Promise<OrganizationSSOConfig | null> => apiFetch('/organization/sso'),
|
||||||
|
|||||||
Reference in New Issue
Block a user