Compare commits
21 Commits
e60a4c9ab4
...
9b1cd772fb
| Author | SHA1 | Date | |
|---|---|---|---|
| 9b1cd772fb | |||
| 6fbfd419ea | |||
| 95d6cc192d | |||
| 319b3da294 | |||
| b688bb1ec3 | |||
| 2aa4b2b4cd | |||
| bba1be1f71 | |||
| a5a7a01da0 | |||
| 0e8d43f1ea | |||
| e635fd9c2c | |||
| 2772b36447 | |||
| 9ed7cb73e2 | |||
| 1c97339648 | |||
| d348eed47d | |||
| 60aa9c035a | |||
| 4ac0fd22e5 | |||
| a2bc1aa91f | |||
| 013c78a46d | |||
| 06d083c818 | |||
| 06c05ba8e9 | |||
| eb468333c1 |
217
README.md
217
README.md
@@ -1,73 +1,172 @@
|
||||
# React + TypeScript + Vite
|
||||
# Qlockify Frontend
|
||||
|
||||
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
|
||||
Frontend web application for Qlockify.
|
||||
|
||||
Currently, two official plugins are available:
|
||||
## Repository
|
||||
|
||||
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Babel](https://babeljs.io/) (or [oxc](https://oxc.rs) when used in [rolldown-vite](https://vite.dev/guide/rolldown)) for Fast Refresh
|
||||
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
|
||||
- Main deployment entrypoint: `https://git.amiirkhl.ir/Qlockify/qlockify-core-deployment.git`
|
||||
- Frontend repository declared by `origin`: `https://git.amiirkhl.ir/Qlockify/qlockify-frontend-deployment.git`
|
||||
- Backend repository declared by `origin`: `https://git.amiirkhl.ir/Qlockify/qlockify-backend-deployment.git`
|
||||
|
||||
## React Compiler
|
||||
## What This Repo Contains
|
||||
|
||||
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
|
||||
- React application
|
||||
- authenticated product UI
|
||||
- public landing page
|
||||
- workspace-based business screens
|
||||
- Persian and English localization
|
||||
- Google sign-in onboarding UI
|
||||
- client-side caching and API integration layer
|
||||
|
||||
## Expanding the ESLint configuration
|
||||
## Stack
|
||||
|
||||
If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
|
||||
- React `19`
|
||||
- TypeScript
|
||||
- Vite
|
||||
- React Router
|
||||
- Tailwind CSS
|
||||
- Headless UI / custom UI primitives
|
||||
- Sonner toasts
|
||||
- Recharts
|
||||
|
||||
```js
|
||||
export default defineConfig([
|
||||
globalIgnores(['dist']),
|
||||
{
|
||||
files: ['**/*.{ts,tsx}'],
|
||||
extends: [
|
||||
// Other configs...
|
||||
## Project Layout
|
||||
|
||||
// Remove tseslint.configs.recommended and replace with this
|
||||
tseslint.configs.recommendedTypeChecked,
|
||||
// Alternatively, use this for stricter rules
|
||||
tseslint.configs.strictTypeChecked,
|
||||
// Optionally, add this for stylistic rules
|
||||
tseslint.configs.stylisticTypeChecked,
|
||||
|
||||
// Other configs...
|
||||
],
|
||||
languageOptions: {
|
||||
parserOptions: {
|
||||
project: ['./tsconfig.node.json', './tsconfig.app.json'],
|
||||
tsconfigRootDir: import.meta.dirname,
|
||||
},
|
||||
// other options...
|
||||
},
|
||||
},
|
||||
])
|
||||
```text
|
||||
qlockify-frontend/
|
||||
public/
|
||||
src/
|
||||
api/
|
||||
components/
|
||||
context/
|
||||
hooks/
|
||||
lib/
|
||||
locales/
|
||||
pages/
|
||||
index.html
|
||||
package.json
|
||||
```
|
||||
|
||||
You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
|
||||
## Main Areas
|
||||
|
||||
```js
|
||||
// eslint.config.js
|
||||
import reactX from 'eslint-plugin-react-x'
|
||||
import reactDom from 'eslint-plugin-react-dom'
|
||||
- `src/pages`: route-level screens
|
||||
- `src/components`: reusable UI and page modules
|
||||
- `src/api`: backend request layer
|
||||
- `src/context`: workspace and notification state
|
||||
- `src/locales`: English and Persian dictionaries
|
||||
- `src/lib`: session, permissions, caching, helpers
|
||||
|
||||
export default defineConfig([
|
||||
globalIgnores(['dist']),
|
||||
{
|
||||
files: ['**/*.{ts,tsx}'],
|
||||
extends: [
|
||||
// Other configs...
|
||||
// Enable lint rules for React
|
||||
reactX.configs['recommended-typescript'],
|
||||
// Enable lint rules for React DOM
|
||||
reactDom.configs.recommended,
|
||||
],
|
||||
languageOptions: {
|
||||
parserOptions: {
|
||||
project: ['./tsconfig.node.json', './tsconfig.app.json'],
|
||||
tsconfigRootDir: import.meta.dirname,
|
||||
},
|
||||
// other options...
|
||||
},
|
||||
},
|
||||
])
|
||||
## Local Development
|
||||
|
||||
### 1. Install dependencies
|
||||
|
||||
```powershell
|
||||
npm install
|
||||
```
|
||||
|
||||
### 2. Configure environment
|
||||
|
||||
Copy and fill:
|
||||
|
||||
```text
|
||||
.env.sample -> .env
|
||||
```
|
||||
|
||||
Default local API base:
|
||||
|
||||
```text
|
||||
VITE_API_BASE_URL=http://localhost:8000
|
||||
```
|
||||
|
||||
If your backend runs behind `/api`, use:
|
||||
|
||||
```text
|
||||
VITE_API_BASE_URL=http://localhost:8000/api
|
||||
```
|
||||
|
||||
### 3. Start development server
|
||||
|
||||
```powershell
|
||||
npm run dev
|
||||
```
|
||||
|
||||
Default local URL:
|
||||
|
||||
- `http://localhost:5173`
|
||||
|
||||
## Available Scripts
|
||||
|
||||
Development:
|
||||
|
||||
```powershell
|
||||
npm run dev
|
||||
```
|
||||
|
||||
Production build:
|
||||
|
||||
```powershell
|
||||
npm run build
|
||||
```
|
||||
|
||||
Preview production build:
|
||||
|
||||
```powershell
|
||||
npm run preview
|
||||
```
|
||||
|
||||
Lint:
|
||||
|
||||
```powershell
|
||||
npm run lint
|
||||
```
|
||||
|
||||
## Product Routes
|
||||
|
||||
Main application routes include:
|
||||
|
||||
- `/`
|
||||
- `/auth`
|
||||
- `/auth/google/callback`
|
||||
- `/timesheet`
|
||||
- `/reports`
|
||||
- `/logs`
|
||||
- `/notifications`
|
||||
- `/workspaces`
|
||||
- `/projects`
|
||||
- `/clients`
|
||||
- `/tags`
|
||||
- `/profile`
|
||||
|
||||
## Authentication UX
|
||||
|
||||
Supported flows in the UI:
|
||||
|
||||
- password login
|
||||
- OTP login
|
||||
- OTP registration
|
||||
- Google sign-in
|
||||
|
||||
Google sign-in flow:
|
||||
|
||||
- start from the auth page
|
||||
- backend performs OAuth callback handling
|
||||
- frontend callback page loads the flow state
|
||||
- new users complete mobile onboarding
|
||||
- existing mobile owners verify claim via OTP
|
||||
|
||||
## Localization
|
||||
|
||||
The application is bilingual:
|
||||
|
||||
- English
|
||||
- Persian
|
||||
|
||||
Translation dictionaries live in:
|
||||
|
||||
- `src/locales/en.ts`
|
||||
- `src/locales/fa.ts`
|
||||
|
||||
## Notes
|
||||
|
||||
- the frontend expects the backend API contract defined in the backend repo
|
||||
- deployment, domain, SSL, and Nginx details belong in the deployment repo
|
||||
- this repo focuses on application UI and browser runtime behavior
|
||||
|
||||
@@ -2,9 +2,9 @@
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>frontend</title>
|
||||
<title>Qlockify.ir | Time Tracking for Modern Teams</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
|
||||
20
public/favicon.svg
Normal file
20
public/favicon.svg
Normal file
@@ -0,0 +1,20 @@
|
||||
<svg width="64" height="64" viewBox="0 0 64 64" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<rect width="64" height="64" rx="18" fill="#0F172A"/>
|
||||
<path
|
||||
d="M24 14C18.4772 14 14 18.4772 14 24V28H20V24C20 21.7909 21.7909 20 24 20H28V14H24Z"
|
||||
fill="#60A5FA"
|
||||
/>
|
||||
<path
|
||||
d="M40 14H36V20H40C42.2091 20 44 21.7909 44 24V28H50V24C50 18.4772 45.5228 14 40 14Z"
|
||||
fill="#60A5FA"
|
||||
/>
|
||||
<path
|
||||
d="M44 40C44 42.2091 42.2091 44 40 44H36V50H40C45.5228 50 50 45.5228 50 40V36H44V40Z"
|
||||
fill="#38BDF8"
|
||||
/>
|
||||
<path
|
||||
d="M20 40V36H14V40C14 45.5228 18.4772 50 24 50H28V44H24C21.7909 44 20 42.2091 20 40Z"
|
||||
fill="#38BDF8"
|
||||
/>
|
||||
<rect x="23" y="23" width="18" height="18" rx="5" fill="white" fill-opacity="0.08"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 734 B |
42
src/App.css
42
src/App.css
@@ -1,42 +0,0 @@
|
||||
#root {
|
||||
max-width: 1280px;
|
||||
margin: 0 auto;
|
||||
padding: 2rem;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.logo {
|
||||
height: 6em;
|
||||
padding: 1.5em;
|
||||
will-change: filter;
|
||||
transition: filter 300ms;
|
||||
}
|
||||
.logo:hover {
|
||||
filter: drop-shadow(0 0 2em #646cffaa);
|
||||
}
|
||||
.logo.react:hover {
|
||||
filter: drop-shadow(0 0 2em #61dafbaa);
|
||||
}
|
||||
|
||||
@keyframes logo-spin {
|
||||
from {
|
||||
transform: rotate(0deg);
|
||||
}
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: no-preference) {
|
||||
a:nth-of-type(2) .logo {
|
||||
animation: logo-spin infinite 20s linear;
|
||||
}
|
||||
}
|
||||
|
||||
.card {
|
||||
padding: 2em;
|
||||
}
|
||||
|
||||
.read-the-docs {
|
||||
color: #888;
|
||||
}
|
||||
76
src/App.tsx
76
src/App.tsx
@@ -1,4 +1,4 @@
|
||||
import { createBrowserRouter, RouterProvider, Navigate, Outlet } from "react-router-dom"
|
||||
import { createBrowserRouter, RouterProvider, Navigate, Outlet, useLocation } from "react-router-dom"
|
||||
import { useState } from "react"
|
||||
import { ThemeProvider } from "./components/ThemeProvider"
|
||||
import { LanguageProvider } from "./components/LanguageProvider"
|
||||
@@ -8,6 +8,7 @@ import { Sidebar } from './components/Sidebar';
|
||||
import { NotificationsProvider } from "./context/NotificationsContext"
|
||||
import { WorkspaceProvider } from "./context/WorkspaceContext"
|
||||
import Auth from "./pages/Auth"
|
||||
import GoogleAuthCallback from "./pages/GoogleAuthCallback"
|
||||
import Profile from "./pages/Profile"
|
||||
import Terms from "./pages/Terms"
|
||||
import Workspaces from "./pages/Workspaces"
|
||||
@@ -23,6 +24,9 @@ import Reports from "./pages/Reports"
|
||||
import Timesheet from "./pages/Timesheet"
|
||||
import Logs from "./pages/Logs"
|
||||
import NotificationsPage from "./pages/Notifications"
|
||||
import RateLimitPage from "./pages/RateLimit"
|
||||
import Landing from "./pages/Landing"
|
||||
import { isRateLimitActive } from "./lib/rateLimit"
|
||||
|
||||
const MainLayout = () => {
|
||||
const [mobileSidebarOpen, setMobileSidebarOpen] = useState(false)
|
||||
@@ -45,39 +49,61 @@ const MainLayout = () => {
|
||||
);
|
||||
};
|
||||
|
||||
const RootRedirect = () => {
|
||||
const AppRedirect = () => {
|
||||
if (isRateLimitActive()) {
|
||||
return <Navigate to="/rate-limit" replace />
|
||||
}
|
||||
|
||||
const isAuthenticated = !!localStorage.getItem("accessToken")
|
||||
return isAuthenticated ? <Navigate to="/timesheet" replace /> : <Navigate to="/auth" replace />
|
||||
}
|
||||
|
||||
const RateLimitGuard = () => {
|
||||
const location = useLocation()
|
||||
|
||||
if (isRateLimitActive() && location.pathname !== "/rate-limit") {
|
||||
return <Navigate to="/rate-limit" replace />
|
||||
}
|
||||
|
||||
return <Outlet />
|
||||
}
|
||||
|
||||
const router = createBrowserRouter([
|
||||
{
|
||||
element: (
|
||||
<WorkspaceProvider>
|
||||
<Outlet />
|
||||
</WorkspaceProvider>
|
||||
),
|
||||
element: <RateLimitGuard />,
|
||||
children: [
|
||||
{ path: "/", element: <RootRedirect /> },
|
||||
{ path: "/auth", element: <Auth /> },
|
||||
{ path: "/terms", element: <Terms /> },
|
||||
{
|
||||
element: <MainLayout />,
|
||||
element: (
|
||||
<WorkspaceProvider>
|
||||
<Outlet />
|
||||
</WorkspaceProvider>
|
||||
),
|
||||
children: [
|
||||
{ path: "/profile", element: <Profile /> },
|
||||
{ path: "/timesheet", element: <Timesheet /> },
|
||||
{ path: "/reports", element: <Reports /> },
|
||||
{ path: "/notifications", element: <NotificationsPage /> },
|
||||
{ path: "/logs", element: <Logs /> },
|
||||
{ path: "/tags", element: <Tags /> },
|
||||
{ path: "/workspaces", element: <Workspaces /> },
|
||||
{ path: "/workspaces/create", element: <CreateWorkspace /> },
|
||||
{ path: "/workspaces/:id", element: <WorkspaceDetail /> },
|
||||
{ path: "/workspaces/:id/edit", element: <EditWorkspace /> },
|
||||
{ path: "/clients", element: <Clients /> },
|
||||
{ path: "/projects", element: <Projects /> },
|
||||
{ path: "/projects/create", element: <ProjectCreate /> },
|
||||
{ path: "/projects/:id/edit", element: <ProjectEdit /> },
|
||||
{ path: "/", element: <Landing /> },
|
||||
{ path: "/app", element: <AppRedirect /> },
|
||||
{ path: "/auth", element: <Auth /> },
|
||||
{ path: "/auth/google/callback", element: <GoogleAuthCallback /> },
|
||||
{ path: "/terms", element: <Terms /> },
|
||||
{ path: "/rate-limit", element: <RateLimitPage /> },
|
||||
{
|
||||
element: <MainLayout />,
|
||||
children: [
|
||||
{ path: "/profile", element: <Profile /> },
|
||||
{ path: "/timesheet", element: <Timesheet /> },
|
||||
{ path: "/reports", element: <Reports /> },
|
||||
{ path: "/notifications", element: <NotificationsPage /> },
|
||||
{ path: "/logs", element: <Logs /> },
|
||||
{ path: "/tags", element: <Tags /> },
|
||||
{ path: "/workspaces", element: <Workspaces /> },
|
||||
{ path: "/workspaces/create", element: <CreateWorkspace /> },
|
||||
{ path: "/workspaces/:id", element: <WorkspaceDetail /> },
|
||||
{ path: "/workspaces/:id/edit", element: <EditWorkspace /> },
|
||||
{ path: "/clients", element: <Clients /> },
|
||||
{ path: "/projects", element: <Projects /> },
|
||||
{ path: "/projects/create", element: <ProjectCreate /> },
|
||||
{ path: "/projects/:id/edit", element: <ProjectEdit /> },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
|
||||
13
src/api.ts
13
src/api.ts
@@ -1,13 +0,0 @@
|
||||
import axios from 'axios';
|
||||
|
||||
export const api = axios.create({
|
||||
baseURL: 'http://localhost:8000',
|
||||
});
|
||||
|
||||
api.interceptors.request.use((config) => {
|
||||
const token = localStorage.getItem('accessToken');
|
||||
if (token && config.headers) {
|
||||
config.headers.Authorization = `Bearer ${token}`;
|
||||
}
|
||||
return config;
|
||||
});
|
||||
147
src/api/cache.ts
Normal file
147
src/api/cache.ts
Normal file
@@ -0,0 +1,147 @@
|
||||
import { buildApiError, authFetch } from "./client"
|
||||
import { getAccessToken, SESSION_CHANGED_EVENT } from "../lib/session"
|
||||
|
||||
const CACHE_PREFIX = "api-get-cache:v2:"
|
||||
|
||||
interface CacheEntry<T> {
|
||||
expiresAt: number
|
||||
data: T
|
||||
namespaces: string[]
|
||||
}
|
||||
|
||||
const memoryCache = new Map<string, CacheEntry<unknown>>()
|
||||
|
||||
const cloneData = <T>(value: T): T => {
|
||||
if (typeof structuredClone === "function") {
|
||||
return structuredClone(value)
|
||||
}
|
||||
return JSON.parse(JSON.stringify(value)) as T
|
||||
}
|
||||
|
||||
const decodeBase64Url = (value: string) => {
|
||||
const normalized = value.replace(/-/g, "+").replace(/_/g, "/")
|
||||
const padded = normalized.padEnd(Math.ceil(normalized.length / 4) * 4, "=")
|
||||
return atob(padded)
|
||||
}
|
||||
|
||||
const getCurrentUserCacheKey = () => {
|
||||
const token = getAccessToken()
|
||||
if (!token) return "anon"
|
||||
|
||||
try {
|
||||
const payload = JSON.parse(decodeBase64Url(token.split(".")[1] || ""))
|
||||
return String(payload.user_id || payload.sub || "anon")
|
||||
} catch {
|
||||
return "anon"
|
||||
}
|
||||
}
|
||||
|
||||
const normalizeEndpoint = (endpoint: string) => {
|
||||
const base = endpoint.startsWith("http") ? undefined : "https://cache.local"
|
||||
const url = new URL(endpoint, base)
|
||||
const entries = Array.from(url.searchParams.entries()).sort(([aKey, aValue], [bKey, bValue]) => {
|
||||
if (aKey === bKey) return aValue.localeCompare(bValue)
|
||||
return aKey.localeCompare(bKey)
|
||||
})
|
||||
const normalizedSearch = new URLSearchParams()
|
||||
entries.forEach(([key, value]) => normalizedSearch.append(key, value))
|
||||
const queryString = normalizedSearch.toString()
|
||||
return `${url.pathname}${queryString ? `?${queryString}` : ""}`
|
||||
}
|
||||
|
||||
const buildStorageKey = (endpoint: string) => `${CACHE_PREFIX}${getCurrentUserCacheKey()}:${normalizeEndpoint(endpoint)}`
|
||||
|
||||
const readStoredEntry = <T>(key: string): CacheEntry<T> | null => {
|
||||
const cached = memoryCache.get(key)
|
||||
if (cached) {
|
||||
if (cached.expiresAt > Date.now()) {
|
||||
return cached as CacheEntry<T>
|
||||
}
|
||||
memoryCache.delete(key)
|
||||
}
|
||||
|
||||
const raw = sessionStorage.getItem(key)
|
||||
if (!raw) return null
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(raw) as CacheEntry<T>
|
||||
if (parsed.expiresAt <= Date.now()) {
|
||||
sessionStorage.removeItem(key)
|
||||
return null
|
||||
}
|
||||
memoryCache.set(key, parsed as CacheEntry<unknown>)
|
||||
return parsed
|
||||
} catch {
|
||||
sessionStorage.removeItem(key)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
const writeEntry = <T>(key: string, entry: CacheEntry<T>) => {
|
||||
memoryCache.set(key, entry as CacheEntry<unknown>)
|
||||
sessionStorage.setItem(key, JSON.stringify(entry))
|
||||
}
|
||||
|
||||
export const invalidateApiCache = (namespaces: string[]) => {
|
||||
if (!namespaces.length) return
|
||||
|
||||
const namespaceSet = new Set(namespaces)
|
||||
const removeIfMatches = (key: string, entry: CacheEntry<unknown>) => {
|
||||
if (entry.namespaces.some((namespace) => namespaceSet.has(namespace))) {
|
||||
memoryCache.delete(key)
|
||||
sessionStorage.removeItem(key)
|
||||
}
|
||||
}
|
||||
|
||||
memoryCache.forEach((entry, key) => removeIfMatches(key, entry))
|
||||
for (let index = sessionStorage.length - 1; index >= 0; index -= 1) {
|
||||
const key = sessionStorage.key(index)
|
||||
if (!key || !key.startsWith(CACHE_PREFIX)) continue
|
||||
try {
|
||||
const parsed = JSON.parse(sessionStorage.getItem(key) || "null") as CacheEntry<unknown> | null
|
||||
if (parsed) {
|
||||
removeIfMatches(key, parsed)
|
||||
}
|
||||
} catch {
|
||||
sessionStorage.removeItem(key)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const clearApiCache = () => {
|
||||
memoryCache.clear()
|
||||
for (let index = sessionStorage.length - 1; index >= 0; index -= 1) {
|
||||
const key = sessionStorage.key(index)
|
||||
if (key?.startsWith(CACHE_PREFIX)) {
|
||||
sessionStorage.removeItem(key)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const cachedGetJson = async <T>(
|
||||
endpoint: string,
|
||||
options: { ttlMs: number; namespaces: string[]; bypass?: boolean },
|
||||
): Promise<T> => {
|
||||
const storageKey = buildStorageKey(endpoint)
|
||||
if (!options.bypass) {
|
||||
const cached = readStoredEntry<T>(storageKey)
|
||||
if (cached) {
|
||||
return cloneData(cached.data)
|
||||
}
|
||||
}
|
||||
|
||||
const response = await authFetch(endpoint)
|
||||
if (!response.ok) {
|
||||
throw await buildApiError(response)
|
||||
}
|
||||
|
||||
const data = (await response.json()) as T
|
||||
writeEntry(storageKey, {
|
||||
expiresAt: Date.now() + options.ttlMs,
|
||||
data,
|
||||
namespaces: options.namespaces,
|
||||
})
|
||||
return cloneData(data)
|
||||
}
|
||||
|
||||
window.addEventListener(SESSION_CHANGED_EVENT, clearApiCache)
|
||||
@@ -1,4 +1,10 @@
|
||||
import { API_BASE_URL } from "../config/constants"
|
||||
import {
|
||||
activateRateLimitLock,
|
||||
getRateLimitRemainingSeconds,
|
||||
getStoredRateLimitLock,
|
||||
isRateLimitActive,
|
||||
} from "../lib/rateLimit"
|
||||
import {
|
||||
clearSessionTokens,
|
||||
emitSessionChanged,
|
||||
@@ -8,9 +14,45 @@ import {
|
||||
|
||||
let refreshRequest: Promise<string | null> | null = null
|
||||
|
||||
export interface ApiErrorMessage {
|
||||
attr?: string | null
|
||||
detail: string
|
||||
code?: string | null
|
||||
}
|
||||
|
||||
export interface ApiErrorPayload {
|
||||
error?: string
|
||||
status_code?: number
|
||||
messages?: ApiErrorMessage[]
|
||||
code?: string
|
||||
retry_after_seconds?: number | null
|
||||
throttled_until?: string | null
|
||||
}
|
||||
|
||||
export class ApiError extends Error {
|
||||
status: number
|
||||
error: string
|
||||
messages: ApiErrorMessage[]
|
||||
code: string | null
|
||||
retryAfterSeconds: number | null
|
||||
throttledUntil: string | null
|
||||
|
||||
constructor(status: number, payload: ApiErrorPayload, fallbackMessage: string) {
|
||||
const detailMessage = payload.messages?.[0]?.detail
|
||||
super(detailMessage || payload.error || fallbackMessage)
|
||||
this.name = "ApiError"
|
||||
this.status = status
|
||||
this.error = payload.error || fallbackMessage
|
||||
this.messages = payload.messages || []
|
||||
this.code = payload.code || null
|
||||
this.retryAfterSeconds = payload.retry_after_seconds ?? null
|
||||
this.throttledUntil = payload.throttled_until ?? null
|
||||
}
|
||||
}
|
||||
|
||||
const cleanBaseUrl = API_BASE_URL.replace(/\/+$/, "")
|
||||
|
||||
const buildUrl = (endpoint: string) => {
|
||||
export const buildApiUrl = (endpoint: string) => {
|
||||
const cleanEndpoint = endpoint.startsWith("/") ? endpoint : `/${endpoint}`
|
||||
return `${cleanBaseUrl}${cleanEndpoint}`
|
||||
}
|
||||
@@ -52,6 +94,50 @@ const clearSessionAndRedirect = () => {
|
||||
}
|
||||
}
|
||||
|
||||
const toIntOrNull = (value: string | number | null | undefined) => {
|
||||
if (typeof value === "number" && Number.isFinite(value)) {
|
||||
return Math.max(0, Math.ceil(value))
|
||||
}
|
||||
|
||||
if (typeof value === "string" && value.trim()) {
|
||||
const parsed = Number.parseInt(value, 10)
|
||||
if (Number.isFinite(parsed)) {
|
||||
return Math.max(0, parsed)
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
const redirectToRateLimitPage = () => {
|
||||
if (window.location.pathname !== "/rate-limit") {
|
||||
window.location.replace("/rate-limit")
|
||||
}
|
||||
}
|
||||
|
||||
const createLockedResponse = () => {
|
||||
const lock = getStoredRateLimitLock()
|
||||
const retryAfterSeconds = getRateLimitRemainingSeconds(lock)
|
||||
const payload = {
|
||||
error: lock?.message || "Too many requests",
|
||||
status_code: 429,
|
||||
messages: [{ detail: lock?.message || "Too many requests" }],
|
||||
code: lock?.code || "throttled",
|
||||
retry_after_seconds: retryAfterSeconds,
|
||||
throttled_until: lock?.throttledUntil || null,
|
||||
}
|
||||
|
||||
return normalizeJsonResponse(
|
||||
new Response(JSON.stringify(payload), {
|
||||
status: 429,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Retry-After": String(retryAfterSeconds),
|
||||
},
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
const shouldAttemptRefresh = (endpoint: string) => {
|
||||
const normalizedEndpoint = endpoint.startsWith("/") ? endpoint : `/${endpoint}`
|
||||
return ![
|
||||
@@ -68,7 +154,7 @@ const refreshAccessToken = async () => {
|
||||
|
||||
if (!refreshRequest) {
|
||||
refreshRequest = (async () => {
|
||||
const response = await fetch(buildUrl("/api/users/token/refresh/"), {
|
||||
const response = await fetch(buildApiUrl("/api/users/token/refresh/"), {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
@@ -103,7 +189,34 @@ const refreshAccessToken = async () => {
|
||||
return refreshRequest
|
||||
}
|
||||
|
||||
export const buildApiError = async (response: Response) => {
|
||||
let payload: ApiErrorPayload = {}
|
||||
|
||||
try {
|
||||
payload = await response.clone().json()
|
||||
} catch {
|
||||
payload = {}
|
||||
}
|
||||
|
||||
if (payload.retry_after_seconds == null) {
|
||||
const retryAfter = toIntOrNull(response.headers.get("Retry-After"))
|
||||
if (retryAfter != null) {
|
||||
payload.retry_after_seconds = retryAfter
|
||||
}
|
||||
}
|
||||
|
||||
const fallbackMessage =
|
||||
response.statusText || (response.status === 429 ? "Too many requests" : "Request failed")
|
||||
|
||||
return new ApiError(response.status, payload, fallbackMessage)
|
||||
}
|
||||
|
||||
export const authFetch = async (endpoint: string, options: RequestInit = {}, allowRetry = true): Promise<Response> => {
|
||||
if (isRateLimitActive()) {
|
||||
redirectToRateLimitPage()
|
||||
return createLockedResponse()
|
||||
}
|
||||
|
||||
const token = getAccessToken()
|
||||
const isFormData = options.body instanceof FormData
|
||||
|
||||
@@ -113,7 +226,7 @@ export const authFetch = async (endpoint: string, options: RequestInit = {}, all
|
||||
...options.headers,
|
||||
}
|
||||
|
||||
const response = await fetch(buildUrl(endpoint), {
|
||||
const response = await fetch(buildApiUrl(endpoint), {
|
||||
...options,
|
||||
headers,
|
||||
})
|
||||
@@ -144,5 +257,24 @@ export const authFetch = async (endpoint: string, options: RequestInit = {}, all
|
||||
return response
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
const apiError = await buildApiError(response)
|
||||
if (
|
||||
response.status === 429 ||
|
||||
apiError.code === "throttled" ||
|
||||
apiError.retryAfterSeconds != null ||
|
||||
apiError.throttledUntil
|
||||
) {
|
||||
activateRateLimitLock({
|
||||
status: response.status,
|
||||
code: apiError.code,
|
||||
message: apiError.message,
|
||||
retryAfterSeconds: apiError.retryAfterSeconds,
|
||||
throttledUntil: apiError.throttledUntil,
|
||||
})
|
||||
redirectToRateLimitPage()
|
||||
}
|
||||
}
|
||||
|
||||
return normalizeJsonResponse(response)
|
||||
}
|
||||
|
||||
@@ -1,12 +1,26 @@
|
||||
import { authFetch } from "./client";
|
||||
|
||||
export const getClients = async (
|
||||
workspaceId: string,
|
||||
search: string = "",
|
||||
ordering: string = "",
|
||||
limit: number = 10,
|
||||
offset: number = 0
|
||||
) => {
|
||||
import { authFetch } from "./client";
|
||||
import { cachedGetJson, invalidateApiCache } from "./cache";
|
||||
|
||||
export interface Client {
|
||||
id: string
|
||||
name: string
|
||||
notes?: string
|
||||
}
|
||||
|
||||
interface PaginatedResponse<T> {
|
||||
count: number
|
||||
next: string | null
|
||||
previous: string | null
|
||||
results: T[]
|
||||
}
|
||||
|
||||
export const getClients = async (
|
||||
workspaceId: string,
|
||||
search: string = "",
|
||||
ordering: string = "",
|
||||
limit: number = 10,
|
||||
offset: number = 0
|
||||
): Promise<PaginatedResponse<Client>> => {
|
||||
const queryParams = new URLSearchParams({
|
||||
workspace: workspaceId,
|
||||
limit: limit.toString(),
|
||||
@@ -16,12 +30,11 @@ export const getClients = async (
|
||||
if (search) queryParams.append("search", search);
|
||||
if (ordering) queryParams.append("ordering", ordering);
|
||||
|
||||
const response = await authFetch(`/api/clients/?${queryParams.toString()}`);
|
||||
if (!response.ok) {
|
||||
throw new Error("Failed to fetch clients");
|
||||
}
|
||||
return response.json();
|
||||
};
|
||||
return cachedGetJson<PaginatedResponse<Client>>(`/api/clients/?${queryParams.toString()}`, {
|
||||
ttlMs: 5 * 60 * 1000,
|
||||
namespaces: ["clients"],
|
||||
});
|
||||
};
|
||||
|
||||
export const createClient = async (workspaceId: string, data: { name: string; notes: string }) => {
|
||||
const response = await authFetch("/api/clients/", {
|
||||
@@ -32,12 +45,14 @@ export const createClient = async (workspaceId: string, data: { name: string; no
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => null);
|
||||
throw new Error(errorData?.detail || errorData?.message || "Failed to create client");
|
||||
}
|
||||
return response.json();
|
||||
};
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => null);
|
||||
throw new Error(errorData?.detail || errorData?.message || "Failed to create client");
|
||||
}
|
||||
const payload = await response.json();
|
||||
invalidateApiCache(["clients", "reports"]);
|
||||
return payload;
|
||||
};
|
||||
|
||||
export const updateClient = async (id: string, data: { name?: string; notes?: string }) => {
|
||||
const response = await authFetch(`/api/clients/${id}/`, {
|
||||
@@ -45,25 +60,28 @@ export const updateClient = async (id: string, data: { name?: string; notes?: st
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => null);
|
||||
throw new Error(errorData?.detail || errorData?.message || "Failed to update client");
|
||||
}
|
||||
return response.json();
|
||||
};
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => null);
|
||||
throw new Error(errorData?.detail || errorData?.message || "Failed to update client");
|
||||
}
|
||||
const payload = await response.json();
|
||||
invalidateApiCache(["clients", "reports"]);
|
||||
return payload;
|
||||
};
|
||||
|
||||
export const deleteClient = async (id: string) => {
|
||||
const response = await authFetch(`/api/clients/${id}/`, {
|
||||
method: "DELETE",
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => null);
|
||||
throw new Error(errorData?.detail || errorData?.message || "Failed to delete client");
|
||||
}
|
||||
|
||||
if (response.status === 204) {
|
||||
return { success: true };
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => null);
|
||||
throw new Error(errorData?.detail || errorData?.message || "Failed to delete client");
|
||||
}
|
||||
invalidateApiCache(["clients", "reports"]);
|
||||
|
||||
if (response.status === 204) {
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
return response.json().catch(() => ({ success: true }));
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { authFetch } from "./client";
|
||||
import { cachedGetJson, invalidateApiCache } from "./cache";
|
||||
|
||||
interface AuditUser {
|
||||
id: string;
|
||||
@@ -56,10 +57,10 @@ export const getProjects = async (
|
||||
if (params.is_archived !== undefined) queryParams.append("is_archived", params.is_archived.toString());
|
||||
if (params.ordering !== undefined) queryParams.append("ordering", params.ordering.toString());
|
||||
|
||||
const response = await authFetch(`/api/projects/?${queryParams.toString()}`);
|
||||
|
||||
if (!response.ok) throw new Error("Failed to fetch projects");
|
||||
const data = await response.json();
|
||||
const data = await cachedGetJson<any>(`/api/projects/?${queryParams.toString()}`, {
|
||||
ttlMs: 5 * 60 * 1000,
|
||||
namespaces: ["projects"],
|
||||
});
|
||||
if (Array.isArray(data)) return data;
|
||||
if (Array.isArray(data?.items)) {
|
||||
return {
|
||||
@@ -89,12 +90,14 @@ export const createProject = async (
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => null);
|
||||
throw new Error(errorData?.detail || errorData?.message || "Failed to create project");
|
||||
}
|
||||
return response.json();
|
||||
};
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => null);
|
||||
throw new Error(errorData?.detail || errorData?.message || "Failed to create project");
|
||||
}
|
||||
const payload = await response.json();
|
||||
invalidateApiCache(["projects", "reports"]);
|
||||
return payload;
|
||||
};
|
||||
|
||||
export const updateProject = async (
|
||||
id: string,
|
||||
@@ -105,25 +108,28 @@ export const updateProject = async (
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => null);
|
||||
throw new Error(errorData?.detail || errorData?.message || "Failed to update project");
|
||||
}
|
||||
return response.json();
|
||||
};
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => null);
|
||||
throw new Error(errorData?.detail || errorData?.message || "Failed to update project");
|
||||
}
|
||||
const payload = await response.json();
|
||||
invalidateApiCache(["projects", "reports"]);
|
||||
return payload;
|
||||
};
|
||||
|
||||
export const deleteProject = async (id: string) => {
|
||||
const response = await authFetch(`/api/projects/${id}/`, {
|
||||
method: "DELETE",
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => null);
|
||||
throw new Error(errorData?.detail || errorData?.message || "Failed to delete project");
|
||||
}
|
||||
|
||||
if (response.status === 204) return { success: true };
|
||||
return response.json().catch(() => ({ success: true }));
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => null);
|
||||
throw new Error(errorData?.detail || errorData?.message || "Failed to delete project");
|
||||
}
|
||||
invalidateApiCache(["projects", "reports"]);
|
||||
|
||||
if (response.status === 204) return { success: true };
|
||||
return response.json().catch(() => ({ success: true }));
|
||||
};
|
||||
|
||||
export const toggleArchiveProject = async (id: string) => {
|
||||
@@ -131,9 +137,11 @@ export const toggleArchiveProject = async (id: string) => {
|
||||
method: "POST",
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => null);
|
||||
throw new Error(errorData?.detail || errorData?.message || `Failed to archive project`);
|
||||
}
|
||||
return response.json();
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => null);
|
||||
throw new Error(errorData?.detail || errorData?.message || `Failed to archive project`);
|
||||
}
|
||||
const payload = await response.json();
|
||||
invalidateApiCache(["projects", "reports"]);
|
||||
return payload;
|
||||
};
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { authFetch } from "./client";
|
||||
import { cachedGetJson, invalidateApiCache } from "./cache";
|
||||
|
||||
export interface RateUser {
|
||||
id: string;
|
||||
@@ -55,13 +56,35 @@ const ensurePaginated = async <T>(response: Response): Promise<PaginatedResponse
|
||||
};
|
||||
|
||||
export const getPriceUnits = async () => {
|
||||
const response = await authFetch("/api/price-units/");
|
||||
return ensurePaginated<PriceUnit>(response);
|
||||
const data = await cachedGetJson<any>("/api/price-units/", {
|
||||
ttlMs: 5 * 60 * 1000,
|
||||
namespaces: ["price-units"],
|
||||
});
|
||||
if (Array.isArray(data)) {
|
||||
return { count: data.length, next: null, previous: null, results: data };
|
||||
}
|
||||
return {
|
||||
count: data.count || data.results?.length || 0,
|
||||
next: data.next || null,
|
||||
previous: data.previous || null,
|
||||
results: data.results || [],
|
||||
};
|
||||
};
|
||||
|
||||
export const getWorkspaceUserRates = async (workspaceId: string) => {
|
||||
const response = await authFetch(`/api/workspace-user-rates/?workspace=${workspaceId}`);
|
||||
return ensurePaginated<WorkspaceUserRate>(response);
|
||||
const data = await cachedGetJson<any>(`/api/workspace-user-rates/?workspace=${workspaceId}`, {
|
||||
ttlMs: 5 * 60 * 1000,
|
||||
namespaces: ["workspace-rates"],
|
||||
});
|
||||
if (Array.isArray(data)) {
|
||||
return { count: data.length, next: null, previous: null, results: data };
|
||||
}
|
||||
return {
|
||||
count: data.count || data.results?.length || 0,
|
||||
next: data.next || null,
|
||||
previous: data.previous || null,
|
||||
results: data.results || [],
|
||||
};
|
||||
};
|
||||
|
||||
export const createWorkspaceUserRate = async (data: {
|
||||
@@ -78,6 +101,7 @@ export const createWorkspaceUserRate = async (data: {
|
||||
const errorData = await response.json().catch(() => null);
|
||||
throw new Error(errorData?.detail || errorData?.message || "Failed to save workspace user rate");
|
||||
}
|
||||
invalidateApiCache(["workspace-rates", "reports"]);
|
||||
return response.json() as Promise<WorkspaceUserRate>;
|
||||
};
|
||||
|
||||
@@ -93,6 +117,7 @@ export const updateWorkspaceUserRate = async (
|
||||
const errorData = await response.json().catch(() => null);
|
||||
throw new Error(errorData?.detail || errorData?.message || "Failed to update workspace user rate");
|
||||
}
|
||||
invalidateApiCache(["workspace-rates", "reports"]);
|
||||
return response.json() as Promise<WorkspaceUserRate>;
|
||||
};
|
||||
|
||||
@@ -104,4 +129,5 @@ export const deleteWorkspaceUserRate = async (rateId: string) => {
|
||||
const errorData = await response.json().catch(() => null);
|
||||
throw new Error(errorData?.detail || errorData?.message || "Failed to delete workspace user rate");
|
||||
}
|
||||
invalidateApiCache(["workspace-rates", "reports"]);
|
||||
};
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { authFetch } from "./client";
|
||||
import { cachedGetJson } from "./cache";
|
||||
|
||||
export type ReportPeriod =
|
||||
| "this_week"
|
||||
@@ -150,15 +151,17 @@ const toQueryString = (filters: ReportFilters) => {
|
||||
};
|
||||
|
||||
export const getChartReport = async (filters: ReportFilters): Promise<ChartReportResponse> => {
|
||||
const response = await authFetch(`/api/reports/chart/?${toQueryString(filters)}`);
|
||||
if (!response.ok) throw new Error("Failed to load chart report");
|
||||
return response.json();
|
||||
return cachedGetJson(`/api/reports/chart/?${toQueryString(filters)}`, {
|
||||
ttlMs: 60 * 1000,
|
||||
namespaces: ["reports"],
|
||||
});
|
||||
};
|
||||
|
||||
export const getTableReport = async (filters: ReportFilters): Promise<TableReportResponse> => {
|
||||
const response = await authFetch(`/api/reports/table/?${toQueryString(filters)}`);
|
||||
if (!response.ok) throw new Error("Failed to load table report");
|
||||
return response.json();
|
||||
return cachedGetJson(`/api/reports/table/?${toQueryString(filters)}`, {
|
||||
ttlMs: 60 * 1000,
|
||||
namespaces: ["reports"],
|
||||
});
|
||||
};
|
||||
|
||||
export const getDayDetailsReport = async (
|
||||
@@ -166,9 +169,10 @@ export const getDayDetailsReport = async (
|
||||
day: string,
|
||||
): Promise<DayDetailsResponse> => {
|
||||
const query = `${toQueryString(filters)}&day=${encodeURIComponent(day)}`;
|
||||
const response = await authFetch(`/api/reports/day-details/?${query}`);
|
||||
if (!response.ok) throw new Error("Failed to load day details");
|
||||
return response.json();
|
||||
return cachedGetJson(`/api/reports/day-details/?${query}`, {
|
||||
ttlMs: 30 * 1000,
|
||||
namespaces: ["reports"],
|
||||
});
|
||||
};
|
||||
|
||||
export const createReportExport = async (
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { authFetch } from "./client";
|
||||
import { cachedGetJson, invalidateApiCache } from "./cache";
|
||||
|
||||
interface AuditUser {
|
||||
id: string;
|
||||
@@ -36,9 +37,10 @@ export const getTags = async (
|
||||
if (params.search) query.append("search", params.search);
|
||||
if (params.ordering) query.append("ordering", params.ordering);
|
||||
|
||||
const response = await authFetch(`/api/tags/?${query.toString()}`);
|
||||
if (!response.ok) throw new Error("Failed to fetch tags");
|
||||
return response.json();
|
||||
return cachedGetJson(`/api/tags/?${query.toString()}`, {
|
||||
ttlMs: 5 * 60 * 1000,
|
||||
namespaces: ["tags"],
|
||||
});
|
||||
};
|
||||
|
||||
export const createTag = async (workspaceId: string, data: { name: string; color: string }) => {
|
||||
@@ -50,7 +52,9 @@ export const createTag = async (workspaceId: string, data: { name: string; color
|
||||
}),
|
||||
});
|
||||
if (!response.ok) throw new Error("Failed to create tag");
|
||||
return response.json();
|
||||
const payload = await response.json();
|
||||
invalidateApiCache(["tags", "reports"]);
|
||||
return payload;
|
||||
};
|
||||
|
||||
export const updateTag = async (id: string, data: Partial<Pick<Tag, "name" | "color">>) => {
|
||||
@@ -59,7 +63,9 @@ export const updateTag = async (id: string, data: Partial<Pick<Tag, "name" | "co
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
if (!response.ok) throw new Error("Failed to update tag");
|
||||
return response.json();
|
||||
const payload = await response.json();
|
||||
invalidateApiCache(["tags", "reports"]);
|
||||
return payload;
|
||||
};
|
||||
|
||||
export const deleteTag = async (id: string) => {
|
||||
@@ -67,4 +73,5 @@ export const deleteTag = async (id: string) => {
|
||||
method: "DELETE",
|
||||
});
|
||||
if (!response.ok) throw new Error("Failed to delete tag");
|
||||
invalidateApiCache(["tags", "reports"]);
|
||||
};
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { authFetch } from "./client";
|
||||
import { invalidateApiCache } from "./cache";
|
||||
|
||||
export interface TimeEntryProjectDetails {
|
||||
id: string;
|
||||
@@ -109,7 +110,9 @@ export const createTimeEntry = async (payload: TimeEntryPayload) => {
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
if (!response.ok) throw new Error("Failed to create time entry");
|
||||
return response.json();
|
||||
const data = await response.json();
|
||||
invalidateApiCache(["reports"]);
|
||||
return data;
|
||||
};
|
||||
|
||||
export const updateTimeEntry = async (id: string, payload: TimeEntryPayload) => {
|
||||
@@ -118,7 +121,9 @@ export const updateTimeEntry = async (id: string, payload: TimeEntryPayload) =>
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
if (!response.ok) throw new Error("Failed to update time entry");
|
||||
return response.json();
|
||||
const data = await response.json();
|
||||
invalidateApiCache(["reports"]);
|
||||
return data;
|
||||
};
|
||||
|
||||
export const stopTimeEntry = async (id: string, endTime?: string) => {
|
||||
@@ -127,7 +132,9 @@ export const stopTimeEntry = async (id: string, endTime?: string) => {
|
||||
body: JSON.stringify(endTime ? { end_time: endTime } : {}),
|
||||
});
|
||||
if (!response.ok) throw new Error("Failed to stop time entry");
|
||||
return response.json();
|
||||
const data = await response.json();
|
||||
invalidateApiCache(["reports"]);
|
||||
return data;
|
||||
};
|
||||
|
||||
export const deleteTimeEntry = async (id: string) => {
|
||||
@@ -135,4 +142,5 @@ export const deleteTimeEntry = async (id: string) => {
|
||||
method: "DELETE",
|
||||
});
|
||||
if (!response.ok) throw new Error("Failed to delete time entry");
|
||||
invalidateApiCache(["reports"]);
|
||||
};
|
||||
|
||||
104
src/api/users.ts
104
src/api/users.ts
@@ -1,35 +1,99 @@
|
||||
import { authFetch } from './client';
|
||||
import { authFetch, buildApiError, buildApiUrl } from './client';
|
||||
|
||||
// --- Auth Endpoints ---
|
||||
|
||||
export const loginWithPassword = async (mobile: string, password: string) => {
|
||||
const response = await authFetch('/api/users/login/', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ mobile, password })
|
||||
});
|
||||
if (!response.ok) throw new Error('Failed to login with password');
|
||||
return response.json();
|
||||
};
|
||||
export const loginWithPassword = async (mobile: string, password: string) => {
|
||||
const response = await authFetch('/api/users/login/', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ mobile, password })
|
||||
});
|
||||
if (!response.ok) throw await buildApiError(response);
|
||||
return response.json();
|
||||
};
|
||||
|
||||
export const sendOtp = async (mobile: string, mode: string) => {
|
||||
const response = await authFetch('/api/users/otp/send/', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ mobile, mode })
|
||||
});
|
||||
if (!response.ok) throw new Error('Failed to send OTP');
|
||||
return response.json();
|
||||
};
|
||||
export const sendOtp = async (mobile: string, mode: string) => {
|
||||
const response = await authFetch('/api/users/otp/send/', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ mobile, mode })
|
||||
});
|
||||
if (!response.ok) throw await buildApiError(response);
|
||||
return response.json();
|
||||
};
|
||||
|
||||
export const loginWithOtp = async (mobile: string, otp: string) => {
|
||||
const response = await authFetch('/api/users/otp/login/', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ mobile, code: otp })
|
||||
});
|
||||
if (!response.ok) throw new Error('Failed to login with OTP');
|
||||
if (!response.ok) throw await buildApiError(response);
|
||||
return response.json();
|
||||
};
|
||||
|
||||
export const logoutUser = async (refreshToken: string) => {
|
||||
|
||||
export const startGoogleLogin = () => {
|
||||
window.location.assign(buildApiUrl("/api/users/oauth/google/start/"));
|
||||
};
|
||||
|
||||
export type GoogleOAuthFlowResponse =
|
||||
| {
|
||||
status: "authenticated";
|
||||
access: string;
|
||||
refresh: string;
|
||||
}
|
||||
| {
|
||||
status: "collect_mobile";
|
||||
email: string;
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
avatar_url: string;
|
||||
}
|
||||
| {
|
||||
status: "claim_required";
|
||||
mobile: string;
|
||||
detail?: string;
|
||||
};
|
||||
|
||||
export const getGoogleOAuthFlow = async (flow: string): Promise<GoogleOAuthFlowResponse> => {
|
||||
const response = await authFetch(`/api/users/oauth/google/flow/?flow=${encodeURIComponent(flow)}`, {
|
||||
method: "GET",
|
||||
});
|
||||
if (!response.ok) throw await buildApiError(response);
|
||||
return response.json();
|
||||
};
|
||||
|
||||
export const completeGoogleOAuthSignup = async (
|
||||
flow: string,
|
||||
mobile: string,
|
||||
): Promise<GoogleOAuthFlowResponse> => {
|
||||
const response = await authFetch("/api/users/oauth/google/complete/", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ flow, mobile }),
|
||||
});
|
||||
if (!response.ok) throw await buildApiError(response);
|
||||
return response.json();
|
||||
};
|
||||
|
||||
export const sendGoogleOAuthClaimOtp = async (flow: string) => {
|
||||
const response = await authFetch("/api/users/oauth/google/claim/send-otp/", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ flow }),
|
||||
});
|
||||
if (!response.ok) throw await buildApiError(response);
|
||||
return response.json();
|
||||
};
|
||||
|
||||
export const verifyGoogleOAuthClaim = async (
|
||||
flow: string,
|
||||
code: string,
|
||||
): Promise<GoogleOAuthFlowResponse> => {
|
||||
const response = await authFetch("/api/users/oauth/google/claim/verify/", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ flow, code }),
|
||||
});
|
||||
if (!response.ok) throw await buildApiError(response);
|
||||
return response.json();
|
||||
};
|
||||
|
||||
export const logoutUser = async (refreshToken: string) => {
|
||||
const response = await authFetch('/api/users/logout/', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ refresh: refreshToken })
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { authFetch } from "./client";
|
||||
import { authFetch } from "./client";
|
||||
import { cachedGetJson, invalidateApiCache } from "./cache";
|
||||
|
||||
export interface Workspace {
|
||||
id: string;
|
||||
@@ -52,13 +53,10 @@ const toQueryString = (params?: Record<string, QueryValue>) => {
|
||||
export const fetchWorkspaces = async (params?: Record<string, QueryValue>): Promise<PaginatedResponse<Workspace>> => {
|
||||
const query = toQueryString(params);
|
||||
const url = `/api/workspaces/${query ? `?${query}` : ''}`;
|
||||
const response = await authFetch(url);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error("Failed to fetch workspaces");
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
const data = await cachedGetJson<any>(url, {
|
||||
ttlMs: 60 * 1000,
|
||||
namespaces: ["workspaces"],
|
||||
});
|
||||
|
||||
if (Array.isArray(data)) {
|
||||
return { count: data.length, next: null, previous: null, results: data };
|
||||
@@ -109,12 +107,14 @@ export const createWorkspace = async (data: {
|
||||
body,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json();
|
||||
throw new Error(errorData.error || JSON.stringify(errorData) || 'Failed to create workspace');
|
||||
}
|
||||
return await response.json();
|
||||
};
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json();
|
||||
throw new Error(errorData.error || JSON.stringify(errorData) || 'Failed to create workspace');
|
||||
}
|
||||
const payload = await response.json();
|
||||
invalidateApiCache(["workspaces", "workspace-memberships", "reports"]);
|
||||
return payload;
|
||||
};
|
||||
|
||||
export const updateWorkspace = async (
|
||||
id: string,
|
||||
@@ -144,30 +144,32 @@ export const updateWorkspace = async (
|
||||
body,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json();
|
||||
throw new Error(errorData.error || JSON.stringify(errorData) || 'Failed to update workspace');
|
||||
}
|
||||
return await response.json();
|
||||
};
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json();
|
||||
throw new Error(errorData.error || JSON.stringify(errorData) || 'Failed to update workspace');
|
||||
}
|
||||
const payload = await response.json();
|
||||
invalidateApiCache(["workspaces"]);
|
||||
return payload;
|
||||
};
|
||||
|
||||
export const deleteWorkspace = async (id: string): Promise<void> => {
|
||||
const response = await authFetch(`/api/workspaces/${id}/`, {
|
||||
method: 'DELETE',
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to delete workspace');
|
||||
}
|
||||
};
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to delete workspace');
|
||||
}
|
||||
invalidateApiCache(["workspaces", "workspace-memberships", "workspace-rates", "reports"]);
|
||||
};
|
||||
|
||||
export const fetchWorkspaceMemberships = async (params?: Record<string, QueryValue>): Promise<PaginatedResponse<WorkspaceMembership>> => {
|
||||
const queryParams = toQueryString(params);
|
||||
const response = await authFetch(`/api/workspace-memberships/?${queryParams.toString()}`);
|
||||
|
||||
if (!response.ok) throw new Error("Failed to fetch workspace memberships");
|
||||
|
||||
const data = await response.json();
|
||||
const data = await cachedGetJson<any>(`/api/workspace-memberships/?${queryParams.toString()}`, {
|
||||
ttlMs: 5 * 60 * 1000,
|
||||
namespaces: ["workspace-memberships"],
|
||||
});
|
||||
|
||||
if (Array.isArray(data)) {
|
||||
return { count: data.length, next: null, previous: null, results: data };
|
||||
@@ -187,23 +189,26 @@ export const addWorkspaceMembership = async (data: { workspace: string; user: st
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => ({}));
|
||||
throw new Error(errorData.error || JSON.stringify(errorData) || 'Failed to add workspace membership');
|
||||
}
|
||||
|
||||
return await response.json();
|
||||
};
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => ({}));
|
||||
throw new Error(errorData.error || JSON.stringify(errorData) || 'Failed to add workspace membership');
|
||||
}
|
||||
|
||||
const payload = await response.json();
|
||||
invalidateApiCache(["workspace-memberships", "reports"]);
|
||||
return payload;
|
||||
};
|
||||
|
||||
export const removeWorkspaceMembership = async (membershipId: string): Promise<void> => {
|
||||
const response = await authFetch(`/api/workspace-memberships/${membershipId}/`, {
|
||||
method: 'DELETE',
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to remove workspace membership');
|
||||
}
|
||||
};
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to remove workspace membership');
|
||||
}
|
||||
invalidateApiCache(["workspace-memberships", "reports"]);
|
||||
};
|
||||
|
||||
export const updateWorkspaceMembership = async (membershipId: string | number, data: { role: string }) => {
|
||||
const response = await authFetch(`/api/workspace-memberships/${membershipId}/`, {
|
||||
@@ -211,10 +216,12 @@ export const updateWorkspaceMembership = async (membershipId: string | number, d
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => ({}));
|
||||
throw new Error(errorData.error || JSON.stringify(errorData) || 'Failed to update membership');
|
||||
}
|
||||
|
||||
return await response.json();
|
||||
};
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => ({}));
|
||||
throw new Error(errorData.error || JSON.stringify(errorData) || 'Failed to update membership');
|
||||
}
|
||||
|
||||
const payload = await response.json();
|
||||
invalidateApiCache(["workspace-memberships", "reports"]);
|
||||
return payload;
|
||||
};
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>
|
||||
|
Before Width: | Height: | Size: 4.0 KiB |
@@ -1,9 +0,0 @@
|
||||
import React from "react"
|
||||
|
||||
export function AppLayout({ children }: { children: React.ReactNode }) {
|
||||
return (
|
||||
<div className="min-h-screen flex flex-col bg-white dark:bg-slate-950 text-slate-900 dark:text-slate-50 transition-colors">
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
25
src/components/EmptyStateCard.tsx
Normal file
25
src/components/EmptyStateCard.tsx
Normal file
@@ -0,0 +1,25 @@
|
||||
import type { LucideIcon } from "lucide-react";
|
||||
|
||||
interface EmptyStateCardProps {
|
||||
icon: LucideIcon;
|
||||
title: string;
|
||||
description: string;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export default function EmptyStateCard({
|
||||
icon: Icon,
|
||||
title,
|
||||
description,
|
||||
className = "",
|
||||
}: EmptyStateCardProps) {
|
||||
return (
|
||||
<div
|
||||
className={`flex flex-1 flex-col justify-center rounded-3xl border-2 border-dashed border-slate-200 bg-white p-12 text-center shadow-sm dark:border-slate-800 dark:bg-slate-900 ${className}`}
|
||||
>
|
||||
<Icon className="mx-auto mb-3 h-12 w-12 text-slate-300 dark:text-slate-700" />
|
||||
<h3 className="text-lg font-medium text-slate-900 dark:text-white">{title}</h3>
|
||||
<p className="mt-1 text-slate-500 dark:text-slate-400">{description}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Search, ArrowUpDown } from 'lucide-react';
|
||||
import { Select } from './ui/Select';
|
||||
import { Input } from './ui/input';
|
||||
import { Select } from './ui/Select';
|
||||
|
||||
interface FilterBarProps {
|
||||
searchQuery: string;
|
||||
@@ -11,38 +11,55 @@ interface FilterBarProps {
|
||||
searchPlaceholder: string;
|
||||
}
|
||||
|
||||
export default function FilterBar({
|
||||
searchQuery,
|
||||
setSearchQuery,
|
||||
ordering,
|
||||
setOrdering,
|
||||
orderingOptions,
|
||||
searchPlaceholder
|
||||
export default function FilterBar({
|
||||
searchQuery,
|
||||
setSearchQuery,
|
||||
ordering,
|
||||
setOrdering,
|
||||
orderingOptions,
|
||||
searchPlaceholder
|
||||
}: FilterBarProps) {
|
||||
|
||||
const [inputValue, setInputValue] = useState(searchQuery);
|
||||
|
||||
useEffect(() => {
|
||||
if (inputValue === searchQuery) return;
|
||||
|
||||
const timeout = setTimeout(() => {
|
||||
setSearchQuery(inputValue);
|
||||
}, 1000);
|
||||
|
||||
return () => clearTimeout(timeout);
|
||||
}, [inputValue, searchQuery, setSearchQuery]);
|
||||
|
||||
useEffect(() => {
|
||||
setInputValue(searchQuery);
|
||||
}, [searchQuery]);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col sm:flex-row gap-4 mb-6">
|
||||
<div className="relative flex-1">
|
||||
<Search className="absolute left-3 rtl:left-auto rtl:right-3 top-1/2 -translate-y-1/2 h-5 w-5 text-slate-400" />
|
||||
|
||||
<input
|
||||
type="text"
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
value={inputValue}
|
||||
onChange={(e) => setInputValue(e.target.value)}
|
||||
placeholder={searchPlaceholder || "Search..."}
|
||||
className="w-full pl-10 pr-4 rtl:pl-4 rtl:pr-10 py-2.5 rounded-xl border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-800 text-slate-900 dark:text-white outline-none focus:ring-2 focus:ring-blue-500 transition-shadow"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex w-full items-center gap-2 sm:w-auto">
|
||||
<ArrowUpDown className="h-5 w-5 text-slate-400 hidden sm:block" />
|
||||
<Select
|
||||
value={ordering}
|
||||
onChange={setOrdering}
|
||||
options={orderingOptions}
|
||||
className="w-full sm:w-max"
|
||||
buttonClassName="w-full whitespace-nowrap sm:min-w-[150px]"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex w-full items-center gap-2 sm:w-auto">
|
||||
<ArrowUpDown className="h-5 w-5 text-slate-400 hidden sm:block" />
|
||||
|
||||
<Select
|
||||
value={ordering}
|
||||
onChange={setOrdering}
|
||||
options={orderingOptions}
|
||||
className="w-full sm:w-max"
|
||||
buttonClassName="w-full whitespace-nowrap sm:min-w-[150px]"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import React, { useEffect, useRef } from "react";
|
||||
import React, { useEffect, useRef } from "react";
|
||||
import { useTranslation } from "../hooks/useTranslation";
|
||||
|
||||
interface InfiniteScrollProps {
|
||||
children: React.ReactNode;
|
||||
@@ -16,8 +17,9 @@ export const InfiniteScroll: React.FC<InfiniteScrollProps> = ({
|
||||
isLoading,
|
||||
className = "",
|
||||
loader,
|
||||
}) => {
|
||||
const observerTarget = useRef<HTMLDivElement>(null);
|
||||
}) => {
|
||||
const { t } = useTranslation();
|
||||
const observerTarget = useRef<HTMLDivElement>(null);
|
||||
const onLoadMoreRef = useRef(onLoadMore);
|
||||
const hasMoreRef = useRef(hasMore);
|
||||
const isLoadingRef = useRef(isLoading);
|
||||
@@ -56,11 +58,11 @@ export const InfiniteScroll: React.FC<InfiniteScrollProps> = ({
|
||||
|
||||
{isLoading && (
|
||||
loader || (
|
||||
<div className="py-2 text-center text-xs text-slate-500 dark:text-slate-400">
|
||||
Loading...
|
||||
</div>
|
||||
)
|
||||
)}
|
||||
<div className="py-2 text-center text-xs text-slate-500 dark:text-slate-400">
|
||||
{t.loading || "Loading..."}
|
||||
</div>
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -25,7 +25,7 @@ export function ListPageSkeleton({
|
||||
: "grid grid-cols-1 gap-4 md:grid-cols-2 2xl:grid-cols-3";
|
||||
|
||||
return (
|
||||
<div className="flex flex-1 flex-col rounded-3xl border border-slate-200 bg-white p-5 shadow-sm dark:border-slate-800 dark:bg-slate-900 sm:p-6">
|
||||
<div>
|
||||
{variant === "list" ? (
|
||||
<div className="flex flex-1 flex-col gap-4 animate-pulse">
|
||||
{items.map((item) => (
|
||||
|
||||
@@ -19,10 +19,13 @@ export function Navbar({ onOpenSidebar }: NavbarProps) {
|
||||
const { t, lang, setLanguage } = useTranslation()
|
||||
const { theme, setTheme } = useTheme()
|
||||
const navigate = useNavigate()
|
||||
|
||||
const [showLogoutModal, setShowLogoutModal] = useState(false)
|
||||
const [isDropdownOpen, setIsDropdownOpen] = useState(false)
|
||||
const [user, setUser] = useState<any>(null)
|
||||
|
||||
const dropdownRef = useRef<HTMLDivElement>(null)
|
||||
|
||||
const isFa = lang === "fa"
|
||||
const isDarkMode =
|
||||
theme === "dark" ||
|
||||
@@ -61,6 +64,7 @@ export function Navbar({ onOpenSidebar }: NavbarProps) {
|
||||
setIsDropdownOpen(false)
|
||||
}
|
||||
}
|
||||
|
||||
document.addEventListener("mousedown", handleClickOutside)
|
||||
return () => document.removeEventListener("mousedown", handleClickOutside)
|
||||
}, [])
|
||||
@@ -88,6 +92,7 @@ export function Navbar({ onOpenSidebar }: NavbarProps) {
|
||||
|
||||
const toggleLanguage = () => {
|
||||
const newLang = isFa ? "en" : "fa"
|
||||
|
||||
if (setLanguage) {
|
||||
setLanguage(newLang)
|
||||
} else {
|
||||
@@ -98,7 +103,7 @@ export function Navbar({ onOpenSidebar }: NavbarProps) {
|
||||
|
||||
return (
|
||||
<>
|
||||
<header className="sticky top-0 z-50 flex items-center justify-between border-b border-slate-200/80 bg-white/70 px-8 py-6 backdrop-blur-md transition-colors dark:border-slate-800/80 dark:bg-slate-900/70">
|
||||
<header className="sticky top-0 z-50 flex items-center justify-between border-b border-slate-200/80 bg-white/70 px-4 py-4 backdrop-blur-md transition-colors md:px-8 md:py-6 dark:border-slate-800/80 dark:bg-slate-900/70">
|
||||
<div className="flex items-center gap-3">
|
||||
<button
|
||||
type="button"
|
||||
@@ -108,19 +113,40 @@ export function Navbar({ onOpenSidebar }: NavbarProps) {
|
||||
>
|
||||
<Menu className="h-5 w-5" />
|
||||
</button>
|
||||
<div className="flex cursor-pointer items-center gap-2" onClick={() => navigate("/")}>
|
||||
<span className="relative z-20 flex items-center gap-2 text-xl font-bold tracking-tight text-slate-900 dark:text-slate-50">
|
||||
<Command className="h-7 w-7" />
|
||||
{t.title || "Qlockify"}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div
|
||||
className="flex cursor-pointer items-center gap-2"
|
||||
onClick={() => navigate("/")}
|
||||
>
|
||||
<span className="relative z-20 flex items-center gap-2 text-lg font-bold tracking-tight text-slate-900 md:text-xl dark:text-slate-50">
|
||||
<Command className="h-6 w-6 md:h-7 md:w-7" />
|
||||
Qlockify.ir
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-4">
|
||||
{/* Mobile navbar: theme toggle + notification bell */}
|
||||
<div className="flex items-center gap-2 md:hidden">
|
||||
<button
|
||||
type="button"
|
||||
onClick={toggleTheme}
|
||||
className="inline-flex h-9 w-9 items-center justify-center rounded-lg text-slate-600 transition-colors hover:bg-slate-100 dark:text-slate-300 dark:hover:bg-slate-800"
|
||||
title={isDarkMode ? t.lightMode || "Light Mode" : t.darkMode || "Dark Mode"}
|
||||
>
|
||||
{isDarkMode ? <Sun className="h-5 w-5" /> : <Moon className="h-5 w-5" />}
|
||||
</button>
|
||||
|
||||
{user && <NotificationBell />}
|
||||
</div>
|
||||
|
||||
{/* Desktop navbar: keep the old controls here */}
|
||||
<div className="hidden items-center gap-4 md:flex">
|
||||
{user && <WorkspaceSelector />}
|
||||
|
||||
{user ? (
|
||||
<>
|
||||
<NotificationBell />
|
||||
|
||||
<div className="relative" ref={dropdownRef}>
|
||||
<button
|
||||
onClick={() => setIsDropdownOpen((current) => !current)}
|
||||
@@ -141,8 +167,10 @@ export function Navbar({ onOpenSidebar }: NavbarProps) {
|
||||
|
||||
{isDropdownOpen && (
|
||||
<div
|
||||
dir="rtl"
|
||||
className={`absolute ${isFa ? "left-0" : "right-0"} z-50 mt-2 w-56 overflow-hidden rounded-lg border border-slate-200 bg-white py-2 shadow-lg ring-1 ring-black ring-opacity-5 dark:border-slate-800 dark:bg-slate-900`}
|
||||
dir={isFa ? "rtl" : "ltr"}
|
||||
className={`absolute ${
|
||||
isFa ? "left-0" : "right-0"
|
||||
} z-50 mt-2 w-56 overflow-hidden rounded-lg border border-slate-200 bg-white py-2 shadow-lg ring-1 ring-black ring-opacity-5 dark:border-slate-800 dark:bg-slate-900`}
|
||||
>
|
||||
<div className="mb-2 border-b border-slate-100 px-4 py-2 dark:border-slate-800">
|
||||
<p className="truncate text-sm font-semibold text-slate-800 dark:text-slate-400">
|
||||
@@ -151,6 +179,7 @@ export function Navbar({ onOpenSidebar }: NavbarProps) {
|
||||
: user.email}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={() => {
|
||||
navigate("/profile")
|
||||
@@ -166,8 +195,16 @@ export function Navbar({ onOpenSidebar }: NavbarProps) {
|
||||
onClick={toggleTheme}
|
||||
className="flex w-full items-center gap-3 px-4 py-2.5 text-sm text-slate-700 transition-colors hover:bg-slate-100 dark:text-slate-200 dark:hover:bg-slate-800"
|
||||
>
|
||||
{isDarkMode ? <Sun className="h-4 w-4" /> : <Moon className="h-4 w-4" />}
|
||||
<span>{isDarkMode ? (t.lightMode || "Light Mode") : (t.darkMode || "Dark Mode")}</span>
|
||||
{isDarkMode ? (
|
||||
<Sun className="h-4 w-4" />
|
||||
) : (
|
||||
<Moon className="h-4 w-4" />
|
||||
)}
|
||||
<span>
|
||||
{isDarkMode
|
||||
? t.lightMode || "Light Mode"
|
||||
: t.darkMode || "Dark Mode"}
|
||||
</span>
|
||||
</button>
|
||||
|
||||
<button
|
||||
@@ -178,7 +215,7 @@ export function Navbar({ onOpenSidebar }: NavbarProps) {
|
||||
<span>{isFa ? "English" : "فارسی"}</span>
|
||||
</button>
|
||||
|
||||
<div className="my-1 h-px bg-slate-200 dark:bg-slate-800"></div>
|
||||
<div className="my-1 h-px bg-slate-200 dark:bg-slate-800" />
|
||||
|
||||
<button
|
||||
onClick={() => {
|
||||
@@ -197,6 +234,7 @@ export function Navbar({ onOpenSidebar }: NavbarProps) {
|
||||
) : (
|
||||
<>
|
||||
<SettingsMenu />
|
||||
|
||||
<Button
|
||||
onClick={() => navigate("/auth")}
|
||||
className="bg-blue-600 text-white hover:bg-blue-700 dark:bg-blue-600 dark:hover:bg-blue-700"
|
||||
@@ -210,7 +248,7 @@ export function Navbar({ onOpenSidebar }: NavbarProps) {
|
||||
|
||||
{showLogoutModal && (
|
||||
<div
|
||||
className="fixed inset-0 z-60 flex items-center justify-center bg-black/50 px-4"
|
||||
className="fixed inset-0 z-[80] flex items-center justify-center bg-black/50 px-4"
|
||||
onClick={() => setShowLogoutModal(false)}
|
||||
>
|
||||
<div
|
||||
@@ -220,9 +258,12 @@ export function Navbar({ onOpenSidebar }: NavbarProps) {
|
||||
<h2 className="mb-2 text-lg font-bold text-slate-900 dark:text-white">
|
||||
{t.confirmLogoutTitle || "Confirm Logout"}
|
||||
</h2>
|
||||
|
||||
<p className="mb-6 text-slate-600 dark:text-slate-400">
|
||||
{t.confirmLogoutMessage || "Are you sure you want to log out of your account?"}
|
||||
{t.confirmLogoutMessage ||
|
||||
"Are you sure you want to log out of your account?"}
|
||||
</p>
|
||||
|
||||
<div className="flex justify-end gap-3">
|
||||
<Button
|
||||
variant="outline"
|
||||
@@ -231,6 +272,7 @@ export function Navbar({ onOpenSidebar }: NavbarProps) {
|
||||
>
|
||||
{t.actions?.cancel || "Cancel"}
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
variant="destructive"
|
||||
onClick={handleLogout}
|
||||
@@ -244,4 +286,4 @@ export function Navbar({ onOpenSidebar }: NavbarProps) {
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,186 +1,405 @@
|
||||
import { useState } from 'react';
|
||||
import { NavLink } from 'react-router-dom';
|
||||
import {
|
||||
import { useEffect, useState } from "react"
|
||||
import { NavLink, useNavigate } from "react-router-dom"
|
||||
import {
|
||||
Users,
|
||||
LayoutDashboard,
|
||||
LayoutDashboard,
|
||||
X,
|
||||
PanelLeftClose,
|
||||
PanelLeftOpen,
|
||||
PanelRightClose,
|
||||
PanelLeftClose,
|
||||
PanelLeftOpen,
|
||||
PanelRightClose,
|
||||
PanelRightOpen,
|
||||
Briefcase,
|
||||
ChartColumn,
|
||||
Clock3,
|
||||
History,
|
||||
Tags,
|
||||
} from 'lucide-react';
|
||||
import { useWorkspace } from '../context/WorkspaceContext';
|
||||
import { useTranslation } from '../hooks/useTranslation';
|
||||
import { canWorkspace, WORKSPACE_LOGS_VIEW } from '../lib/permissions';
|
||||
User,
|
||||
Globe,
|
||||
LogOut,
|
||||
LogIn,
|
||||
} from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
|
||||
import { useOptionalWorkspace } from "../context/WorkspaceContext"
|
||||
import { useTranslation } from "../hooks/useTranslation"
|
||||
import { canWorkspace, WORKSPACE_LOGS_VIEW } from "../lib/permissions"
|
||||
import { WorkspaceSelector } from "./WorkspaceSelector"
|
||||
import { SettingsMenu } from "./SettingsMenu"
|
||||
import { Button } from "./ui/button"
|
||||
import { getUserProfile, logoutUser } from "../api/users"
|
||||
import { clearSessionTokens, getAccessToken, getRefreshToken } from "../lib/session"
|
||||
|
||||
type SidebarProps = {
|
||||
mobileOpen?: boolean;
|
||||
onMobileClose?: () => void;
|
||||
};
|
||||
mobileOpen?: boolean
|
||||
onMobileClose?: () => void
|
||||
}
|
||||
|
||||
export const Sidebar = ({ mobileOpen = false, onMobileClose }: SidebarProps) => {
|
||||
const [isCollapsed, setIsCollapsed] = useState(false);
|
||||
|
||||
const { t, lang } = useTranslation();
|
||||
const { activeWorkspace } = useWorkspace();
|
||||
const isRtl = lang === 'fa';
|
||||
const canViewLogs = canWorkspace(activeWorkspace?.my_role, WORKSPACE_LOGS_VIEW);
|
||||
const [isCollapsed, setIsCollapsed] = useState(false)
|
||||
const [showLogoutModal, setShowLogoutModal] = useState(false)
|
||||
const [user, setUser] = useState<any>(null)
|
||||
|
||||
const navigate = useNavigate()
|
||||
const { t, lang, setLanguage } = useTranslation()
|
||||
|
||||
const workspaceContext = useOptionalWorkspace()
|
||||
const activeWorkspace = workspaceContext?.activeWorkspace ?? null
|
||||
|
||||
const isRtl = lang === "fa"
|
||||
const canViewLogs = canWorkspace(activeWorkspace?.my_role, WORKSPACE_LOGS_VIEW)
|
||||
|
||||
const ToggleIcon = isRtl
|
||||
? (isCollapsed ? PanelRightOpen : PanelRightClose)
|
||||
: (isCollapsed ? PanelLeftOpen : PanelLeftClose);
|
||||
? isCollapsed
|
||||
? PanelRightOpen
|
||||
: PanelRightClose
|
||||
: isCollapsed
|
||||
? PanelLeftOpen
|
||||
: PanelLeftClose
|
||||
|
||||
useEffect(() => {
|
||||
const handleProfileUpdated = ((e: CustomEvent) => {
|
||||
if (e.detail) {
|
||||
setUser((prev: any) => (prev ? { ...prev, ...e.detail } : e.detail))
|
||||
}
|
||||
}) as EventListener
|
||||
|
||||
window.addEventListener("profile_updated", handleProfileUpdated)
|
||||
return () => window.removeEventListener("profile_updated", handleProfileUpdated)
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
const fetchUser = async () => {
|
||||
const token = getAccessToken()
|
||||
if (!token) return
|
||||
|
||||
try {
|
||||
const userData = await getUserProfile()
|
||||
setUser(userData)
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch user profile:", error)
|
||||
}
|
||||
}
|
||||
|
||||
void fetchUser()
|
||||
}, [])
|
||||
|
||||
const handleLogout = async () => {
|
||||
try {
|
||||
const refreshToken = getRefreshToken()
|
||||
if (refreshToken) {
|
||||
await logoutUser(refreshToken)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Logout API failed:", error)
|
||||
} finally {
|
||||
clearSessionTokens()
|
||||
setUser(null)
|
||||
setShowLogoutModal(false)
|
||||
onMobileClose?.()
|
||||
toast.success(t.logoutToast || "Successfully logged out!")
|
||||
navigate("/auth")
|
||||
}
|
||||
}
|
||||
|
||||
const toggleLanguage = () => {
|
||||
const newLang = isRtl ? "en" : "fa"
|
||||
|
||||
if (setLanguage) {
|
||||
setLanguage(newLang)
|
||||
} else {
|
||||
localStorage.setItem("language", newLang)
|
||||
window.location.reload()
|
||||
}
|
||||
}
|
||||
|
||||
const navItems = [
|
||||
{
|
||||
path: '/timesheet',
|
||||
path: "/timesheet",
|
||||
icon: Clock3,
|
||||
label: t.sidebar?.timesheet || 'Timesheet'
|
||||
label: t.sidebar?.timesheet || "Timesheet",
|
||||
},
|
||||
{
|
||||
path: '/tags',
|
||||
path: "/tags",
|
||||
icon: Tags,
|
||||
label: t.sidebar?.tags || 'Tags'
|
||||
},
|
||||
{
|
||||
path: '/clients',
|
||||
icon: Users,
|
||||
label: t.sidebar?.clients || 'Clients'
|
||||
},
|
||||
{
|
||||
path: '/projects',
|
||||
icon: Briefcase,
|
||||
label: t.sidebar?.projects || 'Projects'
|
||||
},
|
||||
{
|
||||
path: '/workspaces',
|
||||
icon: LayoutDashboard,
|
||||
label: t.sidebar?.workspaces || 'Workspaces'
|
||||
label: t.sidebar?.tags || "Tags",
|
||||
},
|
||||
{
|
||||
path: '/reports',
|
||||
path: "/clients",
|
||||
icon: Users,
|
||||
label: t.sidebar?.clients || "Clients",
|
||||
},
|
||||
{
|
||||
path: "/projects",
|
||||
icon: Briefcase,
|
||||
label: t.sidebar?.projects || "Projects",
|
||||
},
|
||||
{
|
||||
path: "/workspaces",
|
||||
icon: LayoutDashboard,
|
||||
label: t.sidebar?.workspaces || "Workspaces",
|
||||
},
|
||||
{
|
||||
path: "/reports",
|
||||
icon: ChartColumn,
|
||||
label: t.sidebar?.reports || 'Reports'
|
||||
label: t.sidebar?.reports || "Reports",
|
||||
},
|
||||
...(canViewLogs
|
||||
? [
|
||||
{
|
||||
path: '/logs',
|
||||
path: "/logs",
|
||||
icon: History,
|
||||
label: t.sidebar?.logs || 'Logs',
|
||||
label: t.sidebar?.logs || "Logs",
|
||||
},
|
||||
]
|
||||
: []),
|
||||
];
|
||||
]
|
||||
|
||||
const renderNavItems = (mobile = false) =>
|
||||
navItems.map((item) => {
|
||||
const Icon = item.icon;
|
||||
const Icon = item.icon
|
||||
|
||||
return (
|
||||
<NavLink
|
||||
key={`${mobile ? 'mobile' : 'desktop'}-${item.path}`}
|
||||
key={`${mobile ? "mobile" : "desktop"}-${item.path}`}
|
||||
to={item.path}
|
||||
title={!mobile && isCollapsed ? item.label : undefined}
|
||||
onClick={() => {
|
||||
if (mobile) onMobileClose?.();
|
||||
if (mobile) onMobileClose?.()
|
||||
}}
|
||||
className={({ isActive }) =>
|
||||
`flex items-center rounded-lg text-sm font-medium transition-colors ${
|
||||
mobile
|
||||
? 'gap-3 px-4 py-3'
|
||||
? "gap-3 px-4 py-3"
|
||||
: isCollapsed
|
||||
? 'justify-center px-0 py-2.5'
|
||||
: 'gap-3 px-3 py-2.5'
|
||||
? "justify-center px-0 py-2.5"
|
||||
: "gap-3 px-3 py-2.5"
|
||||
} ${
|
||||
isActive
|
||||
? 'bg-blue-50 text-blue-600 dark:bg-blue-500/10 dark:text-blue-400'
|
||||
: 'text-slate-600 hover:bg-slate-100 dark:text-slate-400 dark:hover:bg-slate-900/50'
|
||||
? "bg-blue-50 text-blue-600 dark:bg-blue-500/10 dark:text-blue-400"
|
||||
: "text-slate-600 hover:bg-slate-100 dark:text-slate-400 dark:hover:bg-slate-900/50"
|
||||
}`
|
||||
}
|
||||
>
|
||||
<Icon size={mobile ? 20 : isCollapsed ? 22 : 18} className="shrink-0" />
|
||||
|
||||
{(mobile || !isCollapsed) && (
|
||||
<span className="truncate whitespace-nowrap">{item.label}</span>
|
||||
)}
|
||||
</NavLink>
|
||||
);
|
||||
});
|
||||
)
|
||||
})
|
||||
|
||||
const renderMobileTopSection = () => {
|
||||
if (!user) {
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="border-b border-slate-200 p-4 dark:border-slate-800">
|
||||
<div className="w-full">
|
||||
<WorkspaceSelector className="w-full" />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const renderMobileFooterSection = () => {
|
||||
if (!user) {
|
||||
return (
|
||||
<div className="border-t border-slate-200 p-4 dark:border-slate-800">
|
||||
<button
|
||||
onClick={toggleLanguage}
|
||||
className="flex w-full items-center gap-3 rounded-lg px-4 py-3 mb-3 text-sm font-medium text-slate-600 transition-colors hover:bg-slate-100 dark:text-slate-400 dark:hover:bg-slate-900/50"
|
||||
>
|
||||
<Globe size={20} className="shrink-0" />
|
||||
<span className="truncate whitespace-nowrap">
|
||||
{isRtl ? "English" : "فارسی"}
|
||||
</span>
|
||||
</button>
|
||||
|
||||
<Button
|
||||
onClick={() => {
|
||||
onMobileClose?.()
|
||||
navigate("/auth")
|
||||
}}
|
||||
className="w-full bg-blue-600 text-white hover:bg-blue-700 dark:bg-blue-600 dark:hover:bg-blue-700"
|
||||
>
|
||||
<LogIn className="mr-2 h-4 w-4" />
|
||||
{t.login?.signIn || "Login"}
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-1 p-4">
|
||||
<button
|
||||
onClick={() => {
|
||||
onMobileClose?.()
|
||||
navigate("/profile")
|
||||
}}
|
||||
className="flex w-full items-center gap-3 rounded-lg px-4 py-3 text-sm font-medium text-slate-600 transition-colors hover:bg-slate-100 dark:text-slate-400 dark:hover:bg-slate-900/50"
|
||||
>
|
||||
<User size={20} className="shrink-0" />
|
||||
<span className="truncate whitespace-nowrap">
|
||||
{t.profile?.title || "Profile"}
|
||||
</span>
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={toggleLanguage}
|
||||
className="flex w-full items-center gap-3 rounded-lg px-4 py-3 text-sm font-medium text-slate-600 transition-colors hover:bg-slate-100 dark:text-slate-400 dark:hover:bg-slate-900/50"
|
||||
>
|
||||
<Globe size={20} className="shrink-0" />
|
||||
<span className="truncate whitespace-nowrap">
|
||||
{isRtl ? "English" : "فارسی"}
|
||||
</span>
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={() => setShowLogoutModal(true)}
|
||||
className="flex w-full items-center gap-3 rounded-lg px-4 py-3 text-sm font-medium text-red-600 transition-colors hover:bg-red-50 dark:text-red-500 dark:hover:bg-red-950/50"
|
||||
>
|
||||
<LogOut size={20} className="shrink-0" />
|
||||
<span className="truncate whitespace-nowrap">{t.logout || "Logout"}</span>
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<aside
|
||||
className={`border-e border-slate-200 dark:border-slate-800 bg-white dark:bg-slate-950 hidden md:flex flex-col h-screen sticky top-0 shrink-0 transition-all duration-300 ease-in-out ${
|
||||
isCollapsed ? 'w-20' : 'w-64'
|
||||
{/* Desktop sidebar */}
|
||||
<aside
|
||||
className={`hidden h-screen shrink-0 flex-col border-e border-slate-200 bg-white transition-all duration-300 ease-in-out md:sticky md:top-0 md:flex dark:border-slate-800 dark:bg-slate-950 ${
|
||||
isCollapsed ? "w-20" : "w-64"
|
||||
}`}
|
||||
>
|
||||
<div className={`h-18.25 flex items-center border-b border-slate-200 dark:border-slate-800 shrink-0 transition-all ${
|
||||
isCollapsed ? 'justify-center px-0' : 'justify-between px-6'
|
||||
}`}>
|
||||
<div
|
||||
className={`flex h-[73px] shrink-0 items-center border-b border-slate-200 transition-all dark:border-slate-800 ${
|
||||
isCollapsed ? "justify-center px-0" : "justify-between px-6"
|
||||
}`}
|
||||
>
|
||||
{!isCollapsed && (
|
||||
<h2 className="text-xl font-bold text-slate-800 dark:text-white truncate">
|
||||
<h2 className="truncate text-xl font-bold text-slate-800 dark:text-white">
|
||||
{t.title || "Qlockify"}
|
||||
</h2>
|
||||
)}
|
||||
|
||||
<button
|
||||
onClick={() => setIsCollapsed(!isCollapsed)}
|
||||
className="p-2 rounded-lg text-slate-500 hover:bg-slate-100 dark:text-slate-400 dark:hover:bg-slate-800 transition-colors"
|
||||
title={isCollapsed ? (t.sidebar?.expand || 'Expand') : (t.sidebar?.collapse || 'Collapse')}
|
||||
className="rounded-lg p-2 text-slate-500 transition-colors hover:bg-slate-100 dark:text-slate-400 dark:hover:bg-slate-800"
|
||||
title={
|
||||
isCollapsed
|
||||
? t.sidebar?.expand || "Expand"
|
||||
: t.sidebar?.collapse || "Collapse"
|
||||
}
|
||||
>
|
||||
<ToggleIcon size={20} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<nav className="flex-1 p-4 space-y-1 overflow-y-auto overflow-x-hidden">
|
||||
|
||||
<nav className="flex-1 space-y-1 overflow-y-auto overflow-x-hidden p-4">
|
||||
{renderNavItems(false)}
|
||||
</nav>
|
||||
</aside>
|
||||
|
||||
{/* Mobile sidebar */}
|
||||
<div
|
||||
className={`fixed inset-0 z-[70] md:hidden transition-all duration-200 ${
|
||||
mobileOpen ? 'pointer-events-auto' : 'pointer-events-none'
|
||||
className={`fixed inset-0 z-[70] transition-all duration-200 md:hidden ${
|
||||
mobileOpen ? "pointer-events-auto" : "pointer-events-none"
|
||||
}`}
|
||||
aria-hidden={!mobileOpen}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
className={`absolute inset-0 bg-slate-950/50 backdrop-blur-[1px] transition-opacity ${
|
||||
mobileOpen ? 'opacity-100' : 'opacity-0'
|
||||
mobileOpen ? "opacity-100" : "opacity-0"
|
||||
}`}
|
||||
onClick={onMobileClose}
|
||||
/>
|
||||
|
||||
<aside
|
||||
className={`absolute inset-y-0 flex w-[18.5rem] max-w-[86vw] flex-col bg-white shadow-2xl transition-transform dark:bg-slate-950 ${
|
||||
dir={isRtl ? "rtl" : "ltr"}
|
||||
className={`absolute inset-y-0 flex w-[19.5rem] max-w-[88vw] flex-col overflow-hidden bg-white shadow-2xl transition-transform dark:bg-slate-950 ${
|
||||
isRtl
|
||||
? `right-0 border-s border-slate-200 dark:border-slate-800 ${
|
||||
mobileOpen ? 'translate-x-0' : 'translate-x-full'
|
||||
mobileOpen ? "translate-x-0" : "translate-x-full"
|
||||
}`
|
||||
: `left-0 border-e border-slate-200 dark:border-slate-800 ${
|
||||
mobileOpen ? 'translate-x-0' : '-translate-x-full'
|
||||
mobileOpen ? "translate-x-0" : "-translate-x-full"
|
||||
}`
|
||||
}`}
|
||||
>
|
||||
<div className="flex items-center justify-between border-b border-slate-200 px-5 py-5 dark:border-slate-800">
|
||||
<h2 className="truncate text-lg font-bold text-slate-800 dark:text-white">
|
||||
{t.title || "Qlockify"}
|
||||
</h2>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onMobileClose}
|
||||
className="rounded-lg p-2 text-slate-500 transition-colors hover:bg-slate-100 dark:text-slate-400 dark:hover:bg-slate-800"
|
||||
title="Close"
|
||||
>
|
||||
<X size={20} />
|
||||
</button>
|
||||
<div className="flex min-h-0 flex-1 flex-col overflow-y-auto">
|
||||
<div className="flex shrink-0 items-center justify-between border-b border-slate-200 px-5 py-5 dark:border-slate-800">
|
||||
<h2 className="truncate text-lg font-bold text-slate-800 dark:text-white">
|
||||
Qlockify.ir
|
||||
</h2>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={onMobileClose}
|
||||
className="rounded-lg p-2 text-slate-500 transition-colors hover:bg-slate-100 dark:text-slate-400 dark:hover:bg-slate-800"
|
||||
title="Close"
|
||||
>
|
||||
<X size={20} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="shrink-0">
|
||||
{renderMobileTopSection()}
|
||||
</div>
|
||||
|
||||
<nav className="shrink-0 space-y-1 p-4">
|
||||
{renderNavItems(true)}
|
||||
</nav>
|
||||
|
||||
<div className="mt-auto shrink-0">
|
||||
{renderMobileFooterSection()}
|
||||
</div>
|
||||
</div>
|
||||
<nav className="flex-1 space-y-1 overflow-y-auto p-4">
|
||||
{renderNavItems(true)}
|
||||
</nav>
|
||||
</aside>
|
||||
</div>
|
||||
|
||||
{showLogoutModal && (
|
||||
<div
|
||||
className="fixed inset-0 z-[90] flex items-center justify-center bg-black/50 px-4"
|
||||
onClick={() => setShowLogoutModal(false)}
|
||||
>
|
||||
<div
|
||||
className="w-full max-w-sm rounded-lg border bg-white p-6 shadow-lg dark:border-slate-800 dark:bg-slate-900"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<h2 className="mb-2 text-lg font-bold text-slate-900 dark:text-white">
|
||||
{t.confirmLogoutTitle || "Confirm Logout"}
|
||||
</h2>
|
||||
|
||||
<p className="mb-6 text-slate-600 dark:text-slate-400">
|
||||
{t.confirmLogoutMessage ||
|
||||
"Are you sure you want to log out of your account?"}
|
||||
</p>
|
||||
|
||||
<div className="flex justify-end gap-3">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => setShowLogoutModal(false)}
|
||||
className="dark:text-white"
|
||||
>
|
||||
{t.actions?.cancel || "Cancel"}
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
variant="destructive"
|
||||
onClick={handleLogout}
|
||||
className="bg-red-500 text-white hover:bg-red-600 dark:bg-red-600 dark:hover:bg-red-700"
|
||||
>
|
||||
{t.logout || "Logout"}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
};
|
||||
)
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
import { Moon, Sun } from "lucide-react"
|
||||
import { useTheme } from "./ThemeProvider"
|
||||
|
||||
export function ThemeToggle() {
|
||||
const { theme, setTheme } = useTheme()
|
||||
|
||||
return (
|
||||
<button
|
||||
onClick={() => setTheme(theme === "light" ? "dark" : "light")}
|
||||
className="relative inline-flex h-10 w-10 items-center justify-center rounded-md border border-slate-200 bg-white transition-colors hover:bg-slate-100 dark:border-slate-800 dark:bg-slate-950 dark:hover:bg-slate-800"
|
||||
>
|
||||
<Sun className="h-[1.2rem] w-[1.2rem] rotate-0 scale-100 transition-all text-slate-900 dark:-rotate-90 dark:scale-0" />
|
||||
<Moon className="absolute h-[1.2rem] w-[1.2rem] rotate-90 scale-0 transition-all text-slate-50 dark:rotate-0 dark:scale-100" />
|
||||
<span className="sr-only">Toggle theme</span>
|
||||
</button>
|
||||
)
|
||||
}
|
||||
@@ -6,7 +6,11 @@ import { useNavigate } from "react-router-dom";
|
||||
import { fetchWorkspaces, type Workspace } from "../api/workspaces";
|
||||
import { InfiniteScroll } from "./InfiniteScroll";
|
||||
|
||||
export const WorkspaceSelector: React.FC = () => {
|
||||
type WorkspaceSelectorProps = {
|
||||
className?: string
|
||||
}
|
||||
|
||||
export const WorkspaceSelector: React.FC<WorkspaceSelectorProps> = ({ className = "" }) => {
|
||||
const { workspaces, activeWorkspace, setActiveWorkspace } = useWorkspace();
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const dropdownRef = useRef<HTMLDivElement>(null);
|
||||
@@ -40,21 +44,21 @@ export const WorkspaceSelector: React.FC = () => {
|
||||
refreshWorkspacesList();
|
||||
}) as EventListener;
|
||||
|
||||
const handleWorkspaceCreated = ((e: CustomEvent) => {
|
||||
if (e.detail?.id) {
|
||||
setActiveWorkspace(e.detail);
|
||||
}
|
||||
refreshWorkspacesList();
|
||||
}) as EventListener;
|
||||
const handleWorkspaceCreated = ((e: CustomEvent) => {
|
||||
if (e.detail?.id) {
|
||||
setActiveWorkspace(e.detail);
|
||||
}
|
||||
refreshWorkspacesList();
|
||||
}) as EventListener;
|
||||
|
||||
const handleWorkspaceEdited = ((e: CustomEvent) => {
|
||||
// آپدیت نام کارتابل در نوبار در صورتی که کارتابل فعال ویرایش شده باشد
|
||||
if (activeWorkspace?.id === e.detail?.id) {
|
||||
setActiveWorkspace({
|
||||
...activeWorkspace,
|
||||
...e.detail,
|
||||
} as Workspace);
|
||||
}
|
||||
if (activeWorkspace?.id === e.detail?.id) {
|
||||
setActiveWorkspace({
|
||||
...activeWorkspace,
|
||||
...e.detail,
|
||||
} as Workspace);
|
||||
}
|
||||
refreshWorkspacesList();
|
||||
}) as EventListener;
|
||||
|
||||
@@ -116,23 +120,23 @@ export const WorkspaceSelector: React.FC = () => {
|
||||
}, [offset, hasMore, isLoadingMore]);
|
||||
|
||||
return (
|
||||
<div className="relative" ref={dropdownRef}>
|
||||
<div className={`relative ${className}`} ref={dropdownRef}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setIsOpen(!isOpen)}
|
||||
className="flex items-center gap-2 px-3 py-2 text-base font-medium text-slate-700 dark:text-slate-200 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-800 transition-colors"
|
||||
className="flex w-full items-center gap-2 rounded-lg px-3 py-2 text-base font-medium text-slate-700 transition-colors hover:bg-slate-100 dark:text-slate-200 dark:hover:bg-slate-800"
|
||||
>
|
||||
<div className="w-6 h-6 flex items-center justify-center overflow-hidden rounded-md bg-blue-100 text-blue-600 dark:bg-blue-900/50 dark:text-blue-400">
|
||||
{activeWorkspace?.thumbnail ? (
|
||||
<img src={activeWorkspace.thumbnail} alt={activeWorkspace?.name || "Workspace"} className="h-full w-full object-cover" />
|
||||
) : (
|
||||
activeWorkspace?.name?.charAt(0)?.toUpperCase() || <Briefcase className="w-4 h-4" />
|
||||
)}
|
||||
</div>
|
||||
<span className="max-w-30 truncate">
|
||||
<div className="w-6 h-6 flex items-center justify-center overflow-hidden rounded-md bg-blue-100 text-blue-600 dark:bg-blue-900/50 dark:text-blue-400">
|
||||
{activeWorkspace?.thumbnail ? (
|
||||
<img src={activeWorkspace.thumbnail} alt={activeWorkspace?.name || "Workspace"} className="h-full w-full object-cover" />
|
||||
) : (
|
||||
activeWorkspace?.name?.charAt(0)?.toUpperCase() || <Briefcase className="w-4 h-4" />
|
||||
)}
|
||||
</div>
|
||||
<span className="min-w-0 flex-1 truncate text-start">
|
||||
{activeWorkspace?.name || t.workspace?.title || "Workspaces"}
|
||||
</span>
|
||||
<ChevronDown className="w-4 h-4 text-slate-400" />
|
||||
<ChevronDown className="h-4 w-4 shrink-0 text-slate-400" />
|
||||
</button>
|
||||
|
||||
{isOpen && (
|
||||
@@ -162,13 +166,13 @@ export const WorkspaceSelector: React.FC = () => {
|
||||
className="w-full flex items-center justify-between px-3 py-2 text-sm text-slate-700 dark:text-slate-200 hover:bg-slate-100 dark:hover:bg-slate-800 transition-colors"
|
||||
>
|
||||
<div className="flex items-center gap-2 truncate">
|
||||
<div className="w-6 h-6 flex items-center justify-center overflow-hidden rounded-md bg-slate-100 font-medium dark:bg-slate-800">
|
||||
{ws.thumbnail ? (
|
||||
<img src={ws.thumbnail} alt={ws.name} className="h-full w-full object-cover" />
|
||||
) : (
|
||||
ws.name.charAt(0).toUpperCase()
|
||||
)}
|
||||
</div>
|
||||
<div className="w-6 h-6 flex items-center justify-center overflow-hidden rounded-md bg-slate-100 font-medium dark:bg-slate-800">
|
||||
{ws.thumbnail ? (
|
||||
<img src={ws.thumbnail} alt={ws.name} className="h-full w-full object-cover" />
|
||||
) : (
|
||||
ws.name.charAt(0).toUpperCase()
|
||||
)}
|
||||
</div>
|
||||
<span className="truncate">{ws.name}</span>
|
||||
</div>
|
||||
{activeWorkspace?.id === ws.id && (
|
||||
|
||||
@@ -153,6 +153,17 @@ export function ReportsTablePanel({
|
||||
|
||||
if (!data) return null;
|
||||
|
||||
const days = Array.isArray(data.days) ? data.days : [];
|
||||
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 entries = Array.isArray(dayDetails?.entries) ? dayDetails.entries : [];
|
||||
const summary = data.summary ?? {
|
||||
billable_duration: "00:00:00",
|
||||
non_billable_duration: "00:00:00",
|
||||
income_totals: [],
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex flex-col gap-2 sm:flex-row sm:justify-end">
|
||||
@@ -188,7 +199,7 @@ export function ReportsTablePanel({
|
||||
<div className="mb-4 text-sm font-semibold text-slate-900 dark:text-white">{labels.details}</div>
|
||||
|
||||
<div className="space-y-3 sm:hidden">
|
||||
{data.days.map((day) => {
|
||||
{days.map((day) => {
|
||||
const isOpen = openDay === day.date;
|
||||
return (
|
||||
<div key={day.date} className="rounded-2xl border border-slate-200 bg-slate-50/80 p-3 dark:border-slate-800 dark:bg-slate-950/70">
|
||||
@@ -229,7 +240,7 @@ export function ReportsTablePanel({
|
||||
|
||||
{isOpen && dayDetails?.day === day.date ? (
|
||||
<div className="mt-3 space-y-2 border-t border-slate-200 pt-3 dark:border-slate-800">
|
||||
{dayDetails.entries.map((entry) => (
|
||||
{entries.map((entry) => (
|
||||
<div key={entry.id} className="rounded-xl border border-slate-200 bg-white p-3 dark:border-slate-700 dark:bg-slate-900">
|
||||
<div className="text-sm font-medium text-slate-900 dark:text-slate-100">
|
||||
{entry.description || labels.noDescription}
|
||||
@@ -249,9 +260,9 @@ export function ReportsTablePanel({
|
||||
<div className="rounded-2xl border border-sky-200 bg-sky-50 p-3 dark:border-sky-500/20 dark:bg-sky-500/10">
|
||||
<div className="text-sm font-semibold text-slate-900 dark:text-white">{labels.total}</div>
|
||||
<div className="mt-3 grid grid-cols-2 gap-3 text-xs text-slate-700 dark:text-slate-300">
|
||||
<div>{labels.billableHours}: {localizeDigits(data.summary.billable_duration, lang)}</div>
|
||||
<div>{labels.nonBillableHours}: {localizeDigits(data.summary.non_billable_duration, lang)}</div>
|
||||
<div>{labels.totalIncome}: {formatMoneyTotals(data.summary.income_totals, lang)}</div>
|
||||
<div>{labels.billableHours}: {localizeDigits(summary.billable_duration, lang)}</div>
|
||||
<div>{labels.nonBillableHours}: {localizeDigits(summary.non_billable_duration, lang)}</div>
|
||||
<div>{labels.totalIncome}: {formatMoneyTotals(summary.income_totals, lang)}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -269,7 +280,7 @@ export function ReportsTablePanel({
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{data.days.map((day) => {
|
||||
{days.map((day) => {
|
||||
const isOpen = openDay === day.date;
|
||||
return (
|
||||
<Fragment key={day.date}>
|
||||
@@ -293,7 +304,7 @@ export function ReportsTablePanel({
|
||||
<tr className="border-b border-slate-100 bg-slate-50/70 dark:border-slate-800/80 dark:bg-slate-950/70">
|
||||
<td colSpan={6} className="px-3 py-4">
|
||||
<div className="space-y-2">
|
||||
{dayDetails.entries.map((entry) => (
|
||||
{entries.map((entry) => (
|
||||
<div key={entry.id} className="rounded-2xl border border-slate-200 bg-white px-4 py-3 dark:border-slate-700 dark:bg-slate-900">
|
||||
<div className="flex flex-wrap items-center gap-2 text-sm">
|
||||
<span className="font-medium text-slate-900 dark:text-slate-100">{entry.description || labels.noDescription}</span>
|
||||
@@ -312,10 +323,10 @@ export function ReportsTablePanel({
|
||||
})}
|
||||
<tr className="bg-sky-50/80 font-semibold dark:bg-sky-500/10">
|
||||
<td className="px-3 py-3">{labels.total}</td>
|
||||
<td className="px-3 py-3">{localizeDigits(data.summary.billable_duration, lang)}</td>
|
||||
<td className="px-3 py-3">{localizeDigits(data.summary.non_billable_duration, lang)}</td>
|
||||
<td className="px-3 py-3">{localizeDigits(summary.billable_duration, lang)}</td>
|
||||
<td className="px-3 py-3">{localizeDigits(summary.non_billable_duration, lang)}</td>
|
||||
<td className="px-3 py-3">-</td>
|
||||
<td className="px-3 py-3">{formatMoneyTotals(data.summary.income_totals, lang)}</td>
|
||||
<td className="px-3 py-3">{formatMoneyTotals(summary.income_totals, lang)}</td>
|
||||
<td className="px-3 py-3" />
|
||||
</tr>
|
||||
</tbody>
|
||||
@@ -323,9 +334,9 @@ export function ReportsTablePanel({
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<BreakdownCards title={labels.clientsTable} rows={data.clients} labels={labels} lang={lang} />
|
||||
<BreakdownCards title={labels.projectsTable} rows={data.projects} labels={labels} lang={lang} />
|
||||
<BreakdownCards title={labels.tagsTable} rows={data.tags} labels={labels} lang={lang} />
|
||||
<BreakdownCards title={labels.clientsTable} rows={clients} labels={labels} lang={lang} />
|
||||
<BreakdownCards title={labels.projectsTable} rows={projects} labels={labels} lang={lang} />
|
||||
<BreakdownCards title={labels.tagsTable} rows={tags} labels={labels} lang={lang} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -27,8 +27,8 @@ export function SearchableSelect({
|
||||
onChange,
|
||||
options,
|
||||
placeholder = "",
|
||||
searchPlaceholder = "Search...",
|
||||
emptyLabel = "No results",
|
||||
searchPlaceholder,
|
||||
emptyLabel,
|
||||
disabled = false,
|
||||
className = "",
|
||||
buttonClassName = "",
|
||||
@@ -111,7 +111,7 @@ export function SearchableSelect({
|
||||
<Input
|
||||
value={query}
|
||||
onChange={(event) => setQuery(event.target.value)}
|
||||
placeholder={searchPlaceholder}
|
||||
placeholder={searchPlaceholder || "Search..."}
|
||||
className="h-9 pl-9"
|
||||
autoFocus
|
||||
/>
|
||||
@@ -138,7 +138,9 @@ export function SearchableSelect({
|
||||
</button>
|
||||
))}
|
||||
{filteredOptions.length === 0 && (
|
||||
<div className="px-3 py-3 text-sm text-slate-500 dark:text-slate-400">{emptyLabel}</div>
|
||||
<div className="px-3 py-3 text-sm text-slate-500 dark:text-slate-400">
|
||||
{emptyLabel || "No results"}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>,
|
||||
|
||||
@@ -23,6 +23,7 @@ import {
|
||||
} from "../api/notifications"
|
||||
import { useTranslation } from "../hooks/useTranslation"
|
||||
import { presentNotification } from "../lib/notificationPresenter"
|
||||
import { isRateLimitActive } from "../lib/rateLimit"
|
||||
import {
|
||||
getAccessToken,
|
||||
SESSION_CHANGED_EVENT,
|
||||
@@ -171,7 +172,7 @@ export function NotificationsProvider({ children }: { children: ReactNode }) {
|
||||
)
|
||||
|
||||
const refreshNotifications = useCallback(async () => {
|
||||
if (!getAccessToken()) {
|
||||
if (!getAccessToken() || isRateLimitActive()) {
|
||||
setNotifications([])
|
||||
setUnreadCount(0)
|
||||
setTotalCount(0)
|
||||
@@ -279,7 +280,7 @@ export function NotificationsProvider({ children }: { children: ReactNode }) {
|
||||
}, [markAsSeen, openNotificationTarget, t.notifications])
|
||||
|
||||
const connectToStream = useCallback(async () => {
|
||||
if (!getAccessToken()) {
|
||||
if (!getAccessToken() || isRateLimitActive()) {
|
||||
closeEventSource()
|
||||
setConnectionStatus("idle")
|
||||
return
|
||||
@@ -413,7 +414,7 @@ export function NotificationsProvider({ children }: { children: ReactNode }) {
|
||||
|
||||
useEffect(() => {
|
||||
const startNotifications = async () => {
|
||||
if (!getAccessToken()) {
|
||||
if (!getAccessToken() || isRateLimitActive()) {
|
||||
closeEventSource()
|
||||
setNotifications([])
|
||||
setUnreadCount(0)
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import { createContext, useContext, useState, useEffect, type ReactNode } from "react"
|
||||
import { fetchWorkspaces, createWorkspace, type Workspace } from "../api/workspaces"
|
||||
import { useTranslation } from "../hooks/useTranslation"
|
||||
import { toast } from "sonner"
|
||||
import { Button } from "../components/ui/button"
|
||||
import { Input } from "../components/ui/input"
|
||||
import { fetchWorkspaces, createWorkspace, type Workspace } from "../api/workspaces"
|
||||
import { useTranslation } from "../hooks/useTranslation"
|
||||
import { isRateLimitActive } from "../lib/rateLimit"
|
||||
import { toast } from "sonner"
|
||||
import { Button } from "../components/ui/button"
|
||||
import { Input } from "../components/ui/input"
|
||||
|
||||
interface WorkspaceContextType {
|
||||
workspaces: Workspace[]
|
||||
@@ -14,13 +15,15 @@ interface WorkspaceContextType {
|
||||
isLoading: boolean
|
||||
}
|
||||
|
||||
const WorkspaceContext = createContext<WorkspaceContextType | undefined>(undefined)
|
||||
|
||||
export const useWorkspace = () => {
|
||||
const context = useContext(WorkspaceContext)
|
||||
if (!context) throw new Error("useWorkspace must be used within a WorkspaceProvider")
|
||||
return context
|
||||
}
|
||||
const WorkspaceContext = createContext<WorkspaceContextType | undefined>(undefined)
|
||||
|
||||
export const useWorkspace = () => {
|
||||
const context = useContext(WorkspaceContext)
|
||||
if (!context) throw new Error("useWorkspace must be used within a WorkspaceProvider")
|
||||
return context
|
||||
}
|
||||
|
||||
export const useOptionalWorkspace = () => useContext(WorkspaceContext)
|
||||
|
||||
export const WorkspaceProvider = ({ children }: { children: ReactNode }) => {
|
||||
const { t } = useTranslation()
|
||||
@@ -31,9 +34,10 @@ export const WorkspaceProvider = ({ children }: { children: ReactNode }) => {
|
||||
const [isCreatingFirst, setIsCreatingFirst] = useState(false)
|
||||
|
||||
const isAuthenticated = !!localStorage.getItem("accessToken")
|
||||
const rateLimited = isRateLimitActive()
|
||||
|
||||
const refreshWorkspaces = async () => {
|
||||
if (!isAuthenticated) {
|
||||
if (!isAuthenticated || isRateLimitActive()) {
|
||||
setIsLoading(false)
|
||||
return
|
||||
}
|
||||
@@ -66,13 +70,13 @@ export const WorkspaceProvider = ({ children }: { children: ReactNode }) => {
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (!isAuthenticated) {
|
||||
if (!isAuthenticated || rateLimited) {
|
||||
setIsLoading(false)
|
||||
return
|
||||
}
|
||||
|
||||
void refreshWorkspaces()
|
||||
}, [isAuthenticated])
|
||||
}, [isAuthenticated, rateLimited])
|
||||
|
||||
const setActiveWorkspace = (workspace: Workspace | null) => {
|
||||
setActiveWorkspaceState(workspace)
|
||||
@@ -100,7 +104,7 @@ export const WorkspaceProvider = ({ children }: { children: ReactNode }) => {
|
||||
}
|
||||
|
||||
// Force workspace creation if authenticated but none exist
|
||||
if (!isLoading && isAuthenticated && workspaces.length === 0) {
|
||||
if (!rateLimited && !isLoading && isAuthenticated && workspaces.length === 0) {
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-slate-50 dark:bg-slate-900 px-4">
|
||||
<div className="w-full max-w-md bg-white dark:bg-slate-800 p-8 rounded-xl shadow-lg border border-slate-200 dark:border-slate-700">
|
||||
|
||||
123
src/index.css
123
src/index.css
@@ -1,26 +1,44 @@
|
||||
@import "tailwindcss";
|
||||
|
||||
@font-face {
|
||||
font-family: "Vazirmatn";
|
||||
font-family: "AppSans";
|
||||
src: url("/fonts/Vazirmatn[wght].woff2") format("woff2");
|
||||
font-weight: 100 900;
|
||||
font-style: normal;
|
||||
font-display: swap;
|
||||
|
||||
/* Arabic + Persian Unicode blocks */
|
||||
unicode-range:
|
||||
U+0600-06FF,
|
||||
U+0750-077F,
|
||||
U+08A0-08FF,
|
||||
U+FB50-FDFF,
|
||||
U+FE70-FEFF;
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: "AppSans";
|
||||
src: local("Inter");
|
||||
font-weight: 100 900;
|
||||
font-style: normal;
|
||||
font-display: swap;
|
||||
|
||||
/* Latin */
|
||||
unicode-range:
|
||||
U+0000-00FF,
|
||||
U+0100-024F,
|
||||
U+1E00-1EFF;
|
||||
}
|
||||
|
||||
@custom-variant dark (&:is(.dark *));
|
||||
|
||||
@theme {
|
||||
--color-quera-blue: #2563eb;
|
||||
--font-sans: "Vazirmatn", ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
|
||||
--font-sans: "AppSans", ui-sans-serif, system-ui, sans-serif;
|
||||
}
|
||||
|
||||
:root {
|
||||
font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif;
|
||||
}
|
||||
|
||||
:lang(fa) {
|
||||
font-family: "Vazirmatn", system-ui, Avenir, Helvetica, Arial, sans-serif;
|
||||
font-family: "AppSans", system-ui, sans-serif;
|
||||
}
|
||||
|
||||
@layer base {
|
||||
@@ -65,6 +83,93 @@
|
||||
line-height: 1.75rem !important;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes landing-rise {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(28px);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes landing-float {
|
||||
0%,
|
||||
100% {
|
||||
transform: translateY(0px);
|
||||
}
|
||||
50% {
|
||||
transform: translateY(-14px);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes landing-grid {
|
||||
from {
|
||||
transform: translate3d(0, 0, 0);
|
||||
}
|
||||
to {
|
||||
transform: translate3d(0, 36px, 0);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes landing-aurora {
|
||||
0%,
|
||||
100% {
|
||||
opacity: 0.8;
|
||||
transform: translate3d(0, 0, 0) scale(1);
|
||||
}
|
||||
50% {
|
||||
opacity: 1;
|
||||
transform: translate3d(0, -1%, 0) scale(1.04);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes landing-shimmer {
|
||||
0% {
|
||||
background-position: 0% 50%;
|
||||
}
|
||||
100% {
|
||||
background-position: 100% 50%;
|
||||
}
|
||||
}
|
||||
|
||||
.animate-landing-rise {
|
||||
animation: landing-rise 0.9s cubic-bezier(0.22, 1, 0.36, 1) both;
|
||||
}
|
||||
|
||||
.animate-landing-float {
|
||||
animation: landing-float 6s ease-in-out infinite;
|
||||
}
|
||||
|
||||
.landing-hero-grid {
|
||||
background-image:
|
||||
linear-gradient(to right, rgba(15, 23, 42, 0.06) 1px, transparent 1px),
|
||||
linear-gradient(to bottom, rgba(15, 23, 42, 0.06) 1px, transparent 1px);
|
||||
background-size: 72px 72px;
|
||||
mask-image: radial-gradient(circle at top, rgba(0, 0, 0, 0.95), transparent 78%);
|
||||
animation: landing-grid 16s linear infinite;
|
||||
}
|
||||
|
||||
.dark .landing-hero-grid {
|
||||
background-image:
|
||||
linear-gradient(to right, rgba(148, 163, 184, 0.09) 1px, transparent 1px),
|
||||
linear-gradient(to bottom, rgba(148, 163, 184, 0.09) 1px, transparent 1px);
|
||||
}
|
||||
|
||||
.landing-aurora {
|
||||
background:
|
||||
radial-gradient(circle at 10% 10%, rgba(34, 211, 238, 0.18), transparent 34%),
|
||||
radial-gradient(circle at 85% 18%, rgba(245, 158, 11, 0.18), transparent 28%),
|
||||
radial-gradient(circle at 58% 34%, rgba(20, 184, 166, 0.12), transparent 30%);
|
||||
animation: landing-aurora 14s ease-in-out infinite;
|
||||
}
|
||||
|
||||
.landing-shimmer {
|
||||
background-size: 200% 200%;
|
||||
animation: landing-shimmer 7s linear infinite;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -102,6 +207,10 @@
|
||||
scrollbar-color: #cbd5e1 transparent;
|
||||
}
|
||||
|
||||
html {
|
||||
scroll-behavior: smooth;
|
||||
}
|
||||
|
||||
.dark * {
|
||||
scrollbar-color: #334155 transparent;
|
||||
}
|
||||
|
||||
90
src/lib/queryParams.ts
Normal file
90
src/lib/queryParams.ts
Normal file
@@ -0,0 +1,90 @@
|
||||
export type QueryParamUpdateValue =
|
||||
| string
|
||||
| number
|
||||
| boolean
|
||||
| null
|
||||
| undefined
|
||||
| Array<string | number>;
|
||||
|
||||
type QueryParamDefaults = Record<string, string | number | boolean | undefined>;
|
||||
|
||||
const normalizeScalar = (value: string | number | boolean) => {
|
||||
if (typeof value === "boolean") {
|
||||
return value ? "1" : "0";
|
||||
}
|
||||
|
||||
return String(value);
|
||||
};
|
||||
|
||||
export const readStringParam = (
|
||||
searchParams: URLSearchParams,
|
||||
key: string,
|
||||
fallback = "",
|
||||
) => searchParams.get(key) ?? fallback;
|
||||
|
||||
export const readNumberParam = (
|
||||
searchParams: URLSearchParams,
|
||||
key: string,
|
||||
fallback: number,
|
||||
) => {
|
||||
const rawValue = searchParams.get(key);
|
||||
if (!rawValue) return fallback;
|
||||
|
||||
const parsedValue = Number(rawValue);
|
||||
if (!Number.isFinite(parsedValue)) return fallback;
|
||||
|
||||
return parsedValue;
|
||||
};
|
||||
|
||||
export const readBooleanParam = (
|
||||
searchParams: URLSearchParams,
|
||||
key: string,
|
||||
fallback = false,
|
||||
) => {
|
||||
const rawValue = searchParams.get(key);
|
||||
if (rawValue === null) return fallback;
|
||||
|
||||
return rawValue === "1" || rawValue === "true";
|
||||
};
|
||||
|
||||
export const readArrayParam = (searchParams: URLSearchParams, key: string) =>
|
||||
searchParams.getAll(key).filter(Boolean);
|
||||
|
||||
export const updateQueryParams = (
|
||||
currentParams: URLSearchParams,
|
||||
updates: Record<string, QueryParamUpdateValue>,
|
||||
defaults: QueryParamDefaults = {},
|
||||
) => {
|
||||
const nextParams = new URLSearchParams(currentParams);
|
||||
|
||||
Object.entries(updates).forEach(([key, value]) => {
|
||||
nextParams.delete(key);
|
||||
|
||||
if (Array.isArray(value)) {
|
||||
const normalizedValues = value
|
||||
.map((item) => String(item).trim())
|
||||
.filter(Boolean);
|
||||
|
||||
normalizedValues.forEach((item) => nextParams.append(key, item));
|
||||
return;
|
||||
}
|
||||
|
||||
if (value === null || value === undefined) return;
|
||||
|
||||
const normalizedValue =
|
||||
typeof value === "string" ? value.trim() : normalizeScalar(value);
|
||||
const defaultValue = defaults[key];
|
||||
|
||||
if (!normalizedValue.length) return;
|
||||
if (
|
||||
defaultValue !== undefined &&
|
||||
normalizedValue === normalizeScalar(defaultValue)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
nextParams.set(key, normalizedValue);
|
||||
});
|
||||
|
||||
return nextParams;
|
||||
};
|
||||
144
src/lib/rateLimit.ts
Normal file
144
src/lib/rateLimit.ts
Normal file
@@ -0,0 +1,144 @@
|
||||
const STORAGE_KEY = "qlockify:rate-limit-lock"
|
||||
|
||||
export interface RateLimitLock {
|
||||
status: number
|
||||
code: string | null
|
||||
message: string
|
||||
retryAfterSeconds: number
|
||||
throttledUntil: string
|
||||
returnTo: string
|
||||
}
|
||||
|
||||
interface ActivateRateLimitInput {
|
||||
status: number
|
||||
code?: string | null
|
||||
message?: string | null
|
||||
retryAfterSeconds?: number | null
|
||||
throttledUntil?: string | null
|
||||
returnTo?: string | null
|
||||
}
|
||||
|
||||
const DEFAULT_RETRY_SECONDS = 60
|
||||
|
||||
const isBrowser = typeof window !== "undefined"
|
||||
|
||||
const getCurrentPath = () => {
|
||||
if (!isBrowser) {
|
||||
return "/"
|
||||
}
|
||||
|
||||
return `${window.location.pathname}${window.location.search}${window.location.hash}`
|
||||
}
|
||||
|
||||
const parseIsoDate = (value: string | null | undefined) => {
|
||||
if (!value) {
|
||||
return null
|
||||
}
|
||||
|
||||
const timestamp = Date.parse(value)
|
||||
return Number.isFinite(timestamp) ? timestamp : null
|
||||
}
|
||||
|
||||
const readStoredLock = (): RateLimitLock | null => {
|
||||
if (!isBrowser) {
|
||||
return null
|
||||
}
|
||||
|
||||
try {
|
||||
const raw = window.localStorage.getItem(STORAGE_KEY)
|
||||
if (!raw) {
|
||||
return null
|
||||
}
|
||||
|
||||
const parsed = JSON.parse(raw) as Partial<RateLimitLock>
|
||||
if (
|
||||
typeof parsed.status !== "number" ||
|
||||
typeof parsed.message !== "string" ||
|
||||
typeof parsed.retryAfterSeconds !== "number" ||
|
||||
typeof parsed.throttledUntil !== "string" ||
|
||||
typeof parsed.returnTo !== "string"
|
||||
) {
|
||||
window.localStorage.removeItem(STORAGE_KEY)
|
||||
return null
|
||||
}
|
||||
|
||||
if (parseIsoDate(parsed.throttledUntil) == null) {
|
||||
window.localStorage.removeItem(STORAGE_KEY)
|
||||
return null
|
||||
}
|
||||
|
||||
return {
|
||||
status: parsed.status,
|
||||
code: typeof parsed.code === "string" ? parsed.code : null,
|
||||
message: parsed.message,
|
||||
retryAfterSeconds: parsed.retryAfterSeconds,
|
||||
throttledUntil: parsed.throttledUntil,
|
||||
returnTo: parsed.returnTo,
|
||||
}
|
||||
} catch {
|
||||
window.localStorage.removeItem(STORAGE_KEY)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export const getRateLimitRemainingSeconds = (lock: RateLimitLock | null) => {
|
||||
if (!lock) {
|
||||
return 0
|
||||
}
|
||||
|
||||
const untilTimestamp = parseIsoDate(lock.throttledUntil)
|
||||
if (untilTimestamp == null) {
|
||||
return 0
|
||||
}
|
||||
|
||||
return Math.max(0, Math.ceil((untilTimestamp - Date.now()) / 1000))
|
||||
}
|
||||
|
||||
export const getStoredRateLimitLock = () => readStoredLock()
|
||||
|
||||
export const isRateLimitActive = () => getRateLimitRemainingSeconds(readStoredLock()) > 0
|
||||
|
||||
export const clearRateLimitLock = () => {
|
||||
if (!isBrowser) {
|
||||
return
|
||||
}
|
||||
|
||||
window.localStorage.removeItem(STORAGE_KEY)
|
||||
}
|
||||
|
||||
export const activateRateLimitLock = (input: ActivateRateLimitInput) => {
|
||||
if (!isBrowser) {
|
||||
return null
|
||||
}
|
||||
|
||||
const parsedThrottledUntil = parseIsoDate(input.throttledUntil)
|
||||
const retryFromUntil =
|
||||
parsedThrottledUntil != null
|
||||
? Math.ceil(Math.max(parsedThrottledUntil - Date.now(), 0) / 1000)
|
||||
: 0
|
||||
const retryAfterSeconds = Math.max(
|
||||
input.retryAfterSeconds ?? retryFromUntil ?? DEFAULT_RETRY_SECONDS,
|
||||
retryFromUntil,
|
||||
0,
|
||||
) || DEFAULT_RETRY_SECONDS
|
||||
|
||||
const throttledUntil =
|
||||
input.throttledUntil && parsedThrottledUntil != null
|
||||
? input.throttledUntil
|
||||
: new Date(Date.now() + retryAfterSeconds * 1000).toISOString()
|
||||
|
||||
const returnTo =
|
||||
input.returnTo && input.returnTo !== "/rate-limit" ? input.returnTo : getCurrentPath()
|
||||
|
||||
const lock: RateLimitLock = {
|
||||
status: input.status,
|
||||
code: input.code ?? "throttled",
|
||||
message: input.message || "Too many requests",
|
||||
retryAfterSeconds,
|
||||
throttledUntil,
|
||||
returnTo: returnTo === "/rate-limit" ? "/" : returnTo,
|
||||
}
|
||||
|
||||
window.localStorage.setItem(STORAGE_KEY, JSON.stringify(lock))
|
||||
return lock
|
||||
}
|
||||
54
src/lib/reportFilters.ts
Normal file
54
src/lib/reportFilters.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
import type { ReportPeriod } from "../api/reports";
|
||||
import type { ReportsFilterDraft } from "../components/reports/ReportsFilterBar";
|
||||
import { readArrayParam, readStringParam, updateQueryParams } from "./queryParams";
|
||||
|
||||
export const DEFAULT_REPORTS_FILTERS: ReportsFilterDraft = {
|
||||
period: "this_month",
|
||||
from_date: "",
|
||||
to_date: "",
|
||||
user: "",
|
||||
client: "",
|
||||
project: "",
|
||||
tags: [],
|
||||
};
|
||||
|
||||
export const readReportsFiltersFromParams = (
|
||||
searchParams: URLSearchParams,
|
||||
): ReportsFilterDraft => ({
|
||||
period: readStringParam(
|
||||
searchParams,
|
||||
"period",
|
||||
DEFAULT_REPORTS_FILTERS.period,
|
||||
) as ReportPeriod,
|
||||
from_date: readStringParam(searchParams, "from", ""),
|
||||
to_date: readStringParam(searchParams, "to", ""),
|
||||
user: readStringParam(searchParams, "user", ""),
|
||||
client: readStringParam(searchParams, "client", ""),
|
||||
project: readStringParam(searchParams, "project", ""),
|
||||
tags: readArrayParam(searchParams, "tags"),
|
||||
});
|
||||
|
||||
export const writeReportsFiltersToParams = (
|
||||
currentParams: URLSearchParams,
|
||||
filters: ReportsFilterDraft,
|
||||
) =>
|
||||
updateQueryParams(
|
||||
currentParams,
|
||||
{
|
||||
period: filters.period,
|
||||
from: filters.from_date,
|
||||
to: filters.to_date,
|
||||
user: filters.user,
|
||||
client: filters.client,
|
||||
project: filters.project,
|
||||
tags: filters.tags,
|
||||
},
|
||||
{
|
||||
period: DEFAULT_REPORTS_FILTERS.period,
|
||||
from: "",
|
||||
to: "",
|
||||
user: "",
|
||||
client: "",
|
||||
project: "",
|
||||
},
|
||||
);
|
||||
@@ -6,10 +6,11 @@ export const en = {
|
||||
confirmLogoutMessage: "Are you sure you want to log out of your account?",
|
||||
confirmLeave: "You have unsaved changes. Are you sure you want to leave?",
|
||||
cancel: "Cancel",
|
||||
save: "Save",
|
||||
lightMode: "Light Mode",
|
||||
darkMode: "Dark Mode",
|
||||
loadingText: "Loading...",
|
||||
save: "Save",
|
||||
lightMode: "Light Mode",
|
||||
darkMode: "Dark Mode",
|
||||
settings: "Settings",
|
||||
loadingText: "Loading...",
|
||||
loading: "Loading...",
|
||||
add: "Add",
|
||||
create: "Create",
|
||||
@@ -31,9 +32,10 @@ export const en = {
|
||||
enterMobileDesc: "Enter your mobile number to continue",
|
||||
signInDesc: "Sign in using your account password",
|
||||
sentCodeDesc: (mobile: string) => `We sent a 6-digit code to ${mobile}`,
|
||||
mobilePlaceholder: "Mobile Number (e.g. 09123456789)",
|
||||
continueWithPassword: "Continue with Password",
|
||||
orContinueWith: "Or continue with",
|
||||
mobilePlaceholder: "Mobile Number (e.g. 09123456789)",
|
||||
continueWithPassword: "Continue with Password",
|
||||
continueWithGoogle: "Continue with Google",
|
||||
orContinueWith: "Or continue with",
|
||||
otpLogin: "OTP Login",
|
||||
register: "Register",
|
||||
passwordPlaceholder: "Password",
|
||||
@@ -52,8 +54,37 @@ export const en = {
|
||||
invalidCreds: "Invalid credentials",
|
||||
enterOtp: "Please enter the OTP code",
|
||||
invalidOtp: "Invalid OTP code"
|
||||
}
|
||||
},
|
||||
},
|
||||
throttle: {
|
||||
title: "Too many attempts",
|
||||
genericMessage: (time: string) => `Too many requests. Try again in ${time}.`,
|
||||
otpSendMessage: (time: string) => `Too many OTP requests. Try again in ${time}.`,
|
||||
passwordLoginMessage: (time: string) => `Too many password login attempts. Try again in ${time}.`,
|
||||
otpLoginMessage: (time: string) => `Too many OTP login attempts. Try again in ${time}.`,
|
||||
countdownLabel: (time: string) => `Retry in ${time}`,
|
||||
fallback: "Too many requests. Please wait and try again.",
|
||||
},
|
||||
google: {
|
||||
loadingTitle: "Completing Google sign in",
|
||||
loadingDescription: "We are validating your Google account and preparing the next step.",
|
||||
collectMobileTitle: "Finish your account setup",
|
||||
collectMobileDescription: (email: string) =>
|
||||
`Google verified ${email}. Enter your mobile number to finish creating your account.`,
|
||||
claimTitle: "Verify your existing account",
|
||||
claimDescription: (mobile: string) =>
|
||||
`An account with ${mobile} already exists. Enter the verification code sent to that number to attach Google.`,
|
||||
errorTitle: "Google sign in could not be completed",
|
||||
missingFlow: "The Google sign-in flow is missing or has expired.",
|
||||
loadFailed: "We could not load your Google sign-in state.",
|
||||
completeFailed: "We could not finish your Google account setup.",
|
||||
claimOtpSent: "Verification code sent successfully.",
|
||||
googleAccount: "Google account",
|
||||
completeButton: "Continue and create account",
|
||||
verifyClaimButton: "Verify and continue",
|
||||
resendClaimOtp: "Resend verification code",
|
||||
restartGoogle: "Start Google sign in again",
|
||||
},
|
||||
},
|
||||
|
||||
loginTerms: {
|
||||
prefix: "By logging in, you agree to our ",
|
||||
@@ -61,6 +92,18 @@ export const en = {
|
||||
suffix: ""
|
||||
},
|
||||
|
||||
rateLimit: {
|
||||
eyebrow: "Request limit reached",
|
||||
title: "Please wait before trying again",
|
||||
message: "You have sent too many requests. Access is temporarily locked until the cooldown finishes.",
|
||||
cooldownLabel: "Cooldown",
|
||||
waitingMessage: (time: string) => `Requests are blocked for now.`,
|
||||
finishedMessage: "The cooldown has finished. You can continue now.",
|
||||
continue: "Continue",
|
||||
continueCooldown: (time: string) => `Continue in ${time}`,
|
||||
ready: "Ready",
|
||||
},
|
||||
|
||||
terms: {
|
||||
back: "Back",
|
||||
title: "Terms of Service and Privacy Policy",
|
||||
@@ -131,13 +174,13 @@ export const en = {
|
||||
nameLabel: "Workspace Name",
|
||||
namePlaceholder: "Enter workspace name",
|
||||
descriptionLabel: "Description",
|
||||
descriptionPlaceholder: "Enter description (optional)",
|
||||
thumbnailLabel: "Thumbnail",
|
||||
uploadImage: "Click to upload image",
|
||||
removeImage: "Remove image",
|
||||
thumbnailInvalidType: "Unsupported image type. Use JPG, PNG, or WebP.",
|
||||
thumbnailMaxSizeError: "Image size must be 2MB or less.",
|
||||
searchMemberPlaceholder: "Search exact mobile (e.g. 09123456789)",
|
||||
descriptionPlaceholder: "Enter description (optional)",
|
||||
thumbnailLabel: "Thumbnail",
|
||||
uploadImage: "Click to upload image",
|
||||
removeImage: "Remove image",
|
||||
thumbnailInvalidType: "Unsupported image type. Use JPG, PNG, or WebP.",
|
||||
thumbnailMaxSizeError: "Image size must be 2MB or less.",
|
||||
searchMemberPlaceholder: "Search exact mobile (e.g. 09123456789)",
|
||||
addMember: "Add Member",
|
||||
roleAdmin: "Admin",
|
||||
roleMember: "Member",
|
||||
@@ -154,6 +197,8 @@ export const en = {
|
||||
subtitle: "Manage your workspaces",
|
||||
noDescription: "No description",
|
||||
emptyState: "You are not a member of any workspace.",
|
||||
noWorkspaceSearch: "Try adjusting your search query.",
|
||||
noWorkspace: "No workspaces found.",
|
||||
createTitle: "Create Workspace",
|
||||
editTitle: "Edit Workspace",
|
||||
detailTitle: "Workspace Details",
|
||||
@@ -222,6 +267,7 @@ export const en = {
|
||||
cannotAddSelf: "You are automatically the owner.",
|
||||
},
|
||||
onlyNumbersAllowed: "Only numbers are allowed for mobile number.",
|
||||
weekTotal: "Week Total"
|
||||
},
|
||||
|
||||
clients: {
|
||||
@@ -244,13 +290,13 @@ export const en = {
|
||||
editClient: "Edit Client",
|
||||
deleteConfirmTitle: "Delete Client",
|
||||
deleteConfirmMessage: (name: string) => `Are you sure you want to delete ${name}?`,
|
||||
delete: "Delete",
|
||||
saveChanges: "Save Changes",
|
||||
createSuccess: "Client created successfully.",
|
||||
updateSuccess: "Client updated successfully.",
|
||||
deleteSuccess: "Client deleted successfully.",
|
||||
errors: {
|
||||
createFailed: "Failed to create client",
|
||||
delete: "Delete",
|
||||
saveChanges: "Save Changes",
|
||||
createSuccess: "Client created successfully.",
|
||||
updateSuccess: "Client updated successfully.",
|
||||
deleteSuccess: "Client deleted successfully.",
|
||||
errors: {
|
||||
createFailed: "Failed to create client",
|
||||
fetchFailed: "Failed to fetch clients",
|
||||
updateFailed: "Failed to update client",
|
||||
deleteFailed: "Failed to delete client",
|
||||
@@ -271,16 +317,104 @@ export const en = {
|
||||
timesheet: "Timesheet",
|
||||
reports: "Reports",
|
||||
logs: "Logs",
|
||||
workspaces: 'Workspaces',
|
||||
clients: 'Clients',
|
||||
projects: "Projects",
|
||||
workspaces: 'Workspaces',
|
||||
clients: 'Clients',
|
||||
projects: "Projects",
|
||||
tags: "Tags",
|
||||
expand: 'Expand',
|
||||
collapse: 'Collapse',
|
||||
},
|
||||
|
||||
ordering: {
|
||||
createdAtDesc: "Newest First",
|
||||
collapse: 'Collapse',
|
||||
},
|
||||
|
||||
landing: {
|
||||
brandLabel: "Operating system for time",
|
||||
eyebrow: "Built for high-discipline teams that need clean time intelligence",
|
||||
nav: {
|
||||
demo: "Product demo",
|
||||
features: "Core capabilities",
|
||||
workflow: "How it works",
|
||||
},
|
||||
actions: {
|
||||
switchToEnglish: "English",
|
||||
switchToPersian: "فارسی",
|
||||
signIn: "Sign in",
|
||||
openApp: "Open app",
|
||||
openWorkspace: "Open workspace",
|
||||
startNow: "Start tracking with control",
|
||||
watchDemo: "See the product demo",
|
||||
readTerms: "Read terms",
|
||||
},
|
||||
hero: {
|
||||
titleTop: "Turn every working hour into a reliable operating signal.",
|
||||
titleAccent: "Qlockify makes time visible, accountable, and billable.",
|
||||
description:
|
||||
"A focused workspace for modern teams that need fast time capture, trustworthy project tracking, structured reports, and a log trail that management can actually use.",
|
||||
},
|
||||
metrics: {
|
||||
capture: "cleaner billable capture",
|
||||
visibility: "faster reporting visibility",
|
||||
decision: "from raw entries to management context",
|
||||
},
|
||||
trust: {
|
||||
first: "Precise timers with manual control when needed",
|
||||
second: "Workspace permissions, logs, and rate-aware reporting",
|
||||
third: "Built for agencies, consultancies, product teams, and operators",
|
||||
},
|
||||
capabilities: {
|
||||
time: {
|
||||
title: "Capture work without friction",
|
||||
description:
|
||||
"Start a timer, adjust historical entries, and keep project and tag context attached to every hour without slowing the team down.",
|
||||
},
|
||||
reports: {
|
||||
title: "Read the business in minutes",
|
||||
description:
|
||||
"See daily output, billable performance, project distribution, and exportable report packs without spreadsheet cleanup.",
|
||||
},
|
||||
control: {
|
||||
title: "Keep operations explainable",
|
||||
description:
|
||||
"Track who changed what, keep workspace roles explicit, and give management a cleaner operational trail than ad hoc chat or manual files.",
|
||||
},
|
||||
},
|
||||
demo: {
|
||||
timerTag: "Live timer",
|
||||
timerTitle: "Current execution window",
|
||||
timerText: "Design system refinement synced to the correct project, tags, and billable rate.",
|
||||
panelLabel: "Interactive product preview",
|
||||
panelTitle: "One surface for tracking, reporting, and operational clarity",
|
||||
runningCard: "Active entry",
|
||||
currentTask: "Enterprise landing page rollout",
|
||||
currentTaskMeta: "Project: Qlockify Marketing · Tags: Design, Review, Delivery",
|
||||
billableLabel: "Live billable rate",
|
||||
reportCard: "Daily report trend",
|
||||
opsCard: "Operational health",
|
||||
opsLabels: ["Coverage", "Team focus", "Billing readiness"],
|
||||
logCard: "Recent workspace activity",
|
||||
logItems: [
|
||||
{ title: "Rate updated for product design", meta: "Owner action · 3 minutes ago" },
|
||||
{ title: "Client-facing project moved to archived", meta: "Admin action · 18 minutes ago" },
|
||||
{ title: "Historic tag preserved on edited entry", meta: "Member action · 41 minutes ago" },
|
||||
],
|
||||
outcomeTag: "Management result",
|
||||
outcomeText: "Less ambiguity at month end, fewer missing billable hours, and faster operational reviews.",
|
||||
},
|
||||
workflowTag: "Operational workflow",
|
||||
workflowTitle: "A tighter loop from raw effort to usable management data.",
|
||||
workflowDescription:
|
||||
"Qlockify is designed to keep the path short: capture accurately, structure context once, and reuse the result everywhere from timesheets to reports to workspace-level decisions.",
|
||||
workflow: {
|
||||
capture: "Capture time at the source with project, tags, and billing context attached immediately.",
|
||||
structure: "Keep every workspace action, membership change, and rate update visible and reviewable.",
|
||||
improve: "Review daily and monthly performance with reports that are ready to export or act on.",
|
||||
},
|
||||
finalCtaTag: "Ready for production teams",
|
||||
finalCtaTitle: "If your team sells expertise or ships client work, your time system should look this serious.",
|
||||
finalCtaDescription:
|
||||
"Open the app, create a workspace, and see how fast your reporting discipline improves when the product stops leaking context.",
|
||||
},
|
||||
|
||||
ordering: {
|
||||
createdAtDesc: "Newest First",
|
||||
createdAt: "Olders First",
|
||||
updatedAtDesc: "Recently Updated",
|
||||
name: "Name (A-Z)",
|
||||
@@ -292,11 +426,11 @@ export const en = {
|
||||
description: (workspaceName: string) => `Manage projects for ${workspaceName}`,
|
||||
active: "Active Projects",
|
||||
archived: "Archived Projects",
|
||||
createNew: "Create New",
|
||||
searchPlaceholder: "Search projects...",
|
||||
selectWorkspace: "Please select a workspace first.",
|
||||
titlePlaceholder: "Enter title",
|
||||
descriptionPlaceholder: "Enter desription",
|
||||
createNew: "Create New",
|
||||
searchPlaceholder: "Search projects...",
|
||||
selectWorkspace: "Please select a workspace first.",
|
||||
titlePlaceholder: "Enter title",
|
||||
descriptionPlaceholder: "Enter desription",
|
||||
titleLabel: "Title",
|
||||
clientLabel: "Client",
|
||||
colorLabel: "Color",
|
||||
@@ -305,6 +439,7 @@ export const en = {
|
||||
client: "Client",
|
||||
noClient: "No client",
|
||||
emptyState: "No projects found",
|
||||
noProjectsSearch: "Try adjusting your search query.",
|
||||
deleteTitle: "Delete Project",
|
||||
deleteWarning: "To confirm deletion, please type the project name:",
|
||||
deleteSuccess: "Project deleted successfully",
|
||||
@@ -314,13 +449,13 @@ export const en = {
|
||||
createProject: "Create New Project",
|
||||
editProject: "Edit Project",
|
||||
restore: "Restore",
|
||||
archive: "Archive",
|
||||
archiveSuccess: "Project archived successfully.",
|
||||
restoreSuccess: "Project restored successfully.",
|
||||
fetchError: "Failed to fetch projects.",
|
||||
clientFetchError: "Failed to load clients.",
|
||||
filterClients: "Filter by client",
|
||||
clearClientFilters: "Clear filters",
|
||||
archive: "Archive",
|
||||
archiveSuccess: "Project archived successfully.",
|
||||
restoreSuccess: "Project restored successfully.",
|
||||
fetchError: "Failed to fetch projects.",
|
||||
clientFetchError: "Failed to load clients.",
|
||||
filterClients: "Filter by client",
|
||||
clearClientFilters: "Clear filters",
|
||||
namePlaceholder: "Project name...",
|
||||
teamMembers: "Team Members",
|
||||
creator: "Creator",
|
||||
@@ -362,6 +497,7 @@ export const en = {
|
||||
namePlaceholder: "e.g. Design",
|
||||
colorLabel: "Color",
|
||||
emptyState: "No tags found",
|
||||
noTagsSearch: "Try adjusting your search query.",
|
||||
selectWorkspace: "Please select a workspace first.",
|
||||
fetchError: "Failed to load tags",
|
||||
createSuccess: "Tag created successfully.",
|
||||
@@ -407,6 +543,8 @@ export const en = {
|
||||
orderingNewest: "Newest first",
|
||||
orderingOldest: "Oldest first",
|
||||
emptyState: "No time entries found",
|
||||
emptyStateDescription: "Start the timer or add a manual entry to get started.",
|
||||
noEntriesSearch: "Try adjusting your search query or filters.",
|
||||
emptyDescription: "No description",
|
||||
createTitle: "Add Time Entry",
|
||||
startTitle: "Start Timer",
|
||||
@@ -423,14 +561,14 @@ export const en = {
|
||||
optionsError: "Failed to load projects and tags.",
|
||||
descriptionLabel: "Description",
|
||||
descriptionPlaceholder: "What are you working on?",
|
||||
projectLabel: "Project",
|
||||
noProject: "No project",
|
||||
startLabel: "Start",
|
||||
endLabel: "End",
|
||||
timeLabel: "Time",
|
||||
billable: "Billable",
|
||||
noTagsHint: "Create tags first from the Tags page.",
|
||||
clearFilters: "Clear filters",
|
||||
projectLabel: "Project",
|
||||
noProject: "No project",
|
||||
startLabel: "Start",
|
||||
endLabel: "End",
|
||||
timeLabel: "Time",
|
||||
billable: "Billable",
|
||||
noTagsHint: "Create tags first from the Tags page.",
|
||||
clearFilters: "Clear filters",
|
||||
customFromLabel: "From date",
|
||||
customToLabel: "To date",
|
||||
allClientsLabel: "All clients",
|
||||
@@ -440,23 +578,23 @@ export const en = {
|
||||
hideFiltersLabel: "Hide filters",
|
||||
applyFiltersLabel: "Apply",
|
||||
clientFilterPrefix: "Client",
|
||||
projectFilterPrefix: "Project",
|
||||
tagFilterPrefix: "Tag",
|
||||
fromFilterPrefix: "From",
|
||||
toFilterPrefix: "To",
|
||||
deleteTitle: "Delete Time Entry",
|
||||
deleteConfirmMessage: "Are you sure you want to delete this time entry?",
|
||||
restartConfirmMessage: "Start a new running timer from this entry?",
|
||||
discardConfirmMessage: "Are you sure you want to discard this running timer?",
|
||||
searchTagsLabel: "Search tags...",
|
||||
noTagsFoundLabel: "No tags found.",
|
||||
searchProjectsLabel: "Search projects...",
|
||||
noProjectsFoundLabel: "No projects found.",
|
||||
deletedProjectLabel: "Deleted project",
|
||||
deletedTagLabel: "Deleted tag",
|
||||
},
|
||||
projectFilterPrefix: "Project",
|
||||
tagFilterPrefix: "Tag",
|
||||
fromFilterPrefix: "From",
|
||||
toFilterPrefix: "To",
|
||||
deleteTitle: "Delete Time Entry",
|
||||
deleteConfirmMessage: "Are you sure you want to delete this time entry?",
|
||||
restartConfirmMessage: "Start a new running timer from this entry?",
|
||||
discardConfirmMessage: "Are you sure you want to discard this running timer?",
|
||||
searchTagsLabel: "Search tags...",
|
||||
noTagsFoundLabel: "No tags found.",
|
||||
searchProjectsLabel: "Search projects...",
|
||||
noProjectsFoundLabel: "No projects found.",
|
||||
deletedProjectLabel: "Deleted project",
|
||||
deletedTagLabel: "Deleted tag",
|
||||
},
|
||||
|
||||
reports: {
|
||||
reports: {
|
||||
title: "Reports",
|
||||
description: (workspaceName: string) => `Review activity reports for ${workspaceName}`,
|
||||
selectWorkspace: "Please select a workspace first.",
|
||||
@@ -486,11 +624,11 @@ export const en = {
|
||||
name: "Name",
|
||||
clear: "Clear",
|
||||
apply: "Apply",
|
||||
totalHours: "Total hours",
|
||||
billableHours: "Billable hours",
|
||||
nonBillableHours: "Non-billable hours",
|
||||
hourlyRate: "Hourly rate",
|
||||
totalIncome: "Total income",
|
||||
totalHours: "Total hours",
|
||||
billableHours: "Billable hours",
|
||||
nonBillableHours: "Non-billable hours",
|
||||
hourlyRate: "Hourly rate",
|
||||
totalIncome: "Total income",
|
||||
chartTitle: "Activity chart",
|
||||
totalSeconds: "Total seconds",
|
||||
exportExcel: "Export Excel",
|
||||
@@ -504,120 +642,120 @@ export const en = {
|
||||
loadError: "Failed to load reports.",
|
||||
loadDayDetailsError: "Failed to load day details.",
|
||||
loadFiltersError: "Failed to load report filters.",
|
||||
exportQueued: "Export queued. You will receive a notification with the download link.",
|
||||
exportError: "Failed to queue report export.",
|
||||
},
|
||||
|
||||
logs: {
|
||||
eyebrow: "Workspace activity",
|
||||
title: "Activity logs",
|
||||
description: (workspaceName: string) => `Review what has happened inside ${workspaceName}.`,
|
||||
selectWorkspace: "Please select a workspace first.",
|
||||
unauthorized: "Only owners and admins can access workspace activity logs.",
|
||||
loading: "Loading logs...",
|
||||
loadingUsers: "Loading users...",
|
||||
loadingDetails: "Loading details...",
|
||||
loadError: "Failed to load logs.",
|
||||
loadDetailsError: "Failed to load log details.",
|
||||
loadFiltersError: "Failed to load log filters.",
|
||||
search: "Search",
|
||||
searchPlaceholder: "Search logs...",
|
||||
section: "Section",
|
||||
allSections: "All sections",
|
||||
event: "Event",
|
||||
allEvents: "All events",
|
||||
actor: "Actor",
|
||||
allActors: "All actors",
|
||||
searchActors: "Search users...",
|
||||
ordering: "Ordering",
|
||||
newestFirst: "Newest first",
|
||||
oldestFirst: "Oldest first",
|
||||
fromDate: "From date",
|
||||
toDate: "To date",
|
||||
clear: "Clear",
|
||||
apply: "Apply",
|
||||
loadMore: "Load more",
|
||||
totalLogs: "Total logs",
|
||||
activeFilters: "Active filters",
|
||||
latestActivity: "Latest activity",
|
||||
resultsCount: (count: number) => `${count} results`,
|
||||
empty: "No activity logs found",
|
||||
emptyHint: "Adjust your filters or wait for new workspace activity.",
|
||||
detailsTitle: "Activity details",
|
||||
detailsHint: "Select an activity item to inspect the exact field changes.",
|
||||
selectLogHint: "Select a log entry to see its details.",
|
||||
target: "Target",
|
||||
timestamp: "Timestamp",
|
||||
remoteAddress: "Remote address",
|
||||
previousValue: "Previous",
|
||||
currentValue: "Current",
|
||||
changesTitle: "Changes",
|
||||
noDetails: "No field-level details are available for this activity.",
|
||||
snapshot: "Serialized snapshot",
|
||||
unknownActor: "Unknown actor",
|
||||
summary: (actor: string, event: string, section: string, target: string) =>
|
||||
`${actor} ${event.toLowerCase()} ${target} in ${section.toLowerCase()}`,
|
||||
sections: {
|
||||
workspace: "Workspace",
|
||||
workspace_members: "Workspace members",
|
||||
clients: "Clients",
|
||||
projects: "Projects",
|
||||
tags: "Tags",
|
||||
time_entries: "Time entries",
|
||||
rates: "Rates",
|
||||
report_exports: "Report exports",
|
||||
},
|
||||
events: {
|
||||
create: "Created",
|
||||
update: "Updated",
|
||||
delete: "Deleted",
|
||||
restore: "Restored",
|
||||
archive: "Archived",
|
||||
unarchive: "Unarchived",
|
||||
activate: "Activated",
|
||||
deactivate: "Deactivated",
|
||||
},
|
||||
},
|
||||
|
||||
notifications: {
|
||||
title: "Notifications",
|
||||
pageDescription: "Review all notifications and export updates.",
|
||||
open: "Open notifications",
|
||||
empty: "No notifications yet.",
|
||||
emptyUnread: "No unread notifications.",
|
||||
loading: "Loading notifications...",
|
||||
loadingMore: "Loading more...",
|
||||
loadMore: "Load more",
|
||||
markAllRead: "Mark all as read",
|
||||
viewAll: "View all notifications",
|
||||
totalLabel: "Total notifications",
|
||||
unreadLabel: "Unread notifications",
|
||||
deleteLabel: "Delete notification",
|
||||
markSeenError: "Failed to update notification",
|
||||
markAllError: "Failed to update notifications",
|
||||
deleteError: "Failed to delete notification",
|
||||
loadError: "Failed to load notifications",
|
||||
openError: "Failed to open notification",
|
||||
newTitle: "New notification",
|
||||
openAction: "Open",
|
||||
summary: (total: number, unread: number) => `${total} total, ${unread} unread`,
|
||||
workspaceMembershipAddedTitle: "Added to workspace",
|
||||
workspaceMembershipAddedMessage: (actor: string, workspace: string, role: string) =>
|
||||
`${actor} added you to ${workspace} as ${role}.`,
|
||||
workspaceMembershipRoleChangedTitle: "Workspace role changed",
|
||||
workspaceMembershipRoleChangedMessage: (actor: string, workspace: string, previousRole: string, newRole: string) =>
|
||||
`${actor} changed your role in ${workspace} from ${previousRole} to ${newRole}.`,
|
||||
workspaceMembershipDeactivatedTitle: "Workspace access deactivated",
|
||||
workspaceMembershipDeactivatedMessage: (actor: string, workspace: string) =>
|
||||
`${actor} deactivated your access to ${workspace}.`,
|
||||
workspaceMembershipRemovedTitle: "Removed from workspace",
|
||||
workspaceMembershipRemovedMessage: (actor: string, workspace: string) =>
|
||||
`${actor} removed you from ${workspace}.`,
|
||||
reportExportReadyTitle: "Report export is ready",
|
||||
reportExportReadyMessage: (exportType: string, workspace: string, fileName?: string | null) =>
|
||||
`Your ${exportType.toUpperCase()} report for ${workspace} is ready${fileName ? `: ${fileName}` : ""}.`,
|
||||
reportExportFailedTitle: "Report export failed",
|
||||
reportExportFailedMessage: (exportType: string, workspace: string) =>
|
||||
`Your ${exportType.toUpperCase()} report for ${workspace} could not be generated.`,
|
||||
},
|
||||
}
|
||||
exportQueued: "Export queued. You will receive a notification with the download link.",
|
||||
exportError: "Failed to queue report export.",
|
||||
},
|
||||
|
||||
logs: {
|
||||
eyebrow: "Workspace activity",
|
||||
title: "Activity logs",
|
||||
description: (workspaceName: string) => `Review what has happened inside ${workspaceName}.`,
|
||||
selectWorkspace: "Please select a workspace first.",
|
||||
unauthorized: "Only owners and admins can access workspace activity logs.",
|
||||
loading: "Loading logs...",
|
||||
loadingUsers: "Loading users...",
|
||||
loadingDetails: "Loading details...",
|
||||
loadError: "Failed to load logs.",
|
||||
loadDetailsError: "Failed to load log details.",
|
||||
loadFiltersError: "Failed to load log filters.",
|
||||
search: "Search",
|
||||
searchPlaceholder: "Search logs...",
|
||||
section: "Section",
|
||||
allSections: "All sections",
|
||||
event: "Event",
|
||||
allEvents: "All events",
|
||||
actor: "Actor",
|
||||
allActors: "All actors",
|
||||
searchActors: "Search users...",
|
||||
ordering: "Ordering",
|
||||
newestFirst: "Newest first",
|
||||
oldestFirst: "Oldest first",
|
||||
fromDate: "From date",
|
||||
toDate: "To date",
|
||||
clear: "Clear",
|
||||
apply: "Apply",
|
||||
loadMore: "Load more",
|
||||
totalLogs: "Total logs",
|
||||
activeFilters: "Active filters",
|
||||
latestActivity: "Latest activity",
|
||||
resultsCount: (count: number) => `${count} results`,
|
||||
empty: "No activity logs found",
|
||||
emptyHint: "Adjust your filters or wait for new workspace activity.",
|
||||
detailsTitle: "Activity details",
|
||||
detailsHint: "Select an activity item to inspect the exact field changes.",
|
||||
selectLogHint: "Select a log entry to see its details.",
|
||||
target: "Target",
|
||||
timestamp: "Timestamp",
|
||||
remoteAddress: "Remote address",
|
||||
previousValue: "Previous",
|
||||
currentValue: "Current",
|
||||
changesTitle: "Changes",
|
||||
noDetails: "No field-level details are available for this activity.",
|
||||
snapshot: "Serialized snapshot",
|
||||
unknownActor: "Unknown actor",
|
||||
summary: (actor: string, event: string, section: string, target: string) =>
|
||||
`${actor} ${event.toLowerCase()} ${target} in ${section.toLowerCase()}`,
|
||||
sections: {
|
||||
workspace: "Workspace",
|
||||
workspace_members: "Workspace members",
|
||||
clients: "Clients",
|
||||
projects: "Projects",
|
||||
tags: "Tags",
|
||||
time_entries: "Time entries",
|
||||
rates: "Rates",
|
||||
report_exports: "Report exports",
|
||||
},
|
||||
events: {
|
||||
create: "Created",
|
||||
update: "Updated",
|
||||
delete: "Deleted",
|
||||
restore: "Restored",
|
||||
archive: "Archived",
|
||||
unarchive: "Unarchived",
|
||||
activate: "Activated",
|
||||
deactivate: "Deactivated",
|
||||
},
|
||||
},
|
||||
|
||||
notifications: {
|
||||
title: "Notifications",
|
||||
pageDescription: "Review all notifications and export updates.",
|
||||
open: "Open notifications",
|
||||
empty: "No notifications yet.",
|
||||
emptyUnread: "No unread notifications.",
|
||||
loading: "Loading notifications...",
|
||||
loadingMore: "Loading more...",
|
||||
loadMore: "Load more",
|
||||
markAllRead: "Mark all as read",
|
||||
viewAll: "View all notifications",
|
||||
totalLabel: "Total notifications",
|
||||
unreadLabel: "Unread notifications",
|
||||
deleteLabel: "Delete notification",
|
||||
markSeenError: "Failed to update notification",
|
||||
markAllError: "Failed to update notifications",
|
||||
deleteError: "Failed to delete notification",
|
||||
loadError: "Failed to load notifications",
|
||||
openError: "Failed to open notification",
|
||||
newTitle: "New notification",
|
||||
openAction: "Open",
|
||||
summary: (total: number, unread: number) => `${total} total, ${unread} unread`,
|
||||
workspaceMembershipAddedTitle: "Added to workspace",
|
||||
workspaceMembershipAddedMessage: (actor: string, workspace: string, role: string) =>
|
||||
`${actor} added you to ${workspace} as ${role}.`,
|
||||
workspaceMembershipRoleChangedTitle: "Workspace role changed",
|
||||
workspaceMembershipRoleChangedMessage: (actor: string, workspace: string, previousRole: string, newRole: string) =>
|
||||
`${actor} changed your role in ${workspace} from ${previousRole} to ${newRole}.`,
|
||||
workspaceMembershipDeactivatedTitle: "Workspace access deactivated",
|
||||
workspaceMembershipDeactivatedMessage: (actor: string, workspace: string) =>
|
||||
`${actor} deactivated your access to ${workspace}.`,
|
||||
workspaceMembershipRemovedTitle: "Removed from workspace",
|
||||
workspaceMembershipRemovedMessage: (actor: string, workspace: string) =>
|
||||
`${actor} removed you from ${workspace}.`,
|
||||
reportExportReadyTitle: "Report export is ready",
|
||||
reportExportReadyMessage: (exportType: string, workspace: string, fileName?: string | null) =>
|
||||
`Your ${exportType.toUpperCase()} report for ${workspace} is ready${fileName ? `: ${fileName}` : ""}.`,
|
||||
reportExportFailedTitle: "Report export failed",
|
||||
reportExportFailedMessage: (exportType: string, workspace: string) =>
|
||||
`Your ${exportType.toUpperCase()} report for ${workspace} could not be generated.`,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -11,7 +11,8 @@ export const fa = {
|
||||
save: "ذخیره",
|
||||
remove: "حذف",
|
||||
lightMode: "حالت روشن",
|
||||
darkMode: "حالت تاریک",
|
||||
darkMode: "حالت تاریک",
|
||||
settings: "تنظیمات",
|
||||
loadingText: "در حال بارگذاری...",
|
||||
loading: "در حال بارگذاری...",
|
||||
noMoreResults: "نتیجه دیگری نیست.",
|
||||
@@ -31,9 +32,10 @@ export const fa = {
|
||||
enterMobileDesc: "برای ادامه، شماره موبایل خود را وارد کنید",
|
||||
signInDesc: "با استفاده از رمز عبور خود وارد شوید",
|
||||
sentCodeDesc: (mobile: string) => `کد ۶ رقمی به ${mobile} ارسال شد`,
|
||||
mobilePlaceholder: "شماره موبایل (مثلا ۰۹۱۲۳۴۵۶۷۸۹)",
|
||||
continueWithPassword: "ادامه با رمز عبور",
|
||||
orContinueWith: "یا ادامه با",
|
||||
mobilePlaceholder: "شماره موبایل (مثلا ۰۹۱۲۳۴۵۶۷۸۹)",
|
||||
continueWithPassword: "ادامه با رمز عبور",
|
||||
continueWithGoogle: "ادامه با گوگل",
|
||||
orContinueWith: "یا ادامه با",
|
||||
otpLogin: "ورود با کد یکبار مصرف",
|
||||
register: "ثبت نام",
|
||||
passwordPlaceholder: "رمز عبور",
|
||||
@@ -52,8 +54,37 @@ export const fa = {
|
||||
invalidCreds: "اطلاعات ورود نامعتبر است",
|
||||
enterOtp: "لطفا کد تایید را وارد کنید",
|
||||
invalidOtp: "کد تایید نامعتبر است"
|
||||
}
|
||||
},
|
||||
},
|
||||
throttle: {
|
||||
title: "تعداد تلاشها بیش از حد مجاز است",
|
||||
genericMessage: (time: string) => `درخواستهای زیادی ارسال شده است. ${time} دیگر دوباره تلاش کنید.`,
|
||||
otpSendMessage: (time: string) => `ارسال کد یکبار مصرف بیش از حد مجاز انجام شده است. ${time} دیگر دوباره تلاش کنید.`,
|
||||
passwordLoginMessage: (time: string) => `تلاش برای ورود با رمز عبور بیش از حد مجاز بوده است. ${time} دیگر دوباره تلاش کنید.`,
|
||||
otpLoginMessage: (time: string) => `تلاش برای ورود با کد یکبار مصرف بیش از حد مجاز بوده است. ${time} دیگر دوباره تلاش کنید.`,
|
||||
countdownLabel: (time: string) => `تلاش دوباره تا ${time}`,
|
||||
fallback: "درخواستهای زیادی ارسال شده است. کمی صبر کنید و دوباره تلاش کنید.",
|
||||
},
|
||||
google: {
|
||||
loadingTitle: "در حال تکمیل ورود با گوگل",
|
||||
loadingDescription: "در حال بررسی حساب گوگل شما و آمادهسازی مرحله بعد هستیم.",
|
||||
collectMobileTitle: "ساخت حساب را کامل کنید",
|
||||
collectMobileDescription: (email: string) =>
|
||||
`حساب گوگل ${email} تایید شد. برای تکمیل ساخت حساب، شماره موبایل خود را وارد کنید.`,
|
||||
claimTitle: "حساب موجود خود را تایید کنید",
|
||||
claimDescription: (mobile: string) =>
|
||||
`حسابی با شماره ${mobile} از قبل وجود دارد. کد ارسالشده به این شماره را وارد کنید تا گوگل به همان حساب متصل شود.`,
|
||||
errorTitle: "ورود با گوگل کامل نشد",
|
||||
missingFlow: "جریان ورود با گوگل پیدا نشد یا منقضی شده است.",
|
||||
loadFailed: "بارگذاری وضعیت ورود با گوگل انجام نشد.",
|
||||
completeFailed: "تکمیل ساخت حساب با گوگل انجام نشد.",
|
||||
claimOtpSent: "کد تایید با موفقیت ارسال شد.",
|
||||
googleAccount: "حساب گوگل",
|
||||
completeButton: "ادامه و ایجاد حساب",
|
||||
verifyClaimButton: "تایید و ادامه",
|
||||
resendClaimOtp: "ارسال دوباره کد تایید",
|
||||
restartGoogle: "شروع دوباره ورود با گوگل",
|
||||
}
|
||||
},
|
||||
|
||||
loginTerms: {
|
||||
prefix: "با ورود به سیستم، شما با ",
|
||||
@@ -61,6 +92,18 @@ export const fa = {
|
||||
suffix: " ما موافقت میکنید."
|
||||
},
|
||||
|
||||
rateLimit: {
|
||||
eyebrow: "محدودیت درخواست فعال شده است",
|
||||
title: "لطفاً پیش از تلاش دوباره صبر کنید",
|
||||
message: "درخواستهای زیادی ارسال شده است. دسترسی شما تا پایان زمان انتظار به صورت موقت محدود شده است.",
|
||||
cooldownLabel: "زمان انتظار",
|
||||
waitingMessage: (time: string) => `ارسال درخواست برای مدتی مسدود است.`,
|
||||
finishedMessage: "زمان انتظار به پایان رسیده است. اکنون میتوانید ادامه دهید.",
|
||||
continue: "ادامه",
|
||||
continueCooldown: (time: string) => `ادامه تا ${time}`,
|
||||
ready: "آماده",
|
||||
},
|
||||
|
||||
terms: {
|
||||
back: "بازگشت",
|
||||
title: "شرایط خدمات و حریم خصوصی",
|
||||
@@ -155,6 +198,8 @@ export const fa = {
|
||||
subtitle: "ورکاسپیسهای خود را مدیریت کنید",
|
||||
noDescription: "بدون توضیحات",
|
||||
emptyState: "شما در هیچ ورکاسپیس عضو نیستید.",
|
||||
noWorkspaceSearch: "لطفاً عبارت جستجو را تغییر دهید.",
|
||||
noWorkspace: "ورکاسپیس یافت نشد.",
|
||||
createTitle: "ایجاد ورکاسپیس",
|
||||
editTitle: "ویرایش ورکاسپیس",
|
||||
detailTitle: "جزئیات ورکاسپیس",
|
||||
@@ -219,6 +264,7 @@ export const fa = {
|
||||
cannotAddSelf: "شما بهصورت خودکار مالک هستید.",
|
||||
},
|
||||
onlyNumbersAllowed: "برای شماره موبایل فقط مجاز به وارد کردن عدد هستید.",
|
||||
weekTotal: "مجموع هفته"
|
||||
},
|
||||
|
||||
clients: {
|
||||
@@ -241,13 +287,13 @@ export const fa = {
|
||||
editClient: "ویرایش مشتری",
|
||||
deleteConfirmTitle: "حذف مشتری",
|
||||
deleteConfirmMessage: (name: string) => `آیا از حذف ${name} اطمینان دارید؟`,
|
||||
delete: "حذف",
|
||||
saveChanges: "ذخیره تغییرات",
|
||||
createSuccess: "مشتری با موفقیت ایجاد شد.",
|
||||
updateSuccess: "مشتری با موفقیت بهروزرسانی شد.",
|
||||
deleteSuccess: "مشتری با موفقیت حذف شد.",
|
||||
errors: {
|
||||
createFailed: "خطا در ایجاد مشتری",
|
||||
delete: "حذف",
|
||||
saveChanges: "ذخیره تغییرات",
|
||||
createSuccess: "مشتری با موفقیت ایجاد شد.",
|
||||
updateSuccess: "مشتری با موفقیت بهروزرسانی شد.",
|
||||
deleteSuccess: "مشتری با موفقیت حذف شد.",
|
||||
errors: {
|
||||
createFailed: "خطا در ایجاد مشتری",
|
||||
fetchFailed: "خطا در دریافت لیست مشتریها",
|
||||
updateFailed: "خطا در ویرایش مشتری",
|
||||
deleteFailed: "خطا در حذف مشتری",
|
||||
@@ -264,11 +310,11 @@ export const fa = {
|
||||
next: "بعدی",
|
||||
},
|
||||
|
||||
sidebar: {
|
||||
timesheet: 'تایمشیت',
|
||||
reports: 'گزارشها',
|
||||
logs: "لاگها",
|
||||
workspaces: 'ورکاسپیسها',
|
||||
sidebar: {
|
||||
timesheet: 'تایمشیت',
|
||||
reports: 'گزارشها',
|
||||
logs: "لاگها",
|
||||
workspaces: 'ورکاسپیسها',
|
||||
clients: 'مشتریها',
|
||||
projects: "پروژهها",
|
||||
tags: "تگها",
|
||||
@@ -276,7 +322,95 @@ export const fa = {
|
||||
collapse: 'جمع کردن',
|
||||
},
|
||||
|
||||
ordering: {
|
||||
landing: {
|
||||
brandLabel: "زیرساخت عملیاتی زمان",
|
||||
eyebrow: "طراحیشده برای تیمهای دقیق که به داده زمانی قابل اتکا نیاز دارند",
|
||||
nav: {
|
||||
demo: "دموی محصول",
|
||||
features: "قابلیتها",
|
||||
workflow: "فرآیند کار",
|
||||
},
|
||||
actions: {
|
||||
switchToEnglish: "English",
|
||||
switchToPersian: "فارسی",
|
||||
signIn: "ورود",
|
||||
openApp: "ورود به اپ",
|
||||
openWorkspace: "باز کردن ورکاسپیس",
|
||||
startNow: "شروع با کنترل کامل",
|
||||
watchDemo: "مشاهده دموی محصول",
|
||||
readTerms: "مطالعه قوانین",
|
||||
},
|
||||
hero: {
|
||||
titleTop: "هر ساعت کاری را به یک سیگنال عملیاتی قابل اعتماد تبدیل کنید.",
|
||||
titleAccent: "Qlockify زمان را شفاف، پاسخگو و قابلصورتحساب میکند.",
|
||||
description:
|
||||
"یک محیط متمرکز برای تیمهای مدرن که به ثبت سریع زمان، رهگیری دقیق پروژه، گزارشهای قابل اتکا و لاگ عملیاتی واقعی برای مدیریت نیاز دارند.",
|
||||
},
|
||||
metrics: {
|
||||
capture: "ثبت تمیزتر ساعات قابلصورتحساب",
|
||||
visibility: "دسترسی سریعتر به دید گزارشدهی",
|
||||
decision: "از ورودی خام تا تصمیم مدیریتی",
|
||||
},
|
||||
trust: {
|
||||
first: "تایمر دقیق با امکان ویرایش دستی در زمان لازم",
|
||||
second: "دسترسیها، لاگها و گزارشهای مبتنی بر نرخ",
|
||||
third: "مناسب آژانسها، شرکتهای مشاوره، تیمهای محصول و عملیات",
|
||||
},
|
||||
capabilities: {
|
||||
time: {
|
||||
title: "ثبت کار بدون اصطکاک",
|
||||
description:
|
||||
"تایمر را شروع کنید، ورودیهای گذشته را اصلاح کنید و پروژه و تگ را بدون ایجاد اصطکاک برای تیم به هر ساعت متصل نگه دارید.",
|
||||
},
|
||||
reports: {
|
||||
title: "کسبوکار را در چند دقیقه بخوانید",
|
||||
description:
|
||||
"خروجی روزانه، عملکرد قابلصورتحساب، توزیع پروژهها و بستههای گزارشی قابل خروجی را بدون پاکسازی دستی فایلها ببینید.",
|
||||
},
|
||||
control: {
|
||||
title: "عملیات را قابل توضیح نگه دارید",
|
||||
description:
|
||||
"ببینید چه کسی چه چیزی را تغییر داده، نقشها را شفاف نگه دارید و برای مدیریت یک رد عملیاتی تمیزتر از چت و فایل دستی بسازید.",
|
||||
},
|
||||
},
|
||||
demo: {
|
||||
timerTag: "تایمر زنده",
|
||||
timerTitle: "بازه اجرای فعلی",
|
||||
timerText: "بهبود دیزاین سیستم، متصل به پروژه درست، تگهای صحیح و نرخ قابلصورتحساب.",
|
||||
panelLabel: "پیشنمایش تعاملی محصول",
|
||||
panelTitle: "یک سطح واحد برای رهگیری، گزارشدهی و شفافیت عملیاتی",
|
||||
runningCard: "ورودی فعال",
|
||||
currentTask: "پیادهسازی لندینگ سازمانی",
|
||||
currentTaskMeta: "پروژه: بازاریابی Qlockify · تگها: طراحی، بازبینی، تحویل",
|
||||
billableLabel: "نرخ زنده قابلصورتحساب",
|
||||
reportCard: "روند گزارش روزانه",
|
||||
opsCard: "سلامت عملیات",
|
||||
opsLabels: ["پوشش", "تمرکز تیم", "آمادگی صورتحساب"],
|
||||
logCard: "آخرین فعالیتهای ورکاسپیس",
|
||||
logItems: [
|
||||
{ title: "نرخ تیم طراحی محصول بهروزرسانی شد", meta: "اقدام مالک · ۳ دقیقه پیش" },
|
||||
{ title: "پروژه مشتریمحور بایگانی شد", meta: "اقدام ادمین · ۱۸ دقیقه پیش" },
|
||||
{ title: "تگ تاریخی روی ورودی ویرایششده حفظ شد", meta: "اقدام عضو · ۴۱ دقیقه پیش" },
|
||||
],
|
||||
outcomeTag: "خروجی مدیریتی",
|
||||
outcomeText: "ابهام کمتر در پایان ماه، ساعات قابلصورتحساب ازدسترفته کمتر و بازبینی عملیاتی سریعتر.",
|
||||
},
|
||||
workflowTag: "فرآیند عملیاتی",
|
||||
workflowTitle: "از تلاش خام تا داده مدیریتی قابل استفاده، با یک حلقه کوتاهتر.",
|
||||
workflowDescription:
|
||||
"Qlockify مسیر را کوتاه نگه میدارد: دقیق ثبت کنید، یکبار بستر را درست بسازید و همان نتیجه را در تایمشیت، گزارش و تصمیمگیری مدیریتی مصرف کنید.",
|
||||
workflow: {
|
||||
capture: "زمان را در مبدأ، همراه با پروژه، تگ و بستر مالی ثبت کنید.",
|
||||
structure: "هر تغییر در اعضا، نرخها و تنظیمات ورکاسپیس را قابل مشاهده و قابل بررسی نگه دارید.",
|
||||
improve: "عملکرد روزانه و ماهانه را با گزارشهایی بخوانید که آماده خروجی و اقدام هستند.",
|
||||
},
|
||||
finalCtaTag: "آماده برای تیمهای جدی",
|
||||
finalCtaTitle: "اگر تیم شما تخصص میفروشد یا پروژه مشتری تحویل میدهد، سیستم زمان شما هم باید همینقدر جدی باشد.",
|
||||
finalCtaDescription:
|
||||
"اپ را باز کنید، ورکاسپیس بسازید و ببینید وقتی محصول نشت بستر را متوقف میکند، انضباط گزارشدهی چقدر سریع بهتر میشود.",
|
||||
},
|
||||
|
||||
ordering: {
|
||||
createdAtDesc: "جدیدترین",
|
||||
createdAt: "قدیمیترین",
|
||||
updatedAtDesc: "اخیراً بروزرسانی شده",
|
||||
@@ -288,11 +422,11 @@ export const fa = {
|
||||
title: "پروژهها",
|
||||
description: (workspaceName: string) => `مدیریت پروژهها برای ${workspaceName}`,
|
||||
active: "پروژههای فعال",
|
||||
archived: "پروژههای بایگانی شده",
|
||||
createNew: "ایجاد پروژه جدید",
|
||||
searchPlaceholder: "جستجوی پروژهها...",
|
||||
selectWorkspace: "لطفاً ابتدا یک ورکاسپیس انتخاب کنید.",
|
||||
titlePlaceholder: "عنوان پروژه",
|
||||
archived: "پروژههای بایگانی شده",
|
||||
createNew: "ایجاد پروژه جدید",
|
||||
searchPlaceholder: "جستجوی پروژهها...",
|
||||
selectWorkspace: "لطفاً ابتدا یک ورکاسپیس انتخاب کنید.",
|
||||
titlePlaceholder: "عنوان پروژه",
|
||||
descriptionPlaceholder: "توضیحات پروژه",
|
||||
titleLabel: "عنوان",
|
||||
descriptionLabel: "توضیحات",
|
||||
@@ -302,6 +436,7 @@ export const fa = {
|
||||
client: "مشتری",
|
||||
noClient: "بدون مشتری",
|
||||
emptyState: "پروژهای یافت نشد",
|
||||
noProjectsSearch: "لطفاً عبارت جستجو را تغییر دهید.",
|
||||
deleteTitle: "حذف پروژه",
|
||||
deleteWarning: "برای تایید حذف، لطفاً نام پروژه را تایپ کنید:",
|
||||
deleteSuccess: "پروژه با موفقیت حذف شد",
|
||||
@@ -309,15 +444,15 @@ export const fa = {
|
||||
create: "ایجاد",
|
||||
cancel: "انصراف",
|
||||
createProject: "ایجاد پروژه",
|
||||
editProject: "ویرایش پروژه",
|
||||
restore: "بازیابی",
|
||||
archive: "بایگانی",
|
||||
archiveSuccess: "پروژه با موفقیت بایگانی شد.",
|
||||
restoreSuccess: "پروژه با موفقیت بازیابی شد.",
|
||||
fetchError: "خطا در دریافت پروژهها.",
|
||||
clientFetchError: "خطا در دریافت لیست مشتریها.",
|
||||
filterClients: "فیلتر بر اساس مشتری",
|
||||
clearClientFilters: "پاک کردن فیلترها",
|
||||
editProject: "ویرایش پروژه",
|
||||
restore: "بازیابی",
|
||||
archive: "بایگانی",
|
||||
archiveSuccess: "پروژه با موفقیت بایگانی شد.",
|
||||
restoreSuccess: "پروژه با موفقیت بازیابی شد.",
|
||||
fetchError: "خطا در دریافت پروژهها.",
|
||||
clientFetchError: "خطا در دریافت لیست مشتریها.",
|
||||
filterClients: "فیلتر بر اساس مشتری",
|
||||
clearClientFilters: "پاک کردن فیلترها",
|
||||
memberAlreadyAdded: "این کاربر قبلا اضافه شده است",
|
||||
creator: "سازنده",
|
||||
addUser: "افزودن کاربر",
|
||||
@@ -359,6 +494,7 @@ export const fa = {
|
||||
namePlaceholder: "مثلاً طراحی",
|
||||
colorLabel: "رنگ",
|
||||
emptyState: "تگی یافت نشد",
|
||||
noTagsSearch: "لطفاً عبارت جستجو را تغییر دهید.",
|
||||
selectWorkspace: "لطفاً ابتدا یک ورکاسپیس انتخاب کنید.",
|
||||
fetchError: "دریافت تگها با خطا مواجه شد.",
|
||||
createSuccess: "تگ با موفقیت ایجاد شد.",
|
||||
@@ -405,6 +541,8 @@ export const fa = {
|
||||
orderingOldest: "قدیمیترین",
|
||||
emptyState: "ورودی زمانی یافت نشد",
|
||||
emptyDescription: "بدون توضیح",
|
||||
emptyStateDescription: "برای شروع، تایمر را اجرا کنید یا یک ورودی دستی اضافه کنید.",
|
||||
noEntriesSearch: "عبارت جستوجو یا فیلترهای خود را تغییر دهید.",
|
||||
createTitle: "افزودن ورودی زمان",
|
||||
startTitle: "شروع تایمر",
|
||||
editTitle: "ویرایش ورودی زمان",
|
||||
@@ -420,14 +558,14 @@ export const fa = {
|
||||
optionsError: "دریافت پروژهها و تگها با خطا مواجه شد.",
|
||||
descriptionLabel: "توضیحات",
|
||||
descriptionPlaceholder: "روی چه چیزی کار میکنید؟",
|
||||
projectLabel: "پروژه",
|
||||
noProject: "بدون پروژه",
|
||||
startLabel: "شروع",
|
||||
endLabel: "پایان",
|
||||
timeLabel: "زمان",
|
||||
billable: "قابل صورتحساب",
|
||||
noTagsHint: "ابتدا از صفحه تگها، تگ ایجاد کنید.",
|
||||
clearFilters: "پاک کردن فیلترها",
|
||||
projectLabel: "پروژه",
|
||||
noProject: "بدون پروژه",
|
||||
startLabel: "شروع",
|
||||
endLabel: "پایان",
|
||||
timeLabel: "زمان",
|
||||
billable: "قابل صورتحساب",
|
||||
noTagsHint: "ابتدا از صفحه تگها، تگ ایجاد کنید.",
|
||||
clearFilters: "پاک کردن فیلترها",
|
||||
customFromLabel: "از تاریخ",
|
||||
customToLabel: "تا تاریخ",
|
||||
allClientsLabel: "همه مشتریها",
|
||||
@@ -437,22 +575,22 @@ export const fa = {
|
||||
hideFiltersLabel: "مخفی کردن فیلترها",
|
||||
applyFiltersLabel: "اعمال",
|
||||
clientFilterPrefix: "مشتری",
|
||||
projectFilterPrefix: "پروژه",
|
||||
tagFilterPrefix: "تگ",
|
||||
fromFilterPrefix: "از",
|
||||
toFilterPrefix: "تا",
|
||||
deleteTitle: "حذف ورودی زمان",
|
||||
deleteConfirmMessage: "آیا از حذف این ورودی زمان اطمینان دارید؟",
|
||||
restartConfirmMessage: "میخواهید یک تایمر جدید را از روی این ورودی شروع کنید؟",
|
||||
discardConfirmMessage: "آیا از دور انداختن این تایمر در حال اجرا اطمینان دارید؟",
|
||||
searchTagsLabel: "جستوجوی تگها...",
|
||||
noTagsFoundLabel: "تگی پیدا نشد.",
|
||||
searchProjectsLabel: "جستوجوی پروژهها...",
|
||||
noProjectsFoundLabel: "پروژهای پیدا نشد.",
|
||||
deletedProjectLabel: "پروژه حذفشده",
|
||||
deletedTagLabel: "تگ حذفشده",
|
||||
},
|
||||
reports: {
|
||||
projectFilterPrefix: "پروژه",
|
||||
tagFilterPrefix: "تگ",
|
||||
fromFilterPrefix: "از",
|
||||
toFilterPrefix: "تا",
|
||||
deleteTitle: "حذف ورودی زمان",
|
||||
deleteConfirmMessage: "آیا از حذف این ورودی زمان اطمینان دارید؟",
|
||||
restartConfirmMessage: "میخواهید یک تایمر جدید را از روی این ورودی شروع کنید؟",
|
||||
discardConfirmMessage: "آیا از دور انداختن این تایمر در حال اجرا اطمینان دارید؟",
|
||||
searchTagsLabel: "جستوجوی تگها...",
|
||||
noTagsFoundLabel: "تگی پیدا نشد.",
|
||||
searchProjectsLabel: "جستوجوی پروژهها...",
|
||||
noProjectsFoundLabel: "پروژهای پیدا نشد.",
|
||||
deletedProjectLabel: "پروژه حذفشده",
|
||||
deletedTagLabel: "تگ حذفشده",
|
||||
},
|
||||
reports: {
|
||||
title: "گزارشها",
|
||||
description: (workspaceName: string) => `مرور گزارش فعالیت برای ${workspaceName}`,
|
||||
selectWorkspace: "لطفاً ابتدا یک ورکاسپیس انتخاب کنید.",
|
||||
@@ -482,11 +620,11 @@ export const fa = {
|
||||
name: "نام",
|
||||
clear: "پاک کردن",
|
||||
apply: "اعمال",
|
||||
totalHours: "مجموع ساعت",
|
||||
billableHours: "ساعات کاری",
|
||||
nonBillableHours: "ساعات غیر کاری",
|
||||
hourlyRate: "نرخ ساعتی",
|
||||
totalIncome: "مجموع درآمد",
|
||||
totalHours: "مجموع ساعت",
|
||||
billableHours: "ساعات کاری",
|
||||
nonBillableHours: "ساعات غیر کاری",
|
||||
hourlyRate: "نرخ ساعتی",
|
||||
totalIncome: "مجموع درآمد",
|
||||
chartTitle: "نمودار فعالیت",
|
||||
totalSeconds: "مجموع ثانیه",
|
||||
exportExcel: "خروجی Excel",
|
||||
@@ -500,118 +638,118 @@ export const fa = {
|
||||
loadError: "دریافت گزارشها با خطا مواجه شد.",
|
||||
loadDayDetailsError: "دریافت جزئیات روز با خطا مواجه شد.",
|
||||
loadFiltersError: "دریافت فیلترهای گزارش با خطا مواجه شد.",
|
||||
exportQueued: "درخواست خروجی ثبت شد. پیوند دانلود از طریق اعلان ارسال میشود.",
|
||||
exportError: "ثبت درخواست خروجی با خطا مواجه شد.",
|
||||
},
|
||||
logs: {
|
||||
eyebrow: "فعالیتهای ورکاسپیس",
|
||||
title: "لاگهای فعالیت",
|
||||
description: (workspaceName: string) => `مرور رویدادهای ثبتشده در ${workspaceName}`,
|
||||
selectWorkspace: "لطفاً ابتدا یک ورکاسپیس انتخاب کنید.",
|
||||
unauthorized: "فقط مالک و ادمین میتوانند لاگهای فعالیت ورکاسپیس را مشاهده کنند.",
|
||||
loading: "در حال بارگذاری لاگها...",
|
||||
loadingUsers: "در حال بارگذاری کاربران...",
|
||||
loadingDetails: "در حال بارگذاری جزئیات...",
|
||||
loadError: "دریافت لاگها با خطا مواجه شد.",
|
||||
loadDetailsError: "دریافت جزئیات لاگ با خطا مواجه شد.",
|
||||
loadFiltersError: "دریافت فیلترهای لاگ با خطا مواجه شد.",
|
||||
search: "جستوجو",
|
||||
searchPlaceholder: "جستوجوی لاگها...",
|
||||
section: "بخش",
|
||||
allSections: "همه بخشها",
|
||||
event: "رویداد",
|
||||
allEvents: "همه رویدادها",
|
||||
actor: "انجامدهنده",
|
||||
allActors: "همه کاربران",
|
||||
searchActors: "جستوجوی کاربران...",
|
||||
ordering: "مرتبسازی",
|
||||
newestFirst: "جدیدترین",
|
||||
oldestFirst: "قدیمیترین",
|
||||
fromDate: "از تاریخ",
|
||||
toDate: "تا تاریخ",
|
||||
clear: "پاک کردن",
|
||||
apply: "اعمال",
|
||||
loadMore: "بارگذاری بیشتر",
|
||||
totalLogs: "کل لاگها",
|
||||
activeFilters: "فیلترهای فعال",
|
||||
latestActivity: "آخرین فعالیت",
|
||||
resultsCount: (count: number) => `${count} نتیجه`,
|
||||
empty: "لاگ فعالیتی پیدا نشد",
|
||||
emptyHint: "فیلترها را تغییر دهید یا منتظر فعالیت جدید بمانید.",
|
||||
detailsTitle: "جزئیات فعالیت",
|
||||
detailsHint: "برای بررسی دقیق تغییرات، یک مورد را انتخاب کنید.",
|
||||
selectLogHint: "یک لاگ را برای مشاهده جزئیات انتخاب کنید.",
|
||||
target: "هدف",
|
||||
timestamp: "زمان",
|
||||
remoteAddress: "آدرس شبکه",
|
||||
previousValue: "مقدار قبلی",
|
||||
currentValue: "مقدار جدید",
|
||||
changesTitle: "تغییرات",
|
||||
noDetails: "برای این رویداد جزئیات فیلدی در دسترس نیست.",
|
||||
snapshot: "نمونه ذخیرهشده",
|
||||
unknownActor: "کاربر نامشخص",
|
||||
summary: (actor: string, event: string, section: string, target: string) =>
|
||||
`${actor} ${target} را در بخش ${section} ${event}`,
|
||||
sections: {
|
||||
workspace: "ورکاسپیس",
|
||||
workspace_members: "اعضای ورکاسپیس",
|
||||
clients: "مشتریها",
|
||||
projects: "پروژهها",
|
||||
tags: "تگها",
|
||||
time_entries: "ورودیهای زمان",
|
||||
rates: "نرخها",
|
||||
report_exports: "خروجیهای گزارش",
|
||||
},
|
||||
events: {
|
||||
create: "ایجاد کرد",
|
||||
update: "ویرایش کرد",
|
||||
delete: "حذف کرد",
|
||||
restore: "بازیابی کرد",
|
||||
archive: "بایگانی کرد",
|
||||
unarchive: "از بایگانی خارج کرد",
|
||||
activate: "فعال کرد",
|
||||
deactivate: "غیرفعال کرد",
|
||||
},
|
||||
},
|
||||
notifications: {
|
||||
title: "اعلانها",
|
||||
pageDescription: "مرور همه اعلانها و وضعیت خروجیهای گزارش.",
|
||||
open: "باز کردن اعلانها",
|
||||
empty: "هنوز اعلانی وجود ندارد.",
|
||||
emptyUnread: "اعلان خواندهنشدهای وجود ندارد.",
|
||||
loading: "در حال بارگذاری اعلانها...",
|
||||
loadingMore: "در حال بارگذاری بیشتر...",
|
||||
loadMore: "بارگذاری بیشتر",
|
||||
markAllRead: "خواندن همه",
|
||||
viewAll: "نمایش همه اعلانها",
|
||||
totalLabel: "مجموع اعلانها",
|
||||
unreadLabel: "اعلانهای خواندهنشده",
|
||||
deleteLabel: "حذف اعلان",
|
||||
markSeenError: "بهروزرسانی اعلان با خطا مواجه شد.",
|
||||
markAllError: "بهروزرسانی اعلانها با خطا مواجه شد.",
|
||||
deleteError: "حذف اعلان با خطا مواجه شد.",
|
||||
loadError: "دریافت اعلانها با خطا مواجه شد.",
|
||||
openError: "باز کردن اعلان با خطا مواجه شد.",
|
||||
newTitle: "اعلان جدید",
|
||||
openAction: "باز کردن",
|
||||
summary: (total: number, unread: number) => `${total} کل، ${unread} خواندهنشده`,
|
||||
workspaceMembershipAddedTitle: "به ورکاسپیس اضافه شدید",
|
||||
workspaceMembershipAddedMessage: (actor: string, workspace: string, role: string) =>
|
||||
`${actor} شما را با نقش ${role} به ${workspace} اضافه کرد.`,
|
||||
workspaceMembershipRoleChangedTitle: "نقش شما در ورکاسپیس تغییر کرد",
|
||||
workspaceMembershipRoleChangedMessage: (actor: string, workspace: string, previousRole: string, newRole: string) =>
|
||||
`${actor} نقش شما را در ${workspace} از ${previousRole} به ${newRole} تغییر داد.`,
|
||||
workspaceMembershipDeactivatedTitle: "دسترسی ورکاسپیس غیرفعال شد",
|
||||
workspaceMembershipDeactivatedMessage: (actor: string, workspace: string) =>
|
||||
`${actor} دسترسی شما به ${workspace} را غیرفعال کرد.`,
|
||||
workspaceMembershipRemovedTitle: "از ورکاسپیس حذف شدید",
|
||||
workspaceMembershipRemovedMessage: (actor: string, workspace: string) =>
|
||||
`${actor} شما را از ${workspace} حذف کرد.`,
|
||||
reportExportReadyTitle: "خروجی گزارش آماده است",
|
||||
reportExportReadyMessage: (exportType: string, workspace: string, fileName?: string | null) =>
|
||||
`خروجی ${exportType.toUpperCase()} گزارش ${workspace}${fileName ? ` با نام ${fileName}` : ""} آماده دانلود است.`,
|
||||
reportExportFailedTitle: "خروجی گزارش ناموفق بود",
|
||||
reportExportFailedMessage: (exportType: string, workspace: string) =>
|
||||
`تولید خروجی ${exportType.toUpperCase()} گزارش ${workspace} با خطا مواجه شد.`,
|
||||
},
|
||||
}
|
||||
exportQueued: "درخواست خروجی ثبت شد. پیوند دانلود از طریق اعلان ارسال میشود.",
|
||||
exportError: "ثبت درخواست خروجی با خطا مواجه شد.",
|
||||
},
|
||||
logs: {
|
||||
eyebrow: "فعالیتهای ورکاسپیس",
|
||||
title: "لاگهای فعالیت",
|
||||
description: (workspaceName: string) => `مرور رویدادهای ثبتشده در ${workspaceName}`,
|
||||
selectWorkspace: "لطفاً ابتدا یک ورکاسپیس انتخاب کنید.",
|
||||
unauthorized: "فقط مالک و ادمین میتوانند لاگهای فعالیت ورکاسپیس را مشاهده کنند.",
|
||||
loading: "در حال بارگذاری لاگها...",
|
||||
loadingUsers: "در حال بارگذاری کاربران...",
|
||||
loadingDetails: "در حال بارگذاری جزئیات...",
|
||||
loadError: "دریافت لاگها با خطا مواجه شد.",
|
||||
loadDetailsError: "دریافت جزئیات لاگ با خطا مواجه شد.",
|
||||
loadFiltersError: "دریافت فیلترهای لاگ با خطا مواجه شد.",
|
||||
search: "جستوجو",
|
||||
searchPlaceholder: "جستوجوی لاگها...",
|
||||
section: "بخش",
|
||||
allSections: "همه بخشها",
|
||||
event: "رویداد",
|
||||
allEvents: "همه رویدادها",
|
||||
actor: "انجامدهنده",
|
||||
allActors: "همه کاربران",
|
||||
searchActors: "جستوجوی کاربران...",
|
||||
ordering: "مرتبسازی",
|
||||
newestFirst: "جدیدترین",
|
||||
oldestFirst: "قدیمیترین",
|
||||
fromDate: "از تاریخ",
|
||||
toDate: "تا تاریخ",
|
||||
clear: "پاک کردن",
|
||||
apply: "اعمال",
|
||||
loadMore: "بارگذاری بیشتر",
|
||||
totalLogs: "کل لاگها",
|
||||
activeFilters: "فیلترهای فعال",
|
||||
latestActivity: "آخرین فعالیت",
|
||||
resultsCount: (count: number) => `${count} نتیجه`,
|
||||
empty: "لاگ فعالیتی پیدا نشد",
|
||||
emptyHint: "فیلترها را تغییر دهید یا منتظر فعالیت جدید بمانید.",
|
||||
detailsTitle: "جزئیات فعالیت",
|
||||
detailsHint: "برای بررسی دقیق تغییرات، یک مورد را انتخاب کنید.",
|
||||
selectLogHint: "یک لاگ را برای مشاهده جزئیات انتخاب کنید.",
|
||||
target: "هدف",
|
||||
timestamp: "زمان",
|
||||
remoteAddress: "آدرس شبکه",
|
||||
previousValue: "مقدار قبلی",
|
||||
currentValue: "مقدار جدید",
|
||||
changesTitle: "تغییرات",
|
||||
noDetails: "برای این رویداد جزئیات فیلدی در دسترس نیست.",
|
||||
snapshot: "نمونه ذخیرهشده",
|
||||
unknownActor: "کاربر نامشخص",
|
||||
summary: (actor: string, event: string, section: string, target: string) =>
|
||||
`${actor} ${target} را در بخش ${section} ${event}`,
|
||||
sections: {
|
||||
workspace: "ورکاسپیس",
|
||||
workspace_members: "اعضای ورکاسپیس",
|
||||
clients: "مشتریها",
|
||||
projects: "پروژهها",
|
||||
tags: "تگها",
|
||||
time_entries: "ورودیهای زمان",
|
||||
rates: "نرخها",
|
||||
report_exports: "خروجیهای گزارش",
|
||||
},
|
||||
events: {
|
||||
create: "ایجاد کرد",
|
||||
update: "ویرایش کرد",
|
||||
delete: "حذف کرد",
|
||||
restore: "بازیابی کرد",
|
||||
archive: "بایگانی کرد",
|
||||
unarchive: "از بایگانی خارج کرد",
|
||||
activate: "فعال کرد",
|
||||
deactivate: "غیرفعال کرد",
|
||||
},
|
||||
},
|
||||
notifications: {
|
||||
title: "اعلانها",
|
||||
pageDescription: "مرور همه اعلانها و وضعیت خروجیهای گزارش.",
|
||||
open: "باز کردن اعلانها",
|
||||
empty: "هنوز اعلانی وجود ندارد.",
|
||||
emptyUnread: "اعلان خواندهنشدهای وجود ندارد.",
|
||||
loading: "در حال بارگذاری اعلانها...",
|
||||
loadingMore: "در حال بارگذاری بیشتر...",
|
||||
loadMore: "بارگذاری بیشتر",
|
||||
markAllRead: "خواندن همه",
|
||||
viewAll: "نمایش همه اعلانها",
|
||||
totalLabel: "مجموع اعلانها",
|
||||
unreadLabel: "اعلانهای خواندهنشده",
|
||||
deleteLabel: "حذف اعلان",
|
||||
markSeenError: "بهروزرسانی اعلان با خطا مواجه شد.",
|
||||
markAllError: "بهروزرسانی اعلانها با خطا مواجه شد.",
|
||||
deleteError: "حذف اعلان با خطا مواجه شد.",
|
||||
loadError: "دریافت اعلانها با خطا مواجه شد.",
|
||||
openError: "باز کردن اعلان با خطا مواجه شد.",
|
||||
newTitle: "اعلان جدید",
|
||||
openAction: "باز کردن",
|
||||
summary: (total: number, unread: number) => `${total} کل، ${unread} خواندهنشده`,
|
||||
workspaceMembershipAddedTitle: "به ورکاسپیس اضافه شدید",
|
||||
workspaceMembershipAddedMessage: (actor: string, workspace: string, role: string) =>
|
||||
`${actor} شما را با نقش ${role} به ${workspace} اضافه کرد.`,
|
||||
workspaceMembershipRoleChangedTitle: "نقش شما در ورکاسپیس تغییر کرد",
|
||||
workspaceMembershipRoleChangedMessage: (actor: string, workspace: string, previousRole: string, newRole: string) =>
|
||||
`${actor} نقش شما را در ${workspace} از ${previousRole} به ${newRole} تغییر داد.`,
|
||||
workspaceMembershipDeactivatedTitle: "دسترسی ورکاسپیس غیرفعال شد",
|
||||
workspaceMembershipDeactivatedMessage: (actor: string, workspace: string) =>
|
||||
`${actor} دسترسی شما به ${workspace} را غیرفعال کرد.`,
|
||||
workspaceMembershipRemovedTitle: "از ورکاسپیس حذف شدید",
|
||||
workspaceMembershipRemovedMessage: (actor: string, workspace: string) =>
|
||||
`${actor} شما را از ${workspace} حذف کرد.`,
|
||||
reportExportReadyTitle: "خروجی گزارش آماده است",
|
||||
reportExportReadyMessage: (exportType: string, workspace: string, fileName?: string | null) =>
|
||||
`خروجی ${exportType.toUpperCase()} گزارش ${workspace}${fileName ? ` با نام ${fileName}` : ""} آماده دانلود است.`,
|
||||
reportExportFailedTitle: "خروجی گزارش ناموفق بود",
|
||||
reportExportFailedMessage: (exportType: string, workspace: string) =>
|
||||
`تولید خروجی ${exportType.toUpperCase()} گزارش ${workspace} با خطا مواجه شد.`,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -1,233 +1,429 @@
|
||||
import React, { useState } from "react"
|
||||
import { useNavigate, Link } from "react-router-dom"
|
||||
import { Button } from "../components/ui/button"
|
||||
import { Input } from "../components/ui/input"
|
||||
import { SettingsMenu } from "../components/SettingsMenu"
|
||||
import { ArrowLeft, ArrowRight, Command, Loader2, Eye, EyeOff } from "lucide-react"
|
||||
import React, { useEffect, useMemo, useState } from "react"
|
||||
import { useNavigate, Link } from "react-router-dom"
|
||||
import { Button } from "../components/ui/button"
|
||||
import { Input } from "../components/ui/input"
|
||||
import { SettingsMenu } from "../components/SettingsMenu"
|
||||
import { AlertTriangle, ArrowLeft, ArrowRight, Command, Eye, EyeOff, Loader2 } from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
import { useTranslation } from "../hooks/useTranslation"
|
||||
import { loginWithPassword, sendOtp, loginWithOtp } from "../api/users"
|
||||
import { loginWithOtp, loginWithPassword, sendOtp, startGoogleLogin } from "../api/users"
|
||||
import { ApiError } from "../api/client"
|
||||
import { setSessionTokens } from "../lib/session"
|
||||
|
||||
type AuthStep = "mobile" | "password" | "otp"
|
||||
type AuthMode = "login" | "register"
|
||||
|
||||
export default function Auth() {
|
||||
const navigate = useNavigate()
|
||||
const { t, lang } = useTranslation()
|
||||
const isRtl = lang === "fa"
|
||||
|
||||
const [step, setStep] = useState<AuthStep>("mobile")
|
||||
const [mode, setMode] = useState<AuthMode>("login")
|
||||
const [mobile, setMobile] = useState("")
|
||||
const [password, setPassword] = useState("")
|
||||
const [otpCode, setOtpCode] = useState("")
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [showPassword, setShowPassword] = useState(false) // Added state for password visibility
|
||||
|
||||
|
||||
type AuthStep = "mobile" | "password" | "otp"
|
||||
type AuthMode = "login" | "register"
|
||||
type CooldownKey = "otpSend" | "passwordLogin" | "otpLogin"
|
||||
|
||||
type Cooldowns = Record<CooldownKey, number>
|
||||
|
||||
const PERSIAN_DIGITS = ["۰", "۱", "۲", "۳", "۴", "۵", "۶", "۷", "۸", "۹"]
|
||||
|
||||
const toPersianDigits = (value: string) =>
|
||||
value.replace(/\d/g, (digit) => PERSIAN_DIGITS[Number.parseInt(digit, 10)] ?? digit)
|
||||
|
||||
const GoogleIcon = () => (
|
||||
<svg aria-hidden="true" className="h-5 w-5" viewBox="0 0 24 24">
|
||||
<path
|
||||
d="M21.805 10.023h-9.72v3.955h5.57c-.24 1.272-.96 2.35-2.042 3.07v2.548h3.3c1.933-1.78 3.042-4.4 3.042-7.506 0-.692-.062-1.357-.15-2.067Z"
|
||||
fill="#4285F4"
|
||||
/>
|
||||
<path
|
||||
d="M12.085 22c2.79 0 5.13-.925 6.84-2.504l-3.3-2.548c-.924.617-2.103.986-3.54.986-2.705 0-4.99-1.823-5.807-4.28H2.87v2.626A10.33 10.33 0 0 0 12.085 22Z"
|
||||
fill="#34A853"
|
||||
/>
|
||||
<path
|
||||
d="M6.278 13.654A6.214 6.214 0 0 1 5.95 11.7c0-.68.117-1.34.328-1.954V7.12H2.87A10.31 10.31 0 0 0 1.75 11.7c0 1.65.39 3.218 1.12 4.58l3.408-2.626Z"
|
||||
fill="#FBBC05"
|
||||
/>
|
||||
<path
|
||||
d="M12.085 5.466c1.52 0 2.882.522 3.955 1.55l2.966-2.966C17.21 2.387 14.874 1.4 12.085 1.4A10.33 10.33 0 0 0 2.87 7.12l3.408 2.626c.818-2.457 3.103-4.28 5.807-4.28Z"
|
||||
fill="#EA4335"
|
||||
/>
|
||||
</svg>
|
||||
)
|
||||
|
||||
export default function Auth() {
|
||||
const navigate = useNavigate()
|
||||
const { t, lang } = useTranslation()
|
||||
const isRtl = lang === "fa"
|
||||
|
||||
const [step, setStep] = useState<AuthStep>("mobile")
|
||||
const [mode, setMode] = useState<AuthMode>("login")
|
||||
const [mobile, setMobile] = useState("")
|
||||
const [password, setPassword] = useState("")
|
||||
const [otpCode, setOtpCode] = useState("")
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [showPassword, setShowPassword] = useState(false)
|
||||
const [cooldowns, setCooldowns] = useState<Cooldowns>({
|
||||
otpSend: 0,
|
||||
passwordLogin: 0,
|
||||
otpLogin: 0,
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
if (!Object.values(cooldowns).some((value) => value > 0)) {
|
||||
return
|
||||
}
|
||||
|
||||
const timer = window.setInterval(() => {
|
||||
setCooldowns((current) => ({
|
||||
otpSend: Math.max(0, current.otpSend - 1),
|
||||
passwordLogin: Math.max(0, current.passwordLogin - 1),
|
||||
otpLogin: Math.max(0, current.otpLogin - 1),
|
||||
}))
|
||||
}, 1000)
|
||||
|
||||
return () => window.clearInterval(timer)
|
||||
}, [cooldowns])
|
||||
|
||||
const localizeDigits = (value: string) => (isRtl ? toPersianDigits(value) : value)
|
||||
|
||||
const formatCooldown = (seconds: number) => {
|
||||
const minutes = Math.floor(seconds / 60)
|
||||
const remainingSeconds = seconds % 60
|
||||
const base = minutes > 0
|
||||
? `${minutes}:${remainingSeconds.toString().padStart(2, "0")}`
|
||||
: `${remainingSeconds}s`
|
||||
|
||||
return localizeDigits(base)
|
||||
}
|
||||
|
||||
const setCooldown = (key: CooldownKey, seconds: number) => {
|
||||
setCooldowns((current) => ({
|
||||
...current,
|
||||
[key]: Math.max(current[key], seconds),
|
||||
}))
|
||||
}
|
||||
|
||||
const handleTokenResponse = (access: string, refresh: string) => {
|
||||
setSessionTokens(access, refresh)
|
||||
toast.success(t.login.toasts.successLogin)
|
||||
navigate("/profile")
|
||||
}
|
||||
|
||||
const handleSendOtp = async (selectedMode: AuthMode) => {
|
||||
if (!mobile) return toast.error(t.login.toasts.enterMobile)
|
||||
setLoading(true)
|
||||
|
||||
try {
|
||||
await sendOtp(mobile, selectedMode)
|
||||
setMode(selectedMode)
|
||||
setStep("otp")
|
||||
toast.success(t.login.toasts.verifySent)
|
||||
} catch (err: any) {
|
||||
toast.error(t.login.toasts.failedOtp)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handlePasswordLogin = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
if (!mobile || !password) return toast.error(t.login.toasts.fillAll)
|
||||
setLoading(true)
|
||||
|
||||
try {
|
||||
const data = await loginWithPassword(mobile, password)
|
||||
handleTokenResponse(data.access, data.refresh)
|
||||
} catch (err: any) {
|
||||
toast.error(t.login.toasts.invalidCreds)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleOtpVerify = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
if (!mobile || !otpCode) return toast.error(t.login.toasts.enterOtp)
|
||||
setLoading(true)
|
||||
|
||||
try {
|
||||
const data = await loginWithOtp(mobile, otpCode)
|
||||
handleTokenResponse(data.access, data.refresh)
|
||||
} catch (err: any) {
|
||||
toast.error(t.login.toasts.invalidOtp)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const BackIcon = isRtl ? ArrowRight : ArrowLeft
|
||||
|
||||
return (
|
||||
<div className="container relative min-h-screen flex-col items-center justify-center grid lg:max-w-none lg:grid-cols-2 lg:px-0 bg-white dark:bg-slate-950 transition-colors">
|
||||
|
||||
<div className="absolute inset-e-4 top-4 z-50 md:inset-e-8 md:top-8">
|
||||
<SettingsMenu />
|
||||
</div>
|
||||
|
||||
<div className="relative hidden h-full flex-col bg-slate-900 dark:bg-slate-900/50 p-10 text-white lg:flex border-e border-slate-200 dark:border-slate-800">
|
||||
<div className="relative z-20 flex items-center text-lg font-medium gap-2">
|
||||
<Command className="h-6 w-6" />
|
||||
{t.title || "Qlockify"}
|
||||
</div>
|
||||
<div className="relative z-20 mt-auto">
|
||||
<blockquote className="space-y-2">
|
||||
<p className="text-lg">"{t.login.brandingQuote}"</p>
|
||||
</blockquote>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="p-8 lg:p-8 flex h-screen items-center justify-center">
|
||||
<div className="mx-auto flex w-full flex-col justify-center space-y-6 sm:w-87.5">
|
||||
|
||||
<div className="flex flex-col space-y-2 text-center text-slate-900 dark:text-slate-50">
|
||||
<div className="flex justify-center lg:hidden mb-4">
|
||||
<Command className="h-8 w-8" />
|
||||
</div>
|
||||
<h1 className="text-2xl font-semibold tracking-tight">
|
||||
{step === "mobile" && t.login.welcome(t.title)}
|
||||
{step === "password" && t.login.enterPassword}
|
||||
{step === "otp" && t.login.verifyNumber}
|
||||
</h1>
|
||||
<p className="text-sm text-slate-500 dark:text-slate-400">
|
||||
{step === "mobile" && t.login.enterMobileDesc}
|
||||
{step === "password" && t.login.signInDesc}
|
||||
{step === "otp" && t.login.sentCodeDesc(mobile)}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-6">
|
||||
{step === "mobile" && (
|
||||
<div className="grid gap-4">
|
||||
<Input
|
||||
id="mobile"
|
||||
placeholder={t.login.mobilePlaceholder}
|
||||
type="tel"
|
||||
dir="ltr"
|
||||
value={mobile}
|
||||
onChange={(e) => setMobile(e.target.value)}
|
||||
maxLength={11}
|
||||
disabled={loading}
|
||||
className={`h-11 ${isRtl ? "text-end" : "text-start"}`}
|
||||
/>
|
||||
<Button onClick={() => { if (!mobile) return toast.error(t.login.toasts.enterMobile); setStep("password") }} className="w-full h-11">
|
||||
{t.login.continueWithPassword}
|
||||
</Button>
|
||||
|
||||
<div className="relative">
|
||||
<div className="absolute inset-0 flex items-center">
|
||||
<span className="w-full border-t border-slate-200 dark:border-slate-800" />
|
||||
</div>
|
||||
<div className="relative flex justify-center text-xs uppercase">
|
||||
<span className="bg-white dark:bg-slate-950 px-2 text-slate-500 dark:text-slate-400 transition-colors">
|
||||
{t.login.orContinueWith}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<Button variant="outline" onClick={() => handleSendOtp("login")} disabled={loading} className="h-11">
|
||||
{loading && mode === "login" && <Loader2 className="me-2 h-4 w-4 animate-spin" />}
|
||||
{t.login.otpLogin}
|
||||
</Button>
|
||||
<Button variant="outline" onClick={() => handleSendOtp("register")} disabled={loading} className="h-11">
|
||||
{loading && mode === "register" && <Loader2 className="me-2 h-4 w-4 animate-spin" />}
|
||||
{t.login.register}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{step === "password" && (
|
||||
<form onSubmit={handlePasswordLogin} autoComplete="off" className="grid gap-4">
|
||||
<div className="relative w-full" dir="ltr">
|
||||
<Input
|
||||
id="password"
|
||||
placeholder={t.login.passwordPlaceholder}
|
||||
type={showPassword ? "text" : "password"}
|
||||
autoComplete="new-password"
|
||||
dir="ltr"
|
||||
name="some-random-name-to-disable-auto-complete-on-browser"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
disabled={loading}
|
||||
className={`h-11 pr-10 ${isRtl ? "text-end" : "text-start"}`}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
tabIndex={-1}
|
||||
onClick={() => setShowPassword((prev) => !prev)}
|
||||
className="absolute inset-y-0 right-0 flex items-center pr-3 text-slate-500 hover:text-slate-700 dark:text-slate-400 dark:hover:text-slate-300"
|
||||
>
|
||||
{showPassword ? <EyeOff size={18} /> : <Eye size={18} />}
|
||||
</button>
|
||||
</div>
|
||||
<Button type="submit" className="w-full h-11" disabled={loading}>
|
||||
{loading && <Loader2 className="me-2 h-4 w-4 animate-spin" />} {t.login.signIn}
|
||||
</Button>
|
||||
<Button type="button" variant="ghost" onClick={() => setStep("mobile")} className="text-sm text-slate-500 dark:text-slate-400">
|
||||
<BackIcon className="me-2 h-4 w-4" /> {t.login.back}
|
||||
</Button>
|
||||
</form>
|
||||
)}
|
||||
|
||||
{step === "otp" && (
|
||||
<form onSubmit={handleOtpVerify} className="grid gap-4">
|
||||
<Input
|
||||
id="otp"
|
||||
placeholder={t.login.otpPlaceholder}
|
||||
type="text"
|
||||
dir="ltr"
|
||||
value={otpCode}
|
||||
onChange={(e) => setOtpCode(e.target.value)}
|
||||
maxLength={6}
|
||||
disabled={loading}
|
||||
className="h-11 text-center tracking-widest text-lg"
|
||||
/>
|
||||
<Button type="submit" className="w-full h-11" disabled={loading}>
|
||||
{loading && <Loader2 className="me-2 h-4 w-4 animate-spin" />} {t.login.verifyAndContinue}
|
||||
</Button>
|
||||
<Button type="button" variant="ghost" onClick={() => setStep("mobile")} className="text-sm text-slate-500 dark:text-slate-400">
|
||||
<BackIcon className="me-2 h-4 w-4" /> {t.login.back}
|
||||
</Button>
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="mt-6 text-center text-sm text-slate-500 dark:text-slate-400">
|
||||
{t.loginTerms?.prefix}
|
||||
<Link
|
||||
to="/terms"
|
||||
className="font-medium text-blue-600 hover:text-blue-500 dark:text-blue-400 dark:hover:text-blue-300 transition-colors"
|
||||
>
|
||||
{t.loginTerms?.link}
|
||||
</Link>
|
||||
{t.loginTerms?.suffix}
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const handleThrottleError = (error: unknown, key: CooldownKey) => {
|
||||
if (!(error instanceof ApiError) || error.code !== "throttled") {
|
||||
return false
|
||||
}
|
||||
|
||||
const seconds = Math.max(1, error.retryAfterSeconds ?? 0)
|
||||
const formattedTime = formatCooldown(seconds)
|
||||
|
||||
setCooldown(key, seconds)
|
||||
|
||||
const throttleCopy = t.login.throttle
|
||||
const message =
|
||||
key === "otpSend"
|
||||
? throttleCopy.otpSendMessage(formattedTime)
|
||||
: key === "passwordLogin"
|
||||
? throttleCopy.passwordLoginMessage(formattedTime)
|
||||
: throttleCopy.otpLoginMessage(formattedTime)
|
||||
|
||||
toast.error(message, {
|
||||
description: throttleCopy.countdownLabel(formattedTime),
|
||||
})
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
const handleSendOtp = async (selectedMode: AuthMode) => {
|
||||
if (!mobile) {
|
||||
toast.error(t.login.toasts.enterMobile)
|
||||
return
|
||||
}
|
||||
|
||||
setLoading(true)
|
||||
|
||||
try {
|
||||
await sendOtp(mobile, selectedMode)
|
||||
setCooldowns((current) => ({ ...current, otpSend: 0 }))
|
||||
setMode(selectedMode)
|
||||
setStep("otp")
|
||||
toast.success(t.login.toasts.verifySent)
|
||||
} catch (error) {
|
||||
if (!handleThrottleError(error, "otpSend")) {
|
||||
toast.error(error instanceof Error ? error.message : t.login.toasts.failedOtp)
|
||||
}
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handlePasswordLogin = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
if (!mobile || !password) {
|
||||
toast.error(t.login.toasts.fillAll)
|
||||
return
|
||||
}
|
||||
|
||||
setLoading(true)
|
||||
|
||||
try {
|
||||
const data = await loginWithPassword(mobile, password)
|
||||
setCooldowns((current) => ({ ...current, passwordLogin: 0 }))
|
||||
handleTokenResponse(data.access, data.refresh)
|
||||
} catch (error) {
|
||||
if (!handleThrottleError(error, "passwordLogin")) {
|
||||
toast.error(error instanceof Error ? error.message : t.login.toasts.invalidCreds)
|
||||
}
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleOtpVerify = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
if (!mobile || !otpCode) {
|
||||
toast.error(t.login.toasts.enterOtp)
|
||||
return
|
||||
}
|
||||
|
||||
setLoading(true)
|
||||
|
||||
try {
|
||||
const data = await loginWithOtp(mobile, otpCode)
|
||||
setCooldowns((current) => ({ ...current, otpLogin: 0 }))
|
||||
handleTokenResponse(data.access, data.refresh)
|
||||
} catch (error) {
|
||||
if (!handleThrottleError(error, "otpLogin")) {
|
||||
toast.error(error instanceof Error ? error.message : t.login.toasts.invalidOtp)
|
||||
}
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const activeCooldownMessage = useMemo(() => {
|
||||
const throttleCopy = t.login.throttle
|
||||
|
||||
if (step === "mobile" && cooldowns.otpSend > 0) {
|
||||
const formatted = formatCooldown(cooldowns.otpSend)
|
||||
return {
|
||||
title: throttleCopy.title,
|
||||
description: throttleCopy.otpSendMessage(formatted),
|
||||
}
|
||||
}
|
||||
|
||||
if (step === "password" && cooldowns.passwordLogin > 0) {
|
||||
const formatted = formatCooldown(cooldowns.passwordLogin)
|
||||
return {
|
||||
title: throttleCopy.title,
|
||||
description: throttleCopy.passwordLoginMessage(formatted),
|
||||
}
|
||||
}
|
||||
|
||||
if (step === "otp" && cooldowns.otpLogin > 0) {
|
||||
const formatted = formatCooldown(cooldowns.otpLogin)
|
||||
return {
|
||||
title: throttleCopy.title,
|
||||
description: throttleCopy.otpLoginMessage(formatted),
|
||||
}
|
||||
}
|
||||
|
||||
return null
|
||||
}, [cooldowns, formatCooldown, step, t.login.throttle])
|
||||
|
||||
const otpCooldownLabel =
|
||||
cooldowns.otpSend > 0 ? t.login.throttle.countdownLabel(formatCooldown(cooldowns.otpSend)) : null
|
||||
const passwordCooldownLabel =
|
||||
cooldowns.passwordLogin > 0
|
||||
? t.login.throttle.countdownLabel(formatCooldown(cooldowns.passwordLogin))
|
||||
: null
|
||||
const otpLoginCooldownLabel =
|
||||
cooldowns.otpLogin > 0 ? t.login.throttle.countdownLabel(formatCooldown(cooldowns.otpLogin)) : null
|
||||
|
||||
const BackIcon = isRtl ? ArrowRight : ArrowLeft
|
||||
|
||||
return (
|
||||
<div className="container relative min-h-screen flex-col items-center justify-center grid lg:max-w-none lg:grid-cols-2 lg:px-0 bg-white dark:bg-slate-950 transition-colors">
|
||||
<div className="absolute inset-e-4 top-4 z-50 md:inset-e-8 md:top-8">
|
||||
<SettingsMenu />
|
||||
</div>
|
||||
|
||||
<div className="relative hidden h-full flex-col bg-slate-900 dark:bg-slate-900/50 p-10 text-white lg:flex border-e border-slate-200 dark:border-slate-800">
|
||||
<div className="relative z-20 flex items-center text-lg font-medium gap-2">
|
||||
<Command className="h-6 w-6" />
|
||||
{t.title || "Qlockify"}
|
||||
</div>
|
||||
<div className="relative z-20 mt-auto">
|
||||
<blockquote className="space-y-2">
|
||||
<p className="text-lg">"{t.login.brandingQuote}"</p>
|
||||
</blockquote>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="p-8 lg:p-8 flex h-screen items-center justify-center">
|
||||
<div className="mx-auto flex w-full flex-col justify-center space-y-6 sm:w-87.5">
|
||||
<div className="flex flex-col space-y-2 text-center text-slate-900 dark:text-slate-50">
|
||||
<div className="flex justify-center lg:hidden mb-4">
|
||||
<Command className="h-8 w-8" />
|
||||
</div>
|
||||
<h1 className="text-2xl font-semibold tracking-tight">
|
||||
{step === "mobile" && t.login.welcome(t.title)}
|
||||
{step === "password" && t.login.enterPassword}
|
||||
{step === "otp" && t.login.verifyNumber}
|
||||
</h1>
|
||||
<p className="text-sm text-slate-500 dark:text-slate-400">
|
||||
{step === "mobile" && t.login.enterMobileDesc}
|
||||
{step === "password" && t.login.signInDesc}
|
||||
{step === "otp" && t.login.sentCodeDesc(mobile)}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{activeCooldownMessage && (
|
||||
<div className="rounded-2xl border border-amber-200 bg-amber-50 px-4 py-3 text-start text-amber-900 shadow-sm dark:border-amber-900/50 dark:bg-amber-950/40 dark:text-amber-100">
|
||||
<div className="flex items-start gap-3">
|
||||
<AlertTriangle className="mt-0.5 h-4 w-4 shrink-0" />
|
||||
<div className="space-y-1">
|
||||
<p className="text-sm font-medium">{activeCooldownMessage.title}</p>
|
||||
<p className="text-sm">{activeCooldownMessage.description}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="grid gap-6">
|
||||
{step === "mobile" && (
|
||||
<div className="grid gap-4">
|
||||
<Input
|
||||
id="mobile"
|
||||
placeholder={t.login.mobilePlaceholder}
|
||||
type="tel"
|
||||
dir="ltr"
|
||||
value={mobile}
|
||||
onChange={(e) => setMobile(e.target.value)}
|
||||
maxLength={11}
|
||||
disabled={loading}
|
||||
className={`h-11 ${isRtl ? "text-end" : "text-start"}`}
|
||||
/>
|
||||
<Button
|
||||
onClick={() => {
|
||||
if (!mobile) {
|
||||
toast.error(t.login.toasts.enterMobile)
|
||||
return
|
||||
}
|
||||
setStep("password")
|
||||
}}
|
||||
className="w-full h-11"
|
||||
>
|
||||
{t.login.continueWithPassword}
|
||||
</Button>
|
||||
|
||||
<div className="relative">
|
||||
<div className="absolute inset-0 flex items-center">
|
||||
<span className="w-full border-t border-slate-200 dark:border-slate-800" />
|
||||
</div>
|
||||
<div className="relative flex justify-center text-xs uppercase">
|
||||
<span className="bg-white dark:bg-slate-950 px-2 text-slate-500 dark:text-slate-400 transition-colors">
|
||||
{t.login.orContinueWith}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={startGoogleLogin}
|
||||
disabled={loading}
|
||||
className="h-11 w-full"
|
||||
>
|
||||
<GoogleIcon />
|
||||
<span className="ms-3">{t.login.continueWithGoogle}</span>
|
||||
</Button>
|
||||
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => handleSendOtp("login")}
|
||||
disabled={loading || cooldowns.otpSend > 0}
|
||||
className="h-11"
|
||||
>
|
||||
{loading && mode === "login" && <Loader2 className="me-2 h-4 w-4 animate-spin" />}
|
||||
{cooldowns.otpSend > 0 ? otpCooldownLabel : t.login.otpLogin}
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => handleSendOtp("register")}
|
||||
disabled={loading || cooldowns.otpSend > 0}
|
||||
className="h-11"
|
||||
>
|
||||
{loading && mode === "register" && <Loader2 className="me-2 h-4 w-4 animate-spin" />}
|
||||
{cooldowns.otpSend > 0 ? otpCooldownLabel : t.login.register}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{step === "password" && (
|
||||
<form onSubmit={handlePasswordLogin} autoComplete="off" className="grid gap-4">
|
||||
<div className="relative w-full" dir="ltr">
|
||||
<Input
|
||||
id="password"
|
||||
placeholder={t.login.passwordPlaceholder}
|
||||
type={showPassword ? "text" : "password"}
|
||||
autoComplete="new-password"
|
||||
dir="ltr"
|
||||
name="some-random-name-to-disable-auto-complete-on-browser"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
disabled={loading}
|
||||
className={`h-11 pr-10 ${isRtl ? "text-end" : "text-start"}`}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
tabIndex={-1}
|
||||
onClick={() => setShowPassword((prev) => !prev)}
|
||||
className="absolute inset-y-0 right-0 flex cursor-pointer items-center pr-3 text-slate-500 hover:text-slate-700 dark:text-slate-400 dark:hover:text-slate-300"
|
||||
>
|
||||
{showPassword ? <EyeOff size={18} /> : <Eye size={18} />}
|
||||
</button>
|
||||
</div>
|
||||
<Button type="submit" className="w-full h-11" disabled={loading || cooldowns.passwordLogin > 0}>
|
||||
{loading && <Loader2 className="me-2 h-4 w-4 animate-spin" />}
|
||||
{passwordCooldownLabel || t.login.signIn}
|
||||
</Button>
|
||||
<Button type="button" variant="ghost" onClick={() => setStep("mobile")} className="text-sm text-slate-500 dark:text-slate-400">
|
||||
<BackIcon className="me-2 h-4 w-4" /> {t.login.back}
|
||||
</Button>
|
||||
</form>
|
||||
)}
|
||||
|
||||
{step === "otp" && (
|
||||
<form onSubmit={handleOtpVerify} className="grid gap-4">
|
||||
<Input
|
||||
id="otp"
|
||||
placeholder={t.login.otpPlaceholder}
|
||||
type="text"
|
||||
dir="ltr"
|
||||
value={otpCode}
|
||||
onChange={(e) => setOtpCode(e.target.value)}
|
||||
maxLength={6}
|
||||
disabled={loading}
|
||||
className="h-11 text-center tracking-widest text-lg"
|
||||
/>
|
||||
<Button type="submit" className="w-full h-11" disabled={loading || cooldowns.otpLogin > 0}>
|
||||
{loading && <Loader2 className="me-2 h-4 w-4 animate-spin" />}
|
||||
{otpLoginCooldownLabel || t.login.verifyAndContinue}
|
||||
</Button>
|
||||
<Button type="button" variant="ghost" onClick={() => setStep("mobile")} className="text-sm text-slate-500 dark:text-slate-400">
|
||||
<BackIcon className="me-2 h-4 w-4" /> {t.login.back}
|
||||
</Button>
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="mt-6 text-center text-sm text-slate-500 dark:text-slate-400">
|
||||
{t.loginTerms?.prefix}
|
||||
<Link
|
||||
to="/terms"
|
||||
className="font-medium text-blue-600 hover:text-blue-500 dark:text-blue-400 dark:hover:text-blue-300 transition-colors"
|
||||
>
|
||||
{t.loginTerms?.link}
|
||||
</Link>
|
||||
{t.loginTerms?.suffix}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useEffect, useState } from "react"
|
||||
import { useSearchParams } from "react-router-dom"
|
||||
import { Plus, Building2, Pencil, Trash2 } from "lucide-react"
|
||||
import { toast } from "sonner"
|
||||
import { useWorkspace } from "../context/WorkspaceContext"
|
||||
@@ -10,106 +11,114 @@ import {
|
||||
canDeleteWorkspaceResource,
|
||||
canWorkspace,
|
||||
} from "../lib/permissions"
|
||||
import { type Client } from "../types/client"
|
||||
import { getClients } from "../api/clients"
|
||||
import CreateClientModal from "../components/CreateClientModal"
|
||||
import EditClientModal from "../components/EditClientModal"
|
||||
import { type Client } from "../types/client"
|
||||
import { getClients } from "../api/clients"
|
||||
import CreateClientModal from "../components/CreateClientModal"
|
||||
import EditClientModal from "../components/EditClientModal"
|
||||
import DeleteClientModal from "../components/DeleteClientModal"
|
||||
import EmptyStateCard from "../components/EmptyStateCard"
|
||||
import FilterBar from "../components/FilterBar"
|
||||
import { ListPageSkeleton } from "../components/ListPageSkeleton"
|
||||
import { Button } from "../components/ui/button"
|
||||
import { Card, CardContent, CardTitle } from "../components/ui/card"
|
||||
import { Pagination } from "../components/Pagination"
|
||||
|
||||
import { readNumberParam, readStringParam, updateQueryParams } from "../lib/queryParams"
|
||||
|
||||
export default function Clients() {
|
||||
const { activeWorkspace } = useWorkspace()
|
||||
const { user } = useAppContext()
|
||||
const [clients, setClients] = useState<Client[]>([])
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
|
||||
// Pagination States
|
||||
const [currentPage, setCurrentPage] = useState(1)
|
||||
const [totalItems, setTotalItems] = useState(0)
|
||||
const [limit, setLimit] = useState(10)
|
||||
|
||||
// Filter States
|
||||
const [searchQuery, setSearchQuery] = useState("")
|
||||
const [debouncedSearch, setDebouncedSearch] = useState("")
|
||||
const [ordering, setOrdering] = useState("-created_at")
|
||||
|
||||
// Modal States
|
||||
const [isCreateModalOpen, setIsCreateModalOpen] = useState(false)
|
||||
const [editClient, setEditClient] = useState<Client | null>(null)
|
||||
const [deleteClient, setDeleteClient] = useState<Client | null>(null)
|
||||
|
||||
const { t, lang } = useTranslation()
|
||||
const isFa = lang === "fa"
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
const [searchParams, setSearchParams] = useSearchParams()
|
||||
const [totalItems, setTotalItems] = useState(0)
|
||||
const [debouncedSearch, setDebouncedSearch] = useState("")
|
||||
const searchQuery = readStringParam(searchParams, "search", "")
|
||||
const ordering = readStringParam(searchParams, "ordering", "-created_at")
|
||||
const currentPage = Math.max(1, readNumberParam(searchParams, "page", 1))
|
||||
const limit = Math.max(1, readNumberParam(searchParams, "limit", 10))
|
||||
|
||||
// Modal States
|
||||
const [isCreateModalOpen, setIsCreateModalOpen] = useState(false)
|
||||
const [editClient, setEditClient] = useState<Client | null>(null)
|
||||
const [deleteClient, setDeleteClient] = useState<Client | null>(null)
|
||||
|
||||
const { t, lang } = useTranslation()
|
||||
const isFa = lang === "fa"
|
||||
const workspaceRole = activeWorkspace?.my_role
|
||||
const canCreateClient = canWorkspace(workspaceRole, CLIENTS_CREATE)
|
||||
const canEditClient = canWorkspace(workspaceRole, CLIENTS_EDIT)
|
||||
|
||||
const orderingOptions = [
|
||||
{ value: "-created_at", label: t.ordering?.createdAtDesc || "Newest First" },
|
||||
{ value: "created_at", label: t.ordering?.createdAt || "Oldest First" },
|
||||
{ value: "name", label: t.ordering?.name || "Name (A-Z)" },
|
||||
{ value: "-name", label: t.ordering?.nameDesc || "Name (Z-A)" },
|
||||
{ value: "-updated_at", label: t.ordering?.updatedAtDesc || "Recently Updated" },
|
||||
]
|
||||
|
||||
useEffect(() => {
|
||||
setCurrentPage(1)
|
||||
}, [debouncedSearch, ordering])
|
||||
|
||||
// Debounce search input to avoid spamming the API
|
||||
useEffect(() => {
|
||||
const handler = setTimeout(() => {
|
||||
setDebouncedSearch(searchQuery)
|
||||
}, 500)
|
||||
return () => clearTimeout(handler)
|
||||
}, [searchQuery])
|
||||
|
||||
const fetchClientsList = async () => {
|
||||
if (!activeWorkspace?.id) {
|
||||
setIsLoading(false)
|
||||
return
|
||||
}
|
||||
|
||||
setIsLoading(true)
|
||||
try {
|
||||
const offset = (currentPage - 1) * limit
|
||||
const data: any = await getClients(activeWorkspace.id, debouncedSearch, ordering, limit, offset)
|
||||
|
||||
const items = data?.results || (Array.isArray(data) ? data : [])
|
||||
const count = data?.count !== undefined ? data.count : items.length
|
||||
|
||||
setClients(items)
|
||||
setTotalItems(count)
|
||||
|
||||
const orderingOptions = [
|
||||
{ value: "-created_at", label: t.ordering?.createdAtDesc || "Newest First" },
|
||||
{ value: "created_at", label: t.ordering?.createdAt || "Oldest First" },
|
||||
{ value: "name", label: t.ordering?.name || "Name (A-Z)" },
|
||||
{ value: "-name", label: t.ordering?.nameDesc || "Name (Z-A)" },
|
||||
{ value: "-updated_at", label: t.ordering?.updatedAtDesc || "Recently Updated" },
|
||||
]
|
||||
|
||||
// Debounce search input to avoid spamming the API
|
||||
useEffect(() => {
|
||||
const handler = setTimeout(() => {
|
||||
setDebouncedSearch(searchQuery)
|
||||
}, 500)
|
||||
return () => clearTimeout(handler)
|
||||
}, [searchQuery])
|
||||
|
||||
const fetchClientsList = async () => {
|
||||
if (!activeWorkspace?.id) {
|
||||
setIsLoading(false)
|
||||
return
|
||||
}
|
||||
|
||||
setIsLoading(true)
|
||||
try {
|
||||
const offset = (currentPage - 1) * limit
|
||||
const data: any = await getClients(activeWorkspace.id, debouncedSearch, ordering, limit, offset)
|
||||
|
||||
const items = data?.results || (Array.isArray(data) ? data : [])
|
||||
const count = data?.count !== undefined ? data.count : items.length
|
||||
|
||||
setClients(items)
|
||||
setTotalItems(count)
|
||||
} catch (error) {
|
||||
console.error(t.clients.errors.fetchFailed, error)
|
||||
toast.error(t.clients.errors.fetchFailed)
|
||||
setClients([])
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const formatDate = (dateStr: string | undefined) => {
|
||||
if (!dateStr) return "-"
|
||||
try {
|
||||
const date = new Date(dateStr)
|
||||
return new Intl.DateTimeFormat(isFa ? "fa-IR" : "en-US", {
|
||||
dateStyle: "long",
|
||||
timeZone: "Asia/Tehran"
|
||||
}).format(date)
|
||||
} catch (e) {
|
||||
return dateStr
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
fetchClientsList()
|
||||
}, [activeWorkspace?.id, debouncedSearch, ordering, currentPage, limit])
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
const formatDate = (dateStr: string | undefined) => {
|
||||
if (!dateStr) return "-"
|
||||
try {
|
||||
const date = new Date(dateStr)
|
||||
return new Intl.DateTimeFormat(isFa ? "fa-IR" : "en-US", {
|
||||
dateStyle: "long",
|
||||
timeZone: "Asia/Tehran"
|
||||
}).format(date)
|
||||
} catch (e) {
|
||||
return dateStr
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
fetchClientsList()
|
||||
}, [activeWorkspace?.id, debouncedSearch, ordering, currentPage, limit])
|
||||
|
||||
const updateListParams = (updates: Record<string, string | number | null | undefined>) => {
|
||||
setSearchParams(
|
||||
(current) =>
|
||||
updateQueryParams(current, updates, {
|
||||
search: "",
|
||||
ordering: "-created_at",
|
||||
page: 1,
|
||||
limit: 10,
|
||||
}),
|
||||
{ replace: true },
|
||||
)
|
||||
}
|
||||
|
||||
if (!activeWorkspace) {
|
||||
return (
|
||||
<div className="mx-auto max-w-7xl p-4 md:p-6">
|
||||
@@ -148,9 +157,9 @@ export default function Clients() {
|
||||
<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">
|
||||
<FilterBar
|
||||
searchQuery={searchQuery}
|
||||
setSearchQuery={setSearchQuery}
|
||||
setSearchQuery={(value) => updateListParams({ search: value, page: 1 })}
|
||||
ordering={ordering}
|
||||
setOrdering={setOrdering}
|
||||
setOrdering={(value) => updateListParams({ ordering: value, page: 1 })}
|
||||
orderingOptions={orderingOptions}
|
||||
searchPlaceholder={t.clients.searchPlaceholder}
|
||||
/>
|
||||
@@ -161,13 +170,11 @@ export default function Clients() {
|
||||
) : (
|
||||
<div className="flex flex-1 flex-col gap-6">
|
||||
{clients.length === 0 ? (
|
||||
<div className="flex flex-1 rounded-3xl border-2 border-dashed border-slate-200 bg-white p-12 text-center shadow-sm dark:border-slate-800 dark:bg-slate-900">
|
||||
<Building2 className="mx-auto mb-3 h-12 w-12 text-slate-300 dark:text-slate-700" />
|
||||
<h3 className="text-lg font-medium text-slate-900 dark:text-white">{t.clients.noClients}</h3>
|
||||
<p className="mt-1 text-slate-500 dark:text-slate-400">
|
||||
{searchQuery ? t.clients.noClientsSearch : t.clients.noClientsAdd}
|
||||
</p>
|
||||
</div>
|
||||
<EmptyStateCard
|
||||
icon={Building2}
|
||||
title={t.clients.noClients}
|
||||
description={searchQuery ? t.clients.noClientsSearch : t.clients.noClientsAdd}
|
||||
/>
|
||||
) : (
|
||||
<div className="grid grid-cols-1 gap-4 md:grid-cols-2 2xl:grid-cols-3">
|
||||
{clients.map((client) => {
|
||||
@@ -238,8 +245,8 @@ export default function Clients() {
|
||||
currentPage={currentPage}
|
||||
totalCount={totalItems}
|
||||
limit={limit}
|
||||
onPageChange={setCurrentPage}
|
||||
onLimitChange={setLimit}
|
||||
onPageChange={(page) => updateListParams({ page })}
|
||||
onLimitChange={(pageLimit) => updateListParams({ limit: pageLimit, page: 1 })}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
@@ -248,30 +255,30 @@ export default function Clients() {
|
||||
|
||||
{canCreateClient && (
|
||||
<CreateClientModal
|
||||
isOpen={isCreateModalOpen}
|
||||
onClose={() => setIsCreateModalOpen(false)}
|
||||
onSuccess={fetchClientsList}
|
||||
workspaceId={activeWorkspace.id}
|
||||
/>
|
||||
)}
|
||||
|
||||
{canEditClient && (
|
||||
<EditClientModal
|
||||
isOpen={!!editClient}
|
||||
onClose={() => setEditClient(null)}
|
||||
onSuccess={fetchClientsList}
|
||||
client={editClient}
|
||||
/>
|
||||
)}
|
||||
|
||||
isOpen={isCreateModalOpen}
|
||||
onClose={() => setIsCreateModalOpen(false)}
|
||||
onSuccess={fetchClientsList}
|
||||
workspaceId={activeWorkspace.id}
|
||||
/>
|
||||
)}
|
||||
|
||||
{canEditClient && (
|
||||
<EditClientModal
|
||||
isOpen={!!editClient}
|
||||
onClose={() => setEditClient(null)}
|
||||
onSuccess={fetchClientsList}
|
||||
client={editClient}
|
||||
/>
|
||||
)}
|
||||
|
||||
{!!deleteClient && (
|
||||
<DeleteClientModal
|
||||
isOpen={!!deleteClient}
|
||||
onClose={() => setDeleteClient(null)}
|
||||
onSuccess={fetchClientsList}
|
||||
client={deleteClient}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
392
src/pages/GoogleAuthCallback.tsx
Normal file
392
src/pages/GoogleAuthCallback.tsx
Normal file
@@ -0,0 +1,392 @@
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { Link, useNavigate, useSearchParams } from "react-router-dom";
|
||||
import { AlertTriangle, ArrowLeft, ArrowRight, CheckCircle2, Command, Loader2 } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import { Button } from "../components/ui/button";
|
||||
import { Input } from "../components/ui/input";
|
||||
import { SettingsMenu } from "../components/SettingsMenu";
|
||||
import { ApiError } from "../api/client";
|
||||
import {
|
||||
completeGoogleOAuthSignup,
|
||||
getGoogleOAuthFlow,
|
||||
sendGoogleOAuthClaimOtp,
|
||||
startGoogleLogin,
|
||||
verifyGoogleOAuthClaim,
|
||||
type GoogleOAuthFlowResponse,
|
||||
} from "../api/users";
|
||||
import { useTranslation } from "../hooks/useTranslation";
|
||||
import { setSessionTokens } from "../lib/session";
|
||||
|
||||
type GoogleStep = "loading" | "collect_mobile" | "claim_required" | "error";
|
||||
type CooldownKey = "otpSend" | "otpVerify";
|
||||
|
||||
const PERSIAN_DIGITS = ["۰", "۱", "۲", "۳", "۴", "۵", "۶", "۷", "۸", "۹"];
|
||||
|
||||
const toPersianDigits = (value: string) =>
|
||||
value.replace(/\d/g, (digit) => PERSIAN_DIGITS[Number.parseInt(digit, 10)] ?? digit);
|
||||
|
||||
export default function GoogleAuthCallback() {
|
||||
const navigate = useNavigate();
|
||||
const [searchParams] = useSearchParams();
|
||||
const { t, lang } = useTranslation();
|
||||
const isRtl = lang === "fa";
|
||||
|
||||
const flow = searchParams.get("flow") ?? "";
|
||||
|
||||
const [step, setStep] = useState<GoogleStep>("loading");
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [mobile, setMobile] = useState("");
|
||||
const [otpCode, setOtpCode] = useState("");
|
||||
const [googleEmail, setGoogleEmail] = useState("");
|
||||
const [errorMessage, setErrorMessage] = useState("");
|
||||
const [cooldowns, setCooldowns] = useState<Record<CooldownKey, number>>({
|
||||
otpSend: 0,
|
||||
otpVerify: 0,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!Object.values(cooldowns).some((value) => value > 0)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const timer = window.setInterval(() => {
|
||||
setCooldowns((current) => ({
|
||||
otpSend: Math.max(0, current.otpSend - 1),
|
||||
otpVerify: Math.max(0, current.otpVerify - 1),
|
||||
}));
|
||||
}, 1000);
|
||||
|
||||
return () => window.clearInterval(timer);
|
||||
}, [cooldowns]);
|
||||
|
||||
const localizeDigits = (value: string) => (isRtl ? toPersianDigits(value) : value);
|
||||
|
||||
const formatCooldown = (seconds: number) => {
|
||||
const minutes = Math.floor(seconds / 60);
|
||||
const remainingSeconds = seconds % 60;
|
||||
const formatted =
|
||||
minutes > 0
|
||||
? `${minutes}:${remainingSeconds.toString().padStart(2, "0")}`
|
||||
: `${remainingSeconds}s`;
|
||||
return localizeDigits(formatted);
|
||||
};
|
||||
|
||||
const setCooldown = (key: CooldownKey, seconds: number) => {
|
||||
setCooldowns((current) => ({
|
||||
...current,
|
||||
[key]: Math.max(current[key], seconds),
|
||||
}));
|
||||
};
|
||||
|
||||
const handleAuthenticated = (payload: Extract<GoogleOAuthFlowResponse, { status: "authenticated" }>) => {
|
||||
setSessionTokens(payload.access, payload.refresh);
|
||||
toast.success(t.login.toasts.successLogin);
|
||||
navigate("/profile", { replace: true });
|
||||
};
|
||||
|
||||
const applyFlowPayload = (payload: GoogleOAuthFlowResponse) => {
|
||||
if (payload.status === "authenticated") {
|
||||
handleAuthenticated(payload);
|
||||
return;
|
||||
}
|
||||
|
||||
if (payload.status === "collect_mobile") {
|
||||
setGoogleEmail(payload.email);
|
||||
setStep("collect_mobile");
|
||||
return;
|
||||
}
|
||||
|
||||
if (payload.status === "claim_required") {
|
||||
setMobile(payload.mobile);
|
||||
setStep("claim_required");
|
||||
}
|
||||
};
|
||||
|
||||
const handleThrottleError = (error: unknown, key: CooldownKey) => {
|
||||
if (!(error instanceof ApiError) || error.code !== "throttled") {
|
||||
return false;
|
||||
}
|
||||
|
||||
const seconds = Math.max(1, error.retryAfterSeconds ?? 0);
|
||||
const formattedTime = formatCooldown(seconds);
|
||||
setCooldown(key, seconds);
|
||||
|
||||
const message =
|
||||
key === "otpSend"
|
||||
? t.login.throttle.otpSendMessage(formattedTime)
|
||||
: t.login.throttle.otpLoginMessage(formattedTime);
|
||||
|
||||
toast.error(message, {
|
||||
description: t.login.throttle.countdownLabel(formattedTime),
|
||||
});
|
||||
|
||||
return true;
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (!flow) {
|
||||
setErrorMessage(t.login.google.missingFlow);
|
||||
setStep("error");
|
||||
return;
|
||||
}
|
||||
|
||||
let cancelled = false;
|
||||
|
||||
const loadFlow = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const payload = await getGoogleOAuthFlow(flow);
|
||||
if (!cancelled) {
|
||||
applyFlowPayload(payload);
|
||||
}
|
||||
} catch (error) {
|
||||
if (!cancelled) {
|
||||
setErrorMessage(error instanceof Error ? error.message : t.login.google.loadFailed);
|
||||
setStep("error");
|
||||
}
|
||||
} finally {
|
||||
if (!cancelled) {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
loadFlow();
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [flow]);
|
||||
|
||||
const handleCompleteSignup = async (event: React.FormEvent) => {
|
||||
event.preventDefault();
|
||||
if (!mobile) {
|
||||
toast.error(t.login.toasts.enterMobile);
|
||||
return;
|
||||
}
|
||||
|
||||
setLoading(true);
|
||||
try {
|
||||
const payload = await completeGoogleOAuthSignup(flow, mobile);
|
||||
applyFlowPayload(payload);
|
||||
if (payload.status === "claim_required") {
|
||||
toast.success(t.login.google.claimOtpSent);
|
||||
}
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : t.login.google.completeFailed);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleResendClaimOtp = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
await sendGoogleOAuthClaimOtp(flow);
|
||||
setCooldowns((current) => ({ ...current, otpSend: 0 }));
|
||||
toast.success(t.login.google.claimOtpSent);
|
||||
} catch (error) {
|
||||
if (!handleThrottleError(error, "otpSend")) {
|
||||
toast.error(error instanceof Error ? error.message : t.login.toasts.failedOtp);
|
||||
}
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleVerifyClaim = async (event: React.FormEvent) => {
|
||||
event.preventDefault();
|
||||
if (!otpCode) {
|
||||
toast.error(t.login.toasts.enterOtp);
|
||||
return;
|
||||
}
|
||||
|
||||
setLoading(true);
|
||||
try {
|
||||
const payload = await verifyGoogleOAuthClaim(flow, otpCode);
|
||||
setCooldowns((current) => ({ ...current, otpVerify: 0 }));
|
||||
applyFlowPayload(payload);
|
||||
} catch (error) {
|
||||
if (!handleThrottleError(error, "otpVerify")) {
|
||||
toast.error(error instanceof Error ? error.message : t.login.toasts.invalidOtp);
|
||||
}
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const activeWarning = useMemo(() => {
|
||||
if (cooldowns.otpSend > 0) {
|
||||
return t.login.throttle.otpSendMessage(formatCooldown(cooldowns.otpSend));
|
||||
}
|
||||
if (cooldowns.otpVerify > 0) {
|
||||
return t.login.throttle.otpLoginMessage(formatCooldown(cooldowns.otpVerify));
|
||||
}
|
||||
return null;
|
||||
}, [cooldowns, isRtl, lang]);
|
||||
|
||||
const BackIcon = isRtl ? ArrowRight : ArrowLeft;
|
||||
|
||||
return (
|
||||
<div className="container relative min-h-screen grid flex-col items-center justify-center bg-white transition-colors lg:max-w-none lg:grid-cols-2 lg:px-0 dark:bg-slate-950">
|
||||
<div className="absolute inset-e-4 top-4 z-50 md:inset-e-8 md:top-8">
|
||||
<SettingsMenu />
|
||||
</div>
|
||||
|
||||
<div className="relative hidden h-full flex-col border-e border-slate-200 bg-slate-900 p-10 text-white dark:border-slate-800 dark:bg-slate-900/50 lg:flex">
|
||||
<div className="relative z-20 flex items-center gap-2 text-lg font-medium">
|
||||
<Command className="h-6 w-6" />
|
||||
{t.title || "Qlockify"}
|
||||
</div>
|
||||
<div className="relative z-20 mt-auto">
|
||||
<blockquote className="space-y-2">
|
||||
<p className="text-lg">"{t.login.brandingQuote}"</p>
|
||||
</blockquote>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex h-screen items-center justify-center p-8 lg:p-8">
|
||||
<div className="mx-auto flex w-full flex-col justify-center space-y-6 sm:w-[420px]">
|
||||
<div className="flex flex-col space-y-2 text-center text-slate-900 dark:text-slate-50">
|
||||
<div className="mb-4 flex justify-center lg:hidden">
|
||||
<Command className="h-8 w-8" />
|
||||
</div>
|
||||
<h1 className="text-2xl font-semibold tracking-tight">
|
||||
{step === "loading" && t.login.google.loadingTitle}
|
||||
{step === "collect_mobile" && t.login.google.collectMobileTitle}
|
||||
{step === "claim_required" && t.login.google.claimTitle}
|
||||
{step === "error" && t.login.google.errorTitle}
|
||||
</h1>
|
||||
<p className="text-sm text-slate-500 dark:text-slate-400">
|
||||
{step === "loading" && t.login.google.loadingDescription}
|
||||
{step === "collect_mobile" &&
|
||||
t.login.google.collectMobileDescription(googleEmail || "-")}
|
||||
{step === "claim_required" && t.login.google.claimDescription(mobile)}
|
||||
{step === "error" && (errorMessage || t.login.google.loadFailed)}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{activeWarning && (
|
||||
<div className="rounded-2xl border border-amber-200 bg-amber-50 px-4 py-3 text-start text-amber-900 shadow-sm dark:border-amber-900/50 dark:bg-amber-950/40 dark:text-amber-100">
|
||||
<div className="flex items-start gap-3">
|
||||
<AlertTriangle className="mt-0.5 h-4 w-4 shrink-0" />
|
||||
<div className="space-y-1">
|
||||
<p className="text-sm font-medium">{t.login.throttle.title}</p>
|
||||
<p className="text-sm">{activeWarning}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="grid gap-6">
|
||||
{step === "loading" && (
|
||||
<div className="rounded-3xl border border-slate-200 bg-white p-8 text-center shadow-sm dark:border-slate-800 dark:bg-slate-900">
|
||||
<Loader2 className="mx-auto mb-4 h-8 w-8 animate-spin text-slate-400" />
|
||||
<p className="text-sm text-slate-500 dark:text-slate-400">
|
||||
{t.login.google.loadingDescription}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{step === "collect_mobile" && (
|
||||
<form onSubmit={handleCompleteSignup} className="grid gap-4">
|
||||
<div className="rounded-3xl border border-slate-200 bg-white p-5 shadow-sm dark:border-slate-800 dark:bg-slate-900">
|
||||
<div className="mb-4 flex items-center gap-3">
|
||||
<div className="flex h-10 w-10 items-center justify-center rounded-2xl bg-slate-100 text-slate-700 dark:bg-slate-800 dark:text-slate-200">
|
||||
<CheckCircle2 className="h-5 w-5" />
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<p className="text-sm font-medium text-slate-900 dark:text-white">
|
||||
{t.login.google.googleAccount}
|
||||
</p>
|
||||
<p className="truncate text-sm text-slate-500 dark:text-slate-400">{googleEmail}</p>
|
||||
</div>
|
||||
</div>
|
||||
<Input
|
||||
id="google-mobile"
|
||||
placeholder={t.login.mobilePlaceholder}
|
||||
type="tel"
|
||||
dir="ltr"
|
||||
value={mobile}
|
||||
onChange={(event) => setMobile(event.target.value)}
|
||||
maxLength={11}
|
||||
disabled={loading}
|
||||
className={`h-11 ${isRtl ? "text-end" : "text-start"}`}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Button type="submit" className="h-11 w-full" disabled={loading}>
|
||||
{loading && <Loader2 className="me-2 h-4 w-4 animate-spin" />}
|
||||
{t.login.google.completeButton}
|
||||
</Button>
|
||||
<Button type="button" variant="ghost" onClick={() => startGoogleLogin()} className="text-sm text-slate-500 dark:text-slate-400">
|
||||
{t.login.google.restartGoogle}
|
||||
</Button>
|
||||
</form>
|
||||
)}
|
||||
|
||||
{step === "claim_required" && (
|
||||
<form onSubmit={handleVerifyClaim} className="grid gap-4">
|
||||
<div className="rounded-3xl border border-slate-200 bg-white p-5 shadow-sm dark:border-slate-800 dark:bg-slate-900">
|
||||
<p className="mb-3 text-sm text-slate-500 dark:text-slate-400">
|
||||
{t.login.google.claimDescription(mobile)}
|
||||
</p>
|
||||
<Input
|
||||
id="google-claim-otp"
|
||||
placeholder={t.login.otpPlaceholder}
|
||||
type="text"
|
||||
dir="ltr"
|
||||
value={otpCode}
|
||||
onChange={(event) => setOtpCode(event.target.value)}
|
||||
maxLength={6}
|
||||
disabled={loading}
|
||||
className="h-11 text-center text-lg tracking-widest"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Button type="submit" className="h-11 w-full" disabled={loading || cooldowns.otpVerify > 0}>
|
||||
{loading && <Loader2 className="me-2 h-4 w-4 animate-spin" />}
|
||||
{cooldowns.otpVerify > 0
|
||||
? t.login.throttle.countdownLabel(formatCooldown(cooldowns.otpVerify))
|
||||
: t.login.google.verifyClaimButton}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={handleResendClaimOtp}
|
||||
disabled={loading || cooldowns.otpSend > 0}
|
||||
className="h-11"
|
||||
>
|
||||
{cooldowns.otpSend > 0
|
||||
? t.login.throttle.countdownLabel(formatCooldown(cooldowns.otpSend))
|
||||
: t.login.google.resendClaimOtp}
|
||||
</Button>
|
||||
</form>
|
||||
)}
|
||||
|
||||
{step === "error" && (
|
||||
<div className="rounded-3xl border border-red-200 bg-red-50 p-6 text-center shadow-sm dark:border-red-900/50 dark:bg-red-950/20">
|
||||
<AlertTriangle className="mx-auto mb-3 h-8 w-8 text-red-500" />
|
||||
<p className="mb-4 text-sm text-red-700 dark:text-red-200">
|
||||
{errorMessage || t.login.google.loadFailed}
|
||||
</p>
|
||||
<div className="grid gap-3">
|
||||
<Button type="button" onClick={() => startGoogleLogin()} className="h-11">
|
||||
{t.login.google.restartGoogle}
|
||||
</Button>
|
||||
<Button type="button" variant="ghost" asChild className="text-sm text-slate-500 dark:text-slate-400">
|
||||
<Link to="/auth">
|
||||
<BackIcon className="me-2 h-4 w-4" />
|
||||
{t.login.back}
|
||||
</Link>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
418
src/pages/Landing.tsx
Normal file
418
src/pages/Landing.tsx
Normal file
@@ -0,0 +1,418 @@
|
||||
import { useMemo } from "react"
|
||||
import { Link, useNavigate } from "react-router-dom"
|
||||
import {
|
||||
ArrowRight,
|
||||
BarChart3,
|
||||
CheckCircle2,
|
||||
Clock3,
|
||||
Command,
|
||||
Globe2,
|
||||
Layers3,
|
||||
Moon,
|
||||
ShieldCheck,
|
||||
Sparkles,
|
||||
Sun,
|
||||
TimerReset,
|
||||
Waypoints,
|
||||
} from "lucide-react"
|
||||
|
||||
import { Button } from "../components/ui/button"
|
||||
import { useTheme } from "../components/ThemeProvider"
|
||||
import { useTranslation } from "../hooks/useTranslation"
|
||||
import { cn } from "../lib/utils"
|
||||
|
||||
const formatNumber = (value: number, lang: "en" | "fa") =>
|
||||
new Intl.NumberFormat(lang === "fa" ? "fa-IR" : "en-US").format(value)
|
||||
|
||||
export default function Landing() {
|
||||
const navigate = useNavigate()
|
||||
const { t, lang, setLanguage } = useTranslation()
|
||||
const { theme, setTheme } = useTheme()
|
||||
|
||||
const isAuthenticated = typeof window !== "undefined" && !!localStorage.getItem("accessToken")
|
||||
const isDarkMode =
|
||||
theme === "dark" ||
|
||||
(theme === "system" && document.documentElement.classList.contains("dark"))
|
||||
|
||||
const metrics = useMemo(
|
||||
() => [
|
||||
{
|
||||
value: lang === "fa" ? "۹۸٪" : "98%",
|
||||
label: t.landing.metrics.capture,
|
||||
tone: "from-cyan-500/20 to-cyan-500/5 text-cyan-700 dark:text-cyan-200",
|
||||
},
|
||||
{
|
||||
value: lang === "fa" ? "۴.۶×" : "4.6x",
|
||||
label: t.landing.metrics.visibility,
|
||||
tone: "from-emerald-500/20 to-emerald-500/5 text-emerald-700 dark:text-emerald-200",
|
||||
},
|
||||
{
|
||||
value: lang === "fa" ? "< ۲m" : "< 2m",
|
||||
label: t.landing.metrics.decision,
|
||||
tone: "from-amber-500/20 to-amber-500/5 text-amber-700 dark:text-amber-200",
|
||||
},
|
||||
],
|
||||
[lang, t.landing.metrics],
|
||||
)
|
||||
|
||||
const capabilityCards = useMemo(
|
||||
() => [
|
||||
{
|
||||
icon: TimerReset,
|
||||
title: t.landing.capabilities.time.title,
|
||||
description: t.landing.capabilities.time.description,
|
||||
},
|
||||
{
|
||||
icon: BarChart3,
|
||||
title: t.landing.capabilities.reports.title,
|
||||
description: t.landing.capabilities.reports.description,
|
||||
},
|
||||
{
|
||||
icon: ShieldCheck,
|
||||
title: t.landing.capabilities.control.title,
|
||||
description: t.landing.capabilities.control.description,
|
||||
},
|
||||
],
|
||||
[t.landing.capabilities],
|
||||
)
|
||||
|
||||
const workflow = useMemo(
|
||||
() => [
|
||||
t.landing.workflow.capture,
|
||||
t.landing.workflow.structure,
|
||||
t.landing.workflow.improve,
|
||||
],
|
||||
[t.landing.workflow],
|
||||
)
|
||||
|
||||
const ctaTarget = isAuthenticated ? "/timesheet" : "/auth"
|
||||
|
||||
return (
|
||||
<div className="scroll-smooth min-h-screen overflow-x-hidden bg-[radial-gradient(circle_at_top,#e0f2fe_0%,#f8fafc_36%,#eef2ff_100%)] text-slate-950 dark:bg-[radial-gradient(circle_at_top,#082f49_0%,#020617_40%,#020617_100%)] dark:text-slate-50">
|
||||
<div className="landing-aurora pointer-events-none fixed inset-0 opacity-80" />
|
||||
<div className="landing-hero-grid pointer-events-none fixed inset-0 opacity-70 dark:opacity-40" />
|
||||
<div className="pointer-events-none fixed left-[-12rem] top-24 h-80 w-80 rounded-full bg-cyan-400/20 blur-3xl dark:bg-cyan-500/10" />
|
||||
<div className="pointer-events-none fixed right-[-10rem] top-44 h-72 w-72 rounded-full bg-amber-300/25 blur-3xl dark:bg-amber-400/10" />
|
||||
|
||||
<div className="relative mx-auto flex min-h-screen max-w-7xl flex-col px-4 pb-14 pt-5 sm:px-6 lg:px-8">
|
||||
<header className="animate-landing-rise flex items-center justify-between rounded-full border border-white/70 bg-white/75 px-4 py-3 shadow-[0_20px_60px_-36px_rgba(15,23,42,0.45)] backdrop-blur-xl dark:border-white/10 dark:bg-slate-950/55">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => navigate("/")}
|
||||
className="inline-flex items-center gap-3 rounded-full px-2 py-1 text-left"
|
||||
>
|
||||
<span className="flex h-10 w-10 items-center justify-center rounded-2xl bg-slate-950 text-white shadow-lg shadow-cyan-500/20 dark:bg-white dark:text-slate-950">
|
||||
<Command className="h-5 w-5" />
|
||||
</span>
|
||||
<span>
|
||||
<span className="block text-lg font-semibold">{t.title}</span>
|
||||
</span>
|
||||
</button>
|
||||
|
||||
<div className="hidden items-center gap-2 md:flex">
|
||||
<a href="#demo" className="rounded-full px-4 py-2 text-sm font-medium text-slate-600 transition hover:bg-slate-100 hover:text-slate-950 dark:text-slate-300 dark:hover:bg-slate-900 dark:hover:text-white">
|
||||
{t.landing.nav.demo}
|
||||
</a>
|
||||
<a href="#features" className="rounded-full px-4 py-2 text-sm font-medium text-slate-600 transition hover:bg-slate-100 hover:text-slate-950 dark:text-slate-300 dark:hover:bg-slate-900 dark:hover:text-white">
|
||||
{t.landing.nav.features}
|
||||
</a>
|
||||
<a href="#workflow" className="rounded-full px-4 py-2 text-sm font-medium text-slate-600 transition hover:bg-slate-100 hover:text-slate-950 dark:text-slate-300 dark:hover:bg-slate-900 dark:hover:text-white">
|
||||
{t.landing.nav.workflow}
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setLanguage(lang === "fa" ? "en" : "fa")}
|
||||
className="inline-flex h-11 items-center gap-2 rounded-full border border-slate-200/80 bg-white/80 px-4 text-sm font-medium text-slate-700 transition hover:bg-slate-50 dark:border-slate-800 dark:bg-slate-950/80 dark:text-slate-200 dark:hover:bg-slate-900"
|
||||
>
|
||||
<Globe2 className="h-4 w-4" />
|
||||
{lang === "fa" ? t.landing.actions.switchToEnglish : t.landing.actions.switchToPersian}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setTheme(isDarkMode ? "light" : "dark")}
|
||||
className="inline-flex h-11 w-11 items-center justify-center rounded-full border border-slate-200/80 bg-white/80 text-slate-700 transition hover:bg-slate-50 dark:border-slate-800 dark:bg-slate-950/80 dark:text-slate-200 dark:hover:bg-slate-900"
|
||||
aria-label={isDarkMode ? t.lightMode : t.darkMode}
|
||||
>
|
||||
{isDarkMode ? <Sun className="h-4 w-4" /> : <Moon className="h-4 w-4" />}
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<section className="relative grid flex-1 items-center gap-10 py-12 lg:grid-cols-[1.08fr_0.92fr] lg:py-20">
|
||||
<div className="space-y-8">
|
||||
<div className="animate-landing-rise [animation-delay:120ms]">
|
||||
<div className="mb-5 inline-flex items-center gap-2 rounded-full border border-cyan-200/70 bg-white/75 px-4 py-2 text-sm font-medium text-cyan-900 shadow-sm backdrop-blur dark:border-cyan-500/20 dark:bg-cyan-500/10 dark:text-cyan-100">
|
||||
<Sparkles className="h-4 w-4" />
|
||||
{t.landing.eyebrow}
|
||||
</div>
|
||||
<h1 className="max-w-4xl text-4xl font-semibold leading-[1.1] text-slate-950 sm:text-5xl lg:text-6xl dark:text-white">
|
||||
{t.landing.hero.titleTop}
|
||||
<span className="mt-4 pb-4 landing-shimmer block bg-[linear-gradient(120deg,#0f172a_15%,#0891b2_48%,#0f766e_78%,#0f172a_100%)] bg-clip-text text-transparent dark:bg-[linear-gradient(120deg,#ffffff_18%,#67e8f9_48%,#2dd4bf_78%,#ffffff_100%)]">
|
||||
{t.landing.hero.titleAccent}
|
||||
</span>
|
||||
</h1>
|
||||
<p className="mt-6 max-w-2xl text-lg leading-8 text-slate-600 dark:text-slate-300 sm:text-xl">
|
||||
{t.landing.hero.description}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="animate-landing-rise flex flex-col gap-3 sm:flex-row [animation-delay:220ms]">
|
||||
<Button
|
||||
onClick={() => navigate(ctaTarget)}
|
||||
className="h-14 rounded-full bg-slate-950 px-7 text-base text-white shadow-[0_30px_80px_-28px_rgba(8,145,178,0.45)] hover:bg-slate-800 dark:bg-cyan-400 dark:text-slate-950 dark:hover:bg-cyan-300"
|
||||
>
|
||||
{isAuthenticated ? t.landing.actions.openWorkspace : t.landing.actions.startNow}
|
||||
<ArrowRight className={cn("ms-2 h-4 w-4", lang === "fa" && "rtl:rotate-180")} />
|
||||
</Button>
|
||||
<a
|
||||
href="#demo"
|
||||
className="inline-flex h-14 items-center justify-center rounded-full border border-slate-200 bg-white/85 px-7 text-base font-medium text-slate-800 shadow-sm backdrop-blur transition hover:bg-white dark:border-slate-800 dark:bg-slate-950/70 dark:text-slate-100 dark:hover:bg-slate-900"
|
||||
>
|
||||
{t.landing.actions.watchDemo}
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<div className="animate-landing-rise grid gap-3 sm:grid-cols-3 [animation-delay:320ms]">
|
||||
{metrics.map((metric) => (
|
||||
<div
|
||||
key={metric.label}
|
||||
className={cn(
|
||||
"rounded-3xl border border-white/70 bg-gradient-to-br p-5 shadow-[0_28px_70px_-40px_rgba(15,23,42,0.55)] backdrop-blur-lg dark:border-white/10 dark:bg-slate-950/60",
|
||||
metric.tone,
|
||||
)}
|
||||
>
|
||||
<div className="text-3xl font-semibold tracking-[-0.04em]">{metric.value}</div>
|
||||
<div className="mt-2 text-sm font-medium text-slate-600 dark:text-slate-300">{metric.label}</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="animate-landing-rise flex flex-wrap items-center gap-4 text-sm text-slate-500 dark:text-slate-400 [animation-delay:420ms]">
|
||||
<span className="inline-flex items-center gap-2">
|
||||
<CheckCircle2 className="h-4 w-4 text-emerald-500" />
|
||||
{t.landing.trust.first}
|
||||
</span>
|
||||
<span className="inline-flex items-center gap-2">
|
||||
<CheckCircle2 className="h-4 w-4 text-emerald-500" />
|
||||
{t.landing.trust.second}
|
||||
</span>
|
||||
<span className="inline-flex items-center gap-2">
|
||||
<CheckCircle2 className="h-4 w-4 text-emerald-500" />
|
||||
{t.landing.trust.third}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="demo" className="relative animate-landing-rise [animation-delay:180ms]">
|
||||
<div className="animate-landing-float absolute -left-6 top-10 hidden rounded-3xl border border-white/60 bg-white/80 p-4 shadow-[0_24px_70px_-34px_rgba(8,145,178,0.6)] backdrop-blur-xl lg:block dark:border-white/10 dark:bg-slate-950/70">
|
||||
<div className="mb-3 flex items-center gap-3">
|
||||
<div className="flex h-10 w-10 items-center justify-center rounded-2xl bg-cyan-500/15 text-cyan-700 dark:text-cyan-200">
|
||||
<Clock3 className="h-5 w-5" />
|
||||
</div>
|
||||
<div>
|
||||
<div className="text-xs uppercase tracking-[0.18em] text-slate-400">{t.landing.demo.timerTag}</div>
|
||||
<div className="text-sm font-semibold text-slate-900 dark:text-white">{t.landing.demo.timerTitle}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-3xl font-semibold tracking-[-0.05em] text-slate-950 dark:text-white">
|
||||
{lang === "fa" ? "۰۲:۴۶:۱۸" : "02:46:18"}
|
||||
</div>
|
||||
<div className="mt-2 text-sm text-slate-500 dark:text-slate-400">{t.landing.demo.timerText}</div>
|
||||
</div>
|
||||
|
||||
<div className="relative overflow-hidden rounded-[2rem] border border-white/70 bg-white/80 p-4 shadow-[0_45px_110px_-48px_rgba(15,23,42,0.6)] backdrop-blur-2xl dark:border-white/10 dark:bg-slate-950/70 sm:p-6">
|
||||
<div className="mb-5 flex items-center justify-between">
|
||||
<div>
|
||||
<div className="text-xs uppercase tracking-[0.22em] text-slate-400 dark:text-slate-500">
|
||||
{t.landing.demo.panelLabel}
|
||||
</div>
|
||||
<div className="mt-2 text-2xl font-semibold tracking-[-0.04em] text-slate-950 dark:text-white">
|
||||
{t.landing.demo.panelTitle}
|
||||
</div>
|
||||
</div>
|
||||
<div className="rounded-full border border-emerald-200 bg-emerald-50 px-4 py-2 text-sm font-semibold text-emerald-700 dark:border-emerald-500/20 dark:bg-emerald-500/10 dark:text-emerald-200">
|
||||
{lang === "fa" ? "زنده" : "Live"}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-4 lg:grid-cols-[1.15fr_0.85fr]">
|
||||
<div className="space-y-4">
|
||||
<div className="rounded-[1.5rem] border border-slate-200/80 bg-slate-950 p-5 text-white shadow-inner dark:border-slate-800">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<div>
|
||||
<div className="text-xs uppercase tracking-[0.2em] text-cyan-200/70">{t.landing.demo.runningCard}</div>
|
||||
<div className="mt-2 text-xl font-semibold">{t.landing.demo.currentTask}</div>
|
||||
<div className="mt-2 text-sm text-slate-300">{t.landing.demo.currentTaskMeta}</div>
|
||||
</div>
|
||||
<div className="rounded-3xl bg-white/10 px-4 py-3 text-right backdrop-blur">
|
||||
<div className="text-xs uppercase tracking-[0.18em] text-slate-300">{t.landing.demo.billableLabel}</div>
|
||||
<div className="mt-2 text-2xl font-semibold">{lang === "fa" ? "۹۵ دلار" : "$95"}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-5 h-2 overflow-hidden rounded-full bg-white/10">
|
||||
<div className="h-full w-[78%] rounded-full bg-[linear-gradient(90deg,#67e8f9,#14b8a6)]" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<div className="rounded-[1.5rem] border border-slate-200/80 bg-white p-4 shadow-sm dark:border-slate-800 dark:bg-slate-900">
|
||||
<div className="flex items-center gap-2 text-sm font-semibold text-slate-900 dark:text-white">
|
||||
<BarChart3 className="h-4 w-4 text-cyan-500" />
|
||||
{t.landing.demo.reportCard}
|
||||
</div>
|
||||
<div className="mt-4 flex h-32 items-end gap-2">
|
||||
{[34, 56, 48, 72, 65, 88, 76].map((height, index) => (
|
||||
<div
|
||||
key={height}
|
||||
className="flex-1 rounded-t-2xl bg-[linear-gradient(180deg,#67e8f9_0%,#0f766e_100%)] opacity-90"
|
||||
style={{
|
||||
height: `${height}%`,
|
||||
animationDelay: `${index * 120}ms`,
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="rounded-[1.5rem] border border-slate-200/80 bg-white p-4 shadow-sm dark:border-slate-800 dark:bg-slate-900">
|
||||
<div className="flex items-center gap-2 text-sm font-semibold text-slate-900 dark:text-white">
|
||||
<Waypoints className="h-4 w-4 text-amber-500" />
|
||||
{t.landing.demo.opsCard}
|
||||
</div>
|
||||
<div className="mt-4 space-y-3">
|
||||
{[82, 63, 91].map((value, index) => (
|
||||
<div key={value}>
|
||||
<div className="mb-2 flex items-center justify-between text-xs text-slate-500 dark:text-slate-400">
|
||||
<span>{t.landing.demo.opsLabels[index]}</span>
|
||||
<span>{formatNumber(value, lang)}%</span>
|
||||
</div>
|
||||
<div className="h-2 rounded-full bg-slate-100 dark:bg-slate-800">
|
||||
<div
|
||||
className="h-full rounded-full bg-[linear-gradient(90deg,#f59e0b,#f97316)]"
|
||||
style={{ width: `${value}%` }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div className="rounded-[1.5rem] border border-slate-200/80 bg-white p-4 shadow-sm dark:border-slate-800 dark:bg-slate-900">
|
||||
<div className="flex items-center gap-2 text-sm font-semibold text-slate-900 dark:text-white">
|
||||
<Layers3 className="h-4 w-4 text-violet-500" />
|
||||
{t.landing.demo.logCard}
|
||||
</div>
|
||||
<div className="mt-4 space-y-3">
|
||||
{t.landing.demo.logItems.map((item: { title: string; meta: string }, index: number) => (
|
||||
<div key={item.title} className="rounded-2xl border border-slate-200 bg-slate-50 p-3 dark:border-slate-800 dark:bg-slate-950">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div>
|
||||
<div className="text-sm font-medium text-slate-900 dark:text-white">{item.title}</div>
|
||||
<div className="mt-1 text-xs text-slate-500 dark:text-slate-400">{item.meta}</div>
|
||||
</div>
|
||||
<div className={cn(
|
||||
"mt-0.5 h-2.5 w-2.5 rounded-full",
|
||||
index === 0 ? "bg-emerald-500" : index === 1 ? "bg-cyan-500" : "bg-amber-500",
|
||||
)} />
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="rounded-[1.5rem] border border-slate-200/80 bg-slate-950 p-4 text-white shadow-inner dark:border-slate-800">
|
||||
<div className="text-xs uppercase tracking-[0.18em] text-slate-400">{t.landing.demo.outcomeTag}</div>
|
||||
<div className="mt-3 text-4xl font-semibold tracking-[-0.05em]">{lang === "fa" ? "۳۶٪" : "36%"}</div>
|
||||
<div className="mt-2 text-sm text-slate-300">{t.landing.demo.outcomeText}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section id="features" className="grid gap-4 py-8 md:grid-cols-3">
|
||||
{capabilityCards.map(({ icon: Icon, title, description }, index) => (
|
||||
<div
|
||||
key={title}
|
||||
className="animate-landing-rise rounded-[2rem] border border-white/70 bg-white/80 p-6 shadow-[0_30px_80px_-50px_rgba(15,23,42,0.6)] backdrop-blur-xl dark:border-white/10 dark:bg-slate-950/65"
|
||||
style={{ animationDelay: `${index * 120}ms` }}
|
||||
>
|
||||
<div className="flex h-12 w-12 items-center justify-center rounded-2xl bg-slate-950 text-white dark:bg-cyan-400 dark:text-slate-950">
|
||||
<Icon className="h-5 w-5" />
|
||||
</div>
|
||||
<h2 className="mt-5 text-2xl font-semibold tracking-[-0.04em] text-slate-950 dark:text-white">{title}</h2>
|
||||
<p className="mt-3 text-base leading-7 text-slate-600 dark:text-slate-300">{description}</p>
|
||||
</div>
|
||||
))}
|
||||
</section>
|
||||
|
||||
<section id="workflow" className="grid gap-6 py-8 lg:grid-cols-[0.9fr_1.1fr]">
|
||||
<div className="rounded-[2rem] border border-white/70 bg-white/80 p-7 shadow-[0_30px_80px_-50px_rgba(15,23,42,0.6)] backdrop-blur-xl dark:border-white/10 dark:bg-slate-950/65">
|
||||
<div className="text-sm font-semibold uppercase tracking-[0.2em] text-cyan-700 dark:text-cyan-300">
|
||||
{t.landing.workflowTag}
|
||||
</div>
|
||||
<h2 className="mt-4 text-4xl font-semibold tracking-[-0.05em] text-slate-950 dark:text-white">
|
||||
{t.landing.workflowTitle}
|
||||
</h2>
|
||||
<p className="mt-4 max-w-xl text-lg leading-8 text-slate-600 dark:text-slate-300">
|
||||
{t.landing.workflowDescription}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-4 md:grid-cols-3">
|
||||
{workflow.map((item, index) => (
|
||||
<div
|
||||
key={item}
|
||||
className="rounded-[2rem] border border-white/70 bg-gradient-to-br from-white/95 to-slate-50/80 p-6 shadow-[0_26px_70px_-48px_rgba(15,23,42,0.65)] backdrop-blur-xl dark:border-white/10 dark:from-slate-950/80 dark:to-slate-900/55"
|
||||
>
|
||||
<div className="text-sm font-semibold uppercase tracking-[0.2em] text-slate-400 dark:text-slate-500">
|
||||
{lang === "fa" ? `گام ${formatNumber(index + 1, lang)}` : `Step ${index + 1}`}
|
||||
</div>
|
||||
<div className="mt-12 text-xl font-semibold leading-8 tracking-[-0.03em] text-slate-950 dark:text-white">
|
||||
{item}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="py-8">
|
||||
<div className="relative overflow-hidden rounded-[2.5rem] border border-slate-950/5 bg-slate-950 px-6 py-10 text-white shadow-[0_40px_100px_-40px_rgba(15,23,42,0.8)] dark:border-white/10 sm:px-10">
|
||||
<div className="pointer-events-none absolute inset-y-0 right-0 w-[45%] bg-[radial-gradient(circle_at_top_right,rgba(34,211,238,0.35),transparent_55%),radial-gradient(circle_at_bottom_right,rgba(245,158,11,0.22),transparent_45%)]" />
|
||||
<div className="relative flex flex-col gap-6 lg:flex-row lg:items-end lg:justify-between">
|
||||
<div className="max-w-3xl">
|
||||
<div className="text-sm font-semibold uppercase tracking-[0.2em] text-cyan-300">{t.landing.finalCtaTag}</div>
|
||||
<h2 className="mt-4 text-4xl font-semibold leading-[1.1] tracking-[-0.05em] sm:text-5xl">
|
||||
{t.landing.finalCtaTitle}
|
||||
</h2>
|
||||
<p className="mt-4 text-lg leading-8 text-slate-300">{t.landing.finalCtaDescription}</p>
|
||||
</div>
|
||||
<div className="flex flex-col gap-3 sm:flex-row">
|
||||
<Button
|
||||
onClick={() => navigate(ctaTarget)}
|
||||
className="h-14 rounded-full bg-white px-7 text-base font-semibold text-slate-950 hover:bg-slate-100"
|
||||
>
|
||||
{isAuthenticated ? t.landing.actions.openWorkspace : t.landing.actions.startNow}
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
asChild
|
||||
className="h-14 rounded-full border-white/20 bg-white/5 px-7 text-base text-white hover:bg-white/10 dark:border-white/20 dark:bg-white/5 dark:text-white dark:hover:bg-white/10"
|
||||
>
|
||||
<Link to="/terms">{t.landing.actions.readTerms}</Link>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { useSearchParams } from "react-router-dom";
|
||||
import { History, ShieldCheck, SlidersHorizontal } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
@@ -14,6 +15,7 @@ import { LogsFeed } from "../components/logs/LogsFeed";
|
||||
import { LogsFilterBar, type LogsFilterDraft } from "../components/logs/LogsFilterBar";
|
||||
import { useWorkspace } from "../context/WorkspaceContext";
|
||||
import { useTranslation } from "../hooks/useTranslation";
|
||||
import { readStringParam, updateQueryParams } from "../lib/queryParams";
|
||||
import { canWorkspace, WORKSPACE_LOGS_VIEW } from "../lib/permissions";
|
||||
|
||||
const DEFAULT_FILTERS: LogsFilterDraft = {
|
||||
@@ -26,12 +28,22 @@ const DEFAULT_FILTERS: LogsFilterDraft = {
|
||||
ordering: "-timestamp",
|
||||
};
|
||||
|
||||
const DEFAULT_QUERY_FILTERS: Record<string, string> = {
|
||||
search: DEFAULT_FILTERS.search,
|
||||
section: DEFAULT_FILTERS.section,
|
||||
event: DEFAULT_FILTERS.event,
|
||||
actor: DEFAULT_FILTERS.actor,
|
||||
from: DEFAULT_FILTERS.from,
|
||||
to: DEFAULT_FILTERS.to,
|
||||
ordering: DEFAULT_FILTERS.ordering,
|
||||
};
|
||||
|
||||
const PAGE_SIZE = 20;
|
||||
|
||||
export default function Logs() {
|
||||
const { t, lang } = useTranslation();
|
||||
const { activeWorkspace } = useWorkspace();
|
||||
const [filters, setFilters] = useState<LogsFilterDraft>(DEFAULT_FILTERS);
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
const [memberships, setMemberships] = useState<WorkspaceMembership[]>([]);
|
||||
const [logs, setLogs] = useState<WorkspaceLogItem[]>([]);
|
||||
const [totalLogs, setTotalLogs] = useState(0);
|
||||
@@ -45,9 +57,20 @@ export default function Logs() {
|
||||
const workspaceRole = activeWorkspace?.my_role;
|
||||
const canViewLogs = canWorkspace(workspaceRole, WORKSPACE_LOGS_VIEW);
|
||||
const isWorkspaceRoleResolved = Boolean(workspaceRole);
|
||||
const filters = useMemo<LogsFilterDraft>(
|
||||
() => ({
|
||||
search: readStringParam(searchParams, "search", DEFAULT_FILTERS.search),
|
||||
section: readStringParam(searchParams, "section", DEFAULT_FILTERS.section) as LogsFilterDraft["section"],
|
||||
event: readStringParam(searchParams, "event", DEFAULT_FILTERS.event) as LogsFilterDraft["event"],
|
||||
actor: readStringParam(searchParams, "actor", DEFAULT_FILTERS.actor),
|
||||
from: readStringParam(searchParams, "from", DEFAULT_FILTERS.from),
|
||||
to: readStringParam(searchParams, "to", DEFAULT_FILTERS.to),
|
||||
ordering: readStringParam(searchParams, "ordering", DEFAULT_FILTERS.ordering) as LogsFilterDraft["ordering"],
|
||||
}),
|
||||
[searchParams],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
setFilters(DEFAULT_FILTERS);
|
||||
setLogs([]);
|
||||
setTotalLogs(0);
|
||||
setSelectedLogId(null);
|
||||
@@ -284,7 +307,25 @@ export default function Logs() {
|
||||
users={memberships}
|
||||
isLoadingUsers={isLoadingUsers}
|
||||
canSelectUsers={canViewLogs}
|
||||
onApply={setFilters}
|
||||
onApply={(nextFilters) =>
|
||||
setSearchParams(
|
||||
(current) =>
|
||||
updateQueryParams(
|
||||
current,
|
||||
{
|
||||
search: nextFilters.search,
|
||||
section: nextFilters.section,
|
||||
event: nextFilters.event,
|
||||
actor: nextFilters.actor,
|
||||
from: nextFilters.from,
|
||||
to: nextFilters.to,
|
||||
ordering: nextFilters.ordering,
|
||||
},
|
||||
DEFAULT_QUERY_FILTERS,
|
||||
),
|
||||
{ replace: true },
|
||||
)
|
||||
}
|
||||
/>
|
||||
|
||||
<LogsFeed
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import React, { useEffect, useMemo, useState } from "react";
|
||||
import { useSearchParams } from "react-router-dom";
|
||||
import { useTranslation } from "../hooks/useTranslation";
|
||||
import { getProjects, deleteProject, type Project } from "../api/projects";
|
||||
import { getClients } from "../api/clients";
|
||||
@@ -9,6 +10,7 @@ import { ProjectEditModal } from "../components/projects/ProjectEditModal";
|
||||
import { Pagination } from "../components/Pagination";
|
||||
import { Plus, Archive, Building2, Pencil, Trash2, X } from "lucide-react";
|
||||
|
||||
import EmptyStateCard from "../components/EmptyStateCard";
|
||||
import FilterBar from "../components/FilterBar";
|
||||
import { ListPageSkeleton } from "../components/ListPageSkeleton";
|
||||
import { Button } from "../components/ui/button";
|
||||
@@ -16,14 +18,21 @@ import { Card, CardContent, CardTitle } from "../components/ui/card";
|
||||
import { Modal } from "../components/Modal";
|
||||
import { toast } from "sonner";
|
||||
import { Input } from "../components/ui/input";
|
||||
import {
|
||||
import {
|
||||
PROJECTS_ARCHIVE,
|
||||
PROJECTS_CREATE,
|
||||
PROJECTS_EDIT,
|
||||
canDeleteWorkspaceResource,
|
||||
canWorkspace,
|
||||
} from "../lib/permissions";
|
||||
|
||||
import {
|
||||
readArrayParam,
|
||||
readBooleanParam,
|
||||
readNumberParam,
|
||||
readStringParam,
|
||||
updateQueryParams,
|
||||
} from "../lib/queryParams";
|
||||
|
||||
export const Projects: React.FC = () => {
|
||||
const { t, lang } = useTranslation();
|
||||
const { user } = useAppContext();
|
||||
@@ -32,24 +41,44 @@ export const Projects: React.FC = () => {
|
||||
const canCreateProject = canWorkspace(workspaceRole, PROJECTS_CREATE);
|
||||
const canEditProject = canWorkspace(workspaceRole, PROJECTS_EDIT);
|
||||
const canArchiveProject = canWorkspace(workspaceRole, PROJECTS_ARCHIVE);
|
||||
|
||||
|
||||
const [projects, setProjects] = useState<Project[]>([]);
|
||||
const [clients, setClients] = useState<{ id: string; name: string }[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);
|
||||
const [editingProject, setEditingProject] = useState<Project | null>(null);
|
||||
|
||||
const [search, setSearch] = useState("");
|
||||
const [ordering, setOrdering] = useState("-created_at");
|
||||
const [isArchived, setIsArchived] = useState(false);
|
||||
const [selectedClientIds, setSelectedClientIds] = useState<string[]>([]);
|
||||
const [currentPage, setCurrentPage] = useState(1);
|
||||
const [limit, setLimit] = useState(10);
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
const search = useMemo(() => readStringParam(searchParams, "search", ""), [searchParams]);
|
||||
const ordering = useMemo(
|
||||
() => readStringParam(searchParams, "ordering", "-created_at"),
|
||||
[searchParams],
|
||||
);
|
||||
const isArchived = useMemo(
|
||||
() => readBooleanParam(searchParams, "archived", false),
|
||||
[searchParams],
|
||||
);
|
||||
const selectedClientIds = useMemo(
|
||||
() => readArrayParam(searchParams, "clients"),
|
||||
[searchParams],
|
||||
);
|
||||
const selectedClientIdsKey = useMemo(
|
||||
() => selectedClientIds.join(","),
|
||||
[selectedClientIds],
|
||||
);
|
||||
const currentPage = useMemo(
|
||||
() => Math.max(1, readNumberParam(searchParams, "page", 1)),
|
||||
[searchParams],
|
||||
);
|
||||
const limit = useMemo(
|
||||
() => Math.max(1, readNumberParam(searchParams, "limit", 10)),
|
||||
[searchParams],
|
||||
);
|
||||
const [totalItems, setTotalItems] = useState(0);
|
||||
|
||||
const [deleteModal, setDeleteModal] = useState<{isOpen: boolean; project: Project | null}>({isOpen: false, project: null});
|
||||
const [deleteInput, setDeleteInput] = useState('');
|
||||
|
||||
|
||||
const orderingOptions = [
|
||||
{ value: '-created_at', label: t.ordering?.createdAtDesc || 'Newest First' },
|
||||
{ value: 'created_at', label: t.ordering?.createdAt || 'Oldest First' },
|
||||
@@ -57,10 +86,6 @@ export const Projects: React.FC = () => {
|
||||
{ value: '-name', label: t.ordering?.nameDesc || 'Name (Z-A)' },
|
||||
];
|
||||
|
||||
useEffect(() => {
|
||||
setCurrentPage(1);
|
||||
}, [search, ordering, isArchived, selectedClientIds]);
|
||||
|
||||
const fetchProjectList = async () => {
|
||||
if (!activeWorkspace) return;
|
||||
setLoading(true);
|
||||
@@ -74,8 +99,8 @@ export const Projects: React.FC = () => {
|
||||
is_archived: isArchived,
|
||||
ordering
|
||||
});
|
||||
const items = data?.results || (Array.isArray(data) ? data : [])
|
||||
const count = data?.count !== undefined ? data.count : items.length
|
||||
const items = data?.results || (Array.isArray(data) ? data : [])
|
||||
const count = data?.count !== undefined ? data.count : items.length
|
||||
setProjects(items);
|
||||
setTotalItems(count)
|
||||
} catch (error) {
|
||||
@@ -106,52 +131,52 @@ export const Projects: React.FC = () => {
|
||||
void fetchProjectList();
|
||||
}, 300);
|
||||
return () => clearTimeout(delayDebounceFn);
|
||||
}, [activeWorkspace, currentPage, limit, search, isArchived, ordering, selectedClientIds]);
|
||||
}, [activeWorkspace?.id, currentPage, limit, search, isArchived, ordering, selectedClientIdsKey]);
|
||||
|
||||
useEffect(() => {
|
||||
const handleCreated = () => void fetchProjectList();
|
||||
const handleUpdated = () => void fetchProjectList();
|
||||
|
||||
window.addEventListener("project_created", handleCreated);
|
||||
window.addEventListener("project_updated", handleUpdated);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener("project_created", handleCreated);
|
||||
window.removeEventListener("project_updated", handleUpdated);
|
||||
};
|
||||
}, [activeWorkspace, currentPage, limit, search, isArchived, ordering]);
|
||||
|
||||
|
||||
window.addEventListener("project_created", handleCreated);
|
||||
window.addEventListener("project_updated", handleUpdated);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener("project_created", handleCreated);
|
||||
window.removeEventListener("project_updated", handleUpdated);
|
||||
};
|
||||
}, [activeWorkspace?.id, currentPage, limit, search, isArchived, ordering, selectedClientIdsKey]);
|
||||
|
||||
const confirmDelete = async () => {
|
||||
if (!deleteModal.project) return;
|
||||
try {
|
||||
const deletedId = deleteModal.project.id;
|
||||
await deleteProject(deletedId);
|
||||
|
||||
fetchProjectList();
|
||||
|
||||
window.dispatchEvent(new CustomEvent('project_deleted', {
|
||||
detail: { id: deletedId }
|
||||
}));
|
||||
|
||||
toast.success(t.projects?.deleteSuccess || 'Project deleted successfully');
|
||||
setDeleteModal({ isOpen: false, project: null });
|
||||
setDeleteInput('');
|
||||
} catch (error) {
|
||||
toast.error(t.projects?.deleteError || 'Failed to delete project');
|
||||
}
|
||||
};
|
||||
|
||||
const deletedId = deleteModal.project.id;
|
||||
await deleteProject(deletedId);
|
||||
|
||||
fetchProjectList();
|
||||
|
||||
window.dispatchEvent(new CustomEvent('project_deleted', {
|
||||
detail: { id: deletedId }
|
||||
}));
|
||||
|
||||
toast.success(t.projects?.deleteSuccess || 'Project deleted successfully');
|
||||
setDeleteModal({ isOpen: false, project: null });
|
||||
setDeleteInput('');
|
||||
} catch (error) {
|
||||
toast.error(t.projects?.deleteError || 'Failed to delete project');
|
||||
}
|
||||
};
|
||||
|
||||
const formatDate = (dateStr: string | undefined) => {
|
||||
if (!dateStr) return "-"
|
||||
try {
|
||||
const date = new Date(dateStr)
|
||||
return new Intl.DateTimeFormat(lang === "fa" ? "fa-IR" : "en-US", {
|
||||
dateStyle: "long",
|
||||
timeZone: "Asia/Tehran",
|
||||
}).format(date)
|
||||
} catch {
|
||||
return dateStr
|
||||
}
|
||||
if (!dateStr) return "-"
|
||||
try {
|
||||
const date = new Date(dateStr)
|
||||
return new Intl.DateTimeFormat(lang === "fa" ? "fa-IR" : "en-US", {
|
||||
dateStyle: "long",
|
||||
timeZone: "Asia/Tehran",
|
||||
}).format(date)
|
||||
} catch {
|
||||
return dateStr
|
||||
}
|
||||
}
|
||||
|
||||
const sortedClients = useMemo(() => {
|
||||
@@ -159,14 +184,29 @@ export const Projects: React.FC = () => {
|
||||
const selected = clients.filter((client) => selectedClientIds.includes(client.id));
|
||||
const unselected = clients.filter((client) => !selectedClientIds.includes(client.id));
|
||||
return [...selected, ...unselected];
|
||||
}, [clients, selectedClientIds]);
|
||||
}, [clients, selectedClientIdsKey]);
|
||||
|
||||
const toggleClientFilter = (clientId: string) => {
|
||||
setCurrentPage(1);
|
||||
setSelectedClientIds((current) =>
|
||||
current.includes(clientId)
|
||||
? current.filter((id) => id !== clientId)
|
||||
: [...current, clientId],
|
||||
const nextClientIds = selectedClientIds.includes(clientId)
|
||||
? selectedClientIds.filter((id) => id !== clientId)
|
||||
: [...selectedClientIds, clientId];
|
||||
|
||||
updateListParams({ clients: nextClientIds, page: 1 });
|
||||
};
|
||||
|
||||
const updateListParams = (
|
||||
updates: Record<string, string | number | boolean | null | undefined | string[]>,
|
||||
) => {
|
||||
setSearchParams(
|
||||
(current) =>
|
||||
updateQueryParams(current, updates, {
|
||||
search: "",
|
||||
ordering: "-created_at",
|
||||
archived: false,
|
||||
page: 1,
|
||||
limit: 10,
|
||||
}),
|
||||
{ replace: true },
|
||||
);
|
||||
};
|
||||
|
||||
@@ -194,7 +234,7 @@ export const Projects: React.FC = () => {
|
||||
{canArchiveProject && (
|
||||
<Button
|
||||
variant={isArchived ? "default" : "secondary"}
|
||||
onClick={() => setIsArchived(!isArchived)}
|
||||
onClick={() => updateListParams({ archived: !isArchived, page: 1 })}
|
||||
className="flex-1 gap-2 shadow-sm sm:flex-none"
|
||||
>
|
||||
<Archive className="h-4 w-4" />
|
||||
@@ -218,9 +258,9 @@ export const Projects: React.FC = () => {
|
||||
<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">
|
||||
<FilterBar
|
||||
searchQuery={search}
|
||||
setSearchQuery={setSearch}
|
||||
setSearchQuery={(value) => updateListParams({ search: value, page: 1 })}
|
||||
ordering={ordering}
|
||||
setOrdering={setOrdering}
|
||||
setOrdering={(value) => updateListParams({ ordering: value, page: 1 })}
|
||||
orderingOptions={orderingOptions}
|
||||
searchPlaceholder={t.projects?.searchPlaceholder || 'Search projects...'}
|
||||
/>
|
||||
@@ -233,8 +273,7 @@ export const Projects: React.FC = () => {
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setCurrentPage(1);
|
||||
setSelectedClientIds([]);
|
||||
updateListParams({ clients: [], page: 1 });
|
||||
}}
|
||||
className="text-xs font-medium text-slate-500 transition hover:text-slate-900 dark:text-slate-400 dark:hover:text-white"
|
||||
>
|
||||
@@ -291,10 +330,11 @@ export const Projects: React.FC = () => {
|
||||
) : (
|
||||
<div className="flex flex-1 flex-col gap-6">
|
||||
{projects.length === 0 ? (
|
||||
<div className="flex flex-1 rounded-3xl border-2 border-dashed border-slate-200 bg-white p-12 text-center shadow-sm dark:border-slate-800 dark:bg-slate-900">
|
||||
<Building2 className="mx-auto mb-3 h-12 w-12 text-slate-300 dark:text-slate-700" />
|
||||
<p className="font-medium text-slate-500 dark:text-slate-400">{t.projects?.emptyState || 'No projects found'}</p>
|
||||
</div>
|
||||
<EmptyStateCard
|
||||
icon={Building2}
|
||||
title={t.projects?.emptyState || "No projects found"}
|
||||
description={t.projects?.noProjectsSearch || t.projects?.emptyState || "No projects found"}
|
||||
/>
|
||||
) : (
|
||||
<div className="grid grid-cols-1 gap-4 md:grid-cols-2 2xl:grid-cols-3">
|
||||
{projects.map((project) => {
|
||||
@@ -374,8 +414,8 @@ export const Projects: React.FC = () => {
|
||||
currentPage={currentPage}
|
||||
totalCount={totalItems}
|
||||
limit={limit}
|
||||
onPageChange={setCurrentPage}
|
||||
onLimitChange={setLimit}
|
||||
onPageChange={(page) => updateListParams({ page })}
|
||||
onLimitChange={(pageLimit) => updateListParams({ limit: pageLimit, page: 1 })}
|
||||
pageSizeOptions={[10, 20, 50]}
|
||||
/>
|
||||
</div>
|
||||
@@ -384,68 +424,68 @@ export const Projects: React.FC = () => {
|
||||
|
||||
{/* Modals */}
|
||||
{canCreateProject && isCreateModalOpen && (
|
||||
<ProjectCreateModal
|
||||
isOpen={isCreateModalOpen}
|
||||
onClose={() => setIsCreateModalOpen(false)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{canEditProject && editingProject && (
|
||||
<ProjectEditModal
|
||||
project={editingProject}
|
||||
isOpen={!!editingProject}
|
||||
onClose={() => setEditingProject(null)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{deleteModal.project && (
|
||||
<Modal
|
||||
isOpen={deleteModal.isOpen}
|
||||
onClose={() => {
|
||||
setDeleteModal({ isOpen: false, project: null });
|
||||
setDeleteInput('');
|
||||
}}
|
||||
title={t.projects?.deleteTitle || 'Delete Project'}
|
||||
maxWidth="max-w-md"
|
||||
footer={
|
||||
<>
|
||||
<Button
|
||||
variant="secondary"
|
||||
onClick={() => {
|
||||
setDeleteModal({ isOpen: false, project: null });
|
||||
setDeleteInput('');
|
||||
}}
|
||||
className="rounded-xl font-semibold"
|
||||
>
|
||||
{t.actions?.cancel || 'Cancel'}
|
||||
</Button>
|
||||
<Button
|
||||
variant="destructive"
|
||||
disabled={deleteInput !== deleteModal.project.name}
|
||||
onClick={confirmDelete}
|
||||
className="rounded-xl font-semibold"
|
||||
>
|
||||
{t.actions?.delete || 'Delete'}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div className="flex flex-col gap-4">
|
||||
<p className="text-slate-600 dark:text-slate-400 text-sm leading-relaxed">
|
||||
{t.projects?.deleteWarning || 'To confirm deletion, please type the project name:'} <strong className="text-slate-900 dark:text-white select-all">{deleteModal.project.name}</strong>
|
||||
</p>
|
||||
|
||||
<Input
|
||||
type="text"
|
||||
value={deleteInput}
|
||||
onChange={(e) => setDeleteInput(e.target.value)}
|
||||
placeholder={deleteModal.project.name}
|
||||
/>
|
||||
</div>
|
||||
</Modal>
|
||||
)}
|
||||
|
||||
</div>
|
||||
);
|
||||
|
||||
};
|
||||
<ProjectCreateModal
|
||||
isOpen={isCreateModalOpen}
|
||||
onClose={() => setIsCreateModalOpen(false)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{canEditProject && editingProject && (
|
||||
<ProjectEditModal
|
||||
project={editingProject}
|
||||
isOpen={!!editingProject}
|
||||
onClose={() => setEditingProject(null)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{deleteModal.project && (
|
||||
<Modal
|
||||
isOpen={deleteModal.isOpen}
|
||||
onClose={() => {
|
||||
setDeleteModal({ isOpen: false, project: null });
|
||||
setDeleteInput('');
|
||||
}}
|
||||
title={t.projects?.deleteTitle || 'Delete Project'}
|
||||
maxWidth="max-w-md"
|
||||
footer={
|
||||
<>
|
||||
<Button
|
||||
variant="secondary"
|
||||
onClick={() => {
|
||||
setDeleteModal({ isOpen: false, project: null });
|
||||
setDeleteInput('');
|
||||
}}
|
||||
className="rounded-xl font-semibold"
|
||||
>
|
||||
{t.actions?.cancel || 'Cancel'}
|
||||
</Button>
|
||||
<Button
|
||||
variant="destructive"
|
||||
disabled={deleteInput !== deleteModal.project.name}
|
||||
onClick={confirmDelete}
|
||||
className="rounded-xl font-semibold"
|
||||
>
|
||||
{t.actions?.delete || 'Delete'}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div className="flex flex-col gap-4">
|
||||
<p className="text-slate-600 dark:text-slate-400 text-sm leading-relaxed">
|
||||
{t.projects?.deleteWarning || 'To confirm deletion, please type the project name:'} <strong className="text-slate-900 dark:text-white select-all">{deleteModal.project.name}</strong>
|
||||
</p>
|
||||
|
||||
<Input
|
||||
type="text"
|
||||
value={deleteInput}
|
||||
onChange={(e) => setDeleteInput(e.target.value)}
|
||||
placeholder={deleteModal.project.name}
|
||||
/>
|
||||
</div>
|
||||
</Modal>
|
||||
)}
|
||||
|
||||
</div>
|
||||
);
|
||||
|
||||
};
|
||||
|
||||
115
src/pages/RateLimit.tsx
Normal file
115
src/pages/RateLimit.tsx
Normal file
@@ -0,0 +1,115 @@
|
||||
import { useEffect, useMemo, useState } from "react"
|
||||
import { useNavigate } from "react-router-dom"
|
||||
import { AlertTriangle, Clock3 } from "lucide-react"
|
||||
import { Button } from "../components/ui/button"
|
||||
import { useTranslation } from "../hooks/useTranslation"
|
||||
import {
|
||||
clearRateLimitLock,
|
||||
getRateLimitRemainingSeconds,
|
||||
getStoredRateLimitLock,
|
||||
} from "../lib/rateLimit"
|
||||
|
||||
const PERSIAN_DIGITS = ["۰", "۱", "۲", "۳", "۴", "۵", "۶", "۷", "۸", "۹"]
|
||||
|
||||
const toPersianDigits = (value: string) =>
|
||||
value.replace(/\d/g, (digit) => PERSIAN_DIGITS[Number.parseInt(digit, 10)] ?? digit)
|
||||
|
||||
export default function RateLimitPage() {
|
||||
const navigate = useNavigate()
|
||||
const { t, lang } = useTranslation()
|
||||
const isRtl = lang === "fa"
|
||||
|
||||
const initialLock = getStoredRateLimitLock()
|
||||
const [returnTo] = useState(initialLock?.returnTo || "/")
|
||||
const [status] = useState(initialLock?.status ?? 429)
|
||||
const [message] = useState(initialLock?.message || t.rateLimit.message)
|
||||
const [remainingSeconds, setRemainingSeconds] = useState(getRateLimitRemainingSeconds(initialLock))
|
||||
|
||||
useEffect(() => {
|
||||
if (!initialLock) {
|
||||
navigate(returnTo, { replace: true })
|
||||
return
|
||||
}
|
||||
|
||||
const timer = window.setInterval(() => {
|
||||
const currentLock = getStoredRateLimitLock()
|
||||
setRemainingSeconds(getRateLimitRemainingSeconds(currentLock))
|
||||
}, 1000)
|
||||
|
||||
return () => window.clearInterval(timer)
|
||||
}, [initialLock, navigate, returnTo])
|
||||
|
||||
const localizedDigits = (value: string) => (isRtl ? toPersianDigits(value) : value)
|
||||
|
||||
const countdown = useMemo(() => {
|
||||
const minutes = Math.floor(remainingSeconds / 60)
|
||||
const seconds = remainingSeconds % 60
|
||||
const base =
|
||||
minutes > 0
|
||||
? `${minutes}:${seconds.toString().padStart(2, "0")}`
|
||||
: `${seconds}s`
|
||||
|
||||
return localizedDigits(base)
|
||||
}, [isRtl, remainingSeconds])
|
||||
|
||||
const handleContinue = () => {
|
||||
clearRateLimitLock()
|
||||
navigate(returnTo, { replace: true })
|
||||
}
|
||||
|
||||
const isCoolingDown = remainingSeconds > 0
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-slate-50 px-4 py-10 text-slate-900 dark:bg-slate-950 dark:text-slate-100">
|
||||
<div className="mx-auto flex min-h-[calc(100vh-5rem)] max-w-2xl items-center justify-center">
|
||||
<div className="w-full rounded-3xl border border-slate-200 bg-white p-8 shadow-sm dark:border-slate-800 dark:bg-slate-900 sm:p-10">
|
||||
<div className="mb-6 flex items-center justify-center">
|
||||
<div className="flex h-16 w-16 items-center justify-center rounded-2xl bg-amber-100 text-amber-700 dark:bg-amber-950/50 dark:text-amber-300">
|
||||
<AlertTriangle className="h-8 w-8" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4 text-center">
|
||||
<p className="text-sm font-medium uppercase tracking-[0.3em] text-amber-600 dark:text-amber-300">
|
||||
{t.rateLimit.eyebrow}
|
||||
</p>
|
||||
<h1 className="text-3xl font-semibold tracking-tight">
|
||||
{t.rateLimit.title}
|
||||
</h1>
|
||||
<p className="text-sm text-slate-500 dark:text-slate-400 sm:text-base">
|
||||
{t.rateLimit.message}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="mt-8 grid gap-4">
|
||||
<div className="rounded-2xl border border-slate-200 bg-slate-50 p-5 text-start dark:border-slate-800 dark:bg-slate-950/60">
|
||||
<div className="flex items-center gap-2 text-slate-500 dark:text-slate-400">
|
||||
<Clock3 className="h-4 w-4" />
|
||||
<p className="text-xs font-medium uppercase tracking-[0.2em]">
|
||||
{t.rateLimit.cooldownLabel}
|
||||
</p>
|
||||
</div>
|
||||
<p className="mt-2 text-2xl font-semibold">
|
||||
{isCoolingDown ? countdown : t.rateLimit.ready}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-8 rounded-2xl border border-dashed border-slate-200 bg-slate-50/70 p-4 text-sm text-slate-600 dark:border-slate-800 dark:bg-slate-950/50 dark:text-slate-300">
|
||||
{isCoolingDown ? t.rateLimit.waitingMessage(countdown) : t.rateLimit.finishedMessage}
|
||||
</div>
|
||||
|
||||
<div className="mt-8 flex justify-center">
|
||||
<Button
|
||||
onClick={handleContinue}
|
||||
disabled={isCoolingDown}
|
||||
className="h-11 min-w-52"
|
||||
>
|
||||
{isCoolingDown ? t.rateLimit.continueCooldown(countdown) : t.rateLimit.continue}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { useSearchParams } from "react-router-dom";
|
||||
import { BarChart3, Table2 } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
@@ -21,6 +22,12 @@ import { ReportsFilterBar, type ReportsFilterDraft } from "../components/reports
|
||||
import { ReportsTablePanel } from "../components/reports/ReportsTablePanel";
|
||||
import { useWorkspace } from "../context/WorkspaceContext";
|
||||
import { useTranslation } from "../hooks/useTranslation";
|
||||
import {
|
||||
DEFAULT_REPORTS_FILTERS,
|
||||
readReportsFiltersFromParams,
|
||||
writeReportsFiltersToParams,
|
||||
} from "../lib/reportFilters";
|
||||
import { readStringParam, updateQueryParams } from "../lib/queryParams";
|
||||
import { canWorkspace, WORKSPACE_MEMBERS_VIEW } from "../lib/permissions";
|
||||
|
||||
type Tab = "chart" | "table";
|
||||
@@ -86,7 +93,8 @@ const getCurrentLanguageAwareMonthRange = (lang: "en" | "fa") => {
|
||||
export default function Reports() {
|
||||
const { t, lang } = useTranslation();
|
||||
const { activeWorkspace } = useWorkspace();
|
||||
const [tab, setTab] = useState<Tab>("chart");
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
const tab = (readStringParam(searchParams, "tab", "chart") as Tab);
|
||||
const [projects, setProjects] = useState<Project[]>([]);
|
||||
const [clients, setClients] = useState<{ id: string; name: string }[]>([]);
|
||||
const [tags, setTags] = useState<Tag[]>([]);
|
||||
@@ -105,16 +113,10 @@ export default function Reports() {
|
||||
const canSelectUsers = canWorkspace(activeWorkspace?.my_role, WORKSPACE_MEMBERS_VIEW);
|
||||
const isWorkspaceRoleResolved = Boolean(activeWorkspace?.my_role);
|
||||
const showUserFilterLoading = !isWorkspaceRoleResolved || (canSelectUsers && isLoadingUsers);
|
||||
|
||||
const [filters, setFilters] = useState<ReportsFilterDraft>({
|
||||
period: "this_month",
|
||||
from_date: "",
|
||||
to_date: "",
|
||||
user: "",
|
||||
client: "",
|
||||
project: "",
|
||||
tags: [],
|
||||
});
|
||||
const filters = useMemo<ReportsFilterDraft>(
|
||||
() => readReportsFiltersFromParams(searchParams),
|
||||
[searchParams],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!activeWorkspace?.id) return;
|
||||
@@ -177,6 +179,7 @@ export default function Reports() {
|
||||
};
|
||||
|
||||
const apiFilters = useMemo<ReportFilters | null>(() => buildApiFilters(filters), [activeWorkspace?.id, canSelectUsers, filters, lang]);
|
||||
const apiFiltersKey = apiFilters ? JSON.stringify(apiFilters) : "";
|
||||
|
||||
const runReportLoad = async (nextFilters: ReportFilters) => {
|
||||
setIsLoading(true);
|
||||
@@ -199,8 +202,7 @@ export default function Reports() {
|
||||
useEffect(() => {
|
||||
if (!apiFilters) return;
|
||||
void runReportLoad(apiFilters);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [apiFilters?.workspace]);
|
||||
}, [apiFilters, apiFiltersKey]);
|
||||
|
||||
const handleToggleDay = async (day: string) => {
|
||||
if (!apiFilters) return;
|
||||
@@ -283,7 +285,12 @@ export default function Reports() {
|
||||
<div className="grid w-full grid-cols-2 rounded-2xl border border-slate-200 bg-slate-50 p-1 dark:border-slate-800 dark:bg-slate-950 lg:w-auto">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setTab("chart")}
|
||||
onClick={() =>
|
||||
setSearchParams(
|
||||
(current) => updateQueryParams(current, { tab: "chart" }, { tab: "chart" }),
|
||||
{ replace: true },
|
||||
)
|
||||
}
|
||||
className={`inline-flex h-11 items-center justify-center gap-2 rounded-xl px-4 text-sm font-medium transition ${
|
||||
tab === "chart"
|
||||
? "bg-white text-slate-900 shadow-sm dark:bg-slate-900 dark:text-white"
|
||||
@@ -295,7 +302,12 @@ export default function Reports() {
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setTab("table")}
|
||||
onClick={() =>
|
||||
setSearchParams(
|
||||
(current) => updateQueryParams(current, { tab: "table" }, { tab: "chart" }),
|
||||
{ replace: true },
|
||||
)
|
||||
}
|
||||
className={`inline-flex h-11 items-center justify-center gap-2 rounded-xl px-4 text-sm font-medium transition ${
|
||||
tab === "table"
|
||||
? "bg-white text-slate-900 shadow-sm dark:bg-slate-900 dark:text-white"
|
||||
@@ -311,12 +323,12 @@ export default function Reports() {
|
||||
|
||||
<ReportsFilterBar
|
||||
value={filters}
|
||||
onApply={(draft) => {
|
||||
setFilters(draft);
|
||||
const nextFilters = buildApiFilters(draft);
|
||||
if (!nextFilters) return;
|
||||
void runReportLoad(nextFilters);
|
||||
}}
|
||||
onApply={(draft) =>
|
||||
setSearchParams(
|
||||
(current) => writeReportsFiltersToParams(current, draft),
|
||||
{ replace: true },
|
||||
)
|
||||
}
|
||||
projects={projects}
|
||||
clients={clients}
|
||||
tags={tags}
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { useSearchParams } from "react-router-dom";
|
||||
import { Edit2, Plus, Tag as TagIcon, Trash2 } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import { createTag, deleteTag, getTags, type Tag, updateTag } from "../api/tags";
|
||||
import EmptyStateCard from "../components/EmptyStateCard";
|
||||
import { useAppContext } from "../context/AppContext";
|
||||
import { useWorkspace } from "../context/WorkspaceContext";
|
||||
import { useTranslation } from "../hooks/useTranslation";
|
||||
@@ -14,6 +16,7 @@ import { Pagination } from "../components/Pagination";
|
||||
import { Button } from "../components/ui/button";
|
||||
import { Card, CardContent, CardTitle } from "../components/ui/card";
|
||||
import { Input } from "../components/ui/input";
|
||||
import { readNumberParam, readStringParam, updateQueryParams } from "../lib/queryParams";
|
||||
|
||||
const DEFAULT_COLOR = "#3B82F6";
|
||||
|
||||
@@ -24,14 +27,15 @@ export default function Tags() {
|
||||
const workspaceRole = activeWorkspace?.my_role;
|
||||
const canCreateTag = canWorkspace(workspaceRole, TAGS_CREATE);
|
||||
const canEditTag = canWorkspace(workspaceRole, TAGS_EDIT);
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
|
||||
const [tags, setTags] = useState<Tag[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
const [ordering, setOrdering] = useState("-updated_at");
|
||||
const [currentPage, setCurrentPage] = useState(1);
|
||||
const [totalItems, setTotalItems] = useState(0);
|
||||
const [limit, setLimit] = useState(10);
|
||||
const searchQuery = readStringParam(searchParams, "search", "");
|
||||
const ordering = readStringParam(searchParams, "ordering", "-updated_at");
|
||||
const currentPage = Math.max(1, readNumberParam(searchParams, "page", 1));
|
||||
const limit = Math.max(1, readNumberParam(searchParams, "limit", 10));
|
||||
|
||||
const [isModalOpen, setIsModalOpen] = useState(false);
|
||||
const [editingTag, setEditingTag] = useState<Tag | null>(null);
|
||||
@@ -48,10 +52,6 @@ export default function Tags() {
|
||||
{ value: "-name", label: t.ordering?.nameDesc || "Name (Z-A)" },
|
||||
];
|
||||
|
||||
useEffect(() => {
|
||||
setCurrentPage(1);
|
||||
}, [searchQuery, ordering]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!activeWorkspace?.id) return;
|
||||
|
||||
@@ -140,6 +140,19 @@ export default function Tags() {
|
||||
}
|
||||
};
|
||||
|
||||
const updateListParams = (updates: Record<string, string | number | null | undefined>) => {
|
||||
setSearchParams(
|
||||
(current) =>
|
||||
updateQueryParams(current, updates, {
|
||||
search: "",
|
||||
ordering: "-updated_at",
|
||||
page: 1,
|
||||
limit: 10,
|
||||
}),
|
||||
{ replace: true },
|
||||
);
|
||||
};
|
||||
|
||||
if (!activeWorkspace) {
|
||||
return (
|
||||
<div className="mx-auto max-w-7xl p-4 md:p-6">
|
||||
@@ -172,88 +185,94 @@ export default function Tags() {
|
||||
<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">
|
||||
<FilterBar
|
||||
searchQuery={searchQuery}
|
||||
setSearchQuery={setSearchQuery}
|
||||
setSearchQuery={(value) => updateListParams({ search: value, page: 1 })}
|
||||
ordering={ordering}
|
||||
setOrdering={setOrdering}
|
||||
setOrdering={(value) => updateListParams({ ordering: value, page: 1 })}
|
||||
orderingOptions={orderingOptions}
|
||||
searchPlaceholder={t.tags?.searchPlaceholder || "Search tags..."}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{isLoading ? (
|
||||
<ListPageSkeleton variant="dense-grid" />
|
||||
<ListPageSkeleton variant="list" />
|
||||
) : (
|
||||
<div className="flex flex-1 flex-col gap-6">
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2 xl:grid-cols-3 2xl:grid-cols-4">
|
||||
{tags.map((tag) => {
|
||||
const canDeleteTag = canDeleteWorkspaceResource({
|
||||
workspaceRole,
|
||||
currentUserId: user?.id,
|
||||
createdById: tag.created_by?.id,
|
||||
});
|
||||
return (
|
||||
<Card key={tag.id} className="overflow-hidden shadow-sm dark:border-slate-700 dark:bg-slate-800">
|
||||
<CardContent className="flex h-full flex-col gap-4 p-5">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="flex min-w-0 items-center gap-3">
|
||||
<div
|
||||
className="h-9 w-9 shrink-0 rounded-xl border border-slate-200 dark:border-slate-700"
|
||||
style={{ backgroundColor: tag.color || DEFAULT_COLOR }}
|
||||
/>
|
||||
<div className="min-w-0">
|
||||
<CardTitle className="truncate text-base text-slate-900 dark:text-white">{tag.name}</CardTitle>
|
||||
</div>
|
||||
</div>
|
||||
{tags.length === 0 ? (
|
||||
<EmptyStateCard
|
||||
icon={TagIcon}
|
||||
title={t.tags?.emptyState || "No tags found"}
|
||||
description={searchQuery ? t.tags?.noTagsSearch : t.tags?.emptyState || "No tags found"}
|
||||
/>
|
||||
) : (
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2 xl:grid-cols-3 2xl:grid-cols-4">
|
||||
{tags.map((tag) => {
|
||||
const canDeleteTag = canDeleteWorkspaceResource({
|
||||
workspaceRole,
|
||||
currentUserId: user?.id,
|
||||
createdById: tag.created_by?.id,
|
||||
});
|
||||
|
||||
{(canEditTag || canDeleteTag) && (
|
||||
<div className="flex shrink-0 items-center gap-1">
|
||||
{canEditTag && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => openEditModal(tag)}
|
||||
className="h-8 w-8 text-slate-400 hover:bg-blue-50 hover:text-blue-600 dark:hover:bg-blue-900/20 dark:hover:text-blue-400"
|
||||
title={t.actions?.edit || "Edit"}
|
||||
>
|
||||
<Edit2 className="w-4 h-4" />
|
||||
</Button>
|
||||
)}
|
||||
{canDeleteTag && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => setDeleteModal({ isOpen: true, tag })}
|
||||
className="h-8 w-8 text-slate-400 hover:bg-red-50 hover:text-red-600 dark:hover:bg-red-900/20 dark:hover:text-red-400"
|
||||
title={t.actions?.delete || "Delete"}
|
||||
>
|
||||
<Trash2 className="w-4 h-4" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
})}
|
||||
return (
|
||||
<Card
|
||||
key={tag.id}
|
||||
className="flex flex-col text-slate-800 shadow-sm dark:border-slate-700 dark:bg-slate-800 dark:text-slate-100"
|
||||
>
|
||||
<CardContent className="flex h-full flex-col justify-between gap-4 px-5 py-4">
|
||||
<div className="flex min-w-0 items-start justify-between gap-3">
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-center gap-3">
|
||||
<div
|
||||
className="h-9 w-9 shrink-0 rounded-lg border border-slate-200 dark:border-slate-700"
|
||||
style={{ backgroundColor: tag.color || DEFAULT_COLOR }}
|
||||
/>
|
||||
<CardTitle className="text-lg line-clamp-1">{tag.name}</CardTitle>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{tags.length === 0 && (
|
||||
<div className="col-span-full flex flex-1 flex-col items-center justify-center rounded-3xl border-2 border-dashed border-slate-200 bg-white py-16 text-slate-500 shadow-sm dark:border-slate-800 dark:bg-slate-900 dark:text-slate-400">
|
||||
<TagIcon className="w-10 h-10 mb-3" />
|
||||
<p className="font-medium">{t.tags?.emptyState || "No tags found"}</p>
|
||||
{(canEditTag || canDeleteTag) && (
|
||||
<div className="flex shrink-0 items-center gap-2">
|
||||
{canDeleteTag && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => setDeleteModal({ isOpen: true, tag })}
|
||||
className="h-8 w-8 text-slate-400 hover:bg-red-50 hover:text-red-600 dark:hover:bg-red-900/20 dark:hover:text-red-400"
|
||||
title={t.actions?.delete || "Delete"}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{canEditTag && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => openEditModal(tag)}
|
||||
className="h-8 w-8 text-slate-400 hover:bg-blue-50 hover:text-blue-600 dark:hover:bg-blue-900/20 dark:hover:text-blue-400"
|
||||
title={t.actions?.edit || "Edit"}
|
||||
>
|
||||
<Edit2 className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Pagination
|
||||
currentPage={currentPage}
|
||||
totalCount={totalItems}
|
||||
limit={limit}
|
||||
onPageChange={setCurrentPage}
|
||||
onLimitChange={setLimit}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<Pagination
|
||||
currentPage={currentPage}
|
||||
totalCount={totalItems}
|
||||
limit={limit}
|
||||
onPageChange={(page) => updateListParams({ page })}
|
||||
onLimitChange={(pageLimit) => updateListParams({ limit: pageLimit, page: 1 })}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Modal
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,6 +1,6 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { Plus, Trash2, Pencil, Eye } from 'lucide-react';
|
||||
import { useNavigate, useSearchParams } from 'react-router-dom';
|
||||
import { Plus, Trash2, Pencil, Eye, LayoutDashboard } from 'lucide-react';
|
||||
import { toast } from 'sonner';
|
||||
import { fetchWorkspaces, deleteWorkspace, type Workspace } from '../api/workspaces';
|
||||
import { useTranslation } from '../hooks/useTranslation';
|
||||
@@ -11,12 +11,14 @@ import {
|
||||
type WorkspaceRole,
|
||||
} from '../lib/permissions';
|
||||
import FilterBar from '../components/FilterBar';
|
||||
import EmptyStateCard from '../components/EmptyStateCard';
|
||||
import { ListPageSkeleton } from '../components/ListPageSkeleton';
|
||||
import { Button } from '../components/ui/button';
|
||||
import { Button } from '../components/ui/button';
|
||||
import { Input } from '../components/ui/input';
|
||||
import { Card, CardContent, CardTitle } from '../components/ui/card';
|
||||
import { Pagination } from '../components/Pagination';
|
||||
import { Modal } from '../components/Modal';
|
||||
import { readNumberParam, readStringParam, updateQueryParams } from '../lib/queryParams';
|
||||
|
||||
const RoleBadge = ({ role }: { role?: WorkspaceRole }) => {
|
||||
const { t } = useTranslation();
|
||||
@@ -39,18 +41,18 @@ const RoleBadge = ({ role }: { role?: WorkspaceRole }) => {
|
||||
export default function Workspaces() {
|
||||
const [workspaces, setWorkspaces] = useState<Workspace[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const [ordering, setOrdering] = useState('-created_at');
|
||||
|
||||
const [currentPage, setCurrentPage] = useState(1);
|
||||
const [totalItems, setTotalItems] = useState(0);
|
||||
const [limit, setLimit] = useState(10);
|
||||
|
||||
const [deleteModal, setDeleteModal] = useState<{isOpen: boolean; workspace: Workspace | null}>({isOpen: false, workspace: null});
|
||||
const [deleteInput, setDeleteInput] = useState('');
|
||||
|
||||
const navigate = useNavigate();
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
const { t } = useTranslation();
|
||||
const searchQuery = readStringParam(searchParams, 'search', '');
|
||||
const ordering = readStringParam(searchParams, 'ordering', '-created_at');
|
||||
const currentPage = Math.max(1, readNumberParam(searchParams, 'page', 1));
|
||||
const limit = Math.max(1, readNumberParam(searchParams, 'limit', 10));
|
||||
|
||||
const orderingOptions = [
|
||||
{ value: '-created_at', label: t.ordering?.createdAtDesc || 'Newest First' },
|
||||
@@ -60,10 +62,6 @@ export default function Workspaces() {
|
||||
{ value: '-updated_at', label: t.ordering?.updatedAtDesc || 'Recently Updated' },
|
||||
];
|
||||
|
||||
useEffect(() => {
|
||||
setCurrentPage(1);
|
||||
}, [searchQuery, ordering]);
|
||||
|
||||
useEffect(() => {
|
||||
const timer = setTimeout(() => {
|
||||
loadWorkspaces();
|
||||
@@ -116,58 +114,73 @@ export default function Workspaces() {
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="mx-auto flex min-h-full max-w-7xl flex-col p-4 md:p-6">
|
||||
<div className="flex flex-1 flex-col gap-5">
|
||||
<div className="rounded-3xl border border-slate-200 bg-white p-5 shadow-sm dark:border-slate-800 dark:bg-slate-900 sm:p-6">
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-slate-900 dark:text-white">{t.workspace?.title || 'Workspaces'}</h1>
|
||||
<p className="mt-1 text-sm text-slate-500 dark:text-slate-400">{t.workspace?.subtitle || 'Manage your workspaces'}</p>
|
||||
</div>
|
||||
<Button
|
||||
onClick={() => navigate('/workspaces/create')}
|
||||
size="icon"
|
||||
className="shrink-0 shadow-sm"
|
||||
title={t.workspace?.createNew || 'Create New'}
|
||||
>
|
||||
<Plus className="h-5 w-5" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<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">
|
||||
<FilterBar
|
||||
searchQuery={searchQuery}
|
||||
setSearchQuery={setSearchQuery}
|
||||
ordering={ordering}
|
||||
setOrdering={setOrdering}
|
||||
orderingOptions={orderingOptions}
|
||||
searchPlaceholder={t.workspace?.searchPlaceholder || 'Search...'}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{isLoading ? (
|
||||
<ListPageSkeleton variant="list" />
|
||||
) : (
|
||||
<div className="flex flex-1 flex-col gap-6">
|
||||
<div className="flex flex-1 flex-col gap-4">
|
||||
{workspaces.map((workspace) => {
|
||||
const canDeleteWorkspace = canWorkspace(workspace.my_role, WORKSPACE_DELETE);
|
||||
const canEditWorkspace = canWorkspace(workspace.my_role, WORKSPACE_EDIT);
|
||||
const updateListParams = (updates: Record<string, string | number | null | undefined>) => {
|
||||
setSearchParams(
|
||||
(current) =>
|
||||
updateQueryParams(current, updates, {
|
||||
search: '',
|
||||
ordering: '-created_at',
|
||||
page: 1,
|
||||
limit: 10,
|
||||
}),
|
||||
{ replace: true },
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="mx-auto flex min-h-full max-w-7xl flex-col p-4 md:p-6">
|
||||
<div className="flex flex-1 flex-col gap-5">
|
||||
<div className="rounded-3xl border border-slate-200 bg-white p-5 shadow-sm dark:border-slate-800 dark:bg-slate-900 sm:p-6">
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-slate-900 dark:text-white">{t.workspace?.title || 'Workspaces'}</h1>
|
||||
<p className="mt-1 text-sm text-slate-500 dark:text-slate-400">{t.workspace?.subtitle || 'Manage your workspaces'}</p>
|
||||
</div>
|
||||
<Button
|
||||
onClick={() => navigate('/workspaces/create')}
|
||||
size="icon"
|
||||
className="shrink-0 shadow-sm"
|
||||
title={t.workspace?.createNew || 'Create New'}
|
||||
>
|
||||
<Plus className="h-5 w-5" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<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">
|
||||
<FilterBar
|
||||
searchQuery={searchQuery}
|
||||
setSearchQuery={(value) => updateListParams({ search: value, page: 1 })}
|
||||
ordering={ordering}
|
||||
setOrdering={(value) => updateListParams({ ordering: value, page: 1 })}
|
||||
orderingOptions={orderingOptions}
|
||||
searchPlaceholder={t.workspace?.searchPlaceholder || 'Search...'}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{isLoading ? (
|
||||
<ListPageSkeleton variant="list" />
|
||||
) : (
|
||||
<div className="flex flex-1 flex-col gap-6">
|
||||
<div className="flex flex-1 flex-col gap-4">
|
||||
{workspaces.map((workspace) => {
|
||||
const canDeleteWorkspace = canWorkspace(workspace.my_role, WORKSPACE_DELETE);
|
||||
const canEditWorkspace = canWorkspace(workspace.my_role, WORKSPACE_EDIT);
|
||||
|
||||
return (
|
||||
<Card key={workspace.id} className="flex flex-col text-slate-800 dark:text-slate-100 dark:bg-slate-800 dark:border-slate-700 shadow-sm">
|
||||
<CardContent className="flex flex-col sm:flex-row items-start sm:items-center justify-between py-4 px-6 gap-4">
|
||||
<div className="flex-1">
|
||||
<div className="flex items-center gap-3 mb-2">
|
||||
<div className="h-9 w-9 shrink-0 overflow-hidden rounded-lg bg-slate-100 dark:bg-slate-600 flex items-center justify-center text-sm font-semibold text-slate-700 dark:text-slate-200">
|
||||
{workspace.thumbnail ? (
|
||||
{workspace.thumbnail ? (
|
||||
<div className="h-9 w-9 shrink-0 overflow-hidden rounded-lg flex items-center justify-center text-sm font-semibold text-slate-700 dark:text-slate-200">
|
||||
<img src={workspace.thumbnail} alt={workspace.name} className="h-full w-full object-cover" />
|
||||
) : (
|
||||
workspace.name.trim().charAt(0).toUpperCase() || "W"
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="h-9 w-9 shrink-0 overflow-hidden rounded-lg bg-slate-100 dark:bg-slate-600 flex items-center justify-center text-sm font-semibold text-slate-700 dark:text-slate-200">
|
||||
{workspace.name.trim().charAt(0).toUpperCase() || "W"}
|
||||
</div>
|
||||
)}
|
||||
<CardTitle className="text-lg line-clamp-1">
|
||||
{workspace.name}
|
||||
</CardTitle>
|
||||
@@ -215,31 +228,31 @@ export default function Workspaces() {
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
})}
|
||||
|
||||
})}
|
||||
|
||||
{workspaces.length === 0 && (
|
||||
<div className="flex flex-1 rounded-3xl border-2 border-dashed border-slate-200 bg-white py-16 shadow-sm dark:border-slate-800 dark:bg-slate-900">
|
||||
<div className="flex flex-col items-center justify-center">
|
||||
<p className="text-slate-500 dark:text-slate-400 font-medium">{t.workspace?.emptyState || 'No workspaces found'}</p>
|
||||
</div>
|
||||
</div>
|
||||
<EmptyStateCard
|
||||
icon={LayoutDashboard}
|
||||
title={t.workspace.noWorkspace}
|
||||
description={searchQuery ? t.workspace.noWorkspaceSearch : t.workspace?.emptyState || t.workspace.noWorkspace}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Pagination
|
||||
</div>
|
||||
|
||||
<Pagination
|
||||
currentPage={currentPage}
|
||||
totalCount={totalItems}
|
||||
limit={limit}
|
||||
onPageChange={setCurrentPage}
|
||||
onLimitChange={setLimit}
|
||||
pageSizeOptions={[10, 20, 50]}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{deleteModal.workspace && (
|
||||
<Modal
|
||||
onPageChange={(page) => updateListParams({ page })}
|
||||
onLimitChange={(pageLimit) => updateListParams({ limit: pageLimit, page: 1 })}
|
||||
pageSizeOptions={[10, 20, 50]}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{deleteModal.workspace && (
|
||||
<Modal
|
||||
isOpen={deleteModal.isOpen}
|
||||
onClose={() => {
|
||||
setDeleteModal({ isOpen: false, workspace: null });
|
||||
|
||||
Reference in New Issue
Block a user