feat(onboarding): Implement customer onboarding guard in App.tsx, redirecting unprofiled users to OnboardingPage, centralizing user and customer data management in useAuth with cookie-based auth.

This commit is contained in:
ghost2023
2026-05-28 15:41:47 +03:00
parent 4262de5424
commit 0eaa1f93f3
4 changed files with 46 additions and 134 deletions

View File

@@ -42,10 +42,12 @@ import FileUploadSettingsPage from "./pages/admin/FileUploadSettingsPage";
import MyPortalPage from "./pages/portal/MyPortalPage";
import EDRFreightLandingPage from "./pages/EDRFreightLandingPage";
import SignupPage from "./pages/accounts/SignupPage";
import OnboardingPage from "./pages/accounts/OnboardingPage";
import VerificationOtpPage from "./pages/accounts/VerificationOtpPage";
import SetPasswordPage from "./pages/accounts/SetPasswordPage";
import LoginPage from "./pages/accounts/LoginPage";
import Station from "./components/stations/Station";
import { useEffect } from "react";
const sidebarItems: SidebarItem[] = [
{ label: "My Portal", href: "/", icon: <UserCircle /> },
@@ -69,9 +71,14 @@ const sidebarItems: SidebarItem[] = [
const App = () => {
const navigate = useNavigate();
const location = useLocation();
const { user, isPending, logout } = useAuth();
const { user, isPending, logout, customer, customerQuery } = useAuth();
console.log({ customer, isPending, user });
useEffect(() => {
if (!user) return;
// if (!user.hasSetPassword) navigate("/set-password");
}, [user]);
console.log({ user, isPending });
if (isPending) {
return (
<div className="flex items-center justify-center h-screen">
@@ -93,6 +100,10 @@ const App = () => {
);
}
if (user && !customer && !customerQuery.isPending) {
return <OnboardingPage />;
}
const displayName = user?.name?.en || user?.username || user?.email || "User";
const userEmail = user?.email;

View File

@@ -30,6 +30,7 @@ const useAuth = () => {
api.auth.getMyInfo.queryOptions({
enabled: !!getCookie("auth-token"),
retry: false,
staleTime: 10 * 60 * 1000,
}),
);
@@ -38,6 +39,8 @@ const useAuth = () => {
input: { id: authQuery.data?.id ?? "" },
enabled: !!authQuery.data?.id,
retry: false,
staleTime: 10 * 60 * 1000,
refetchOnWindowFocus: false,
}),
);
@@ -63,8 +66,9 @@ const useAuth = () => {
): Promise<Result<SignupResponse>> => {
try {
const res = await api.auth.createUser.call(payload);
localStorage.setItem("auth-token", `auth-token=${res.token}; path=/`);
localStorage.setItem("userId", res.userId);
setCookie("auth-token", res.token, 7);
setCookie("refresh-token", res.refreshToken, 7);
await authQuery.refetch();
const otpCode = res.otp?.split(" ")?.[6] ?? "";
localStorage.setItem("otp", otpCode);
localStorage.setItem("otp-phone", payload.phoneNumber);
@@ -83,7 +87,7 @@ const useAuth = () => {
confirmPassword: string;
}): Promise<Result<void>> => {
try {
const userId = localStorage.getItem("userId") ?? "";
const userId = authQuery.data?.id ?? "";
const email = localStorage.getItem("otp-email") ?? "";
const verificationCode = localStorage.getItem("otp") ?? "";
await api.auth.setPassword.call({
@@ -96,6 +100,9 @@ const useAuth = () => {
["userId", "otp", "otp-phone", "otp-email"].forEach((k) =>
localStorage.removeItem(k),
);
await queryClient.invalidateQueries({
queryKey: api.auth.getMyInfo.queryKey(),
});
return { success: true, data: undefined };
} catch (err) {
return { success: false, error: extractApiError(err) };
@@ -159,10 +166,6 @@ const useAuth = () => {
window.location.href = "/login";
};
const invalidate = async () => {
await Promise.all([authQuery.refetch(), customerQuery.refetch()]);
};
return {
isPending,
user: authQuery.data ?? null,
@@ -174,7 +177,6 @@ const useAuth = () => {
sendOTP,
generateVerificationCode,
logout,
invalidate,
authQuery,
customerQuery,
};

View File

@@ -1,13 +1,6 @@
import {
useEffect,
useMemo,
useState,
} from "react";
import { useEffect, useMemo, useState } from "react";
import {
Link,
useNavigate,
} from "react-router-dom";
import { Link, useNavigate } from "react-router-dom";
import {
Building2,
@@ -31,19 +24,10 @@ import { formatCurrency } from "@/pages/billing/invoices.mock";
import { customersService } from "@/services/customers.service";
import { getMyInfo } from "@/services/account";
import { authService } from "@/services/auth.service";
import NewCustomerPage from "../customers/NewCustomerPage";
import { Button } from "@edr/ui-common";
type Customer = {
id: string;
companyName: string;
firstName: string;
lastName: string;
email: string;
phone: string;
};
export default function MyPortalPage() {
const navigate = useNavigate();
@@ -58,58 +42,10 @@ export default function MyPortalPage() {
// MOCK DATA
// ------------------------------------------------------------
const me = useMemo(() => getCurrentCustomer(), []);
const myBookings = useMemo(() => getMyBookings(), []);
const myShipments = useMemo(() => getMyShipments(), []);
const myInvoices = useMemo(() => getMyInvoices(), []);
// ------------------------------------------------------------
// FETCH CUSTOMER
// ------------------------------------------------------------
useEffect(() => {
const initialize = async () => {
try {
setLoading(true);
const userRes = await getMyInfo();
const userId = userRes?.data?.id;
localStorage.setItem("currentUser", JSON.stringify(userRes.data));
// if (!userId) {
// navigate("/login");
// return;
// }
const res = await customersService.getByUserId(userId);
if (res) {
setCustomer(res);
return;
}
// customer not found → onboarding
// navigate("/customers/register");
} catch (error: any) {
console.error("Customer fetch failed:", error);
const status = error?.response?.status;
if (status === 404) {
// navigate("/customers/register");
return;
}
if (status === 401) {
// navigate("/login");
return;
}
} finally {
setLoading(false);
}
};
initialize();
}, [navigate]);
// ------------------------------------------------------------
// LOADING
// ------------------------------------------------------------
@@ -118,9 +54,7 @@ export default function MyPortalPage() {
return (
<div className="flex min-h-screen items-center justify-center bg-slate-50">
<div className="rounded-2xl bg-white px-6 py-4 shadow-sm">
<p className="text-sm text-slate-600">
Loading portal...
</p>
<p className="text-sm text-slate-600">Loading portal...</p>
</div>
</div>
);
@@ -134,9 +68,7 @@ export default function MyPortalPage() {
return (
<div className="flex min-h-screen items-center justify-center bg-slate-50">
<div className="text-center space-y-4">
<p className="text-slate-600">
No customer profile found
</p>
<p className="text-slate-600">No customer profile found</p>
{/* <Link
to="/customers/register"
@@ -146,12 +78,9 @@ export default function MyPortalPage() {
Create Customer Profile
</Link> */}
<NewCustomerPage>
<Button
className="inline-flex items-center gap-2 rounded-2xl bg-[#10B981] px-4 py-2 text-white"
>
<Button className="inline-flex items-center gap-2 rounded-2xl bg-[#10B981] px-4 py-2 text-white">
<Plus className="h-4 w-4" />
Create Customer Profile
Create Customer Profile
</Button>
</NewCustomerPage>
</div>
@@ -164,31 +93,24 @@ export default function MyPortalPage() {
// ------------------------------------------------------------
const activeBookings = myBookings.filter(
(b) =>
b.status === "Confirmed" ||
b.status === "In Transit"
(b) => b.status === "Confirmed" || b.status === "In Transit",
);
const activeShipments = myShipments.filter(
(s) => s.status === "In Transit"
);
const activeShipments = myShipments.filter((s) => s.status === "In Transit");
const outstandingInvoices = myInvoices.filter(
(i) => i.status === "Sent" || i.status === "Overdue"
(i) => i.status === "Sent" || i.status === "Overdue",
);
const totalOutstanding = outstandingInvoices.reduce(
(sum, i) =>
i.currency === "USD" ? sum + i.amount : sum,
0
(sum, i) => (i.currency === "USD" ? sum + i.amount : sum),
0,
);
const totalSpent = myInvoices.reduce(
(sum, i) =>
i.status === "Paid" && i.currency === "USD"
? sum + i.amount
: sum,
0
i.status === "Paid" && i.currency === "USD" ? sum + i.amount : sum,
0,
);
// ------------------------------------------------------------
@@ -198,13 +120,11 @@ export default function MyPortalPage() {
return (
<div className="min-h-screen bg-slate-50 p-6">
<div className="mx-auto max-w-7xl space-y-6">
<Breadcrumbs items={[{ label: "My Portal" }]} />
{/* HERO */}
<div className="rounded-3xl bg-gradient-to-r from-[#059669] to-[#10B981] p-6 text-white">
<div className="flex justify-between flex-col md:flex-row gap-6">
<div className="flex items-center gap-4">
<div className="h-14 w-14 flex items-center justify-center rounded-2xl bg-white/20 text-xl font-bold">
{customer.companyName?.charAt(0)}
@@ -244,7 +164,6 @@ export default function MyPortalPage() {
{/* KPI */}
<div className="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
<KpiCard
label="Active Bookings"
value={String(activeBookings.length)}
@@ -283,7 +202,6 @@ export default function MyPortalPage() {
);
}
// ------------------------------------------------------------
// KPI CARD
// ------------------------------------------------------------
@@ -304,24 +222,16 @@ function KpiCard({
tone?: "brand" | "danger";
}) {
const iconClassName =
tone === "danger"
? "bg-red-100 text-red-600"
: "bg-[#10B981] text-white";
tone === "danger" ? "bg-red-100 text-red-600" : "bg-[#10B981] text-white";
const content = (
<div className="flex items-start justify-between">
<div>
<p className="text-sm text-slate-500">
{label}
</p>
<p className="text-sm text-slate-500">{label}</p>
<h3 className="mt-2 text-2xl font-bold text-slate-900">
{value}
</h3>
<h3 className="mt-2 text-2xl font-bold text-slate-900">{value}</h3>
<p className="mt-1 text-xs text-slate-500">
{sub}
</p>
<p className="mt-1 text-xs text-slate-500">{sub}</p>
</div>
<div
@@ -337,18 +247,11 @@ function KpiCard({
if (href) {
return (
<Link
to={href}
className={`block ${className}`}
>
<Link to={href} className={`block ${className}`}>
{content}
</Link>
);
}
return (
<div className={className}>
{content}
</div>
);
}
return <div className={className}>{content}</div>;
}

View File

@@ -81,11 +81,7 @@ export const api = {
"verifyOTP",
authService.verifyOTP,
),
logout: endpoint<void, void>(
"auth",
"logout",
authService.logout,
),
logout: endpoint<void, void>("auth", "logout", authService.logout),
},
customers: {
@@ -115,7 +111,7 @@ export const api = {
customersService.remove(id),
),
getByUserId: endpoint<{ id: string }, Customer>(
getByUserId: endpoint<{ id: string }, Customer | null>(
"customers",
"getByUserId",
({ id }) => customersService.getByUserId(id),