Compare commits
4 Commits
be0619f5d9
...
38ba89b82f
| Author | SHA1 | Date | |
|---|---|---|---|
| 38ba89b82f | |||
| 84b7290fe8 | |||
| eaafb6c3b4 | |||
| 64a949e44f |
80
.gitea/workflows/frontend.yml
Normal file
80
.gitea/workflows/frontend.yml
Normal file
@@ -0,0 +1,80 @@
|
||||
name: Frontend CI/CD
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
pull_request:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: qlockify-node
|
||||
steps:
|
||||
- name: Install system dependencies
|
||||
run: |
|
||||
apt-get update
|
||||
apt-get install -y --no-install-recommends git
|
||||
|
||||
- name: Checkout repository
|
||||
env:
|
||||
REPO_URL: ${{ gitea.server_url }}/${{ gitea.repository }}.git
|
||||
REPO_SHA: ${{ gitea.sha }}
|
||||
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
|
||||
WORKSPACE: ${{ gitea.workspace }}
|
||||
run: |
|
||||
mkdir -p "$WORKSPACE"
|
||||
cd "$WORKSPACE"
|
||||
git init
|
||||
git remote add origin "$REPO_URL"
|
||||
git -c http.extraHeader="Authorization: Bearer $GITEA_TOKEN" fetch --depth 1 origin "$REPO_SHA"
|
||||
git checkout --detach FETCH_HEAD
|
||||
|
||||
- name: Install dependencies
|
||||
working-directory: ${{ gitea.workspace }}
|
||||
run: npm ci
|
||||
|
||||
- name: Lint frontend
|
||||
working-directory: ${{ gitea.workspace }}
|
||||
run: npm run lint
|
||||
|
||||
- name: Build frontend
|
||||
working-directory: ${{ gitea.workspace }}
|
||||
run: npm run build
|
||||
|
||||
deploy:
|
||||
if: github.event_name == 'push' && github.ref_name == 'main'
|
||||
needs:
|
||||
- build
|
||||
runs-on: qlockify-deploy
|
||||
steps:
|
||||
- name: Install SSH client
|
||||
run: |
|
||||
apt-get update
|
||||
apt-get install -y --no-install-recommends bash openssh-client
|
||||
|
||||
- name: Configure SSH
|
||||
env:
|
||||
SSH_PRIVATE_KEY: ${{ secrets.SSH_PRIVATE_KEY }}
|
||||
SSH_KNOWN_HOSTS: ${{ secrets.SSH_KNOWN_HOSTS }}
|
||||
run: |
|
||||
install -m 700 -d ~/.ssh
|
||||
printf '%s\n' "$SSH_PRIVATE_KEY" > ~/.ssh/id_ed25519
|
||||
chmod 600 ~/.ssh/id_ed25519
|
||||
printf '%s\n' "$SSH_KNOWN_HOSTS" > ~/.ssh/known_hosts
|
||||
chmod 644 ~/.ssh/known_hosts
|
||||
|
||||
- name: Deploy frontend service
|
||||
env:
|
||||
DEPLOY_HOST: ${{ vars.DEPLOY_HOST }}
|
||||
DEPLOY_PORT: ${{ vars.DEPLOY_PORT }}
|
||||
DEPLOY_USER: ${{ vars.DEPLOY_USER }}
|
||||
DEPLOY_PATH: ${{ vars.DEPLOY_PATH }}
|
||||
DEPLOY_BRANCH: ${{ vars.DEPLOY_BRANCH }}
|
||||
BACKEND_BRANCH: ${{ vars.BACKEND_BRANCH }}
|
||||
FRONTEND_BRANCH: ${{ vars.FRONTEND_BRANCH }}
|
||||
run: |
|
||||
ssh -p "${DEPLOY_PORT:-22}" "${DEPLOY_USER}@${DEPLOY_HOST}" \
|
||||
"DEPLOY_ROOT='${DEPLOY_PATH}' DEPLOY_BRANCH='${DEPLOY_BRANCH}' BACKEND_BRANCH='${BACKEND_BRANCH}' FRONTEND_BRANCH='${FRONTEND_BRANCH}' bash '${DEPLOY_PATH}/scripts/deploy.sh' frontend"
|
||||
@@ -25,6 +25,22 @@ export interface Project {
|
||||
created_by?: AuditUser | null;
|
||||
client: ProjectClient | null;
|
||||
}
|
||||
|
||||
export interface ProjectAccessItem {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string;
|
||||
color: string;
|
||||
is_archived: boolean;
|
||||
client: ProjectClient | null;
|
||||
has_access: boolean;
|
||||
}
|
||||
|
||||
export interface ProjectAccessState {
|
||||
workspace: { id: string; name: string };
|
||||
user: { id: string; name: string; mobile: string; role: "member" | "guest" };
|
||||
items: ProjectAccessItem[];
|
||||
}
|
||||
|
||||
export interface ProjectPayload {
|
||||
name: string;
|
||||
@@ -132,7 +148,7 @@ export const deleteProject = async (id: string) => {
|
||||
return response.json().catch(() => ({ success: true }));
|
||||
};
|
||||
|
||||
export const toggleArchiveProject = async (id: string) => {
|
||||
export const toggleArchiveProject = async (id: string) => {
|
||||
const response = await authFetch(`/api/projects/${id}/archive/`, {
|
||||
method: "POST",
|
||||
});
|
||||
@@ -145,3 +161,41 @@ export const toggleArchiveProject = async (id: string) => {
|
||||
invalidateApiCache(["projects", "reports"]);
|
||||
return payload;
|
||||
};
|
||||
|
||||
export const getProjectAccessState = async (workspaceId: string, userId: string): Promise<ProjectAccessState> => {
|
||||
const query = new URLSearchParams({ workspace: workspaceId, user: userId });
|
||||
const response = await authFetch(`/api/projects/access/?${query.toString()}`);
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => null);
|
||||
throw new Error(errorData?.detail || errorData?.message || "Failed to fetch project access");
|
||||
}
|
||||
return response.json();
|
||||
};
|
||||
|
||||
const mutateProjectAccess = async (
|
||||
path: string,
|
||||
workspaceId: string,
|
||||
userId: string,
|
||||
projectIds: string[],
|
||||
) => {
|
||||
const response = await authFetch(path, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
workspace: workspaceId,
|
||||
user: userId,
|
||||
project_ids: projectIds,
|
||||
}),
|
||||
});
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => null);
|
||||
throw new Error(errorData?.detail || errorData?.message || "Failed to update project access");
|
||||
}
|
||||
invalidateApiCache(["projects", "reports"]);
|
||||
return response.json();
|
||||
};
|
||||
|
||||
export const grantProjectAccess = async (workspaceId: string, userId: string, projectIds: string[]) =>
|
||||
mutateProjectAccess("/api/projects/access/grant/", workspaceId, userId, projectIds);
|
||||
|
||||
export const revokeProjectAccess = async (workspaceId: string, userId: string, projectIds: string[]) =>
|
||||
mutateProjectAccess("/api/projects/access/revoke/", workspaceId, userId, projectIds);
|
||||
|
||||
@@ -45,10 +45,15 @@ export interface ReportChartBucket {
|
||||
total_duration: string;
|
||||
}
|
||||
|
||||
export interface ChartReportSeries {
|
||||
user: { id: string; name: string; mobile: string } | null;
|
||||
buckets: ReportChartBucket[];
|
||||
}
|
||||
|
||||
export interface ChartReportResponse {
|
||||
scope: ReportScope;
|
||||
summary: ReportSummary;
|
||||
buckets: ReportChartBucket[];
|
||||
series: ChartReportSeries[];
|
||||
}
|
||||
|
||||
export interface DailyReportRow {
|
||||
@@ -75,6 +80,35 @@ export interface BreakdownRow {
|
||||
income_totals: CurrencyTotal[];
|
||||
}
|
||||
|
||||
export interface PercentageRow {
|
||||
id: string;
|
||||
name: string;
|
||||
percentage: string;
|
||||
}
|
||||
|
||||
export interface RatePeriodRow {
|
||||
amount: string;
|
||||
currency: string;
|
||||
from_date: string;
|
||||
to_date: string;
|
||||
}
|
||||
|
||||
export interface UserReportSummary {
|
||||
user: { id: string; name: string; mobile: string };
|
||||
hourly_rates: CurrencyTotal[];
|
||||
rate_periods: RatePeriodRow[];
|
||||
total_seconds: number;
|
||||
total_duration: string;
|
||||
billable_seconds: number;
|
||||
billable_duration: string;
|
||||
non_billable_seconds: number;
|
||||
non_billable_duration: string;
|
||||
income_totals: CurrencyTotal[];
|
||||
project_percentages: PercentageRow[];
|
||||
client_percentages: PercentageRow[];
|
||||
tag_percentages: PercentageRow[];
|
||||
}
|
||||
|
||||
export interface DayDetailEntry {
|
||||
id: string;
|
||||
description: string;
|
||||
@@ -109,6 +143,8 @@ export interface TableReportResponse {
|
||||
clients: BreakdownRow[];
|
||||
projects: BreakdownRow[];
|
||||
tags: BreakdownRow[];
|
||||
user_summary?: UserReportSummary;
|
||||
user_summaries?: UserReportSummary[];
|
||||
}
|
||||
|
||||
export interface ReportExportJob {
|
||||
|
||||
@@ -1,29 +1,44 @@
|
||||
import { authFetch, buildApiError, buildApiUrl } from './client';
|
||||
|
||||
// --- Auth Endpoints ---
|
||||
|
||||
|
||||
const normalizeDigits = (value: string) =>
|
||||
value
|
||||
.replace(/[۰-۹]/g, (digit) => String("۰۱۲۳۴۵۶۷۸۹".indexOf(digit)))
|
||||
.replace(/[٠-٩]/g, (digit) => String("٠١٢٣٤٥٦٧٨٩".indexOf(digit)))
|
||||
|
||||
// --- Auth Endpoints ---
|
||||
|
||||
export const loginWithPassword = async (mobile: string, password: string) => {
|
||||
const normalizedMobile = normalizeDigits(mobile)
|
||||
const response = await authFetch('/api/users/login/', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ mobile, password })
|
||||
body: JSON.stringify({ mobile: normalizedMobile, password })
|
||||
});
|
||||
if (!response.ok) throw await buildApiError(response);
|
||||
return response.json();
|
||||
};
|
||||
|
||||
export const sendOtp = async (mobile: string, mode: string) => {
|
||||
export interface SendOtpResponse {
|
||||
detail: string
|
||||
expires_in_seconds: number
|
||||
expires_at?: string | null
|
||||
}
|
||||
|
||||
export const sendOtp = async (mobile: string, mode: string): Promise<SendOtpResponse> => {
|
||||
const normalizedMobile = normalizeDigits(mobile)
|
||||
const response = await authFetch('/api/users/otp/send/', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ mobile, mode })
|
||||
body: JSON.stringify({ mobile: normalizedMobile, mode })
|
||||
});
|
||||
if (!response.ok) throw await buildApiError(response);
|
||||
return response.json();
|
||||
};
|
||||
|
||||
export const loginWithOtp = async (mobile: string, otp: string) => {
|
||||
const normalizedMobile = normalizeDigits(mobile)
|
||||
const normalizedOtp = normalizeDigits(otp)
|
||||
const response = await authFetch('/api/users/otp/login/', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ mobile, code: otp })
|
||||
body: JSON.stringify({ mobile: normalizedMobile, code: normalizedOtp })
|
||||
});
|
||||
if (!response.ok) throw await buildApiError(response);
|
||||
return response.json();
|
||||
@@ -37,9 +52,18 @@ export const registerWithOtp = async (
|
||||
first_name = "",
|
||||
last_name = "",
|
||||
) => {
|
||||
const normalizedMobile = normalizeDigits(mobile)
|
||||
const normalizedCode = normalizeDigits(code)
|
||||
const response = await authFetch("/api/users/register/", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ mobile, code, password, re_password, first_name, last_name }),
|
||||
body: JSON.stringify({
|
||||
mobile: normalizedMobile,
|
||||
code: normalizedCode,
|
||||
password,
|
||||
re_password,
|
||||
first_name,
|
||||
last_name,
|
||||
}),
|
||||
})
|
||||
if (!response.ok) throw await buildApiError(response)
|
||||
return response.json()
|
||||
@@ -51,9 +75,16 @@ export const resetPasswordWithOtp = async (
|
||||
password: string,
|
||||
re_password: string,
|
||||
) => {
|
||||
const normalizedMobile = normalizeDigits(mobile)
|
||||
const normalizedCode = normalizeDigits(code)
|
||||
const response = await authFetch("/api/users/password/reset/", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ mobile, code, password, re_password }),
|
||||
body: JSON.stringify({
|
||||
mobile: normalizedMobile,
|
||||
code: normalizedCode,
|
||||
password,
|
||||
re_password,
|
||||
}),
|
||||
})
|
||||
if (!response.ok) throw await buildApiError(response)
|
||||
return response.json()
|
||||
@@ -107,9 +138,10 @@ export const completeGoogleOAuthSignup = async (
|
||||
flow: string,
|
||||
mobile: string,
|
||||
): Promise<GoogleOAuthFlowResponse> => {
|
||||
const normalizedMobile = normalizeDigits(mobile)
|
||||
const response = await authFetch("/api/users/oauth/google/complete/", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ flow, mobile }),
|
||||
body: JSON.stringify({ flow, mobile: normalizedMobile }),
|
||||
});
|
||||
if (!response.ok) throw await buildApiError(response);
|
||||
return response.json();
|
||||
@@ -128,9 +160,10 @@ export const verifyGoogleOAuthClaim = async (
|
||||
flow: string,
|
||||
code: string,
|
||||
): Promise<GoogleOAuthFlowResponse> => {
|
||||
const normalizedCode = normalizeDigits(code)
|
||||
const response = await authFetch("/api/users/oauth/google/claim/verify/", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ flow, code }),
|
||||
body: JSON.stringify({ flow, code: normalizedCode }),
|
||||
});
|
||||
if (!response.ok) throw await buildApiError(response);
|
||||
return response.json();
|
||||
@@ -193,9 +226,9 @@ export interface SearchedUser {
|
||||
profile_picture: string | null;
|
||||
}
|
||||
|
||||
export const searchUserByExactMobile = async (mobile: string): Promise<SearchedUser | null> => {
|
||||
try {
|
||||
const response = await authFetch(`/api/users/search/?mobile=${encodeURIComponent(mobile)}`);
|
||||
export const searchUserByExactMobile = async (mobile: string): Promise<SearchedUser | null> => {
|
||||
try {
|
||||
const response = await authFetch(`/api/users/search/?mobile=${encodeURIComponent(normalizeDigits(mobile))}`);
|
||||
if (!response.ok) return null; // Returns null on 404 or other errors
|
||||
return await response.json();
|
||||
} catch (error) {
|
||||
|
||||
351
src/components/projects/ProjectAccessModal.tsx
Normal file
351
src/components/projects/ProjectAccessModal.tsx
Normal file
@@ -0,0 +1,351 @@
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { CheckSquare, Filter, ShieldCheck, Square } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import {
|
||||
getProjectAccessState,
|
||||
grantProjectAccess,
|
||||
revokeProjectAccess,
|
||||
type ProjectAccessItem,
|
||||
} from "../../api/projects";
|
||||
import { fetchWorkspaceMemberships, type WorkspaceMembership } from "../../api/workspaces";
|
||||
import { Modal } from "../Modal";
|
||||
import { Button } from "../ui/button";
|
||||
import { Input } from "../ui/input";
|
||||
|
||||
type Labels = {
|
||||
title: string;
|
||||
description: string;
|
||||
close: string;
|
||||
member: string;
|
||||
loading: string;
|
||||
noMembers: string;
|
||||
noProjects: string;
|
||||
searchPlaceholder: string;
|
||||
allClients: string;
|
||||
selectAllVisible: string;
|
||||
clearSelection: string;
|
||||
selectClientProjects: string;
|
||||
grantSelected: string;
|
||||
revokeSelected: string;
|
||||
accessGranted: string;
|
||||
accessRevoked: string;
|
||||
memberRole: string;
|
||||
client: string;
|
||||
noClient: string;
|
||||
accessOn: string;
|
||||
accessOff: string;
|
||||
loadError: string;
|
||||
saveError: string;
|
||||
};
|
||||
|
||||
const MANAGEABLE_ROLES = new Set(["member", "guest"]);
|
||||
|
||||
function getMemberName(member: WorkspaceMembership) {
|
||||
return (
|
||||
member.user?.name ||
|
||||
`${member.user?.first_name || ""} ${member.user?.last_name || ""}`.trim() ||
|
||||
member.user?.mobile ||
|
||||
member.id
|
||||
);
|
||||
}
|
||||
|
||||
export function ProjectAccessModal({
|
||||
isOpen,
|
||||
onClose,
|
||||
workspaceId,
|
||||
labels,
|
||||
onApplied,
|
||||
}: {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
workspaceId: string;
|
||||
labels: Labels;
|
||||
onApplied: () => void;
|
||||
}) {
|
||||
const [members, setMembers] = useState<WorkspaceMembership[]>([]);
|
||||
const [loadingMembers, setLoadingMembers] = useState(false);
|
||||
const [selectedUserId, setSelectedUserId] = useState("");
|
||||
const [projectItems, setProjectItems] = useState<ProjectAccessItem[]>([]);
|
||||
const [selectedUserName, setSelectedUserName] = useState("");
|
||||
const [selectedUserMobile, setSelectedUserMobile] = useState("");
|
||||
const [loadingProjects, setLoadingProjects] = useState(false);
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
const [selectedClientId, setSelectedClientId] = useState("");
|
||||
const [selectedProjectIds, setSelectedProjectIds] = useState<string[]>([]);
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
|
||||
const manageableMembers = useMemo(
|
||||
() => members.filter((member) => member.is_active && MANAGEABLE_ROLES.has(member.role)),
|
||||
[members],
|
||||
);
|
||||
|
||||
const clientOptions = useMemo(() => {
|
||||
const map = new Map<string, string>();
|
||||
projectItems.forEach((item) => {
|
||||
if (item.client) {
|
||||
map.set(item.client.id, item.client.name);
|
||||
}
|
||||
});
|
||||
return Array.from(map.entries()).map(([id, name]) => ({ id, name }));
|
||||
}, [projectItems]);
|
||||
|
||||
const visibleProjects = useMemo(() => {
|
||||
const normalizedSearch = searchQuery.trim().toLowerCase();
|
||||
return projectItems.filter((item) => {
|
||||
const matchesClient = !selectedClientId || item.client?.id === selectedClientId;
|
||||
const matchesSearch =
|
||||
!normalizedSearch ||
|
||||
item.name.toLowerCase().includes(normalizedSearch) ||
|
||||
item.client?.name.toLowerCase().includes(normalizedSearch);
|
||||
return matchesClient && matchesSearch;
|
||||
});
|
||||
}, [projectItems, searchQuery, selectedClientId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isOpen) {
|
||||
setSearchQuery("");
|
||||
setSelectedClientId("");
|
||||
setSelectedProjectIds([]);
|
||||
return;
|
||||
}
|
||||
|
||||
const loadMembers = async () => {
|
||||
setLoadingMembers(true);
|
||||
try {
|
||||
const response = await fetchWorkspaceMemberships({ workspace: workspaceId, limit: 200, offset: 0 });
|
||||
setMembers(response.results || []);
|
||||
} catch {
|
||||
toast.error(labels.loadError);
|
||||
setMembers([]);
|
||||
} finally {
|
||||
setLoadingMembers(false);
|
||||
}
|
||||
};
|
||||
|
||||
void loadMembers();
|
||||
}, [isOpen, labels.loadError, workspaceId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!manageableMembers.length) {
|
||||
setSelectedUserId("");
|
||||
return;
|
||||
}
|
||||
if (!manageableMembers.some((member) => member.user.id === selectedUserId)) {
|
||||
setSelectedUserId(manageableMembers[0].user.id);
|
||||
}
|
||||
}, [manageableMembers, selectedUserId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isOpen || !selectedUserId) {
|
||||
setProjectItems([]);
|
||||
return;
|
||||
}
|
||||
|
||||
const loadAccessState = async () => {
|
||||
setLoadingProjects(true);
|
||||
try {
|
||||
const response = await getProjectAccessState(workspaceId, selectedUserId);
|
||||
setProjectItems(response.items);
|
||||
setSelectedUserName(response.user.name);
|
||||
setSelectedUserMobile(response.user.mobile);
|
||||
setSelectedProjectIds([]);
|
||||
} catch {
|
||||
toast.error(labels.loadError);
|
||||
setProjectItems([]);
|
||||
} finally {
|
||||
setLoadingProjects(false);
|
||||
}
|
||||
};
|
||||
|
||||
void loadAccessState();
|
||||
}, [isOpen, labels.loadError, selectedUserId, workspaceId]);
|
||||
|
||||
const toggleProjectSelection = (projectId: string) => {
|
||||
setSelectedProjectIds((current) =>
|
||||
current.includes(projectId)
|
||||
? current.filter((id) => id !== projectId)
|
||||
: [...current, projectId],
|
||||
);
|
||||
};
|
||||
|
||||
const handleSelectAllVisible = () => {
|
||||
const visibleIds = visibleProjects.map((item) => item.id);
|
||||
setSelectedProjectIds((current) => Array.from(new Set([...current, ...visibleIds])));
|
||||
};
|
||||
|
||||
const handleSelectClientProjects = () => {
|
||||
if (!selectedClientId) return;
|
||||
const clientProjectIds = visibleProjects
|
||||
.filter((item) => item.client?.id === selectedClientId)
|
||||
.map((item) => item.id);
|
||||
setSelectedProjectIds((current) => Array.from(new Set([...current, ...clientProjectIds])));
|
||||
};
|
||||
|
||||
const refreshState = async () => {
|
||||
if (!selectedUserId) return;
|
||||
const response = await getProjectAccessState(workspaceId, selectedUserId);
|
||||
setProjectItems(response.items);
|
||||
setSelectedProjectIds([]);
|
||||
onApplied();
|
||||
};
|
||||
|
||||
const handleMutation = async (mode: "grant" | "revoke") => {
|
||||
if (!selectedUserId || !selectedProjectIds.length) return;
|
||||
setIsSaving(true);
|
||||
try {
|
||||
if (mode === "grant") {
|
||||
await grantProjectAccess(workspaceId, selectedUserId, selectedProjectIds);
|
||||
toast.success(labels.accessGranted);
|
||||
} else {
|
||||
await revokeProjectAccess(workspaceId, selectedUserId, selectedProjectIds);
|
||||
toast.success(labels.accessRevoked);
|
||||
}
|
||||
await refreshState();
|
||||
} catch {
|
||||
toast.error(labels.saveError);
|
||||
} finally {
|
||||
setIsSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal
|
||||
isOpen={isOpen}
|
||||
onClose={onClose}
|
||||
title={labels.title}
|
||||
maxWidth="max-w-6xl"
|
||||
footer={
|
||||
<Button variant="secondary" onClick={onClose}>
|
||||
{labels.close}
|
||||
</Button>
|
||||
}
|
||||
>
|
||||
<div className="space-y-4">
|
||||
<p className="text-sm text-slate-600 dark:text-slate-400">{labels.description}</p>
|
||||
|
||||
<div className="grid gap-4 lg:grid-cols-[280px_minmax(0,1fr)]">
|
||||
<div className="rounded-2xl border border-slate-200 bg-slate-50/80 p-4 dark:border-slate-800 dark:bg-slate-950/60">
|
||||
<label className="mb-2 block text-sm font-medium text-slate-700 dark:text-slate-300">
|
||||
{labels.member}
|
||||
</label>
|
||||
<select
|
||||
value={selectedUserId}
|
||||
onChange={(event) => setSelectedUserId(event.target.value)}
|
||||
className="h-11 w-full rounded-xl border border-slate-200 bg-white px-3 text-sm text-slate-900 outline-none transition focus:border-sky-400 focus:ring-2 focus:ring-sky-500/20 dark:border-slate-700 dark:bg-slate-900 dark:text-white"
|
||||
>
|
||||
{manageableMembers.map((member) => (
|
||||
<option key={member.id} value={member.user.id}>
|
||||
{getMemberName(member)} - {member.user.mobile}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
|
||||
<div className="mt-4 rounded-xl border border-slate-200 bg-white p-3 text-sm dark:border-slate-700 dark:bg-slate-900">
|
||||
<div className="font-medium text-slate-900 dark:text-slate-100">{selectedUserName || "-"}</div>
|
||||
<div className="mt-1 text-slate-500 dark:text-slate-400">{selectedUserMobile || "-"}</div>
|
||||
</div>
|
||||
|
||||
{loadingMembers ? (
|
||||
<div className="mt-4 text-sm text-slate-500 dark:text-slate-400">{labels.loading}</div>
|
||||
) : manageableMembers.length === 0 ? (
|
||||
<div className="mt-4 text-sm text-slate-500 dark:text-slate-400">{labels.noMembers}</div>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div className="grid gap-3 lg:grid-cols-[minmax(0,1fr)_220px]">
|
||||
<Input
|
||||
value={searchQuery}
|
||||
onChange={(event) => setSearchQuery(event.target.value)}
|
||||
placeholder={labels.searchPlaceholder}
|
||||
/>
|
||||
<select
|
||||
value={selectedClientId}
|
||||
onChange={(event) => setSelectedClientId(event.target.value)}
|
||||
className="h-11 rounded-xl border border-slate-200 bg-white px-3 text-sm text-slate-900 outline-none transition focus:border-sky-400 focus:ring-2 focus:ring-sky-500/20 dark:border-slate-700 dark:bg-slate-900 dark:text-white"
|
||||
>
|
||||
<option value="">{labels.allClients}</option>
|
||||
{clientOptions.map((client) => (
|
||||
<option key={client.id} value={client.id}>
|
||||
{client.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button type="button" variant="secondary" onClick={handleSelectAllVisible} disabled={!visibleProjects.length}>
|
||||
<CheckSquare className="me-2 h-4 w-4" />
|
||||
{labels.selectAllVisible}
|
||||
</Button>
|
||||
<Button type="button" variant="secondary" onClick={() => setSelectedProjectIds([])} disabled={!selectedProjectIds.length}>
|
||||
<Square className="me-2 h-4 w-4" />
|
||||
{labels.clearSelection}
|
||||
</Button>
|
||||
<Button type="button" variant="secondary" onClick={handleSelectClientProjects} disabled={!selectedClientId}>
|
||||
<Filter className="me-2 h-4 w-4" />
|
||||
{labels.selectClientProjects}
|
||||
</Button>
|
||||
<Button type="button" onClick={() => void handleMutation("grant")} disabled={!selectedProjectIds.length || isSaving}>
|
||||
{labels.grantSelected}
|
||||
</Button>
|
||||
<Button type="button" variant="destructive" onClick={() => void handleMutation("revoke")} disabled={!selectedProjectIds.length || isSaving}>
|
||||
{labels.revokeSelected}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="rounded-2xl border border-slate-200 bg-white dark:border-slate-800 dark:bg-slate-900">
|
||||
<div className="max-h-[480px] overflow-y-auto">
|
||||
{loadingProjects ? (
|
||||
<div className="p-4 text-sm text-slate-500 dark:text-slate-400">{labels.loading}</div>
|
||||
) : visibleProjects.length === 0 ? (
|
||||
<div className="p-4 text-sm text-slate-500 dark:text-slate-400">{labels.noProjects}</div>
|
||||
) : (
|
||||
<div className="divide-y divide-slate-200 dark:divide-slate-800">
|
||||
{visibleProjects.map((item) => {
|
||||
const isChecked = selectedProjectIds.includes(item.id);
|
||||
return (
|
||||
<label
|
||||
key={item.id}
|
||||
className="flex cursor-pointer items-start gap-3 px-4 py-3 transition hover:bg-slate-50 dark:hover:bg-slate-800/60"
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={isChecked}
|
||||
onChange={() => toggleProjectSelection(item.id)}
|
||||
className="mt-1 h-4 w-4 rounded border-slate-300 text-sky-600 focus:ring-sky-500"
|
||||
/>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<span className="font-medium text-slate-900 dark:text-slate-100">{item.name}</span>
|
||||
<span
|
||||
className={`inline-flex rounded-full px-2 py-1 text-xs font-medium ${
|
||||
item.has_access
|
||||
? "bg-emerald-100 text-emerald-700 dark:bg-emerald-500/15 dark:text-emerald-300"
|
||||
: "bg-slate-100 text-slate-600 dark:bg-slate-800 dark:text-slate-300"
|
||||
}`}
|
||||
>
|
||||
{item.has_access ? labels.accessOn : labels.accessOff}
|
||||
</span>
|
||||
</div>
|
||||
<div className="mt-1 text-sm text-slate-500 dark:text-slate-400">
|
||||
{labels.client}: {item.client?.name || labels.noClient}
|
||||
</div>
|
||||
{item.description ? (
|
||||
<div className="mt-1 text-sm text-slate-500 dark:text-slate-400">{item.description}</div>
|
||||
) : null}
|
||||
</div>
|
||||
</label>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -2,149 +2,118 @@ import {
|
||||
Bar,
|
||||
BarChart,
|
||||
CartesianGrid,
|
||||
Cell,
|
||||
Legend,
|
||||
ResponsiveContainer,
|
||||
Tooltip,
|
||||
XAxis,
|
||||
YAxis,
|
||||
} from "recharts";
|
||||
} from "recharts"
|
||||
|
||||
import type { ChartReportResponse, CurrencyTotal, ReportChartBucket } from "../../api/reports";
|
||||
import { useTranslation } from "../../hooks/useTranslation";
|
||||
import type { ChartReportResponse, ChartReportSeries, CurrencyTotal, ReportChartBucket } from "../../api/reports"
|
||||
import { useTranslation } from "../../hooks/useTranslation"
|
||||
|
||||
const FA_MONTHS = [
|
||||
"فروردین",
|
||||
"اردیبهشت",
|
||||
"خرداد",
|
||||
"تیر",
|
||||
"مرداد",
|
||||
"شهریور",
|
||||
"مهر",
|
||||
"آبان",
|
||||
"آذر",
|
||||
"دی",
|
||||
"بهمن",
|
||||
"اسفند",
|
||||
];
|
||||
const PERSIAN_DIGITS = "۰۱۲۳۴۵۶۷۸۹"
|
||||
const SERIES_PALETTE = ["#0ea5e9", "#f97316", "#10b981", "#8b5cf6", "#ef4444", "#eab308", "#14b8a6", "#3b82f6"]
|
||||
|
||||
const normalizeDigits = (value: string) =>
|
||||
value
|
||||
.replace(/[۰-۹]/g, (digit) => String("۰۱۲۳۴۵۶۷۸۹".indexOf(digit)))
|
||||
.replace(/[٠-٩]/g, (digit) => String("٠١٢٣٤٥٦٧٨٩".indexOf(digit)));
|
||||
type ChartRow = {
|
||||
bucket_key: string
|
||||
bucket_label: string
|
||||
tooltip_label: string
|
||||
[key: string]: string | number
|
||||
}
|
||||
|
||||
const toPersianDigits = (value: string) =>
|
||||
value.replace(/\d/g, (digit) => "۰۱۲۳۴۵۶۷۸۹"[Number(digit)] || digit);
|
||||
|
||||
const localizeDigits = (value: string, lang: "en" | "fa") => (lang === "fa" ? toPersianDigits(value) : value);
|
||||
const localizeDigits = (value: string, lang: "en" | "fa") =>
|
||||
lang === "fa" ? value.replace(/\d/g, (digit) => PERSIAN_DIGITS[Number(digit)] || digit) : value
|
||||
|
||||
const formatAmount = (value: string, lang: "en" | "fa") => {
|
||||
const trimmed = value.trim();
|
||||
if (!trimmed) return trimmed;
|
||||
const numeric = Number(trimmed.replace(/,/g, ""));
|
||||
if (Number.isNaN(numeric)) return localizeDigits(trimmed, lang);
|
||||
const numeric = Number(value.replace(/,/g, ""))
|
||||
if (Number.isNaN(numeric)) {
|
||||
return localizeDigits(value, lang)
|
||||
}
|
||||
|
||||
const [integerPart, fractionalPart] = trimmed.replace(/,/g, "").split(".");
|
||||
const grouped = Math.abs(Number(integerPart)).toLocaleString("en-US");
|
||||
const signed = trimmed.startsWith("-") ? `-${grouped}` : grouped;
|
||||
const normalized = fractionalPart ? `${signed}.${fractionalPart}` : signed;
|
||||
return localizeDigits(normalized, lang);
|
||||
};
|
||||
const [integerPart, fractionalPart] = value.replace(/,/g, "").split(".")
|
||||
const grouped = Math.abs(Number(integerPart)).toLocaleString("en-US")
|
||||
const signed = value.startsWith("-") ? `-${grouped}` : grouped
|
||||
const formatted = fractionalPart ? `${signed}.${fractionalPart}` : signed
|
||||
return localizeDigits(formatted, lang)
|
||||
}
|
||||
|
||||
const currencyLabel = (currency: string, lang: "en" | "fa") => {
|
||||
const normalized = currency.toUpperCase();
|
||||
if (lang !== "fa") return normalized;
|
||||
if (lang !== "fa") {
|
||||
return currency.toUpperCase()
|
||||
}
|
||||
|
||||
return (
|
||||
{
|
||||
USD: "دلار آمریکا",
|
||||
USD: "دلار",
|
||||
EUR: "یورو",
|
||||
GBP: "پوند",
|
||||
IRR: "ریال",
|
||||
IRT: "تومان",
|
||||
AED: "درهم",
|
||||
TRY: "لیر",
|
||||
}[normalized] || normalized
|
||||
);
|
||||
};
|
||||
}[currency.toUpperCase()] || currency.toUpperCase()
|
||||
)
|
||||
}
|
||||
|
||||
const formatMoneyTotals = (totals: CurrencyTotal[], lang: "en" | "fa") => {
|
||||
if (!totals.length) return "-";
|
||||
return totals.map((item) => `${formatAmount(item.amount, lang)} ${currencyLabel(item.currency, lang)}`).join(" | ");
|
||||
};
|
||||
if (!totals.length) {
|
||||
return "-"
|
||||
}
|
||||
|
||||
return totals.map((item) => `${formatAmount(item.amount, lang)} ${currencyLabel(item.currency, lang)}`).join(" | ")
|
||||
}
|
||||
|
||||
const formatSecondsTick = (value: number, lang: "en" | "fa") => {
|
||||
const hours = value / 3600;
|
||||
const rounded = hours >= 10 ? hours.toFixed(0) : hours.toFixed(1);
|
||||
return localizeDigits(rounded, lang);
|
||||
};
|
||||
const hours = value / 3600
|
||||
const rounded = hours >= 10 ? hours.toFixed(0) : hours.toFixed(1)
|
||||
return localizeDigits(rounded, lang)
|
||||
}
|
||||
|
||||
const parseIsoDate = (value: string) => {
|
||||
const [year, month, day] = value.split("-").map(Number);
|
||||
return new Date(year, (month || 1) - 1, day || 1);
|
||||
};
|
||||
const [year, month, day] = value.split("-").map(Number)
|
||||
return new Date(year, (month || 1) - 1, day || 1)
|
||||
}
|
||||
|
||||
const formatIsoDate = (value: Date) => {
|
||||
const year = value.getFullYear();
|
||||
const month = String(value.getMonth() + 1).padStart(2, "0");
|
||||
const day = String(value.getDate()).padStart(2, "0");
|
||||
return `${year}-${month}-${day}`;
|
||||
};
|
||||
const year = value.getFullYear()
|
||||
const month = String(value.getMonth() + 1).padStart(2, "0")
|
||||
const day = String(value.getDate()).padStart(2, "0")
|
||||
return `${year}-${month}-${day}`
|
||||
}
|
||||
|
||||
const monthKeyFromDate = (value: Date) => `${value.getFullYear()}-${String(value.getMonth() + 1).padStart(2, "0")}`;
|
||||
const monthKeyFromDate = (value: Date) => `${value.getFullYear()}-${String(value.getMonth() + 1).padStart(2, "0")}`
|
||||
|
||||
const getPersianDateParts = (value: Date) => {
|
||||
const parts = new Intl.DateTimeFormat("fa-IR-u-ca-persian", {
|
||||
year: "numeric",
|
||||
month: "numeric",
|
||||
day: "numeric",
|
||||
}).formatToParts(value);
|
||||
|
||||
return {
|
||||
year: Number(normalizeDigits(parts.find((part) => part.type === "year")?.value || "")),
|
||||
month: Number(normalizeDigits(parts.find((part) => part.type === "month")?.value || "")),
|
||||
day: Number(normalizeDigits(parts.find((part) => part.type === "day")?.value || "")),
|
||||
};
|
||||
};
|
||||
const getCalendarLocale = (lang: "en" | "fa") => (lang === "fa" ? "fa-IR-u-ca-persian" : "en-US")
|
||||
|
||||
const getDailyAxisLabel = (date: Date, lang: "en" | "fa", period: string) => {
|
||||
if (period === "this_week") {
|
||||
return new Intl.DateTimeFormat(lang === "fa" ? "fa-IR-u-ca-persian" : "en-US", {
|
||||
weekday: "short",
|
||||
}).format(date);
|
||||
return new Intl.DateTimeFormat(getCalendarLocale(lang), { weekday: "short" }).format(date)
|
||||
}
|
||||
|
||||
if (lang === "fa") {
|
||||
return toPersianDigits(String(getPersianDateParts(date).day));
|
||||
}
|
||||
return String(date.getDate());
|
||||
};
|
||||
return new Intl.DateTimeFormat(getCalendarLocale(lang), { day: "numeric" }).format(date)
|
||||
}
|
||||
|
||||
const getDailyTooltipLabel = (date: Date, lang: "en" | "fa") =>
|
||||
new Intl.DateTimeFormat(lang === "fa" ? "fa-IR-u-ca-persian" : "en-US", {
|
||||
new Intl.DateTimeFormat(getCalendarLocale(lang), {
|
||||
weekday: "long",
|
||||
month: "long",
|
||||
day: "numeric",
|
||||
}).format(date);
|
||||
}).format(date)
|
||||
|
||||
const getMonthlyAxisLabel = (bucketKey: string, lang: "en" | "fa") => {
|
||||
if (lang === "fa") {
|
||||
const [, month] = bucketKey.split("-").map(Number);
|
||||
return FA_MONTHS[(month || 1) - 1] || bucketKey;
|
||||
}
|
||||
const [year, month] = bucketKey.split("-").map(Number);
|
||||
return new Intl.DateTimeFormat("en-US", { month: "short" }).format(new Date(year, (month || 1) - 1, 1));
|
||||
};
|
||||
const [year, month] = bucketKey.split("-").map(Number)
|
||||
return new Intl.DateTimeFormat(getCalendarLocale(lang), { month: "short" }).format(
|
||||
new Date(year, (month || 1) - 1, 1),
|
||||
)
|
||||
}
|
||||
|
||||
const getMonthlyTooltipLabel = (bucketKey: string, lang: "en" | "fa") => {
|
||||
if (lang === "fa") {
|
||||
const [year, month] = bucketKey.split("-").map(Number);
|
||||
const monthName = FA_MONTHS[(month || 1) - 1] || bucketKey;
|
||||
return `${monthName} ${toPersianDigits(String(year))}`;
|
||||
}
|
||||
const [year, month] = bucketKey.split("-").map(Number);
|
||||
return new Intl.DateTimeFormat("en-US", { month: "long", year: "numeric" }).format(
|
||||
const [year, month] = bucketKey.split("-").map(Number)
|
||||
return new Intl.DateTimeFormat(getCalendarLocale(lang), { month: "long", year: "numeric" }).format(
|
||||
new Date(year, (month || 1) - 1, 1),
|
||||
);
|
||||
};
|
||||
)
|
||||
}
|
||||
|
||||
const buildDailyBuckets = (
|
||||
fromDate: string,
|
||||
@@ -153,14 +122,14 @@ const buildDailyBuckets = (
|
||||
lang: "en" | "fa",
|
||||
period: string,
|
||||
) => {
|
||||
const map = new Map(existing.map((bucket) => [bucket.bucket_key, bucket]));
|
||||
const result: ReportChartBucket[] = [];
|
||||
const cursor = parseIsoDate(fromDate);
|
||||
const limit = parseIsoDate(toDate);
|
||||
const map = new Map(existing.map((bucket) => [bucket.bucket_key, bucket]))
|
||||
const result: ReportChartBucket[] = []
|
||||
const cursor = parseIsoDate(fromDate)
|
||||
const limit = parseIsoDate(toDate)
|
||||
|
||||
while (cursor.getTime() <= limit.getTime()) {
|
||||
const key = formatIsoDate(cursor);
|
||||
const existingBucket = map.get(key);
|
||||
const key = formatIsoDate(cursor)
|
||||
const existingBucket = map.get(key)
|
||||
result.push(
|
||||
existingBucket ?? {
|
||||
bucket_key: key,
|
||||
@@ -168,59 +137,27 @@ const buildDailyBuckets = (
|
||||
total_seconds: 0,
|
||||
total_duration: "00:00:00",
|
||||
},
|
||||
);
|
||||
cursor.setDate(cursor.getDate() + 1);
|
||||
)
|
||||
cursor.setDate(cursor.getDate() + 1)
|
||||
}
|
||||
|
||||
return result.map((bucket) => ({
|
||||
...bucket,
|
||||
bucket_label: getDailyAxisLabel(parseIsoDate(bucket.bucket_key), lang, period),
|
||||
}));
|
||||
};
|
||||
}))
|
||||
}
|
||||
|
||||
const buildMonthlyBuckets = (fromDate: string, toDate: string, existing: ReportChartBucket[], lang: "en" | "fa") => {
|
||||
const map = new Map(existing.map((bucket) => [bucket.bucket_key, bucket]));
|
||||
|
||||
if (lang === "fa") {
|
||||
const result: ReportChartBucket[] = [];
|
||||
const start = getPersianDateParts(parseIsoDate(fromDate));
|
||||
const end = getPersianDateParts(parseIsoDate(toDate));
|
||||
|
||||
let year = start.year;
|
||||
let month = start.month;
|
||||
while (year < end.year || (year === end.year && month <= end.month)) {
|
||||
const key = `${year}-${String(month).padStart(2, "0")}`;
|
||||
const existingBucket = map.get(key);
|
||||
result.push(
|
||||
existingBucket ?? {
|
||||
bucket_key: key,
|
||||
bucket_label: getMonthlyAxisLabel(key, lang),
|
||||
total_seconds: 0,
|
||||
total_duration: "00:00:00",
|
||||
},
|
||||
);
|
||||
month += 1;
|
||||
if (month > 12) {
|
||||
month = 1;
|
||||
year += 1;
|
||||
}
|
||||
}
|
||||
|
||||
return result.map((bucket) => ({
|
||||
...bucket,
|
||||
bucket_label: getMonthlyAxisLabel(bucket.bucket_key, lang),
|
||||
}));
|
||||
}
|
||||
|
||||
const result: ReportChartBucket[] = [];
|
||||
const start = parseIsoDate(fromDate);
|
||||
const end = parseIsoDate(toDate);
|
||||
const cursor = new Date(start.getFullYear(), start.getMonth(), 1);
|
||||
const limit = new Date(end.getFullYear(), end.getMonth(), 1);
|
||||
const map = new Map(existing.map((bucket) => [bucket.bucket_key, bucket]))
|
||||
const result: ReportChartBucket[] = []
|
||||
const start = parseIsoDate(fromDate)
|
||||
const end = parseIsoDate(toDate)
|
||||
const cursor = new Date(start.getFullYear(), start.getMonth(), 1)
|
||||
const limit = new Date(end.getFullYear(), end.getMonth(), 1)
|
||||
|
||||
while (cursor.getTime() <= limit.getTime()) {
|
||||
const key = monthKeyFromDate(cursor);
|
||||
const existingBucket = map.get(key);
|
||||
const key = monthKeyFromDate(cursor)
|
||||
const existingBucket = map.get(key)
|
||||
result.push(
|
||||
existingBucket ?? {
|
||||
bucket_key: key,
|
||||
@@ -228,77 +165,115 @@ const buildMonthlyBuckets = (fromDate: string, toDate: string, existing: ReportC
|
||||
total_seconds: 0,
|
||||
total_duration: "00:00:00",
|
||||
},
|
||||
);
|
||||
cursor.setMonth(cursor.getMonth() + 1);
|
||||
)
|
||||
cursor.setMonth(cursor.getMonth() + 1)
|
||||
}
|
||||
|
||||
return result.map((bucket) => ({
|
||||
...bucket,
|
||||
bucket_label: getMonthlyAxisLabel(bucket.bucket_key, lang),
|
||||
}));
|
||||
};
|
||||
}))
|
||||
}
|
||||
|
||||
const formatTooltipLabel = (payload: ReportChartBucket | undefined, lang: "en" | "fa", period: string) => {
|
||||
if (!payload) return "";
|
||||
const useMonth = period === "this_year" || period === "half_year_first" || period === "half_year_second";
|
||||
if (useMonth) {
|
||||
return getMonthlyTooltipLabel(payload.bucket_key, lang);
|
||||
}
|
||||
return getDailyTooltipLabel(parseIsoDate(payload.bucket_key), lang);
|
||||
};
|
||||
const buildSeriesBuckets = (
|
||||
series: ChartReportSeries,
|
||||
data: ChartReportResponse,
|
||||
lang: "en" | "fa",
|
||||
useMonthlyBuckets: boolean,
|
||||
) =>
|
||||
useMonthlyBuckets
|
||||
? buildMonthlyBuckets(data.scope.from_date, data.scope.to_date, series.buckets, lang)
|
||||
: buildDailyBuckets(data.scope.from_date, data.scope.to_date, series.buckets, lang, data.scope.period)
|
||||
|
||||
const createSeriesKey = (series: ChartReportSeries, index: number) => series.user?.id ?? `series_${index}`
|
||||
|
||||
const buildChartRows = (data: ChartReportResponse, lang: "en" | "fa") => {
|
||||
const useMonthlyBuckets =
|
||||
data.scope.period === "this_year" ||
|
||||
data.scope.period === "half_year_first" ||
|
||||
data.scope.period === "half_year_second"
|
||||
|
||||
const normalizedSeries = data.series.map((series) => buildSeriesBuckets(series, data, lang, useMonthlyBuckets))
|
||||
const baseBuckets = normalizedSeries[0] ?? []
|
||||
|
||||
const rows: ChartRow[] = baseBuckets.map((bucket, bucketIndex) => {
|
||||
const tooltipLabel = useMonthlyBuckets
|
||||
? getMonthlyTooltipLabel(bucket.bucket_key, lang)
|
||||
: getDailyTooltipLabel(parseIsoDate(bucket.bucket_key), lang)
|
||||
|
||||
const row: ChartRow = {
|
||||
bucket_key: bucket.bucket_key,
|
||||
bucket_label: bucket.bucket_label,
|
||||
tooltip_label: tooltipLabel,
|
||||
}
|
||||
|
||||
data.series.forEach((series, seriesIndex) => {
|
||||
const seriesKey = createSeriesKey(series, seriesIndex)
|
||||
row[seriesKey] = normalizedSeries[seriesIndex]?.[bucketIndex]?.total_seconds ?? 0
|
||||
})
|
||||
|
||||
return row
|
||||
})
|
||||
|
||||
return { rows, useMonthlyBuckets }
|
||||
}
|
||||
|
||||
function ChartTooltip({
|
||||
active,
|
||||
payload,
|
||||
label,
|
||||
lang,
|
||||
totalSecondsLabel,
|
||||
totalHoursLabel,
|
||||
}: {
|
||||
active?: boolean;
|
||||
payload?: ReadonlyArray<{ value?: unknown; payload?: ReportChartBucket }>;
|
||||
label: string;
|
||||
lang: "en" | "fa";
|
||||
totalSecondsLabel: string;
|
||||
active?: boolean
|
||||
payload?: ReadonlyArray<{ color?: string; dataKey?: string | number | ((obj: unknown) => unknown); name?: string | number; value?: unknown }>
|
||||
label: string
|
||||
lang: "en" | "fa"
|
||||
totalHoursLabel: string
|
||||
}) {
|
||||
if (!active || !payload?.length) return null;
|
||||
|
||||
const point = payload[0];
|
||||
const seconds = Number(point.value || 0);
|
||||
const hours = seconds / 3600;
|
||||
if (!active || !payload?.length) {
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="rounded-2xl border border-slate-200 bg-white/95 px-3 py-2 shadow-xl shadow-slate-200/60 backdrop-blur dark:border-slate-700 dark:bg-slate-900/95 dark:shadow-black/30">
|
||||
<div className="text-xs font-semibold text-slate-500 dark:text-slate-400">{label}</div>
|
||||
<div className="mt-1 text-sm font-semibold text-slate-900 dark:text-white">
|
||||
{totalSecondsLabel}: {localizeDigits(hours.toFixed(hours >= 10 ? 0 : 1), lang)}
|
||||
<div className="mt-2 space-y-1">
|
||||
{payload.map((item) => {
|
||||
const seconds = Number(item.value || 0)
|
||||
const hours = seconds / 3600
|
||||
return (
|
||||
<div key={String(item.dataKey)} className="flex items-center gap-2 text-sm text-slate-900 dark:text-white">
|
||||
<span className="h-2.5 w-2.5 rounded-full" style={{ backgroundColor: item.color }} />
|
||||
<span className="font-medium">{item.name}</span>
|
||||
<span className="text-slate-500 dark:text-slate-400">
|
||||
{totalHoursLabel}: {localizeDigits(hours.toFixed(hours >= 10 ? 0 : 1), lang)}
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
export function ReportsChartPanel({
|
||||
data,
|
||||
labels,
|
||||
}: {
|
||||
data: ChartReportResponse | null;
|
||||
labels: Record<string, string>;
|
||||
data: ChartReportResponse | null
|
||||
labels: Record<string, string>
|
||||
}) {
|
||||
const { lang } = useTranslation();
|
||||
const { lang } = useTranslation()
|
||||
|
||||
if (!data) return null;
|
||||
|
||||
const useMonthlyBuckets =
|
||||
data.scope.period === "this_year" ||
|
||||
data.scope.period === "half_year_first" ||
|
||||
data.scope.period === "half_year_second";
|
||||
|
||||
const buckets = useMonthlyBuckets
|
||||
? buildMonthlyBuckets(data.scope.from_date, data.scope.to_date, data.buckets, lang)
|
||||
: buildDailyBuckets(data.scope.from_date, data.scope.to_date, data.buckets, lang, data.scope.period);
|
||||
|
||||
const chartMinWidth = Math.max(640, buckets.length * (useMonthlyBuckets ? 92 : 44));
|
||||
const interval = useMonthlyBuckets ? 0 : buckets.length > 20 ? Math.ceil(buckets.length / 10) - 1 : 0;
|
||||
if (!data || data.series.length === 0) {
|
||||
return null
|
||||
}
|
||||
|
||||
const { rows, useMonthlyBuckets } = buildChartRows(data, lang)
|
||||
const interval = useMonthlyBuckets ? 0 : rows.length > 20 ? Math.ceil(rows.length / 10) - 1 : 0
|
||||
const chartMinWidth = Math.max(640, rows.length * (useMonthlyBuckets ? 110 : 52))
|
||||
const isMultiSeries = data.series.length > 1
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="grid grid-cols-2 gap-3 xl:grid-cols-4">
|
||||
@@ -331,15 +306,13 @@ export function ReportsChartPanel({
|
||||
<div className="rounded-3xl border border-slate-200 bg-white p-4 shadow-sm dark:border-slate-800 dark:bg-slate-900 sm:p-5">
|
||||
<div className="mb-4 flex items-center justify-between gap-3">
|
||||
<div className="text-sm font-semibold text-slate-900 dark:text-white">{labels.chart}</div>
|
||||
<div className="text-xs text-slate-500 dark:text-slate-400">
|
||||
{localizeDigits(`${buckets.length}`, lang)}
|
||||
</div>
|
||||
<div className="text-xs text-slate-500 dark:text-slate-400">{localizeDigits(`${rows.length}`, lang)}</div>
|
||||
</div>
|
||||
|
||||
<div className="overflow-x-auto pb-2">
|
||||
<div className="h-[300px] min-w-full sm:h-[360px]" style={{ minWidth: `${chartMinWidth}px` }}>
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<BarChart data={buckets} barCategoryGap={useMonthlyBuckets ? "26%" : "18%"} margin={{ top: 8, right: 18, bottom: 16, left: 10 }}>
|
||||
<BarChart data={rows} barCategoryGap={useMonthlyBuckets ? "26%" : "18%"} margin={{ top: 8, right: 18, bottom: 16, left: 10 }}>
|
||||
<CartesianGrid strokeDasharray="4 6" stroke="currentColor" className="text-slate-200 dark:text-slate-800" vertical={false} />
|
||||
<XAxis
|
||||
dataKey="bucket_label"
|
||||
@@ -360,29 +333,42 @@ export function ReportsChartPanel({
|
||||
/>
|
||||
<Tooltip
|
||||
cursor={{ fill: "rgba(14,165,233,0.08)" }}
|
||||
content={({ active, payload }) => (
|
||||
content={({ active, payload, label }) => (
|
||||
<ChartTooltip
|
||||
active={active}
|
||||
payload={payload}
|
||||
label={formatTooltipLabel(payload?.[0]?.payload as ReportChartBucket | undefined, lang, data.scope.period)}
|
||||
label={typeof label === "string" ? label : rows[0]?.tooltip_label || ""}
|
||||
lang={lang}
|
||||
totalSecondsLabel={labels.totalHours}
|
||||
totalHoursLabel={labels.totalHours}
|
||||
/>
|
||||
)}
|
||||
labelFormatter={(_, payload) => String(payload?.[0]?.payload?.tooltip_label || "")}
|
||||
/>
|
||||
<Bar dataKey="total_seconds" radius={[12, 12, 4, 4]} maxBarSize={useMonthlyBuckets ? 40 : 22}>
|
||||
{buckets.map((bucket) => (
|
||||
<Cell
|
||||
key={bucket.bucket_key}
|
||||
fill={bucket.total_seconds > 0 ? "#0ea5e9" : "#cbd5e1"}
|
||||
{isMultiSeries ? (
|
||||
<Legend
|
||||
verticalAlign="top"
|
||||
align="left"
|
||||
wrapperStyle={{ paddingBottom: "16px", fontSize: "12px" }}
|
||||
/>
|
||||
) : null}
|
||||
{data.series.map((series, index) => {
|
||||
const dataKey = createSeriesKey(series, index)
|
||||
return (
|
||||
<Bar
|
||||
key={dataKey}
|
||||
dataKey={dataKey}
|
||||
name={series.user?.name || labels.totalHours}
|
||||
fill={SERIES_PALETTE[index % SERIES_PALETTE.length]}
|
||||
radius={[12, 12, 4, 4]}
|
||||
maxBarSize={useMonthlyBuckets ? 36 : 22}
|
||||
/>
|
||||
))}
|
||||
</Bar>
|
||||
)
|
||||
})}
|
||||
</BarChart>
|
||||
</ResponsiveContainer>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { Fragment } from "react";
|
||||
import { Fragment, useState } from "react";
|
||||
import { ChevronDown, ChevronUp, FileSpreadsheet, FileText } from "lucide-react";
|
||||
|
||||
import type { BreakdownRow, DayDetailsResponse, TableReportResponse } from "../../api/reports";
|
||||
import type { BreakdownRow, DayDetailsResponse, TableReportResponse, UserReportSummary } from "../../api/reports";
|
||||
import { Modal } from "../Modal";
|
||||
import { useTranslation } from "../../hooks/useTranslation";
|
||||
|
||||
const toPersianDigits = (value: string) =>
|
||||
@@ -66,6 +67,129 @@ const formatDisplayDateTime = (value: string, lang: "en" | "fa") => {
|
||||
}).format(parsed);
|
||||
};
|
||||
|
||||
function PercentageBreakdownSection({
|
||||
title,
|
||||
rows,
|
||||
lang,
|
||||
emptyLabel,
|
||||
}: {
|
||||
title: string;
|
||||
rows: { id: string; name: string; percentage: string }[];
|
||||
lang: "en" | "fa";
|
||||
emptyLabel: string;
|
||||
}) {
|
||||
return (
|
||||
<section className="space-y-3">
|
||||
<div className="text-sm font-semibold text-slate-900 dark:text-white">{title}</div>
|
||||
{rows.length ? (
|
||||
<div className="space-y-3">
|
||||
{rows.map((row) => {
|
||||
const width = Math.max(Math.min(Number(row.percentage) || 0, 100), 0);
|
||||
return (
|
||||
<div key={row.id} className="rounded-2xl border border-slate-200 bg-slate-50/80 p-3 dark:border-slate-800 dark:bg-slate-950/70">
|
||||
<div className="mb-2 flex items-center justify-between gap-3 text-sm">
|
||||
<span className="font-medium text-slate-900 dark:text-slate-100">{row.name}</span>
|
||||
<span className="text-slate-500 dark:text-slate-400">{formatAmount(row.percentage, lang)}%</span>
|
||||
</div>
|
||||
<div className="h-2 overflow-hidden rounded-full bg-slate-200 dark:bg-slate-800">
|
||||
<div className="h-full rounded-full bg-sky-500" style={{ width: `${width}%` }} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
) : (
|
||||
<div className="rounded-2xl border border-dashed border-slate-200 px-4 py-5 text-sm text-slate-500 dark:border-slate-800 dark:text-slate-400">
|
||||
{emptyLabel}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function UserSummaryDetailsModal({
|
||||
summary,
|
||||
labels,
|
||||
lang,
|
||||
onClose,
|
||||
}: {
|
||||
summary: UserReportSummary | null;
|
||||
labels: Record<string, string>;
|
||||
lang: "en" | "fa";
|
||||
onClose: () => void;
|
||||
}) {
|
||||
if (!summary) return null;
|
||||
|
||||
return (
|
||||
<Modal
|
||||
isOpen
|
||||
onClose={onClose}
|
||||
title={labels.userSummaryDetailsTitle.replace("{name}", summary.user.name)}
|
||||
description={labels.userSummaryDetailsDescription}
|
||||
maxWidth="max-w-4xl"
|
||||
>
|
||||
<div className="space-y-6">
|
||||
<div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-4">
|
||||
<div className="rounded-2xl border border-slate-200 bg-slate-50/80 p-4 dark:border-slate-800 dark:bg-slate-950/70">
|
||||
<div className="mb-1 text-xs uppercase tracking-[0.12em] text-slate-400 dark:text-slate-500">{labels.mobile}</div>
|
||||
<div className="text-sm font-semibold text-slate-900 dark:text-slate-100">{localizeDigits(summary.user.mobile, lang)}</div>
|
||||
</div>
|
||||
<div className="rounded-2xl border border-slate-200 bg-slate-50/80 p-4 dark:border-slate-800 dark:bg-slate-950/70">
|
||||
<div className="mb-1 text-xs uppercase tracking-[0.12em] text-slate-400 dark:text-slate-500">{labels.workingHours}</div>
|
||||
<div className="text-sm font-semibold text-slate-900 dark:text-slate-100">{localizeDigits(summary.billable_duration, lang)}</div>
|
||||
</div>
|
||||
<div className="rounded-2xl border border-slate-200 bg-slate-50/80 p-4 dark:border-slate-800 dark:bg-slate-950/70">
|
||||
<div className="mb-1 text-xs uppercase tracking-[0.12em] text-slate-400 dark:text-slate-500">{labels.nonWorkingHours}</div>
|
||||
<div className="text-sm font-semibold text-slate-900 dark:text-slate-100">{localizeDigits(summary.non_billable_duration, lang)}</div>
|
||||
</div>
|
||||
<div className="rounded-2xl border border-slate-200 bg-slate-50/80 p-4 dark:border-slate-800 dark:bg-slate-950/70">
|
||||
<div className="mb-1 text-xs uppercase tracking-[0.12em] text-slate-400 dark:text-slate-500">{labels.totalIncome}</div>
|
||||
<div className="text-sm font-semibold text-slate-900 dark:text-slate-100">{formatMoneyTotals(summary.income_totals, lang)}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<section className="space-y-3">
|
||||
<div className="text-sm font-semibold text-slate-900 dark:text-white">{labels.rateHistory}</div>
|
||||
<div className="overflow-x-auto rounded-2xl border border-slate-200 dark:border-slate-800">
|
||||
<table className="min-w-full text-sm">
|
||||
<thead>
|
||||
<tr className="border-b border-slate-200 bg-slate-50 text-slate-500 dark:border-slate-800 dark:bg-slate-950/70 dark:text-slate-400">
|
||||
<th className="px-4 py-3 text-start font-medium">{labels.hourlyRate}</th>
|
||||
<th className="px-4 py-3 text-start font-medium">{labels.fromDate}</th>
|
||||
<th className="px-4 py-3 text-start font-medium">{labels.toDate}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{summary.rate_periods.length ? (
|
||||
summary.rate_periods.map((row, index) => (
|
||||
<tr key={`${row.amount}-${row.currency}-${row.from_date}-${index}`} className="border-b border-slate-100 last:border-b-0 dark:border-slate-800/80">
|
||||
<td className="px-4 py-3 text-slate-700 dark:text-slate-300">{`${formatAmount(row.amount, lang)} ${currencyLabel(row.currency, lang)}`}</td>
|
||||
<td className="px-4 py-3 text-slate-700 dark:text-slate-300">{formatDisplayDate(row.from_date, lang)}</td>
|
||||
<td className="px-4 py-3 text-slate-700 dark:text-slate-300">{formatDisplayDate(row.to_date, lang)}</td>
|
||||
</tr>
|
||||
))
|
||||
) : (
|
||||
<tr>
|
||||
<td colSpan={3} className="px-4 py-5 text-center text-slate-500 dark:text-slate-400">
|
||||
{labels.noData}
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<div className="grid gap-4 xl:grid-cols-3">
|
||||
<PercentageBreakdownSection title={labels.projectPercentages} rows={summary.project_percentages} lang={lang} emptyLabel={labels.noData} />
|
||||
<PercentageBreakdownSection title={labels.clientPercentages} rows={summary.client_percentages} lang={lang} emptyLabel={labels.noData} />
|
||||
<PercentageBreakdownSection title={labels.tagPercentages} rows={summary.tag_percentages} lang={lang} emptyLabel={labels.noData} />
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
function BreakdownCards({
|
||||
title,
|
||||
rows,
|
||||
@@ -129,6 +253,57 @@ function BreakdownCards({
|
||||
);
|
||||
}
|
||||
|
||||
function UserSummarySection({
|
||||
rows,
|
||||
labels,
|
||||
lang,
|
||||
}: {
|
||||
rows: UserReportSummary[];
|
||||
labels: Record<string, string>;
|
||||
lang: "en" | "fa";
|
||||
}) {
|
||||
const [selectedSummary, setSelectedSummary] = useState<UserReportSummary | null>(null);
|
||||
|
||||
if (!rows.length) return null;
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="rounded-3xl border border-slate-200 bg-white p-4 shadow-sm dark:border-slate-800 dark:bg-slate-900 sm:p-5">
|
||||
<div className="mb-4 text-sm font-semibold text-slate-900 dark:text-white">{labels.userSummaryTitle}</div>
|
||||
<div className="overflow-x-auto">
|
||||
<table className="min-w-[720px] w-full text-sm">
|
||||
<thead>
|
||||
<tr className="border-b border-slate-200 text-slate-500 dark:border-slate-800 dark:text-slate-400">
|
||||
<th className="px-3 py-3 text-start font-medium">{labels.name}</th>
|
||||
<th className="px-3 py-3 text-start font-medium">{labels.mobile}</th>
|
||||
<th className="px-3 py-3 text-start font-medium">{labels.workingHours}</th>
|
||||
<th className="px-3 py-3 text-start font-medium">{labels.nonWorkingHours}</th>
|
||||
<th className="px-3 py-3 text-start font-medium">{labels.totalIncome}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.map((row) => (
|
||||
<tr
|
||||
key={row.user.id}
|
||||
className="cursor-pointer border-b border-slate-100 transition hover:bg-slate-50 last:border-b-0 dark:border-slate-800/80 dark:hover:bg-slate-800/40"
|
||||
onClick={() => setSelectedSummary(row)}
|
||||
>
|
||||
<td className="px-3 py-3 font-medium text-slate-900 dark:text-slate-100">{row.user.name}</td>
|
||||
<td className="px-3 py-3 text-slate-700 dark:text-slate-300">{localizeDigits(row.user.mobile, lang)}</td>
|
||||
<td className="px-3 py-3 text-slate-700 dark:text-slate-300">{localizeDigits(row.billable_duration, lang)}</td>
|
||||
<td className="px-3 py-3 text-slate-700 dark:text-slate-300">{localizeDigits(row.non_billable_duration, lang)}</td>
|
||||
<td className="px-3 py-3 text-slate-700 dark:text-slate-300">{formatMoneyTotals(row.income_totals, lang)}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
<UserSummaryDetailsModal summary={selectedSummary} labels={labels} lang={lang} onClose={() => setSelectedSummary(null)} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function ReportsTablePanel({
|
||||
data,
|
||||
dayDetails,
|
||||
@@ -157,6 +332,7 @@ export function ReportsTablePanel({
|
||||
const clients = Array.isArray(data.clients) ? data.clients : [];
|
||||
const projects = Array.isArray(data.projects) ? data.projects : [];
|
||||
const tags = Array.isArray(data.tags) ? data.tags : [];
|
||||
const userSummaries = Array.isArray(data.user_summaries) ? data.user_summaries : [];
|
||||
const entries = Array.isArray(dayDetails?.entries) ? dayDetails.entries : [];
|
||||
const summary = data.summary ?? {
|
||||
billable_duration: "00:00:00",
|
||||
@@ -166,6 +342,8 @@ export function ReportsTablePanel({
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<UserSummarySection rows={userSummaries} labels={labels} lang={lang} />
|
||||
|
||||
<div className="flex flex-col gap-2 sm:flex-row sm:justify-end">
|
||||
<button
|
||||
type="button"
|
||||
|
||||
@@ -11,6 +11,8 @@ export type CooldownKey =
|
||||
interface FlowBranchState {
|
||||
mobile: string
|
||||
code: string
|
||||
otpExpiresAt: number | null
|
||||
pendingOtpSend: boolean
|
||||
}
|
||||
|
||||
interface CooldownState {
|
||||
@@ -32,25 +34,34 @@ interface AuthFlowContextValue {
|
||||
state: AuthFlowState
|
||||
setMobile: (flow: FlowName, mobile: string) => void
|
||||
setCode: (flow: FlowName, code: string) => void
|
||||
markOtpSendPending: (flow: FlowName) => void
|
||||
setOtpDelivery: (flow: FlowName, expiresInSeconds: number) => void
|
||||
clearOtpDelivery: (flow: FlowName) => void
|
||||
setCooldown: (key: CooldownKey, seconds: number) => void
|
||||
clearCooldown: (key: CooldownKey) => void
|
||||
resetFlow: (flow: FlowName) => void
|
||||
}
|
||||
|
||||
const STORAGE_KEY = "auth_flow_state:v1"
|
||||
const STORAGE_KEY = "auth_flow_state:v2"
|
||||
|
||||
const defaultState: AuthFlowState = {
|
||||
login: {
|
||||
mobile: "",
|
||||
code: "",
|
||||
otpExpiresAt: null,
|
||||
pendingOtpSend: false,
|
||||
},
|
||||
signup: {
|
||||
mobile: "",
|
||||
code: "",
|
||||
otpExpiresAt: null,
|
||||
pendingOtpSend: false,
|
||||
},
|
||||
forgotPassword: {
|
||||
mobile: "",
|
||||
code: "",
|
||||
otpExpiresAt: null,
|
||||
pendingOtpSend: false,
|
||||
},
|
||||
cooldowns: {
|
||||
loginOtpSend: 0,
|
||||
@@ -80,14 +91,20 @@ const parseStoredState = (): AuthFlowState => {
|
||||
login: {
|
||||
mobile: parsed.login?.mobile ?? "",
|
||||
code: parsed.login?.code ?? "",
|
||||
otpExpiresAt: parsed.login?.otpExpiresAt ?? null,
|
||||
pendingOtpSend: parsed.login?.pendingOtpSend ?? false,
|
||||
},
|
||||
signup: {
|
||||
mobile: parsed.signup?.mobile ?? "",
|
||||
code: parsed.signup?.code ?? "",
|
||||
otpExpiresAt: parsed.signup?.otpExpiresAt ?? null,
|
||||
pendingOtpSend: parsed.signup?.pendingOtpSend ?? false,
|
||||
},
|
||||
forgotPassword: {
|
||||
mobile: parsed.forgotPassword?.mobile ?? "",
|
||||
code: parsed.forgotPassword?.code ?? "",
|
||||
otpExpiresAt: parsed.forgotPassword?.otpExpiresAt ?? null,
|
||||
pendingOtpSend: parsed.forgotPassword?.pendingOtpSend ?? false,
|
||||
},
|
||||
cooldowns: {
|
||||
loginOtpSend: parsed.cooldowns?.loginOtpSend ?? 0,
|
||||
@@ -151,6 +168,36 @@ export function AuthFlowProvider({ children }: { children: ReactNode }) {
|
||||
},
|
||||
}))
|
||||
},
|
||||
markOtpSendPending: (flow) => {
|
||||
setState((current) => ({
|
||||
...current,
|
||||
[flow]: {
|
||||
...current[flow],
|
||||
code: "",
|
||||
pendingOtpSend: true,
|
||||
},
|
||||
}))
|
||||
},
|
||||
setOtpDelivery: (flow, expiresInSeconds) => {
|
||||
setState((current) => ({
|
||||
...current,
|
||||
[flow]: {
|
||||
...current[flow],
|
||||
pendingOtpSend: false,
|
||||
otpExpiresAt: Date.now() + Math.max(0, expiresInSeconds) * 1000,
|
||||
},
|
||||
}))
|
||||
},
|
||||
clearOtpDelivery: (flow) => {
|
||||
setState((current) => ({
|
||||
...current,
|
||||
[flow]: {
|
||||
...current[flow],
|
||||
pendingOtpSend: false,
|
||||
otpExpiresAt: null,
|
||||
},
|
||||
}))
|
||||
},
|
||||
setCooldown: (key, seconds) => {
|
||||
setState((current) => ({
|
||||
...current,
|
||||
@@ -175,6 +222,8 @@ export function AuthFlowProvider({ children }: { children: ReactNode }) {
|
||||
[flow]: {
|
||||
mobile: "",
|
||||
code: "",
|
||||
otpExpiresAt: null,
|
||||
pendingOtpSend: false,
|
||||
},
|
||||
}))
|
||||
},
|
||||
|
||||
@@ -77,9 +77,14 @@ export const en = {
|
||||
passwordPlaceholder: "Password",
|
||||
signIn: "Sign In",
|
||||
back: "Back",
|
||||
otpPlaceholder: "5-digit code",
|
||||
verifyAndContinue: "Verify & Continue",
|
||||
terms: "By clicking continue, you agree to our Terms of Service and Privacy Policy.",
|
||||
otpPlaceholder: "5-digit code",
|
||||
verifyAndContinue: "Verify & Continue",
|
||||
sendingOtp: "Sending code...",
|
||||
verifyingOtp: "Verifying code...",
|
||||
resendOtp: "Resend code",
|
||||
otpExpiresIn: (time: string) => `Code expires in ${time}`,
|
||||
otpExpired: "This code has expired. Request a new code to continue.",
|
||||
terms: "By clicking continue, you agree to our Terms of Service and Privacy Policy.",
|
||||
brandingQuote: "Manage your time and workspaces efficiently with our minimal, fast, and secure platform.",
|
||||
toasts: {
|
||||
enterMobile: "Please enter your mobile number",
|
||||
@@ -511,8 +516,25 @@ export const en = {
|
||||
filterClients: "Filter by client",
|
||||
clearClientFilters: "Clear filters",
|
||||
namePlaceholder: "Project name...",
|
||||
teamMembers: "Team Members",
|
||||
creator: "Creator",
|
||||
teamMembers: "Team Members",
|
||||
manageAccess: "Manage access",
|
||||
accessModalTitle: "Project access",
|
||||
accessModalDescription: "Grant or revoke project access for workspace members.",
|
||||
accessMemberLabel: "Member",
|
||||
accessNoMembers: "No eligible members were found.",
|
||||
accessNoProjects: "No projects found.",
|
||||
accessSelectVisible: "Select all visible",
|
||||
accessClearSelection: "Clear selection",
|
||||
accessSelectClientProjects: "Select all projects for client",
|
||||
accessGrant: "Grant selected",
|
||||
accessRevoke: "Revoke selected",
|
||||
accessOn: "Has access",
|
||||
accessOff: "No access",
|
||||
accessGrantSuccess: "Project access granted.",
|
||||
accessRevokeSuccess: "Project access revoked.",
|
||||
accessLoadError: "Failed to load project access state.",
|
||||
accessSaveError: "Failed to update project access.",
|
||||
creator: "Creator",
|
||||
addUser: "Add user by mobile",
|
||||
addFromWorkspace: "Add from workspace",
|
||||
searchMembers: "Search members...",
|
||||
@@ -663,8 +685,9 @@ export const en = {
|
||||
periodCustom: "Custom period",
|
||||
fromDate: "From date",
|
||||
toDate: "To date",
|
||||
user: "User",
|
||||
allUsers: "All users",
|
||||
user: "User",
|
||||
mobile: "Mobile",
|
||||
allUsers: "All users",
|
||||
searchUsers: "Search users...",
|
||||
client: "Client",
|
||||
allClients: "All clients",
|
||||
@@ -681,16 +704,28 @@ export const en = {
|
||||
totalHours: "Total hours",
|
||||
billableHours: "Billable hours",
|
||||
nonBillableHours: "Non-billable hours",
|
||||
hourlyRate: "Hourly rate",
|
||||
totalIncome: "Total income",
|
||||
chartTitle: "Activity chart",
|
||||
hourlyRate: "Hourly rate",
|
||||
hourlyRates: "Hourly rates",
|
||||
workingHours: "Working hours",
|
||||
nonWorkingHours: "Non-working hours",
|
||||
totalIncome: "Total income",
|
||||
projectPercentages: "Project percentages",
|
||||
clientPercentages: "Client percentages",
|
||||
tagPercentages: "Tag percentages",
|
||||
userSummaryTitle: "Summary by user",
|
||||
userSummaryDetailsTitle: "User details: {name}",
|
||||
userSummaryDetailsDescription: "Review the selected user's rate history and time distribution.",
|
||||
rateHistory: "Rate history",
|
||||
percentage: "Percentage",
|
||||
chartTitle: "Activity chart",
|
||||
totalSeconds: "Total seconds",
|
||||
exportExcel: "Export Excel",
|
||||
exportPdf: "Export PDF",
|
||||
date: "Date",
|
||||
details: "Details",
|
||||
total: "Total",
|
||||
clientsTable: "Clients",
|
||||
details: "Details",
|
||||
total: "Total",
|
||||
noData: "No data",
|
||||
clientsTable: "Clients",
|
||||
projectsTable: "Projects",
|
||||
tagsTable: "Tags",
|
||||
loadError: "Failed to load reports.",
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
export const fa = {
|
||||
export const fa = {
|
||||
title: "Qlockify",
|
||||
logout: "خروج",
|
||||
logoutToast: "با موفقیت خارج شدید!",
|
||||
@@ -75,11 +75,16 @@ export const fa = {
|
||||
otpLogin: "ورود با کد یکبار مصرف",
|
||||
register: "ثبت نام",
|
||||
passwordPlaceholder: "رمز عبور",
|
||||
signIn: "ورود",
|
||||
back: "بازگشت",
|
||||
otpPlaceholder: "کد ۵ رقمی",
|
||||
verifyAndContinue: "تایید و ادامه",
|
||||
terms: "با کلیک روی ادامه، شما با قوانین و مقررات و حریم خصوصی ما موافقت میکنید.",
|
||||
signIn: "ورود",
|
||||
back: "بازگشت",
|
||||
otpPlaceholder: "کد ۵ رقمی",
|
||||
verifyAndContinue: "تایید و ادامه",
|
||||
sendingOtp: "در حال ارسال کد...",
|
||||
verifyingOtp: "در حال تأیید کد...",
|
||||
resendOtp: "ارسال دوباره کد",
|
||||
otpExpiresIn: (time: string) => `اعتبار کد تا ${time} دیگر است`,
|
||||
otpExpired: "اعتبار این کد به پایان رسیده است. برای ادامه کد جدید بگیرید.",
|
||||
terms: "با کلیک روی ادامه، شما با قوانین و مقررات و حریم خصوصی ما موافقت میکنید.",
|
||||
brandingQuote: "زمان و ورکاسپیسها خود را با پلتفرم مینیمال، سریع و امن ما بهینه مدیریت کنید.",
|
||||
toasts: {
|
||||
enterMobile: "لطفا شماره موبایل خود را وارد کنید",
|
||||
@@ -520,7 +525,24 @@ export const fa = {
|
||||
manager: "مدیر"
|
||||
},
|
||||
namePlaceholder: "نام پروژه...",
|
||||
teamMembers: "اعضای تیم",
|
||||
teamMembers: "اعضای تیم",
|
||||
manageAccess: "مدیریت دسترسی",
|
||||
accessModalTitle: "دسترسی پروژهها",
|
||||
accessModalDescription: "دسترسی اعضای ورکاسپیس به پروژهها را اعطا یا لغو کنید.",
|
||||
accessMemberLabel: "عضو",
|
||||
accessNoMembers: "عضو واجد شرایطی پیدا نشد.",
|
||||
accessNoProjects: "پروژهای پیدا نشد.",
|
||||
accessSelectVisible: "انتخاب همه موارد قابل مشاهده",
|
||||
accessClearSelection: "پاک کردن انتخاب",
|
||||
accessSelectClientProjects: "انتخاب همه پروژههای این مشتری",
|
||||
accessGrant: "اعطای دسترسی به موارد انتخابشده",
|
||||
accessRevoke: "لغو دسترسی موارد انتخابشده",
|
||||
accessOn: "دارای دسترسی",
|
||||
accessOff: "بدون دسترسی",
|
||||
accessGrantSuccess: "دسترسی پروژه با موفقیت اعطا شد.",
|
||||
accessRevokeSuccess: "دسترسی پروژه با موفقیت لغو شد.",
|
||||
accessLoadError: "بارگذاری وضعیت دسترسی پروژهها انجام نشد.",
|
||||
accessSaveError: "بهروزرسانی دسترسی پروژهها انجام نشد.",
|
||||
createSuccess: "پروژه با موفقیت ایجاد شد.",
|
||||
createError: "خطا در ایجاد پروژه.",
|
||||
updateSuccess: "پروژه با موفقیت بهروزرسانی شد.",
|
||||
@@ -659,7 +681,8 @@ export const fa = {
|
||||
periodCustom: "بازه دلخواه",
|
||||
fromDate: "از تاریخ",
|
||||
toDate: "تا تاریخ",
|
||||
user: "کاربر",
|
||||
user: "کاربر",
|
||||
mobile: "موبایل",
|
||||
allUsers: "همه کاربران",
|
||||
searchUsers: "جستوجوی کاربران...",
|
||||
client: "مشتری",
|
||||
@@ -677,16 +700,28 @@ export const fa = {
|
||||
totalHours: "مجموع ساعت",
|
||||
billableHours: "ساعات کاری",
|
||||
nonBillableHours: "ساعات غیر کاری",
|
||||
hourlyRate: "نرخ ساعتی",
|
||||
totalIncome: "مجموع درآمد",
|
||||
chartTitle: "نمودار فعالیت",
|
||||
hourlyRate: "نرخ ساعتی",
|
||||
hourlyRates: "نرخهای ساعتی",
|
||||
workingHours: "ساعات کاری",
|
||||
nonWorkingHours: "ساعات غیرکاری",
|
||||
totalIncome: "مجموع کارکرد",
|
||||
projectPercentages: "درصد پروژهها",
|
||||
clientPercentages: "درصد مشتریها",
|
||||
tagPercentages: "درصد تگها",
|
||||
userSummaryTitle: "خلاصه کاربران",
|
||||
userSummaryDetailsTitle: "جزئیات کاربر: {name}",
|
||||
userSummaryDetailsDescription: "تاریخچه نرخهای ساعتی و توزیع زمان کار برای کاربر انتخابشده را بررسی کنید.",
|
||||
rateHistory: "تاریخچه نرخها",
|
||||
percentage: "درصد",
|
||||
chartTitle: "نمودار فعالیت",
|
||||
totalSeconds: "مجموع ثانیه",
|
||||
exportExcel: "خروجی Excel",
|
||||
exportPdf: "خروجی PDF",
|
||||
date: "تاریخ",
|
||||
details: "جزئیات",
|
||||
total: "مجموع",
|
||||
clientsTable: "مشتریها",
|
||||
details: "جزئیات",
|
||||
total: "مجموع",
|
||||
noData: "دادهای وجود ندارد",
|
||||
clientsTable: "مشتریها",
|
||||
projectsTable: "پروژهها",
|
||||
tagsTable: "تگها",
|
||||
loadError: "دریافت گزارشها با خطا مواجه شد.",
|
||||
@@ -805,5 +840,5 @@ export const fa = {
|
||||
reportExportFailedTitle: "خروجی گزارش ناموفق بود",
|
||||
reportExportFailedMessage: (exportType: string, workspace: string) =>
|
||||
`تولید خروجی ${exportType.toUpperCase()} گزارش ${workspace} با خطا مواجه شد.`,
|
||||
},
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
@@ -7,8 +7,9 @@ import { useAppContext } from "../context/AppContext";
|
||||
import { useWorkspace } from "../context/WorkspaceContext";
|
||||
import { ProjectCreateModal } from "../components/projects/ProjectCreateModal";
|
||||
import { ProjectEditModal } from "../components/projects/ProjectEditModal";
|
||||
import { ProjectAccessModal } from "../components/projects/ProjectAccessModal";
|
||||
import { Pagination } from "../components/Pagination";
|
||||
import { Plus, Archive, Building2, Pencil, Trash2, X } from "lucide-react";
|
||||
import { Plus, Archive, Building2, Pencil, ShieldCheck, Trash2, X } from "lucide-react";
|
||||
|
||||
import EmptyStateCard from "../components/EmptyStateCard";
|
||||
import FilterBar from "../components/FilterBar";
|
||||
@@ -47,6 +48,7 @@ export const Projects: React.FC = () => {
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);
|
||||
const [editingProject, setEditingProject] = useState<Project | null>(null);
|
||||
const [isAccessModalOpen, setIsAccessModalOpen] = useState(false);
|
||||
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
const search = useMemo(() => readStringParam(searchParams, "search", ""), [searchParams]);
|
||||
@@ -231,6 +233,16 @@ export const Projects: React.FC = () => {
|
||||
<p className="mt-1 text-sm text-slate-500 dark:text-slate-400">{t.projects?.description(activeWorkspace.name) || 'Manage your projects'}</p>
|
||||
</div>
|
||||
<div className="flex w-full items-center gap-3 sm:w-auto">
|
||||
{canEditProject && (
|
||||
<Button
|
||||
variant="secondary"
|
||||
onClick={() => setIsAccessModalOpen(true)}
|
||||
className="flex-1 gap-2 shadow-sm sm:flex-none"
|
||||
>
|
||||
<ShieldCheck className="h-4 w-4" />
|
||||
{t.projects?.manageAccess || "Manage access"}
|
||||
</Button>
|
||||
)}
|
||||
{canArchiveProject && (
|
||||
<Button
|
||||
variant={isArchived ? "default" : "secondary"}
|
||||
@@ -438,6 +450,42 @@ export const Projects: React.FC = () => {
|
||||
/>
|
||||
)}
|
||||
|
||||
{canEditProject && (
|
||||
<ProjectAccessModal
|
||||
isOpen={isAccessModalOpen}
|
||||
onClose={() => setIsAccessModalOpen(false)}
|
||||
workspaceId={activeWorkspace.id}
|
||||
onApplied={() => {
|
||||
void fetchProjectList();
|
||||
}}
|
||||
labels={{
|
||||
title: t.projects?.accessModalTitle || "Project access",
|
||||
description: t.projects?.accessModalDescription || "Grant or revoke project access for workspace members.",
|
||||
close: t.actions?.cancel || "Close",
|
||||
member: t.projects?.accessMemberLabel || "Member",
|
||||
loading: t.loading || "Loading...",
|
||||
noMembers: t.projects?.accessNoMembers || "No eligible members were found.",
|
||||
noProjects: t.projects?.accessNoProjects || "No projects found.",
|
||||
searchPlaceholder: t.projects?.searchPlaceholder || "Search projects...",
|
||||
allClients: t.reports?.allClients || "All clients",
|
||||
selectAllVisible: t.projects?.accessSelectVisible || "Select all visible",
|
||||
clearSelection: t.projects?.accessClearSelection || "Clear selection",
|
||||
selectClientProjects: t.projects?.accessSelectClientProjects || "Select all projects for client",
|
||||
grantSelected: t.projects?.accessGrant || "Grant selected",
|
||||
revokeSelected: t.projects?.accessRevoke || "Revoke selected",
|
||||
accessGranted: t.projects?.accessGrantSuccess || "Project access granted.",
|
||||
accessRevoked: t.projects?.accessRevokeSuccess || "Project access revoked.",
|
||||
memberRole: t.workspace?.roleLabel || "Role",
|
||||
client: t.projects?.clientLabel || "Client",
|
||||
noClient: t.projects?.noClient || "No client",
|
||||
accessOn: t.projects?.accessOn || "Has access",
|
||||
accessOff: t.projects?.accessOff || "No access",
|
||||
loadError: t.projects?.accessLoadError || "Failed to load project access state.",
|
||||
saveError: t.projects?.accessSaveError || "Failed to update project access.",
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
{deleteModal.project && (
|
||||
<Modal
|
||||
isOpen={deleteModal.isOpen}
|
||||
|
||||
@@ -398,6 +398,20 @@ export default function Reports() {
|
||||
details: t.reports?.details || "Details",
|
||||
total: t.reports?.total || "Total",
|
||||
name: t.reports?.name || "Name",
|
||||
mobile: t.reports?.mobile || "Mobile",
|
||||
hourlyRates: t.reports?.hourlyRates || "Hourly rates",
|
||||
workingHours: t.reports?.workingHours || "Working hours",
|
||||
nonWorkingHours: t.reports?.nonWorkingHours || "Non-working hours",
|
||||
projectPercentages: t.reports?.projectPercentages || "Project percentages",
|
||||
clientPercentages: t.reports?.clientPercentages || "Client percentages",
|
||||
tagPercentages: t.reports?.tagPercentages || "Tag percentages",
|
||||
userSummaryTitle: t.reports?.userSummaryTitle || "Summary by user",
|
||||
userSummaryDetailsTitle: t.reports?.userSummaryDetailsTitle || "User details: {name}",
|
||||
userSummaryDetailsDescription: t.reports?.userSummaryDetailsDescription || "Detailed rate history and distribution for the selected user.",
|
||||
rateHistory: t.reports?.rateHistory || "Rate history",
|
||||
fromDate: t.reports?.fromDate || "From",
|
||||
toDate: t.reports?.toDate || "To",
|
||||
noData: t.reports?.noData || "No data",
|
||||
clientsTable: t.reports?.clientsTable || "Clients",
|
||||
projectsTable: t.reports?.projectsTable || "Projects",
|
||||
tagsTable: t.reports?.tagsTable || "Tags",
|
||||
|
||||
132
src/pages/auth/AuthOtpInput.tsx
Normal file
132
src/pages/auth/AuthOtpInput.tsx
Normal file
@@ -0,0 +1,132 @@
|
||||
import { useEffect, useMemo, useRef } from "react"
|
||||
|
||||
const OTP_LENGTH = 5
|
||||
|
||||
const normalizeDigits = (value: string) =>
|
||||
value
|
||||
.replace(/[۰-۹]/g, (digit) => String("۰۱۲۳۴۵۶۷۸۹".indexOf(digit)))
|
||||
.replace(/[٠-٩]/g, (digit) => String("٠١٢٣٤٥٦٧٨٩".indexOf(digit)))
|
||||
|
||||
const sanitizeOtp = (value: string) => normalizeDigits(value).replace(/\D/g, "").slice(0, OTP_LENGTH)
|
||||
|
||||
export function AuthOtpInput({
|
||||
id,
|
||||
value,
|
||||
disabled,
|
||||
onChange,
|
||||
onComplete,
|
||||
}: {
|
||||
id: string
|
||||
value: string
|
||||
disabled?: boolean
|
||||
onChange: (value: string) => void
|
||||
onComplete?: (value: string) => void
|
||||
}) {
|
||||
const inputRefs = useRef<Array<HTMLInputElement | null>>([])
|
||||
const lastCompletedValueRef = useRef("")
|
||||
const normalizedValue = useMemo(() => sanitizeOtp(value), [value])
|
||||
const digits = useMemo(
|
||||
() => Array.from({ length: OTP_LENGTH }, (_, index) => normalizedValue[index] ?? ""),
|
||||
[normalizedValue],
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
if (normalizedValue.length !== OTP_LENGTH) {
|
||||
lastCompletedValueRef.current = ""
|
||||
return
|
||||
}
|
||||
|
||||
if (normalizedValue !== lastCompletedValueRef.current) {
|
||||
lastCompletedValueRef.current = normalizedValue
|
||||
onComplete?.(normalizedValue)
|
||||
}
|
||||
}, [normalizedValue, onComplete])
|
||||
|
||||
const focusIndex = (index: number) => {
|
||||
inputRefs.current[index]?.focus()
|
||||
inputRefs.current[index]?.select()
|
||||
}
|
||||
|
||||
const handleSlotChange = (index: number, nextRawValue: string) => {
|
||||
const nextValue = sanitizeOtp(nextRawValue)
|
||||
if (!nextValue) {
|
||||
const updated = digits.slice()
|
||||
updated[index] = ""
|
||||
onChange(updated.join(""))
|
||||
return
|
||||
}
|
||||
|
||||
if (nextValue.length > 1) {
|
||||
onChange(nextValue)
|
||||
const focusTarget = Math.min(nextValue.length, OTP_LENGTH - 1)
|
||||
focusIndex(focusTarget)
|
||||
return
|
||||
}
|
||||
|
||||
const updated = digits.slice()
|
||||
updated[index] = nextValue
|
||||
const combined = updated.join("")
|
||||
onChange(combined)
|
||||
|
||||
if (index < OTP_LENGTH - 1) {
|
||||
focusIndex(index + 1)
|
||||
}
|
||||
}
|
||||
|
||||
const handleKeyDown = (index: number, event: React.KeyboardEvent<HTMLInputElement>) => {
|
||||
if (event.key === "Backspace" && !digits[index] && index > 0) {
|
||||
const updated = digits.slice()
|
||||
updated[index - 1] = ""
|
||||
onChange(updated.join(""))
|
||||
focusIndex(index - 1)
|
||||
event.preventDefault()
|
||||
return
|
||||
}
|
||||
|
||||
if (event.key === "ArrowLeft" && index > 0) {
|
||||
focusIndex(index - 1)
|
||||
event.preventDefault()
|
||||
return
|
||||
}
|
||||
|
||||
if (event.key === "ArrowRight" && index < OTP_LENGTH - 1) {
|
||||
focusIndex(index + 1)
|
||||
event.preventDefault()
|
||||
}
|
||||
}
|
||||
|
||||
const handlePaste = (event: React.ClipboardEvent<HTMLInputElement>) => {
|
||||
event.preventDefault()
|
||||
const pasted = sanitizeOtp(event.clipboardData.getData("text"))
|
||||
if (!pasted) {
|
||||
return
|
||||
}
|
||||
onChange(pasted)
|
||||
focusIndex(Math.min(pasted.length, OTP_LENGTH - 1))
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex items-center justify-center gap-2 sm:gap-3" dir="ltr">
|
||||
{digits.map((digit, index) => (
|
||||
<input
|
||||
key={`${id}-${index}`}
|
||||
ref={(element) => {
|
||||
inputRefs.current[index] = element
|
||||
}}
|
||||
id={index === 0 ? id : undefined}
|
||||
type="text"
|
||||
inputMode="numeric"
|
||||
autoComplete="one-time-code"
|
||||
pattern="[0-9]*"
|
||||
maxLength={OTP_LENGTH}
|
||||
disabled={disabled}
|
||||
value={digit}
|
||||
onChange={(event) => handleSlotChange(index, event.target.value)}
|
||||
onKeyDown={(event) => handleKeyDown(index, event)}
|
||||
onPaste={handlePaste}
|
||||
className="h-12 w-12 rounded-2xl border border-slate-200 bg-white text-center text-lg font-semibold tracking-[0.18em] text-slate-900 outline-none transition focus:border-sky-500 focus:ring-2 focus:ring-sky-200 dark:border-slate-700 dark:bg-slate-900 dark:text-white dark:focus:ring-sky-500/20 sm:h-14 sm:w-14"
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,22 +1,19 @@
|
||||
import { Loader2 } from "lucide-react"
|
||||
import { useMemo, useState } from "react"
|
||||
import { useMemo } from "react"
|
||||
import { Link, useNavigate } from "react-router-dom"
|
||||
import { toast } from "sonner"
|
||||
|
||||
import { sendOtp } from "../../api/users"
|
||||
import { Button } from "../../components/ui/button"
|
||||
import { Input } from "../../components/ui/input"
|
||||
import { useAuthFlow } from "../../context/AuthFlowContext"
|
||||
import { useTranslation } from "../../hooks/useTranslation"
|
||||
import { AuthPanel } from "./AuthPanel"
|
||||
import { formatCooldown, getApiErrorMessage, handleThrottleError } from "./utils"
|
||||
import { formatCooldown } from "./utils"
|
||||
|
||||
export function ForgotPasswordMobilePage() {
|
||||
const navigate = useNavigate()
|
||||
const { t, lang } = useTranslation()
|
||||
const { state, setMobile, setCode, setCooldown, clearCooldown } = useAuthFlow()
|
||||
const { state, setMobile, markOtpSendPending, clearOtpDelivery } = useAuthFlow()
|
||||
const isRtl = lang === "fa"
|
||||
const [loading, setLoading] = useState(false)
|
||||
|
||||
const alert = useMemo(() => {
|
||||
if (state.cooldowns.forgotPasswordOtpSend <= 0) {
|
||||
@@ -41,28 +38,9 @@ export function ForgotPasswordMobilePage() {
|
||||
return
|
||||
}
|
||||
|
||||
setLoading(true)
|
||||
try {
|
||||
await sendOtp(state.forgotPassword.mobile, "forget_password")
|
||||
clearCooldown("forgotPasswordOtpSend")
|
||||
setCode("forgotPassword", "")
|
||||
navigate("/auth/forgot-password/verify")
|
||||
toast.success(t.login.toasts.verifySent)
|
||||
} catch (error) {
|
||||
if (
|
||||
!handleThrottleError({
|
||||
error,
|
||||
cooldownKey: "forgotPasswordOtpSend",
|
||||
setCooldown,
|
||||
formatTime: (seconds) => formatCooldown(seconds, isRtl),
|
||||
throttleCopy: t.login.throttle,
|
||||
})
|
||||
) {
|
||||
toast.error(getApiErrorMessage(error, t.login.toasts.failedOtp))
|
||||
}
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
clearOtpDelivery("forgotPassword")
|
||||
markOtpSendPending("forgotPassword")
|
||||
navigate("/auth/forgot-password/verify")
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -78,7 +56,6 @@ export function ForgotPasswordMobilePage() {
|
||||
type="tel"
|
||||
dir="ltr"
|
||||
maxLength={11}
|
||||
disabled={loading}
|
||||
value={state.forgotPassword.mobile}
|
||||
onChange={(event) => setMobile("forgotPassword", event.target.value)}
|
||||
className={`h-11 ${isRtl ? "text-end" : "text-start"}`}
|
||||
@@ -86,10 +63,9 @@ export function ForgotPasswordMobilePage() {
|
||||
|
||||
<Button
|
||||
onClick={handleContinue}
|
||||
disabled={loading || state.cooldowns.forgotPasswordOtpSend > 0}
|
||||
disabled={state.cooldowns.forgotPasswordOtpSend > 0}
|
||||
className="h-11 w-full"
|
||||
>
|
||||
{loading && <Loader2 className="me-2 h-4 w-4 animate-spin" />}
|
||||
{cooldownLabel || t.login.sendResetCode}
|
||||
</Button>
|
||||
|
||||
|
||||
@@ -1,55 +1,161 @@
|
||||
import { useState } from "react"
|
||||
import { Link, Navigate, useNavigate } from "react-router-dom"
|
||||
import { Loader2 } from "lucide-react"
|
||||
import { useEffect, useMemo, useRef, useState } from "react"
|
||||
import { Navigate, useNavigate } from "react-router-dom"
|
||||
import { toast } from "sonner"
|
||||
|
||||
import { sendOtp } from "../../api/users"
|
||||
import { Button } from "../../components/ui/button"
|
||||
import { Input } from "../../components/ui/input"
|
||||
import { useAuthFlow } from "../../context/AuthFlowContext"
|
||||
import { useTranslation } from "../../hooks/useTranslation"
|
||||
import { AuthOtpInput } from "./AuthOtpInput"
|
||||
import { AuthPanel } from "./AuthPanel"
|
||||
import { formatCooldown, getApiErrorMessage, getOtpRemainingSeconds, handleThrottleError } from "./utils"
|
||||
|
||||
export function ForgotPasswordOtpPage() {
|
||||
const navigate = useNavigate()
|
||||
const { t } = useTranslation()
|
||||
const { state, setCode } = useAuthFlow()
|
||||
const [loading, setLoading] = useState(false)
|
||||
const { t, lang } = useTranslation()
|
||||
const {
|
||||
state,
|
||||
setCode,
|
||||
setCooldown,
|
||||
clearCooldown,
|
||||
setOtpDelivery,
|
||||
clearOtpDelivery,
|
||||
} = useAuthFlow()
|
||||
const isRtl = lang === "fa"
|
||||
const autoSendStartedRef = useRef(false)
|
||||
const [isSendingOtp, setIsSendingOtp] = useState(false)
|
||||
const [isContinuing, setIsContinuing] = useState(false)
|
||||
const [now, setNow] = useState(Date.now())
|
||||
|
||||
if (!state.forgotPassword.mobile) {
|
||||
return <Navigate to="/auth/forgot-password" replace />
|
||||
}
|
||||
|
||||
const handleContinue = async (event: React.FormEvent) => {
|
||||
event.preventDefault()
|
||||
useEffect(() => {
|
||||
if (!state.forgotPassword.otpExpiresAt || getOtpRemainingSeconds(state.forgotPassword.otpExpiresAt) <= 0) {
|
||||
return
|
||||
}
|
||||
|
||||
if (!state.forgotPassword.code) {
|
||||
const timer = window.setInterval(() => {
|
||||
setNow(Date.now())
|
||||
}, 1000)
|
||||
|
||||
return () => window.clearInterval(timer)
|
||||
}, [state.forgotPassword.otpExpiresAt])
|
||||
|
||||
const sendForgotPasswordOtp = async () => {
|
||||
setIsSendingOtp(true)
|
||||
try {
|
||||
const response = await sendOtp(state.forgotPassword.mobile, "forget_password")
|
||||
clearCooldown("forgotPasswordOtpSend")
|
||||
setCode("forgotPassword", "")
|
||||
setOtpDelivery("forgotPassword", response.expires_in_seconds)
|
||||
setNow(Date.now())
|
||||
toast.success(t.login.toasts.verifySent)
|
||||
} catch (error) {
|
||||
clearOtpDelivery("forgotPassword")
|
||||
if (
|
||||
!handleThrottleError({
|
||||
error,
|
||||
cooldownKey: "forgotPasswordOtpSend",
|
||||
setCooldown,
|
||||
formatTime: (seconds) => formatCooldown(seconds, isRtl),
|
||||
throttleCopy: t.login.throttle,
|
||||
})
|
||||
) {
|
||||
toast.error(getApiErrorMessage(error, t.login.toasts.failedOtp))
|
||||
}
|
||||
} finally {
|
||||
setIsSendingOtp(false)
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (!state.forgotPassword.pendingOtpSend || autoSendStartedRef.current) {
|
||||
return
|
||||
}
|
||||
|
||||
autoSendStartedRef.current = true
|
||||
void sendForgotPasswordOtp()
|
||||
}, [state.forgotPassword.pendingOtpSend])
|
||||
|
||||
const otpRemainingSeconds = state.forgotPassword.otpExpiresAt
|
||||
? Math.max(0, Math.ceil((state.forgotPassword.otpExpiresAt - now) / 1000))
|
||||
: 0
|
||||
|
||||
const alert = useMemo(() => {
|
||||
if (state.cooldowns.forgotPasswordOtpSend <= 0) {
|
||||
return null
|
||||
}
|
||||
|
||||
const formatted = formatCooldown(state.cooldowns.forgotPasswordOtpSend, isRtl)
|
||||
return {
|
||||
title: t.login.throttle.title,
|
||||
description: t.login.throttle.otpSendMessage(formatted),
|
||||
}
|
||||
}, [isRtl, state.cooldowns.forgotPasswordOtpSend, t.login.throttle])
|
||||
|
||||
const expiryMessage =
|
||||
otpRemainingSeconds > 0
|
||||
? t.login.otpExpiresIn(formatCooldown(otpRemainingSeconds, isRtl))
|
||||
: state.forgotPassword.otpExpiresAt
|
||||
? t.login.otpExpired
|
||||
: null
|
||||
|
||||
const continueToReset = async (code: string) => {
|
||||
if (code.length !== 5) {
|
||||
toast.error(t.login.toasts.enterOtp)
|
||||
return
|
||||
}
|
||||
|
||||
setLoading(true)
|
||||
setIsContinuing(true)
|
||||
setCode("forgotPassword", code)
|
||||
navigate("/auth/forgot-password/password")
|
||||
}
|
||||
|
||||
const isBusy = isSendingOtp || isContinuing
|
||||
|
||||
return (
|
||||
<AuthPanel
|
||||
title={t.login.forgotPasswordVerifyTitle}
|
||||
description={t.login.sentCodeDesc(state.forgotPassword.mobile)}
|
||||
alert={alert}
|
||||
>
|
||||
<form onSubmit={handleContinue} className="grid gap-4">
|
||||
<Input
|
||||
<form
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault()
|
||||
void continueToReset(state.forgotPassword.code)
|
||||
}}
|
||||
className="grid gap-4"
|
||||
>
|
||||
<AuthOtpInput
|
||||
id="forgot-password-otp"
|
||||
placeholder={t.login.otpPlaceholder}
|
||||
type="text"
|
||||
dir="ltr"
|
||||
maxLength={6}
|
||||
disabled={loading}
|
||||
value={state.forgotPassword.code}
|
||||
onChange={(event) => setCode("forgotPassword", event.target.value)}
|
||||
className="h-11 text-center text-lg tracking-widest"
|
||||
disabled={isBusy}
|
||||
onChange={(value) => setCode("forgotPassword", value)}
|
||||
onComplete={(value) => void continueToReset(value)}
|
||||
/>
|
||||
|
||||
<Button type="submit" className="h-11 w-full" disabled={loading}>
|
||||
{t.login.continueToResetPassword}
|
||||
{expiryMessage ? (
|
||||
<p className="text-center text-sm text-slate-500 dark:text-slate-400">{expiryMessage}</p>
|
||||
) : null}
|
||||
|
||||
<Button type="submit" className="h-11 w-full" disabled={isBusy}>
|
||||
{(isSendingOtp || isContinuing) && <Loader2 className="me-2 h-4 w-4 animate-spin" />}
|
||||
{isSendingOtp ? t.login.sendingOtp : t.login.continueToResetPassword}
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className="h-11 w-full"
|
||||
disabled={isBusy || otpRemainingSeconds > 0 || state.cooldowns.forgotPasswordOtpSend > 0}
|
||||
onClick={() => void sendForgotPasswordOtp()}
|
||||
>
|
||||
{state.cooldowns.forgotPasswordOtpSend > 0
|
||||
? t.login.throttle.countdownLabel(formatCooldown(state.cooldowns.forgotPasswordOtpSend, isRtl))
|
||||
: t.login.resendOtp}
|
||||
</Button>
|
||||
</form>
|
||||
</AuthPanel>
|
||||
|
||||
@@ -1,15 +1,14 @@
|
||||
import { Loader2 } from "lucide-react"
|
||||
import { useMemo, useState } from "react"
|
||||
import { useMemo } from "react"
|
||||
import { Link, useNavigate } from "react-router-dom"
|
||||
import { toast } from "sonner"
|
||||
|
||||
import { sendOtp, startGoogleLogin } from "../../api/users"
|
||||
import { startGoogleLogin } from "../../api/users"
|
||||
import { Button } from "../../components/ui/button"
|
||||
import { Input } from "../../components/ui/input"
|
||||
import { useAuthFlow } from "../../context/AuthFlowContext"
|
||||
import { useTranslation } from "../../hooks/useTranslation"
|
||||
import { AuthPanel } from "./AuthPanel"
|
||||
import { formatCooldown, getApiErrorMessage, handleThrottleError } from "./utils"
|
||||
import { formatCooldown } from "./utils"
|
||||
|
||||
const GoogleIcon = () => (
|
||||
<svg aria-hidden="true" className="h-5 w-5" viewBox="0 0 24 24">
|
||||
@@ -35,10 +34,8 @@ const GoogleIcon = () => (
|
||||
export function LoginMobilePage() {
|
||||
const navigate = useNavigate()
|
||||
const { t, lang } = useTranslation()
|
||||
const { state, setMobile, setCooldown, clearCooldown, resetFlow } = useAuthFlow()
|
||||
const { state, setMobile, markOtpSendPending, clearOtpDelivery, resetFlow } = useAuthFlow()
|
||||
const isRtl = lang === "fa"
|
||||
const [loading, setLoading] = useState(false)
|
||||
|
||||
const alert = useMemo(() => {
|
||||
if (state.cooldowns.loginOtpSend <= 0) {
|
||||
return null
|
||||
@@ -62,28 +59,10 @@ export function LoginMobilePage() {
|
||||
return
|
||||
}
|
||||
|
||||
setLoading(true)
|
||||
try {
|
||||
await sendOtp(state.login.mobile, "login")
|
||||
clearCooldown("loginOtpSend")
|
||||
resetFlow("forgotPassword")
|
||||
navigate("/auth/login/verify")
|
||||
toast.success(t.login.toasts.verifySent)
|
||||
} catch (error) {
|
||||
if (
|
||||
!handleThrottleError({
|
||||
error,
|
||||
cooldownKey: "loginOtpSend",
|
||||
setCooldown,
|
||||
formatTime: (seconds) => formatCooldown(seconds, isRtl),
|
||||
throttleCopy: t.login.throttle,
|
||||
})
|
||||
) {
|
||||
toast.error(getApiErrorMessage(error, t.login.toasts.failedOtp))
|
||||
}
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
resetFlow("forgotPassword")
|
||||
clearOtpDelivery("login")
|
||||
markOtpSendPending("login")
|
||||
navigate("/auth/login/verify")
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -99,7 +78,6 @@ export function LoginMobilePage() {
|
||||
type="tel"
|
||||
dir="ltr"
|
||||
maxLength={11}
|
||||
disabled={loading}
|
||||
value={state.login.mobile}
|
||||
onChange={(event) => setMobile("login", event.target.value)}
|
||||
className={`h-11 ${isRtl ? "text-end" : "text-start"}`}
|
||||
@@ -107,10 +85,9 @@ export function LoginMobilePage() {
|
||||
|
||||
<Button
|
||||
onClick={handleLogin}
|
||||
disabled={loading || state.cooldowns.loginOtpSend > 0}
|
||||
disabled={state.cooldowns.loginOtpSend > 0}
|
||||
className="h-11 w-full"
|
||||
>
|
||||
{loading && <Loader2 className="me-2 h-4 w-4 animate-spin" />}
|
||||
{cooldownLabel || t.login.loginCta}
|
||||
</Button>
|
||||
|
||||
@@ -129,7 +106,6 @@ export function LoginMobilePage() {
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={startGoogleLogin}
|
||||
disabled={loading}
|
||||
className="h-11 w-full"
|
||||
>
|
||||
<GoogleIcon />
|
||||
|
||||
@@ -1,56 +1,148 @@
|
||||
import { Loader2 } from "lucide-react"
|
||||
import { useMemo, useState } from "react"
|
||||
import { useEffect, useMemo, useRef, useState } from "react"
|
||||
import { Link, Navigate, useNavigate } from "react-router-dom"
|
||||
import { toast } from "sonner"
|
||||
|
||||
import { loginWithOtp } from "../../api/users"
|
||||
import { loginWithOtp, sendOtp } from "../../api/users"
|
||||
import { Button } from "../../components/ui/button"
|
||||
import { Input } from "../../components/ui/input"
|
||||
import { useAuthFlow } from "../../context/AuthFlowContext"
|
||||
import { useTranslation } from "../../hooks/useTranslation"
|
||||
import { AuthOtpInput } from "./AuthOtpInput"
|
||||
import { AuthPanel } from "./AuthPanel"
|
||||
import { completeAuthentication, formatCooldown, getApiErrorMessage, handleThrottleError } from "./utils"
|
||||
import {
|
||||
completeAuthentication,
|
||||
formatCooldown,
|
||||
getApiErrorMessage,
|
||||
getOtpRemainingSeconds,
|
||||
handleThrottleError,
|
||||
} from "./utils"
|
||||
|
||||
export function LoginOtpPage() {
|
||||
const navigate = useNavigate()
|
||||
const { t, lang } = useTranslation()
|
||||
const { state, setCode, setCooldown, clearCooldown } = useAuthFlow()
|
||||
const {
|
||||
state,
|
||||
setCode,
|
||||
setCooldown,
|
||||
clearCooldown,
|
||||
setOtpDelivery,
|
||||
clearOtpDelivery,
|
||||
} = useAuthFlow()
|
||||
const isRtl = lang === "fa"
|
||||
const [loading, setLoading] = useState(false)
|
||||
const autoSendStartedRef = useRef(false)
|
||||
const activeSubmitCodeRef = useRef("")
|
||||
const lastFailedCodeRef = useRef("")
|
||||
const [isSendingOtp, setIsSendingOtp] = useState(false)
|
||||
const [isSubmitting, setIsSubmitting] = useState(false)
|
||||
const [now, setNow] = useState(Date.now())
|
||||
|
||||
if (!state.login.mobile) {
|
||||
return <Navigate to="/auth/login" replace />
|
||||
}
|
||||
|
||||
const alert = useMemo(() => {
|
||||
if (state.cooldowns.loginOtpVerify <= 0) {
|
||||
return null
|
||||
useEffect(() => {
|
||||
if (!state.login.otpExpiresAt || getOtpRemainingSeconds(state.login.otpExpiresAt) <= 0) {
|
||||
return
|
||||
}
|
||||
|
||||
const formatted = formatCooldown(state.cooldowns.loginOtpVerify, isRtl)
|
||||
return {
|
||||
title: t.login.throttle.title,
|
||||
description: t.login.throttle.otpLoginMessage(formatted),
|
||||
const timer = window.setInterval(() => {
|
||||
setNow(Date.now())
|
||||
}, 1000)
|
||||
|
||||
return () => window.clearInterval(timer)
|
||||
}, [state.login.otpExpiresAt])
|
||||
|
||||
const sendLoginOtp = async () => {
|
||||
setIsSendingOtp(true)
|
||||
try {
|
||||
const response = await sendOtp(state.login.mobile, "login")
|
||||
clearCooldown("loginOtpSend")
|
||||
clearCooldown("loginOtpVerify")
|
||||
lastFailedCodeRef.current = ""
|
||||
setCode("login", "")
|
||||
setOtpDelivery("login", response.expires_in_seconds)
|
||||
setNow(Date.now())
|
||||
toast.success(t.login.toasts.verifySent)
|
||||
} catch (error) {
|
||||
clearOtpDelivery("login")
|
||||
if (
|
||||
!handleThrottleError({
|
||||
error,
|
||||
cooldownKey: "loginOtpSend",
|
||||
setCooldown,
|
||||
formatTime: (seconds) => formatCooldown(seconds, isRtl),
|
||||
throttleCopy: t.login.throttle,
|
||||
})
|
||||
) {
|
||||
toast.error(getApiErrorMessage(error, t.login.toasts.failedOtp))
|
||||
}
|
||||
} finally {
|
||||
setIsSendingOtp(false)
|
||||
}
|
||||
}, [isRtl, state.cooldowns.loginOtpVerify, t.login.throttle])
|
||||
}
|
||||
|
||||
const cooldownLabel =
|
||||
state.cooldowns.loginOtpVerify > 0
|
||||
? t.login.throttle.countdownLabel(formatCooldown(state.cooldowns.loginOtpVerify, isRtl))
|
||||
: null
|
||||
useEffect(() => {
|
||||
if (!state.login.pendingOtpSend || autoSendStartedRef.current) {
|
||||
return
|
||||
}
|
||||
|
||||
const handleVerify = async (event: React.FormEvent) => {
|
||||
event.preventDefault()
|
||||
autoSendStartedRef.current = true
|
||||
void sendLoginOtp()
|
||||
}, [state.login.pendingOtpSend])
|
||||
|
||||
if (!state.login.code) {
|
||||
const otpRemainingSeconds = state.login.otpExpiresAt
|
||||
? Math.max(0, Math.ceil((state.login.otpExpiresAt - now) / 1000))
|
||||
: 0
|
||||
|
||||
const throttleAlert = useMemo(() => {
|
||||
if (state.cooldowns.loginOtpVerify > 0) {
|
||||
const formatted = formatCooldown(state.cooldowns.loginOtpVerify, isRtl)
|
||||
return {
|
||||
title: t.login.throttle.title,
|
||||
description: t.login.throttle.otpLoginMessage(formatted),
|
||||
}
|
||||
}
|
||||
|
||||
if (state.cooldowns.loginOtpSend > 0) {
|
||||
const formatted = formatCooldown(state.cooldowns.loginOtpSend, isRtl)
|
||||
return {
|
||||
title: t.login.throttle.title,
|
||||
description: t.login.throttle.otpSendMessage(formatted),
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
}, [isRtl, state.cooldowns.loginOtpSend, state.cooldowns.loginOtpVerify, t.login.throttle])
|
||||
|
||||
const expiryMessage =
|
||||
otpRemainingSeconds > 0
|
||||
? t.login.otpExpiresIn(formatCooldown(otpRemainingSeconds, isRtl))
|
||||
: state.login.otpExpiresAt
|
||||
? t.login.otpExpired
|
||||
: null
|
||||
|
||||
const submitCode = async (code: string) => {
|
||||
if (code.length !== 5) {
|
||||
toast.error(t.login.toasts.enterOtp)
|
||||
return
|
||||
}
|
||||
|
||||
setLoading(true)
|
||||
if (isSendingOtp || isSubmitting || code === activeSubmitCodeRef.current) {
|
||||
return
|
||||
}
|
||||
|
||||
if (code === lastFailedCodeRef.current) {
|
||||
toast.error(t.login.toasts.invalidOtp)
|
||||
return
|
||||
}
|
||||
|
||||
activeSubmitCodeRef.current = code
|
||||
setIsSubmitting(true)
|
||||
try {
|
||||
const data = await loginWithOtp(state.login.mobile, state.login.code)
|
||||
const data = await loginWithOtp(state.login.mobile, code)
|
||||
clearCooldown("loginOtpVerify")
|
||||
activeSubmitCodeRef.current = ""
|
||||
lastFailedCodeRef.current = ""
|
||||
completeAuthentication({
|
||||
access: data.access,
|
||||
refresh: data.refresh,
|
||||
@@ -68,35 +160,67 @@ export function LoginOtpPage() {
|
||||
throttleCopy: t.login.throttle,
|
||||
})
|
||||
) {
|
||||
lastFailedCodeRef.current = code
|
||||
toast.error(getApiErrorMessage(error, t.login.toasts.invalidOtp))
|
||||
}
|
||||
} finally {
|
||||
setLoading(false)
|
||||
activeSubmitCodeRef.current = ""
|
||||
setIsSubmitting(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleResend = async () => {
|
||||
autoSendStartedRef.current = false
|
||||
await sendLoginOtp()
|
||||
}
|
||||
|
||||
const isBusy = isSendingOtp || isSubmitting
|
||||
const isRepeatedInvalidCode = state.login.code.length === 5 && state.login.code === lastFailedCodeRef.current
|
||||
|
||||
return (
|
||||
<AuthPanel
|
||||
title={t.login.loginOtpTitle}
|
||||
description={t.login.sentCodeDesc(state.login.mobile)}
|
||||
alert={alert}
|
||||
alert={throttleAlert}
|
||||
>
|
||||
<form onSubmit={handleVerify} className="grid gap-4">
|
||||
<Input
|
||||
<form
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault()
|
||||
void submitCode(state.login.code)
|
||||
}}
|
||||
className="grid gap-4"
|
||||
>
|
||||
<AuthOtpInput
|
||||
id="login-otp"
|
||||
placeholder={t.login.otpPlaceholder}
|
||||
type="text"
|
||||
dir="ltr"
|
||||
maxLength={5}
|
||||
disabled={loading}
|
||||
value={state.login.code}
|
||||
onChange={(event) => setCode("login", event.target.value)}
|
||||
className="h-11 text-center text-lg tracking-widest"
|
||||
disabled={isBusy}
|
||||
onChange={(value) => setCode("login", value)}
|
||||
onComplete={(value) => void submitCode(value)}
|
||||
/>
|
||||
|
||||
<Button type="submit" className="h-11 w-full" disabled={loading || state.cooldowns.loginOtpVerify > 0}>
|
||||
{loading && <Loader2 className="me-2 h-4 w-4 animate-spin" />}
|
||||
{cooldownLabel || t.login.verifyAndContinue}
|
||||
{expiryMessage ? (
|
||||
<p className="text-center text-sm text-slate-500 dark:text-slate-400">{expiryMessage}</p>
|
||||
) : null}
|
||||
|
||||
<Button
|
||||
type="submit"
|
||||
className="h-11 w-full"
|
||||
disabled={isBusy || isRepeatedInvalidCode || state.cooldowns.loginOtpVerify > 0}
|
||||
>
|
||||
{(isSubmitting || isSendingOtp) && <Loader2 className="me-2 h-4 w-4 animate-spin" />}
|
||||
{isSubmitting ? t.login.verifyingOtp : isSendingOtp ? t.login.sendingOtp : t.login.verifyAndContinue}
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className="h-11 w-full"
|
||||
disabled={isBusy || otpRemainingSeconds > 0 || state.cooldowns.loginOtpSend > 0}
|
||||
onClick={() => void handleResend()}
|
||||
>
|
||||
{state.cooldowns.loginOtpSend > 0
|
||||
? t.login.throttle.countdownLabel(formatCooldown(state.cooldowns.loginOtpSend, isRtl))
|
||||
: t.login.resendOtp}
|
||||
</Button>
|
||||
|
||||
<div className="text-center text-sm text-slate-500 dark:text-slate-400 underline">
|
||||
|
||||
@@ -1,22 +1,19 @@
|
||||
import { Loader2 } from "lucide-react"
|
||||
import { useMemo, useState } from "react"
|
||||
import { useMemo } from "react"
|
||||
import { Link, useNavigate } from "react-router-dom"
|
||||
import { toast } from "sonner"
|
||||
|
||||
import { sendOtp } from "../../api/users"
|
||||
import { Button } from "../../components/ui/button"
|
||||
import { Input } from "../../components/ui/input"
|
||||
import { useAuthFlow } from "../../context/AuthFlowContext"
|
||||
import { useTranslation } from "../../hooks/useTranslation"
|
||||
import { AuthPanel } from "./AuthPanel"
|
||||
import { formatCooldown, getApiErrorMessage, handleThrottleError } from "./utils"
|
||||
import { formatCooldown } from "./utils"
|
||||
|
||||
export function SignupMobilePage() {
|
||||
const navigate = useNavigate()
|
||||
const { t, lang } = useTranslation()
|
||||
const { state, setMobile, setCode, setCooldown, clearCooldown } = useAuthFlow()
|
||||
const { state, setMobile, markOtpSendPending, clearOtpDelivery } = useAuthFlow()
|
||||
const isRtl = lang === "fa"
|
||||
const [loading, setLoading] = useState(false)
|
||||
|
||||
const alert = useMemo(() => {
|
||||
if (state.cooldowns.signupOtpSend <= 0) {
|
||||
@@ -41,28 +38,9 @@ export function SignupMobilePage() {
|
||||
return
|
||||
}
|
||||
|
||||
setLoading(true)
|
||||
try {
|
||||
await sendOtp(state.signup.mobile, "register")
|
||||
clearCooldown("signupOtpSend")
|
||||
setCode("signup", "")
|
||||
navigate("/auth/signup/verify")
|
||||
toast.success(t.login.toasts.verifySent)
|
||||
} catch (error) {
|
||||
if (
|
||||
!handleThrottleError({
|
||||
error,
|
||||
cooldownKey: "signupOtpSend",
|
||||
setCooldown,
|
||||
formatTime: (seconds) => formatCooldown(seconds, isRtl),
|
||||
throttleCopy: t.login.throttle,
|
||||
})
|
||||
) {
|
||||
toast.error(getApiErrorMessage(error, t.login.toasts.failedOtp))
|
||||
}
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
clearOtpDelivery("signup")
|
||||
markOtpSendPending("signup")
|
||||
navigate("/auth/signup/verify")
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -78,7 +56,6 @@ export function SignupMobilePage() {
|
||||
type="tel"
|
||||
dir="ltr"
|
||||
maxLength={11}
|
||||
disabled={loading}
|
||||
value={state.signup.mobile}
|
||||
onChange={(event) => setMobile("signup", event.target.value)}
|
||||
className={`h-11 ${isRtl ? "text-end" : "text-start"}`}
|
||||
@@ -86,10 +63,9 @@ export function SignupMobilePage() {
|
||||
|
||||
<Button
|
||||
onClick={handleContinue}
|
||||
disabled={loading || state.cooldowns.signupOtpSend > 0}
|
||||
disabled={state.cooldowns.signupOtpSend > 0}
|
||||
className="h-11 w-full"
|
||||
>
|
||||
{loading && <Loader2 className="me-2 h-4 w-4 animate-spin" />}
|
||||
{cooldownLabel || t.login.sendSignupCode}
|
||||
</Button>
|
||||
|
||||
|
||||
@@ -1,55 +1,161 @@
|
||||
import { useState } from "react"
|
||||
import { Link, Navigate, useNavigate } from "react-router-dom"
|
||||
import { Loader2 } from "lucide-react"
|
||||
import { useEffect, useMemo, useRef, useState } from "react"
|
||||
import { Navigate, useNavigate } from "react-router-dom"
|
||||
import { toast } from "sonner"
|
||||
|
||||
import { sendOtp } from "../../api/users"
|
||||
import { Button } from "../../components/ui/button"
|
||||
import { Input } from "../../components/ui/input"
|
||||
import { useAuthFlow } from "../../context/AuthFlowContext"
|
||||
import { useTranslation } from "../../hooks/useTranslation"
|
||||
import { AuthOtpInput } from "./AuthOtpInput"
|
||||
import { AuthPanel } from "./AuthPanel"
|
||||
import { formatCooldown, getApiErrorMessage, getOtpRemainingSeconds, handleThrottleError } from "./utils"
|
||||
|
||||
export function SignupOtpPage() {
|
||||
const navigate = useNavigate()
|
||||
const { t } = useTranslation()
|
||||
const { state, setCode } = useAuthFlow()
|
||||
const [loading, setLoading] = useState(false)
|
||||
const { t, lang } = useTranslation()
|
||||
const {
|
||||
state,
|
||||
setCode,
|
||||
setCooldown,
|
||||
clearCooldown,
|
||||
setOtpDelivery,
|
||||
clearOtpDelivery,
|
||||
} = useAuthFlow()
|
||||
const isRtl = lang === "fa"
|
||||
const autoSendStartedRef = useRef(false)
|
||||
const [isSendingOtp, setIsSendingOtp] = useState(false)
|
||||
const [isContinuing, setIsContinuing] = useState(false)
|
||||
const [now, setNow] = useState(Date.now())
|
||||
|
||||
if (!state.signup.mobile) {
|
||||
return <Navigate to="/auth/signup" replace />
|
||||
}
|
||||
|
||||
const handleContinue = async (event: React.FormEvent) => {
|
||||
event.preventDefault()
|
||||
useEffect(() => {
|
||||
if (!state.signup.otpExpiresAt || getOtpRemainingSeconds(state.signup.otpExpiresAt) <= 0) {
|
||||
return
|
||||
}
|
||||
|
||||
if (!state.signup.code) {
|
||||
const timer = window.setInterval(() => {
|
||||
setNow(Date.now())
|
||||
}, 1000)
|
||||
|
||||
return () => window.clearInterval(timer)
|
||||
}, [state.signup.otpExpiresAt])
|
||||
|
||||
const sendSignupOtp = async () => {
|
||||
setIsSendingOtp(true)
|
||||
try {
|
||||
const response = await sendOtp(state.signup.mobile, "register")
|
||||
clearCooldown("signupOtpSend")
|
||||
setCode("signup", "")
|
||||
setOtpDelivery("signup", response.expires_in_seconds)
|
||||
setNow(Date.now())
|
||||
toast.success(t.login.toasts.verifySent)
|
||||
} catch (error) {
|
||||
clearOtpDelivery("signup")
|
||||
if (
|
||||
!handleThrottleError({
|
||||
error,
|
||||
cooldownKey: "signupOtpSend",
|
||||
setCooldown,
|
||||
formatTime: (seconds) => formatCooldown(seconds, isRtl),
|
||||
throttleCopy: t.login.throttle,
|
||||
})
|
||||
) {
|
||||
toast.error(getApiErrorMessage(error, t.login.toasts.failedOtp))
|
||||
}
|
||||
} finally {
|
||||
setIsSendingOtp(false)
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (!state.signup.pendingOtpSend || autoSendStartedRef.current) {
|
||||
return
|
||||
}
|
||||
|
||||
autoSendStartedRef.current = true
|
||||
void sendSignupOtp()
|
||||
}, [state.signup.pendingOtpSend])
|
||||
|
||||
const otpRemainingSeconds = state.signup.otpExpiresAt
|
||||
? Math.max(0, Math.ceil((state.signup.otpExpiresAt - now) / 1000))
|
||||
: 0
|
||||
|
||||
const alert = useMemo(() => {
|
||||
if (state.cooldowns.signupOtpSend <= 0) {
|
||||
return null
|
||||
}
|
||||
|
||||
const formatted = formatCooldown(state.cooldowns.signupOtpSend, isRtl)
|
||||
return {
|
||||
title: t.login.throttle.title,
|
||||
description: t.login.throttle.otpSendMessage(formatted),
|
||||
}
|
||||
}, [isRtl, state.cooldowns.signupOtpSend, t.login.throttle])
|
||||
|
||||
const expiryMessage =
|
||||
otpRemainingSeconds > 0
|
||||
? t.login.otpExpiresIn(formatCooldown(otpRemainingSeconds, isRtl))
|
||||
: state.signup.otpExpiresAt
|
||||
? t.login.otpExpired
|
||||
: null
|
||||
|
||||
const continueToPassword = async (code: string) => {
|
||||
if (code.length !== 5) {
|
||||
toast.error(t.login.toasts.enterOtp)
|
||||
return
|
||||
}
|
||||
|
||||
setLoading(true)
|
||||
setIsContinuing(true)
|
||||
setCode("signup", code)
|
||||
navigate("/auth/signup/password")
|
||||
}
|
||||
|
||||
const isBusy = isSendingOtp || isContinuing
|
||||
|
||||
return (
|
||||
<AuthPanel
|
||||
title={t.login.signupVerifyTitle}
|
||||
description={t.login.sentCodeDesc(state.signup.mobile)}
|
||||
alert={alert}
|
||||
>
|
||||
<form onSubmit={handleContinue} className="grid gap-4">
|
||||
<Input
|
||||
<form
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault()
|
||||
void continueToPassword(state.signup.code)
|
||||
}}
|
||||
className="grid gap-4"
|
||||
>
|
||||
<AuthOtpInput
|
||||
id="signup-otp"
|
||||
placeholder={t.login.otpPlaceholder}
|
||||
type="text"
|
||||
dir="ltr"
|
||||
maxLength={6}
|
||||
disabled={loading}
|
||||
value={state.signup.code}
|
||||
onChange={(event) => setCode("signup", event.target.value)}
|
||||
className="h-11 text-center text-lg tracking-widest"
|
||||
disabled={isBusy}
|
||||
onChange={(value) => setCode("signup", value)}
|
||||
onComplete={(value) => void continueToPassword(value)}
|
||||
/>
|
||||
|
||||
<Button type="submit" className="h-11 w-full" disabled={loading}>
|
||||
{t.login.continueToPassword}
|
||||
{expiryMessage ? (
|
||||
<p className="text-center text-sm text-slate-500 dark:text-slate-400">{expiryMessage}</p>
|
||||
) : null}
|
||||
|
||||
<Button type="submit" className="h-11 w-full" disabled={isBusy}>
|
||||
{(isSendingOtp || isContinuing) && <Loader2 className="me-2 h-4 w-4 animate-spin" />}
|
||||
{isSendingOtp ? t.login.sendingOtp : t.login.continueToPassword}
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className="h-11 w-full"
|
||||
disabled={isBusy || otpRemainingSeconds > 0 || state.cooldowns.signupOtpSend > 0}
|
||||
onClick={() => void sendSignupOtp()}
|
||||
>
|
||||
{state.cooldowns.signupOtpSend > 0
|
||||
? t.login.throttle.countdownLabel(formatCooldown(state.cooldowns.signupOtpSend, isRtl))
|
||||
: t.login.resendOtp}
|
||||
</Button>
|
||||
</form>
|
||||
</AuthPanel>
|
||||
|
||||
@@ -17,6 +17,14 @@ export const formatCooldown = (seconds: number, isRtl: boolean) => {
|
||||
return localizeDigits(base, isRtl)
|
||||
}
|
||||
|
||||
export const getOtpRemainingSeconds = (expiresAt: number | null) => {
|
||||
if (!expiresAt) {
|
||||
return 0
|
||||
}
|
||||
|
||||
return Math.max(0, Math.ceil((expiresAt - Date.now()) / 1000))
|
||||
}
|
||||
|
||||
export const getApiErrorMessage = (error: unknown, fallbackMessage: string) => {
|
||||
if (error instanceof ApiError) {
|
||||
return error.message
|
||||
|
||||
Reference in New Issue
Block a user