Compare commits
No commits in common. "ac10c461e4f770d622fd0d9fa15faca0f75b3abe" and "d285ea88d855509f4794cba378df82217c7db719" have entirely different histories.
ac10c461e4
...
d285ea88d8
@ -1,27 +0,0 @@
|
|||||||
#Local
|
|
||||||
VITE_PUBLIC_VAPID_KEY=BBb78N3tSTEw6mPbBmvEDX2bhYEDKPc_zffL-vxPV8FBSmR1qSpy9gdV8zt-WFF-q2NPpVmL4BhbUzLSHVAPjcI
|
|
||||||
VITE_BASE_URL=http://localhost:3000
|
|
||||||
VITE_API_BASE_URL=http://localhost:3000/api/v1
|
|
||||||
VITE_OKTA_CLIENT_ID=0oa18b98aari6I6eo2p8
|
|
||||||
VITE_OKTA_DOMAIN=https://royalenfield.okta.com
|
|
||||||
|
|
||||||
#Development
|
|
||||||
# VITE_PUBLIC_VAPID_KEY=BBb78N3tSTEw6mPbBmvEDX2bhYEDKPc_zffL-vxPV8FBSmR1qSpy9gdV8zt-WFF-q2NPpVmL4BhbUzLSHVAPjcI
|
|
||||||
# VITE_BASE_URL=https://re-workflow-nt-dev.siplsolutions.com
|
|
||||||
# VITE_API_BASE_URL=https://re-workflow-nt-dev.siplsolutions.com/api/v1
|
|
||||||
# VITE_OKTA_CLIENT_ID=0oa18b98aari6I6eo2p8
|
|
||||||
# VITE_OKTA_DOMAIN=https://royalenfield.okta.com
|
|
||||||
|
|
||||||
#Uat
|
|
||||||
# VITE_PUBLIC_VAPID_KEY=BBb78N3tSTEw6mPbBmvEDX2bhYEDKPc_zffL-vxPV8FBSmR1qSpy9gdV8zt-WFF-q2NPpVmL4BhbUzLSHVAPjcI
|
|
||||||
# VITE_BASE_URL=https://reflow-uat.royalenfield.com
|
|
||||||
# VITE_API_BASE_URL=https://reflow-uat.royalenfield.com/api/v1/
|
|
||||||
# VITE_OKTA_CLIENT_ID=0oa2jgzvrpdwx2iqd0h8
|
|
||||||
# VITE_OKTA_DOMAIN=https://dev-830839.oktapreview.com
|
|
||||||
|
|
||||||
#Production
|
|
||||||
# VITE_PUBLIC_VAPID_KEY=BBb78N3tSTEw6mPbBmvEDX2bhYEDKPc_zffL-vxPV8FBSmR1qSpy9gdV8zt-WFF-q2NPpVmL4BhbUzLSHVAPjcI
|
|
||||||
# VITE_BASE_URL=https://reflow.royalenfield.com
|
|
||||||
# VITE_API_BASE_URL=https://reflow.royalenfield.com/api/v1
|
|
||||||
# VITE_OKTA_CLIENT_ID=0oa18b98aari6I6eo2p8
|
|
||||||
# VITE_OKTA_DOMAIN=https://royalenfield.okta.com
|
|
||||||
@ -10,7 +10,7 @@
|
|||||||
<meta name="theme-color" content="#2d4a3e" />
|
<meta name="theme-color" content="#2d4a3e" />
|
||||||
<title>Royal Enfield | Approval Portal</title>
|
<title>Royal Enfield | Approval Portal</title>
|
||||||
|
|
||||||
<!-- Preload essential fonts and icons -->
|
<!-- Preload critical fonts and icons -->
|
||||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||||
</head>
|
</head>
|
||||||
|
|||||||
@ -1,4 +0,0 @@
|
|||||||
User-agent: *
|
|
||||||
Disallow: /api/
|
|
||||||
|
|
||||||
Sitemap: https://reflow.royalenfield.com/sitemap.xml
|
|
||||||
@ -1,9 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
|
|
||||||
<url>
|
|
||||||
<loc>https://reflow.royalenfield.com</loc>
|
|
||||||
<lastmod>2024-03-20T12:00:00+00:00</lastmod>
|
|
||||||
<changefreq>daily</changefreq>
|
|
||||||
<priority>1.0</priority>
|
|
||||||
</url>
|
|
||||||
</urlset>
|
|
||||||
259
src/App.tsx
259
src/App.tsx
@ -10,7 +10,7 @@ import { SharedSummaryDetail } from '@/pages/SharedSummaries/SharedSummaryDetail
|
|||||||
import { WorkNotes } from '@/pages/WorkNotes';
|
import { WorkNotes } from '@/pages/WorkNotes';
|
||||||
import { CreateRequest } from '@/pages/CreateRequest';
|
import { CreateRequest } from '@/pages/CreateRequest';
|
||||||
import { ClaimManagementWizard } from '@/dealer-claim/components/request-creation/ClaimManagementWizard';
|
import { ClaimManagementWizard } from '@/dealer-claim/components/request-creation/ClaimManagementWizard';
|
||||||
// import { DealerDashboard } from '@/dealer-claim/pages/Dashboard';
|
import { DealerDashboard } from '@/dealer-claim/pages/Dashboard';
|
||||||
import { MyRequests } from '@/pages/MyRequests';
|
import { MyRequests } from '@/pages/MyRequests';
|
||||||
import { Requests } from '@/pages/Requests/Requests';
|
import { Requests } from '@/pages/Requests/Requests';
|
||||||
import { UserAllRequests } from '@/pages/Requests/UserAllRequests';
|
import { UserAllRequests } from '@/pages/Requests/UserAllRequests';
|
||||||
@ -18,21 +18,21 @@ import { useAuth, hasManagementAccess } from '@/contexts/AuthContext';
|
|||||||
import { ApproverPerformance } from '@/pages/ApproverPerformance/ApproverPerformance';
|
import { ApproverPerformance } from '@/pages/ApproverPerformance/ApproverPerformance';
|
||||||
import { Profile } from '@/pages/Profile';
|
import { Profile } from '@/pages/Profile';
|
||||||
import { Settings } from '@/pages/Settings';
|
import { Settings } from '@/pages/Settings';
|
||||||
import { SecuritySettings } from '@/pages/Settings/SecuritySettings';
|
|
||||||
import { Notifications } from '@/pages/Notifications';
|
import { Notifications } from '@/pages/Notifications';
|
||||||
import { DetailedReports } from '@/pages/DetailedReports';
|
import { DetailedReports } from '@/pages/DetailedReports';
|
||||||
|
import { Admin } from '@/pages/Admin';
|
||||||
import { AdminTemplatesList } from '@/pages/Admin/Templates/AdminTemplatesList';
|
import { AdminTemplatesList } from '@/pages/Admin/Templates/AdminTemplatesList';
|
||||||
import { CreateTemplate } from '@/pages/Admin/Templates/CreateTemplate';
|
import { CreateTemplate } from '@/pages/Admin/Templates/CreateTemplate';
|
||||||
import { CreateAdminRequest } from '@/pages/CreateAdminRequest/CreateAdminRequest';
|
import { CreateAdminRequest } from '@/pages/CreateAdminRequest/CreateAdminRequest';
|
||||||
import { ApprovalActionModal } from '@/components/modals/ApprovalActionModal';
|
import { ApprovalActionModal } from '@/components/modals/ApprovalActionModal';
|
||||||
import { Toaster } from '@/components/ui/sonner';
|
import { Toaster } from '@/components/ui/sonner';
|
||||||
import { toast } from 'sonner';
|
import { toast } from 'sonner';
|
||||||
|
import { CUSTOM_REQUEST_DATABASE } from '@/utils/customRequestDatabase';
|
||||||
import { AuthCallback } from '@/pages/Auth/AuthCallback';
|
import { AuthCallback } from '@/pages/Auth/AuthCallback';
|
||||||
import { createClaimRequest } from '@/services/dealerClaimApi';
|
import { createClaimRequest } from '@/services/dealerClaimApi';
|
||||||
import { ManagerSelectionModal } from '@/components/modals/ManagerSelectionModal';
|
import { ManagerSelectionModal } from '@/components/modals/ManagerSelectionModal';
|
||||||
import { navigateToRequest } from '@/utils/requestNavigation';
|
import { navigateToRequest } from '@/utils/requestNavigation';
|
||||||
import { TokenManager } from '@/utils/tokenManager';
|
// import { TokenManager } from '@/utils/tokenManager';
|
||||||
|
|
||||||
interface AppProps {
|
interface AppProps {
|
||||||
onLogout?: () => void;
|
onLogout?: () => void;
|
||||||
@ -61,8 +61,8 @@ function DashboardRoute({ onNavigate, onNewRequest }: { onNavigate?: (page: stri
|
|||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
try {
|
try {
|
||||||
const userData = TokenManager.getUserData();
|
// const userData = TokenManager.getUserData();
|
||||||
setIsDealer(userData?.jobTitle === 'Dealer');
|
// // setIsDealer(userData?.jobTitle === 'Dealer');
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('[App] Error checking dealer status:', error);
|
console.error('[App] Error checking dealer status:', error);
|
||||||
setIsDealer(false);
|
setIsDealer(false);
|
||||||
@ -84,8 +84,7 @@ function DashboardRoute({ onNavigate, onNewRequest }: { onNavigate?: (page: stri
|
|||||||
|
|
||||||
// Render dealer-specific dashboard if user is a dealer
|
// Render dealer-specific dashboard if user is a dealer
|
||||||
if (isDealer) {
|
if (isDealer) {
|
||||||
console.log("isDealer", isDealer)
|
return <DealerDashboard onNavigate={onNavigate} onNewRequest={onNewRequest} />;
|
||||||
// return <DealerDashboard onNavigate={onNavigate} onNewRequest={onNewRequest} />;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Render regular dashboard for all other users
|
// Render regular dashboard for all other users
|
||||||
@ -194,7 +193,7 @@ function AppRoutes({ onLogout }: AppProps) {
|
|||||||
|
|
||||||
// Regular custom request submission (old flow without API)
|
// Regular custom request submission (old flow without API)
|
||||||
// Generate unique ID for the new custom request
|
// Generate unique ID for the new custom request
|
||||||
const requestId = `RE-REQ-2024-${String(dynamicRequests.length + 1).padStart(3, '0')}`;
|
const requestId = `RE-REQ-2024-${String(Object.keys(CUSTOM_REQUEST_DATABASE).length + dynamicRequests.length + 1).padStart(3, '0')}`;
|
||||||
|
|
||||||
// Create full custom request object
|
// Create full custom request object
|
||||||
const newCustomRequest = {
|
const newCustomRequest = {
|
||||||
@ -413,6 +412,201 @@ function AppRoutes({ onLogout }: AppProps) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Keep the old code below for backward compatibility (local storage fallback)
|
||||||
|
// This can be removed once API integration is fully tested
|
||||||
|
/*
|
||||||
|
// Generate unique ID for the new claim request
|
||||||
|
const requestId = `RE-REQ-2024-CM-${String(dynamicRequests.length + 2).padStart(3, '0')}`;
|
||||||
|
|
||||||
|
// Create full request object
|
||||||
|
const newRequest = {
|
||||||
|
id: requestId,
|
||||||
|
title: `${claimData.activityName} - Claim Request`,
|
||||||
|
description: claimData.requestDescription,
|
||||||
|
category: 'Dealer Operations',
|
||||||
|
subcategory: 'Claim Management',
|
||||||
|
status: 'pending',
|
||||||
|
priority: 'standard',
|
||||||
|
amount: 'TBD',
|
||||||
|
slaProgress: 0,
|
||||||
|
slaRemaining: '7 days',
|
||||||
|
slaEndDate: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString(),
|
||||||
|
currentStep: 1,
|
||||||
|
totalSteps: 8,
|
||||||
|
templateType: 'claim-management',
|
||||||
|
templateName: 'Claim Management',
|
||||||
|
initiator: {
|
||||||
|
name: 'Current User',
|
||||||
|
role: 'Regional Marketing Coordinator',
|
||||||
|
department: 'Marketing',
|
||||||
|
email: 'current.user@royalenfield.com',
|
||||||
|
phone: '+91 98765 43290',
|
||||||
|
avatar: 'CU'
|
||||||
|
},
|
||||||
|
department: 'Marketing',
|
||||||
|
createdAt: new Date().toLocaleString('en-US', {
|
||||||
|
month: 'short',
|
||||||
|
day: 'numeric',
|
||||||
|
year: 'numeric',
|
||||||
|
hour: 'numeric',
|
||||||
|
minute: 'numeric',
|
||||||
|
hour12: true
|
||||||
|
}),
|
||||||
|
updatedAt: new Date().toLocaleString('en-US', {
|
||||||
|
month: 'short',
|
||||||
|
day: 'numeric',
|
||||||
|
year: 'numeric',
|
||||||
|
hour: 'numeric',
|
||||||
|
minute: 'numeric',
|
||||||
|
hour12: true
|
||||||
|
}),
|
||||||
|
dueDate: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString(),
|
||||||
|
conclusionRemark: '',
|
||||||
|
claimDetails: {
|
||||||
|
activityName: claimData.activityName,
|
||||||
|
activityType: claimData.activityType,
|
||||||
|
activityDate: claimData.activityDate ? new Date(claimData.activityDate).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' }) : '',
|
||||||
|
location: claimData.location,
|
||||||
|
dealerCode: claimData.dealerCode,
|
||||||
|
dealerName: claimData.dealerName,
|
||||||
|
dealerEmail: claimData.dealerEmail || 'N/A',
|
||||||
|
dealerPhone: claimData.dealerPhone || 'N/A',
|
||||||
|
dealerAddress: claimData.dealerAddress || 'N/A',
|
||||||
|
requestDescription: claimData.requestDescription,
|
||||||
|
estimatedBudget: claimData.estimatedBudget || 'TBD',
|
||||||
|
periodStart: claimData.periodStartDate ? new Date(claimData.periodStartDate).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' }) : '',
|
||||||
|
periodEnd: claimData.periodEndDate ? new Date(claimData.periodEndDate).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' }) : ''
|
||||||
|
},
|
||||||
|
approvalFlow: claimData.workflowSteps || [
|
||||||
|
{
|
||||||
|
step: 1,
|
||||||
|
approver: `${claimData.dealerName} (Dealer)`,
|
||||||
|
role: 'Dealer - Document Upload',
|
||||||
|
status: 'pending',
|
||||||
|
tatHours: 72,
|
||||||
|
elapsedHours: 0,
|
||||||
|
assignedAt: new Date().toISOString(),
|
||||||
|
comment: null,
|
||||||
|
timestamp: null,
|
||||||
|
description: 'Dealer uploads proposal document, cost breakup, timeline for closure, and other supporting documents'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
step: 2,
|
||||||
|
approver: 'Current User (Initiator)',
|
||||||
|
role: 'Initiator Evaluation',
|
||||||
|
status: 'waiting',
|
||||||
|
tatHours: 48,
|
||||||
|
elapsedHours: 0,
|
||||||
|
assignedAt: null,
|
||||||
|
comment: null,
|
||||||
|
timestamp: null,
|
||||||
|
description: 'Initiator reviews dealer documents and approves or requests modifications'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
step: 3,
|
||||||
|
approver: 'System Auto-Process',
|
||||||
|
role: 'IO Confirmation',
|
||||||
|
status: 'waiting',
|
||||||
|
tatHours: 1,
|
||||||
|
elapsedHours: 0,
|
||||||
|
assignedAt: null,
|
||||||
|
comment: null,
|
||||||
|
timestamp: null,
|
||||||
|
description: 'Automatic IO (Internal Order) confirmation generated upon initiator approval'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
step: 4,
|
||||||
|
approver: 'Rajesh Kumar',
|
||||||
|
role: 'Department Lead Approval',
|
||||||
|
status: 'waiting',
|
||||||
|
tatHours: 72,
|
||||||
|
elapsedHours: 0,
|
||||||
|
assignedAt: null,
|
||||||
|
comment: null,
|
||||||
|
timestamp: null,
|
||||||
|
description: 'Department head approves and blocks budget in IO for this activity'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
step: 5,
|
||||||
|
approver: `${claimData.dealerName} (Dealer)`,
|
||||||
|
role: 'Dealer - Completion Documents',
|
||||||
|
status: 'waiting',
|
||||||
|
tatHours: 120,
|
||||||
|
elapsedHours: 0,
|
||||||
|
assignedAt: null,
|
||||||
|
comment: null,
|
||||||
|
timestamp: null,
|
||||||
|
description: 'Dealer submits activity completion documents and description'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
step: 6,
|
||||||
|
approver: 'Current User (Initiator)',
|
||||||
|
role: 'Initiator Verification',
|
||||||
|
status: 'waiting',
|
||||||
|
tatHours: 48,
|
||||||
|
elapsedHours: 0,
|
||||||
|
assignedAt: null,
|
||||||
|
comment: null,
|
||||||
|
timestamp: null,
|
||||||
|
description: 'Initiator verifies completion documents and can modify approved amount'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
step: 7,
|
||||||
|
approver: 'System Auto-Process',
|
||||||
|
role: 'E-Invoice Generation',
|
||||||
|
status: 'waiting',
|
||||||
|
tatHours: 1,
|
||||||
|
elapsedHours: 0,
|
||||||
|
assignedAt: null,
|
||||||
|
comment: null,
|
||||||
|
timestamp: null,
|
||||||
|
description: 'Auto-generate e-invoice based on final approved amount'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
step: 8,
|
||||||
|
approver: 'Finance Team',
|
||||||
|
role: 'Credit Note Issuance',
|
||||||
|
status: 'waiting',
|
||||||
|
tatHours: 48,
|
||||||
|
elapsedHours: 0,
|
||||||
|
assignedAt: null,
|
||||||
|
comment: null,
|
||||||
|
timestamp: null,
|
||||||
|
description: 'Finance team issues credit note to dealer'
|
||||||
|
}
|
||||||
|
],
|
||||||
|
documents: [],
|
||||||
|
spectators: [],
|
||||||
|
auditTrail: [
|
||||||
|
{
|
||||||
|
type: 'created',
|
||||||
|
action: 'Request Created',
|
||||||
|
details: `Claim request for ${claimData.activityName} created`,
|
||||||
|
user: 'Current User',
|
||||||
|
timestamp: new Date().toLocaleString('en-US', {
|
||||||
|
month: 'short',
|
||||||
|
day: 'numeric',
|
||||||
|
year: 'numeric',
|
||||||
|
hour: 'numeric',
|
||||||
|
minute: 'numeric',
|
||||||
|
hour12: true
|
||||||
|
})
|
||||||
|
}
|
||||||
|
],
|
||||||
|
tags: ['claim-management', 'new-request', claimData.activityType?.toLowerCase().replace(/\s+/g, '-')]
|
||||||
|
};
|
||||||
|
|
||||||
|
// Add to dynamic requests
|
||||||
|
setDynamicRequests(prev => [...prev, newRequest]);
|
||||||
|
|
||||||
|
// Also add to REQUEST_DATABASE for immediate viewing
|
||||||
|
(REQUEST_DATABASE as any)[requestId] = newRequest;
|
||||||
|
|
||||||
|
toast.success('Claim Request Submitted', {
|
||||||
|
description: 'Your claim management request has been created successfully.',
|
||||||
|
});
|
||||||
|
navigate('/my-requests');
|
||||||
|
*/
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@ -464,7 +658,44 @@ function AppRoutes({ onLogout }: AppProps) {
|
|||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
<Route
|
||||||
|
path="/admin"
|
||||||
|
element={
|
||||||
|
<PageLayout currentPage="admin" onNavigate={handleNavigate} onNewRequest={handleNewRequest} onLogout={onLogout}>
|
||||||
|
<Admin />
|
||||||
|
</PageLayout>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* Admin Routes Group with Shared Layout */}
|
||||||
|
<Route
|
||||||
|
element={
|
||||||
|
<PageLayout currentPage="admin-templates" onNavigate={handleNavigate} onNewRequest={handleNewRequest} onLogout={onLogout}>
|
||||||
|
<Outlet />
|
||||||
|
</PageLayout>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<Route path="/admin/create-template" element={<CreateTemplate />} />
|
||||||
|
<Route path="/admin/edit-template/:templateId" element={<CreateTemplate />} />
|
||||||
|
<Route path="/admin/templates" element={<AdminTemplatesList />} />
|
||||||
|
</Route>
|
||||||
|
|
||||||
|
{/* Create Request from Admin Template (Dedicated Flow) */}
|
||||||
|
<Route
|
||||||
|
path="/create-admin-request/:templateId"
|
||||||
|
element={
|
||||||
|
<CreateAdminRequest />
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<Route
|
||||||
|
path="/admin"
|
||||||
|
element={
|
||||||
|
<PageLayout currentPage="admin" onNavigate={handleNavigate} onNewRequest={handleNewRequest} onLogout={onLogout}>
|
||||||
|
<Admin />
|
||||||
|
</PageLayout>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
|
||||||
{/* Open Requests */}
|
{/* Open Requests */}
|
||||||
<Route
|
<Route
|
||||||
@ -611,16 +842,6 @@ function AppRoutes({ onLogout }: AppProps) {
|
|||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
{/* Security Settings */}
|
|
||||||
<Route
|
|
||||||
path="/settings/security"
|
|
||||||
element={
|
|
||||||
<PageLayout currentPage="settings" onNavigate={handleNavigate} onNewRequest={handleNewRequest} onLogout={onLogout}>
|
|
||||||
<SecuritySettings />
|
|
||||||
</PageLayout>
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
|
|
||||||
{/* Notifications */}
|
{/* Notifications */}
|
||||||
<Route
|
<Route
|
||||||
path="/notifications"
|
path="/notifications"
|
||||||
|
|||||||
@ -12,13 +12,6 @@ import {
|
|||||||
DialogHeader,
|
DialogHeader,
|
||||||
DialogTitle,
|
DialogTitle,
|
||||||
} from '@/components/ui/dialog';
|
} from '@/components/ui/dialog';
|
||||||
import {
|
|
||||||
Select,
|
|
||||||
SelectContent,
|
|
||||||
SelectItem,
|
|
||||||
SelectTrigger,
|
|
||||||
SelectValue,
|
|
||||||
} from '@/components/ui/select';
|
|
||||||
import {
|
import {
|
||||||
FileText,
|
FileText,
|
||||||
Plus,
|
Plus,
|
||||||
@ -96,17 +89,16 @@ export function ActivityTypeManager() {
|
|||||||
try {
|
try {
|
||||||
setError(null);
|
setError(null);
|
||||||
|
|
||||||
if (!formData.title.trim() || !formData.taxationType.trim() || !formData.sapRefNo.trim()) {
|
if (!formData.title.trim()) {
|
||||||
setError('Title, Taxation Type, and Claim Document Type (SAP Ref) are required');
|
setError('Activity type title is required');
|
||||||
toast.error('Please fill in all mandatory fields');
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const payload: Partial<ActivityType> = {
|
const payload: Partial<ActivityType> = {
|
||||||
title: formData.title.trim(),
|
title: formData.title.trim(),
|
||||||
itemCode: formData.itemCode.trim() || null,
|
itemCode: formData.itemCode.trim() || null,
|
||||||
taxationType: formData.taxationType.trim(),
|
taxationType: formData.taxationType.trim() || null,
|
||||||
sapRefNo: formData.sapRefNo.trim()
|
sapRefNo: formData.sapRefNo.trim() || null
|
||||||
};
|
};
|
||||||
|
|
||||||
if (editingActivityType) {
|
if (editingActivityType) {
|
||||||
@ -405,37 +397,32 @@ export function ActivityTypeManager() {
|
|||||||
|
|
||||||
{/* Taxation Type Field */}
|
{/* Taxation Type Field */}
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label htmlFor="taxationType" className="text-sm font-semibold text-slate-900 flex items-center gap-1">
|
<Label htmlFor="taxationType" className="text-sm font-semibold text-slate-900">
|
||||||
Taxation Type <span className="text-red-500">*</span>
|
Taxation Type <span className="text-slate-400 font-normal text-xs">(Optional)</span>
|
||||||
</Label>
|
</Label>
|
||||||
<Select
|
<Input
|
||||||
|
id="taxationType"
|
||||||
|
placeholder="e.g., GST, VAT, Exempt"
|
||||||
value={formData.taxationType}
|
value={formData.taxationType}
|
||||||
onValueChange={(value) => setFormData({ ...formData, taxationType: value })}
|
onChange={(e) => setFormData({ ...formData, taxationType: e.target.value })}
|
||||||
>
|
className="h-11 border-slate-300 focus:border-re-green focus:ring-2 focus:ring-re-green/20 rounded-lg transition-all shadow-sm"
|
||||||
<SelectTrigger id="taxationType" className="h-11 border-slate-300 focus:border-re-green focus:ring-2 focus:ring-re-green/20 rounded-lg transition-all shadow-sm">
|
/>
|
||||||
<SelectValue placeholder="Select Taxation Type" />
|
<p className="text-xs text-slate-500">Optional taxation type for the activity</p>
|
||||||
</SelectTrigger>
|
|
||||||
<SelectContent className="rounded-lg">
|
|
||||||
<SelectItem value="GST" className="p-3">GST</SelectItem>
|
|
||||||
<SelectItem value="Non GST" className="p-3">Non GST</SelectItem>
|
|
||||||
</SelectContent>
|
|
||||||
</Select>
|
|
||||||
<p className="text-xs text-slate-500">Select whether the activity is GST or Non-GST</p>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* SAP Reference Number Field */}
|
{/* SAP Reference Number Field */}
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label htmlFor="sapRefNo" className="text-sm font-semibold text-slate-900 flex items-center gap-1">
|
<Label htmlFor="sapRefNo" className="text-sm font-semibold text-slate-900">
|
||||||
Claim Document Type (SAP Ref) <span className="text-red-500">*</span>
|
SAP Reference Number <span className="text-slate-400 font-normal text-xs">(Optional)</span>
|
||||||
</Label>
|
</Label>
|
||||||
<Input
|
<Input
|
||||||
id="sapRefNo"
|
id="sapRefNo"
|
||||||
placeholder="e.g., ZCNS, ZRE"
|
placeholder="e.g., SAP-12345"
|
||||||
value={formData.sapRefNo}
|
value={formData.sapRefNo}
|
||||||
onChange={(e) => setFormData({ ...formData, sapRefNo: e.target.value })}
|
onChange={(e) => setFormData({ ...formData, sapRefNo: e.target.value })}
|
||||||
className="h-11 border-slate-300 focus:border-re-green focus:ring-2 focus:ring-re-green/20 rounded-lg transition-all shadow-sm"
|
className="h-11 border-slate-300 focus:border-re-green focus:ring-2 focus:ring-re-green/20 rounded-lg transition-all shadow-sm"
|
||||||
/>
|
/>
|
||||||
<p className="text-xs text-slate-500">Required SAP reference number for CSV generation</p>
|
<p className="text-xs text-slate-500">Optional SAP reference number</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@ -449,7 +436,7 @@ export function ActivityTypeManager() {
|
|||||||
</Button>
|
</Button>
|
||||||
<Button
|
<Button
|
||||||
onClick={handleSave}
|
onClick={handleSave}
|
||||||
disabled={!formData.title.trim() || !formData.taxationType || !formData.sapRefNo.trim()}
|
disabled={!formData.title.trim()}
|
||||||
className="h-11 bg-re-green hover:bg-re-green/90 text-white shadow-md hover:shadow-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed"
|
className="h-11 bg-re-green hover:bg-re-green/90 text-white shadow-md hover:shadow-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed"
|
||||||
>
|
>
|
||||||
<FileText className="w-4 h-4 mr-2" />
|
<FileText className="w-4 h-4 mr-2" />
|
||||||
|
|||||||
@ -31,7 +31,7 @@ export function AnalyticsConfig() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const handleSave = () => {
|
const handleSave = () => {
|
||||||
|
// TODO: Implement API call to save configuration
|
||||||
toast.success('Analytics configuration saved successfully');
|
toast.success('Analytics configuration saved successfully');
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@ -59,7 +59,7 @@ export function DashboardConfig() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const handleSave = () => {
|
const handleSave = () => {
|
||||||
|
// TODO: Implement API call to save dashboard configuration
|
||||||
toast.success('Dashboard layout saved successfully');
|
toast.success('Dashboard layout saved successfully');
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@ -28,7 +28,7 @@ export function NotificationConfig() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const handleSave = () => {
|
const handleSave = () => {
|
||||||
|
// TODO: Implement API call to save notification configuration
|
||||||
toast.success('Notification configuration saved successfully');
|
toast.success('Notification configuration saved successfully');
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@ -23,7 +23,7 @@ export function SharingConfig() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const handleSave = () => {
|
const handleSave = () => {
|
||||||
|
// TODO: Implement API call to save sharing configuration
|
||||||
toast.success('Sharing policy saved successfully');
|
toast.success('Sharing policy saved successfully');
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@ -318,7 +318,7 @@ export function UserManagement() {
|
|||||||
const user = users.find(u => u.userId === userId);
|
const user = users.find(u => u.userId === userId);
|
||||||
if (!user) return;
|
if (!user) return;
|
||||||
|
|
||||||
|
// TODO: Implement backend API for toggling user status
|
||||||
toast.info('User status toggle functionality coming soon');
|
toast.info('User status toggle functionality coming soon');
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -332,6 +332,7 @@ export function UserManagement() {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO: Implement backend API for deleting users
|
||||||
toast.info('User deletion functionality coming soon');
|
toast.info('User deletion functionality coming soon');
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -514,7 +515,8 @@ export function UserManagement() {
|
|||||||
|
|
||||||
{/* Message */}
|
{/* Message */}
|
||||||
{message && (
|
{message && (
|
||||||
<div className={`border-2 rounded-lg p-4 ${message.type === 'success'
|
<div className={`border-2 rounded-lg p-4 ${
|
||||||
|
message.type === 'success'
|
||||||
? 'border-green-200 bg-green-50'
|
? 'border-green-200 bg-green-50'
|
||||||
: 'border-red-200 bg-red-50'
|
: 'border-red-200 bg-red-50'
|
||||||
}`}>
|
}`}>
|
||||||
@ -662,7 +664,8 @@ export function UserManagement() {
|
|||||||
variant={currentPage === pageNum ? "default" : "outline"}
|
variant={currentPage === pageNum ? "default" : "outline"}
|
||||||
size="sm"
|
size="sm"
|
||||||
onClick={() => handlePageChange(pageNum)}
|
onClick={() => handlePageChange(pageNum)}
|
||||||
className={`w-9 h-9 p-0 ${currentPage === pageNum
|
className={`w-9 h-9 p-0 ${
|
||||||
|
currentPage === pageNum
|
||||||
? 'bg-re-green hover:bg-re-green/90'
|
? 'bg-re-green hover:bg-re-green/90'
|
||||||
: ''
|
: ''
|
||||||
}`}
|
}`}
|
||||||
|
|||||||
@ -1,194 +0,0 @@
|
|||||||
/**
|
|
||||||
* AntivirusScanStatus Component
|
|
||||||
* Displays the antivirus scan result badge/status for uploaded files.
|
|
||||||
* Shows ClamAV scan result and XSS content scan result.
|
|
||||||
*/
|
|
||||||
|
|
||||||
import React from 'react';
|
|
||||||
|
|
||||||
// ── Types ──
|
|
||||||
|
|
||||||
export interface ScanResultData {
|
|
||||||
malwareScan?: {
|
|
||||||
scanned: boolean;
|
|
||||||
isInfected: boolean;
|
|
||||||
skipped?: boolean;
|
|
||||||
virusNames?: string[];
|
|
||||||
scanDuration?: number;
|
|
||||||
error?: string;
|
|
||||||
};
|
|
||||||
contentScan?: {
|
|
||||||
scanned: boolean;
|
|
||||||
safe: boolean;
|
|
||||||
scanType: string;
|
|
||||||
severity: 'SAFE' | 'LOW' | 'MEDIUM' | 'HIGH' | 'CRITICAL';
|
|
||||||
threats?: Array<{ description: string; severity: string }>;
|
|
||||||
patternsChecked: number;
|
|
||||||
};
|
|
||||||
scanEventId?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface AntivirusScanStatusProps {
|
|
||||||
scanResult?: ScanResultData;
|
|
||||||
compact?: boolean;
|
|
||||||
className?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── Helpers ──
|
|
||||||
|
|
||||||
function getStatusColor(result?: ScanResultData): string {
|
|
||||||
if (!result) return '#94a3b8'; // gray — no scan data
|
|
||||||
|
|
||||||
// Check malware first
|
|
||||||
if (result.malwareScan?.isInfected) return '#ef4444'; // red
|
|
||||||
if (result.malwareScan?.error) return '#f59e0b'; // amber
|
|
||||||
|
|
||||||
// Then XSS
|
|
||||||
if (result.contentScan && !result.contentScan.safe) {
|
|
||||||
if (result.contentScan.severity === 'CRITICAL') return '#ef4444';
|
|
||||||
if (result.contentScan.severity === 'HIGH') return '#ef4444';
|
|
||||||
if (result.contentScan.severity === 'MEDIUM') return '#f59e0b';
|
|
||||||
return '#f59e0b';
|
|
||||||
}
|
|
||||||
|
|
||||||
// Skipped
|
|
||||||
if (result.malwareScan?.skipped) return '#94a3b8';
|
|
||||||
|
|
||||||
return '#22c55e'; // green — all clear
|
|
||||||
}
|
|
||||||
|
|
||||||
function getStatusIcon(result?: ScanResultData): string {
|
|
||||||
if (!result) return '⏳';
|
|
||||||
if (result.malwareScan?.isInfected) return '🛑';
|
|
||||||
if (result.contentScan && !result.contentScan.safe) return '⚠️';
|
|
||||||
if (result.malwareScan?.skipped) return '⏭️';
|
|
||||||
if (result.malwareScan?.error) return '❌';
|
|
||||||
if (result.malwareScan?.scanned && result.contentScan?.scanned) return '✅';
|
|
||||||
return '⏳';
|
|
||||||
}
|
|
||||||
|
|
||||||
function getStatusLabel(result?: ScanResultData): string {
|
|
||||||
if (!result) return 'Pending scan';
|
|
||||||
if (result.malwareScan?.isInfected) return 'Malware detected';
|
|
||||||
if (result.contentScan && !result.contentScan.safe) return 'Content threat detected';
|
|
||||||
if (result.malwareScan?.skipped) return 'Scan skipped';
|
|
||||||
if (result.malwareScan?.error) return 'Scan error';
|
|
||||||
if (result.malwareScan?.scanned && result.contentScan?.scanned) return 'Clean';
|
|
||||||
return 'Scanning…';
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── Component ──
|
|
||||||
|
|
||||||
const AntivirusScanStatus: React.FC<AntivirusScanStatusProps> = ({
|
|
||||||
scanResult,
|
|
||||||
compact = false,
|
|
||||||
className = '',
|
|
||||||
}) => {
|
|
||||||
const color = getStatusColor(scanResult);
|
|
||||||
const icon = getStatusIcon(scanResult);
|
|
||||||
const label = getStatusLabel(scanResult);
|
|
||||||
|
|
||||||
// Compact mode: just a badge
|
|
||||||
if (compact) {
|
|
||||||
return (
|
|
||||||
<span
|
|
||||||
className={className}
|
|
||||||
style={{
|
|
||||||
display: 'inline-flex',
|
|
||||||
alignItems: 'center',
|
|
||||||
gap: '4px',
|
|
||||||
padding: '2px 8px',
|
|
||||||
borderRadius: '12px',
|
|
||||||
fontSize: '12px',
|
|
||||||
fontWeight: 500,
|
|
||||||
backgroundColor: `${color}15`,
|
|
||||||
color,
|
|
||||||
border: `1px solid ${color}30`,
|
|
||||||
}}
|
|
||||||
title={label}
|
|
||||||
>
|
|
||||||
<span style={{ fontSize: '11px' }}>{icon}</span>
|
|
||||||
{label}
|
|
||||||
</span>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Full mode: detailed card
|
|
||||||
return (
|
|
||||||
<div
|
|
||||||
className={className}
|
|
||||||
style={{
|
|
||||||
border: `1px solid ${color}30`,
|
|
||||||
borderRadius: '8px',
|
|
||||||
padding: '12px 16px',
|
|
||||||
backgroundColor: `${color}08`,
|
|
||||||
fontSize: '13px',
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{/* Header */}
|
|
||||||
<div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginBottom: '8px' }}>
|
|
||||||
<span style={{ fontSize: '16px' }}>{icon}</span>
|
|
||||||
<span style={{ fontWeight: 600, color }}>{label}</span>
|
|
||||||
{scanResult?.malwareScan?.scanDuration && (
|
|
||||||
<span style={{ marginLeft: 'auto', fontSize: '11px', color: '#94a3b8' }}>
|
|
||||||
{scanResult.malwareScan.scanDuration}ms
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Details */}
|
|
||||||
{scanResult && (
|
|
||||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '4px' }}>
|
|
||||||
{/* ClamAV Result */}
|
|
||||||
{scanResult.malwareScan?.scanned && (
|
|
||||||
<div style={{ display: 'flex', alignItems: 'center', gap: '6px', fontSize: '12px', color: '#64748b' }}>
|
|
||||||
<span>🦠</span>
|
|
||||||
<span>
|
|
||||||
ClamAV:{' '}
|
|
||||||
{scanResult.malwareScan.isInfected
|
|
||||||
? `Infected — ${scanResult.malwareScan.virusNames?.join(', ')}`
|
|
||||||
: 'Clean'}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* XSS Result */}
|
|
||||||
{scanResult.contentScan?.scanned && (
|
|
||||||
<div style={{ display: 'flex', alignItems: 'center', gap: '6px', fontSize: '12px', color: '#64748b' }}>
|
|
||||||
<span>🔍</span>
|
|
||||||
<span>
|
|
||||||
Content scan ({scanResult.contentScan.scanType}):{' '}
|
|
||||||
{scanResult.contentScan.safe
|
|
||||||
? `Safe — ${scanResult.contentScan.patternsChecked} patterns checked`
|
|
||||||
: `${scanResult.contentScan.threats?.length || 0} threats found (${scanResult.contentScan.severity})`}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Threats list */}
|
|
||||||
{scanResult.contentScan?.threats && scanResult.contentScan.threats.length > 0 && (
|
|
||||||
<ul style={{ margin: '4px 0 0 24px', padding: 0, fontSize: '11px', color: '#ef4444' }}>
|
|
||||||
{scanResult.contentScan.threats.slice(0, 5).map((threat, i) => (
|
|
||||||
<li key={i}>
|
|
||||||
{threat.description} ({threat.severity})
|
|
||||||
</li>
|
|
||||||
))}
|
|
||||||
{scanResult.contentScan.threats.length > 5 && (
|
|
||||||
<li>…and {scanResult.contentScan.threats.length - 5} more</li>
|
|
||||||
)}
|
|
||||||
</ul>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Scan event ID */}
|
|
||||||
{scanResult.scanEventId && (
|
|
||||||
<div style={{ fontSize: '10px', color: '#94a3b8', marginTop: '4px' }}>
|
|
||||||
Scan ID: {scanResult.scanEventId}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
export default AntivirusScanStatus;
|
|
||||||
@ -72,8 +72,8 @@ export function PageLayout({ children, currentPage = 'dashboard', onNavigate, on
|
|||||||
const items = [
|
const items = [
|
||||||
{ id: 'dashboard', label: 'Dashboard', icon: Home },
|
{ id: 'dashboard', label: 'Dashboard', icon: Home },
|
||||||
// Add "All Requests" for all users (admin sees org-level, regular users see their participant requests)
|
// Add "All Requests" for all users (admin sees org-level, regular users see their participant requests)
|
||||||
{ id: 'requests', label: 'All Requests', icon: List, adminOnly: false },
|
{ id: 'requests', label: 'All Requests', icon: List },
|
||||||
{ id: 'my-requests', label: 'My Requests', icon: User }
|
{ id: 'my-requests', label: 'My Requests', icon: User, adminOnly: false },
|
||||||
// { id: 'admin/templates', label: 'Admin Templates', icon: Plus, adminOnly: true },
|
// { id: 'admin/templates', label: 'Admin Templates', icon: Plus, adminOnly: true },
|
||||||
];
|
];
|
||||||
|
|
||||||
|
|||||||
@ -151,7 +151,8 @@ export function TemplateSelectionModal({ open, onClose, onSelectTemplate }: Temp
|
|||||||
whileTap={isDisabled ? {} : { scale: 0.98 }}
|
whileTap={isDisabled ? {} : { scale: 0.98 }}
|
||||||
>
|
>
|
||||||
<Card
|
<Card
|
||||||
className={`h-full transition-all duration-300 border-2 ${isDisabled
|
className={`h-full transition-all duration-300 border-2 ${
|
||||||
|
isDisabled
|
||||||
? 'opacity-50 cursor-not-allowed border-gray-200'
|
? 'opacity-50 cursor-not-allowed border-gray-200'
|
||||||
: isSelected
|
: isSelected
|
||||||
? 'cursor-pointer border-blue-500 shadow-xl bg-blue-50/50 ring-2 ring-blue-200'
|
? 'cursor-pointer border-blue-500 shadow-xl bg-blue-50/50 ring-2 ring-blue-200'
|
||||||
@ -261,7 +262,8 @@ export function TemplateSelectionModal({ open, onClose, onSelectTemplate }: Temp
|
|||||||
onClick={handleContinue}
|
onClick={handleContinue}
|
||||||
disabled={!selectedTemplate || isDealer || AVAILABLE_TEMPLATES.find(t => t.id === selectedTemplate)?.disabled}
|
disabled={!selectedTemplate || isDealer || AVAILABLE_TEMPLATES.find(t => t.id === selectedTemplate)?.disabled}
|
||||||
size="lg"
|
size="lg"
|
||||||
className={`gap-2 px-8 ${selectedTemplate && !isDealer && !AVAILABLE_TEMPLATES.find(t => t.id === selectedTemplate)?.disabled
|
className={`gap-2 px-8 ${
|
||||||
|
selectedTemplate && !isDealer && !AVAILABLE_TEMPLATES.find(t => t.id === selectedTemplate)?.disabled
|
||||||
? 'bg-blue-600 hover:bg-blue-700'
|
? 'bg-blue-600 hover:bg-blue-700'
|
||||||
: 'bg-gray-400 cursor-not-allowed'
|
: 'bg-gray-400 cursor-not-allowed'
|
||||||
}`}
|
}`}
|
||||||
|
|||||||
@ -1,297 +0,0 @@
|
|||||||
import { useState, useEffect } from 'react';
|
|
||||||
import { Button } from '@/components/ui/button';
|
|
||||||
import { Input } from '@/components/ui/input';
|
|
||||||
import { Label } from '@/components/ui/label';
|
|
||||||
import {
|
|
||||||
Dialog,
|
|
||||||
DialogContent,
|
|
||||||
DialogDescription,
|
|
||||||
DialogFooter,
|
|
||||||
DialogHeader,
|
|
||||||
DialogTitle,
|
|
||||||
} from '@/components/ui/dialog';
|
|
||||||
import {
|
|
||||||
AlertDialog,
|
|
||||||
AlertDialogAction,
|
|
||||||
AlertDialogCancel,
|
|
||||||
AlertDialogContent,
|
|
||||||
AlertDialogDescription,
|
|
||||||
AlertDialogFooter,
|
|
||||||
AlertDialogHeader,
|
|
||||||
AlertDialogTitle,
|
|
||||||
} from '@/components/ui/alert-dialog';
|
|
||||||
import {
|
|
||||||
Table,
|
|
||||||
TableBody,
|
|
||||||
TableCell,
|
|
||||||
TableHead,
|
|
||||||
TableHeader,
|
|
||||||
TableRow,
|
|
||||||
} from '@/components/ui/table';
|
|
||||||
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
|
|
||||||
import { Key, Plus, Trash2, Copy, Check } from 'lucide-react';
|
|
||||||
import { format } from 'date-fns';
|
|
||||||
import axios from '@/services/authApi';
|
|
||||||
import { toast } from 'sonner';
|
|
||||||
|
|
||||||
interface ApiToken {
|
|
||||||
id: string;
|
|
||||||
name: string;
|
|
||||||
prefix: string;
|
|
||||||
lastUsedAt?: string;
|
|
||||||
expiresAt?: string;
|
|
||||||
createdAt: string;
|
|
||||||
isActive: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function ApiTokenManager() {
|
|
||||||
const [tokens, setTokens] = useState<ApiToken[]>([]);
|
|
||||||
const [isLoading, setIsLoading] = useState(true);
|
|
||||||
const [showCreateModal, setShowCreateModal] = useState(false);
|
|
||||||
const [newTokenName, setNewTokenName] = useState('');
|
|
||||||
const [newTokenExpiry, setNewTokenExpiry] = useState<number | ''>('');
|
|
||||||
const [generatedToken, setGeneratedToken] = useState<string | null>(null);
|
|
||||||
const [isCreating, setIsCreating] = useState(false);
|
|
||||||
const [copied, setCopied] = useState(false);
|
|
||||||
const [tokenToRevoke, setTokenToRevoke] = useState<ApiToken | null>(null);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
fetchTokens();
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const fetchTokens = async () => {
|
|
||||||
try {
|
|
||||||
setIsLoading(true);
|
|
||||||
const response = await axios.get('/api-tokens');
|
|
||||||
setTokens(response.data.data.tokens);
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Failed to fetch API tokens:', error);
|
|
||||||
toast.error('Failed to load API tokens');
|
|
||||||
} finally {
|
|
||||||
setIsLoading(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleCreateToken = async () => {
|
|
||||||
if (!newTokenName.trim()) return;
|
|
||||||
|
|
||||||
try {
|
|
||||||
setIsCreating(true);
|
|
||||||
const payload: any = { name: newTokenName };
|
|
||||||
if (newTokenExpiry) {
|
|
||||||
payload.expiresInDays = Number(newTokenExpiry);
|
|
||||||
}
|
|
||||||
|
|
||||||
const response = await axios.post('/api-tokens', payload);
|
|
||||||
setGeneratedToken(response.data.data.token);
|
|
||||||
toast.success('API Token created successfully');
|
|
||||||
fetchTokens(); // Refresh list
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Failed to create token:', error);
|
|
||||||
toast.error('Failed to create API token');
|
|
||||||
} finally {
|
|
||||||
setIsCreating(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleRevokeToken = (token: ApiToken) => {
|
|
||||||
setTokenToRevoke(token);
|
|
||||||
};
|
|
||||||
|
|
||||||
const confirmRevokeToken = async () => {
|
|
||||||
if (!tokenToRevoke) return;
|
|
||||||
|
|
||||||
|
|
||||||
try {
|
|
||||||
await axios.delete(`/api-tokens/${tokenToRevoke.id}`);
|
|
||||||
toast.success('Token revoked successfully');
|
|
||||||
setTokens(tokens.filter(t => t.id !== tokenToRevoke.id));
|
|
||||||
setTokenToRevoke(null);
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Failed to revoke token:', error);
|
|
||||||
toast.error('Failed to revoke token');
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const copyToClipboard = () => {
|
|
||||||
if (generatedToken) {
|
|
||||||
navigator.clipboard.writeText(generatedToken);
|
|
||||||
setCopied(true);
|
|
||||||
setTimeout(() => setCopied(false), 2000);
|
|
||||||
toast.success('Token copied to clipboard');
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const resetCreateModal = () => {
|
|
||||||
setShowCreateModal(false);
|
|
||||||
setNewTokenName('');
|
|
||||||
setNewTokenExpiry('');
|
|
||||||
setGeneratedToken(null);
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="space-y-6">
|
|
||||||
<div className="flex items-center justify-between">
|
|
||||||
<div>
|
|
||||||
<h3 className="text-lg font-medium text-gray-900">API Tokens</h3>
|
|
||||||
<p className="text-sm text-gray-500">Manage personal access tokens for external integrations</p>
|
|
||||||
</div>
|
|
||||||
<Button onClick={() => setShowCreateModal(true)} size="sm" className="bg-re-green hover:bg-re-green/90 text-white">
|
|
||||||
<Plus className="w-4 h-4 mr-2" />
|
|
||||||
Generate
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
{isLoading ? (
|
|
||||||
<div className="text-center py-4 text-gray-500">Loading tokens...</div>
|
|
||||||
) : tokens.length === 0 ? (
|
|
||||||
<div className="text-center py-8 bg-gray-50 rounded-lg border border-dashed border-gray-300">
|
|
||||||
<Key className="w-10 h-10 text-gray-300 mx-auto mb-2" />
|
|
||||||
<p className="text-gray-500 font-medium">No API tokens found</p>
|
|
||||||
<p className="text-gray-400 text-sm mt-1">Generate a token to access the API programmatically</p>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<div className="rounded-md border">
|
|
||||||
<Table>
|
|
||||||
<TableHeader>
|
|
||||||
<TableRow>
|
|
||||||
<TableHead>Name</TableHead>
|
|
||||||
<TableHead>Prefix</TableHead>
|
|
||||||
<TableHead>Last Used</TableHead>
|
|
||||||
<TableHead>Expires</TableHead>
|
|
||||||
<TableHead className="text-right">Actions</TableHead>
|
|
||||||
</TableRow>
|
|
||||||
</TableHeader>
|
|
||||||
<TableBody>
|
|
||||||
{tokens.map((token) => (
|
|
||||||
<TableRow key={token.id}>
|
|
||||||
<TableCell className="font-medium">{token.name}</TableCell>
|
|
||||||
<TableCell className="font-mono text-xs bg-slate-100 rounded px-2 py-1 w-fit">{token.prefix}...</TableCell>
|
|
||||||
<TableCell className="text-gray-500 text-sm">
|
|
||||||
{token.lastUsedAt ? format(new Date(token.lastUsedAt), 'MMM d, yyyy') : 'Never'}
|
|
||||||
</TableCell>
|
|
||||||
<TableCell className="text-gray-500 text-sm">
|
|
||||||
{token.expiresAt ? format(new Date(token.expiresAt), 'MMM d, yyyy') : 'No Expiry'}
|
|
||||||
</TableCell>
|
|
||||||
<TableCell className="text-right">
|
|
||||||
<Button
|
|
||||||
variant="ghost"
|
|
||||||
size="sm"
|
|
||||||
onClick={() => handleRevokeToken(token)}
|
|
||||||
className="text-red-600 hover:text-red-700 hover:bg-red-50"
|
|
||||||
>
|
|
||||||
<Trash2 className="w-4 h-4" />
|
|
||||||
<span className="sr-only">Revoke</span>
|
|
||||||
</Button>
|
|
||||||
</TableCell>
|
|
||||||
</TableRow>
|
|
||||||
))}
|
|
||||||
</TableBody>
|
|
||||||
</Table>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* Create Token Modal */}
|
|
||||||
<Dialog open={showCreateModal} onOpenChange={(open) => !open && resetCreateModal()}>
|
|
||||||
<DialogContent className="sm:max-w-md">
|
|
||||||
<DialogHeader>
|
|
||||||
<DialogTitle>Generate API Token</DialogTitle>
|
|
||||||
<DialogDescription>
|
|
||||||
Create a new token to access the API. Treat this token like a password.
|
|
||||||
</DialogDescription>
|
|
||||||
</DialogHeader>
|
|
||||||
|
|
||||||
{!generatedToken ? (
|
|
||||||
<div className="space-y-4 py-4">
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label htmlFor="token-name">Token Name</Label>
|
|
||||||
<Input
|
|
||||||
id="token-name"
|
|
||||||
placeholder="e.g., CI/CD Pipeline, Prometheus"
|
|
||||||
value={newTokenName}
|
|
||||||
onChange={(e) => setNewTokenName(e.target.value)}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Label htmlFor="token-expiry">Expiration (Days)</Label>
|
|
||||||
<Input
|
|
||||||
id="token-expiry"
|
|
||||||
type="number"
|
|
||||||
min="1"
|
|
||||||
placeholder="Leave empty for no expiry"
|
|
||||||
value={newTokenExpiry}
|
|
||||||
onChange={(e) => {
|
|
||||||
const val = e.target.value;
|
|
||||||
if (val === '') {
|
|
||||||
setNewTokenExpiry('');
|
|
||||||
} else {
|
|
||||||
const num = parseInt(val);
|
|
||||||
// Prevent negative numbers
|
|
||||||
if (!isNaN(num) && num >= 1) {
|
|
||||||
setNewTokenExpiry(num);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<div className="space-y-4 py-4">
|
|
||||||
<Alert className="bg-green-50 border-green-200">
|
|
||||||
<Check className="h-4 w-4 text-green-600" />
|
|
||||||
<AlertTitle className="text-green-800">Token Generated Successfully</AlertTitle>
|
|
||||||
<AlertDescription className="text-green-700">
|
|
||||||
Please copy your token now. You won't be able to see it again!
|
|
||||||
</AlertDescription>
|
|
||||||
</Alert>
|
|
||||||
|
|
||||||
<div className="relative">
|
|
||||||
<div className="p-4 bg-slate-900 rounded-md font-mono text-sm text-green-400 break-all pr-10">
|
|
||||||
{generatedToken}
|
|
||||||
</div>
|
|
||||||
<Button
|
|
||||||
size="icon"
|
|
||||||
variant="ghost"
|
|
||||||
className="absolute top-1 right-1 text-gray-400 hover:text-white hover:bg-slate-800"
|
|
||||||
onClick={copyToClipboard}
|
|
||||||
>
|
|
||||||
{copied ? <Check className="w-4 h-4 text-green-500" /> : <Copy className="w-4 h-4" />}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<DialogFooter>
|
|
||||||
{!generatedToken ? (
|
|
||||||
<>
|
|
||||||
<Button variant="outline" onClick={resetCreateModal}>Cancel</Button>
|
|
||||||
<Button onClick={handleCreateToken} disabled={!newTokenName.trim() || isCreating}>
|
|
||||||
{isCreating ? 'Generating...' : 'Generate Token'}
|
|
||||||
</Button>
|
|
||||||
</>
|
|
||||||
) : (
|
|
||||||
<Button onClick={resetCreateModal}>Done</Button>
|
|
||||||
)}
|
|
||||||
</DialogFooter>
|
|
||||||
</DialogContent>
|
|
||||||
</Dialog>
|
|
||||||
|
|
||||||
<AlertDialog open={!!tokenToRevoke} onOpenChange={(open) => !open && setTokenToRevoke(null)}>
|
|
||||||
<AlertDialogContent>
|
|
||||||
<AlertDialogHeader>
|
|
||||||
<AlertDialogTitle>Revoke API Token</AlertDialogTitle>
|
|
||||||
<AlertDialogDescription>
|
|
||||||
Are you sure you want to revoke the token <strong>{tokenToRevoke?.name}</strong>?
|
|
||||||
This action cannot be undone and any applications using this token will lose access immediately.
|
|
||||||
</AlertDialogDescription>
|
|
||||||
</AlertDialogHeader>
|
|
||||||
<AlertDialogFooter>
|
|
||||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
|
||||||
<AlertDialogAction onClick={confirmRevokeToken} className="bg-red-600 hover:bg-red-700 text-white">
|
|
||||||
Revoke Token
|
|
||||||
</AlertDialogAction>
|
|
||||||
</AlertDialogFooter>
|
|
||||||
</AlertDialogContent>
|
|
||||||
</AlertDialog>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@ -297,12 +297,14 @@ export function ApprovalWorkflowStep({
|
|||||||
<div className="w-px h-6 bg-gray-300"></div>
|
<div className="w-px h-6 bg-gray-300"></div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className={`p-4 rounded-lg border-2 transition-all ${approver.email
|
<div className={`p-4 rounded-lg border-2 transition-all ${
|
||||||
|
approver.email
|
||||||
? 'border-green-200 bg-green-50'
|
? 'border-green-200 bg-green-50'
|
||||||
: 'border-gray-200 bg-gray-50'
|
: 'border-gray-200 bg-gray-50'
|
||||||
}`}>
|
}`}>
|
||||||
<div className="flex items-center gap-3">
|
<div className="flex items-center gap-3">
|
||||||
<div className={`w-10 h-10 rounded-full flex items-center justify-center ${approver.email
|
<div className={`w-10 h-10 rounded-full flex items-center justify-center ${
|
||||||
|
approver.email
|
||||||
? 'bg-green-600'
|
? 'bg-green-600'
|
||||||
: 'bg-gray-400'
|
: 'bg-gray-400'
|
||||||
}`}>
|
}`}>
|
||||||
@ -334,7 +336,7 @@ export function ApprovalWorkflowStep({
|
|||||||
<Input
|
<Input
|
||||||
id={`approver-${level}`}
|
id={`approver-${level}`}
|
||||||
type="email"
|
type="email"
|
||||||
placeholder={`approver@${import.meta.env.VITE_APP_DOMAIN}`}
|
placeholder="approver@royalenfield.com"
|
||||||
value={approver.email || ''}
|
value={approver.email || ''}
|
||||||
onChange={(e) => handleApproverEmailChange(index, e.target.value)}
|
onChange={(e) => handleApproverEmailChange(index, e.target.value)}
|
||||||
className="h-10 border-2 border-gray-300 focus:border-blue-500 mt-1 w-full"
|
className="h-10 border-2 border-gray-300 focus:border-blue-500 mt-1 w-full"
|
||||||
|
|||||||
@ -107,8 +107,8 @@ export function TemplateSelectionStep({
|
|||||||
<p>No admin templates available yet.</p>
|
<p>No admin templates available yet.</p>
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
displayTemplates.map((template, index) => {
|
displayTemplates.map((template) => {
|
||||||
const isComingSoon = index === 1;
|
const isComingSoon = template.id === 'existing-template' && viewMode === 'main'; // Only show coming soon for placeholder
|
||||||
const isDisabled = isComingSoon;
|
const isDisabled = isComingSoon;
|
||||||
const isCategoryCard = template.id === 'admin-templates-category';
|
const isCategoryCard = template.id === 'admin-templates-category';
|
||||||
// const isCustomCard = template.id === 'custom';
|
// const isCustomCard = template.id === 'custom';
|
||||||
@ -124,7 +124,7 @@ export function TemplateSelectionStep({
|
|||||||
>
|
>
|
||||||
<Card
|
<Card
|
||||||
className={`h-full transition-all duration-300 border-2 ${isDisabled
|
className={`h-full transition-all duration-300 border-2 ${isDisabled
|
||||||
? 'border-gray-200 bg-gray-50/50 opacity-50 cursor-not-allowed'
|
? 'border-gray-200 bg-gray-50/50 opacity-85 cursor-not-allowed'
|
||||||
: isSelected
|
: isSelected
|
||||||
? 'border-blue-500 shadow-xl bg-blue-50/50 ring-2 ring-blue-200 cursor-pointer'
|
? 'border-blue-500 shadow-xl bg-blue-50/50 ring-2 ring-blue-200 cursor-pointer'
|
||||||
: isCategoryCard
|
: isCategoryCard
|
||||||
|
|||||||
@ -129,7 +129,7 @@ function BackendAuthProvider({ children }: { children: ReactNode }) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// PRIORITY 3: Skip auth check if on callback page - let callback handler process first
|
// PRIORITY 3: Skip auth check if on callback page - let callback handler process first
|
||||||
// This is essential for production mode where we need to exchange code for tokens
|
// This is critical for production mode where we need to exchange code for tokens
|
||||||
// before we can verify session with server
|
// before we can verify session with server
|
||||||
if (window.location.pathname === '/login/callback' || window.location.pathname === '/login/tanflow/callback') {
|
if (window.location.pathname === '/login/callback' || window.location.pathname === '/login/tanflow/callback') {
|
||||||
// Don't check auth status here - let the callback handler do its job
|
// Don't check auth status here - let the callback handler do its job
|
||||||
@ -149,14 +149,14 @@ function BackendAuthProvider({ children }: { children: ReactNode }) {
|
|||||||
// In production: Always verify with server (cookies are sent automatically)
|
// In production: Always verify with server (cookies are sent automatically)
|
||||||
// In development: Check local auth data first
|
// In development: Check local auth data first
|
||||||
if (isProductionMode) {
|
if (isProductionMode) {
|
||||||
// Prod: Verify session with server via httpOnly cookie
|
// Production: Verify session with server via httpOnly cookie
|
||||||
if (!isLoggingOut) {
|
if (!isLoggingOut) {
|
||||||
checkAuthStatus();
|
checkAuthStatus();
|
||||||
} else {
|
} else {
|
||||||
setIsLoading(false);
|
setIsLoading(false);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// Dev: If no auth data exists, user is not authenticated
|
// Development: If no auth data exists, user is not authenticated
|
||||||
if (!hasAuthData) {
|
if (!hasAuthData) {
|
||||||
setIsAuthenticated(false);
|
setIsAuthenticated(false);
|
||||||
setUser(null);
|
setUser(null);
|
||||||
@ -323,7 +323,7 @@ function BackendAuthProvider({ children }: { children: ReactNode }) {
|
|||||||
try {
|
try {
|
||||||
setIsLoading(true);
|
setIsLoading(true);
|
||||||
|
|
||||||
// Prod MODE: Verify session via httpOnly cookie
|
// PRODUCTION MODE: Verify session via httpOnly cookie
|
||||||
// The cookie is sent automatically with the request (withCredentials: true)
|
// The cookie is sent automatically with the request (withCredentials: true)
|
||||||
if (isProductionMode) {
|
if (isProductionMode) {
|
||||||
const storedUser = TokenManager.getUserData();
|
const storedUser = TokenManager.getUserData();
|
||||||
@ -369,7 +369,7 @@ function BackendAuthProvider({ children }: { children: ReactNode }) {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Dev MODE: Check local token
|
// DEVELOPMENT MODE: Check local token
|
||||||
const token = TokenManager.getAccessToken();
|
const token = TokenManager.getAccessToken();
|
||||||
const storedUser = TokenManager.getUserData();
|
const storedUser = TokenManager.getUserData();
|
||||||
|
|
||||||
@ -454,7 +454,7 @@ function BackendAuthProvider({ children }: { children: ReactNode }) {
|
|||||||
try {
|
try {
|
||||||
setError(null);
|
setError(null);
|
||||||
// Redirect to Okta login
|
// Redirect to Okta login
|
||||||
const oktaDomain = import.meta.env.VITE_OKTA_DOMAIN || '{{IDP_DOMAIN}}';
|
const oktaDomain = import.meta.env.VITE_OKTA_DOMAIN || 'https://dev-830839.oktapreview.com';
|
||||||
const clientId = import.meta.env.VITE_OKTA_CLIENT_ID || '0oa2jgzvrpdwx2iqd0h8';
|
const clientId = import.meta.env.VITE_OKTA_CLIENT_ID || '0oa2jgzvrpdwx2iqd0h8';
|
||||||
const redirectUri = `${window.location.origin}/login/callback`;
|
const redirectUri = `${window.location.origin}/login/callback`;
|
||||||
const responseType = 'code';
|
const responseType = 'code';
|
||||||
@ -490,7 +490,7 @@ function BackendAuthProvider({ children }: { children: ReactNode }) {
|
|||||||
|
|
||||||
const logout = async () => {
|
const logout = async () => {
|
||||||
try {
|
try {
|
||||||
//: Get id_token from TokenManager before clearing anything
|
// CRITICAL: Get id_token from TokenManager before clearing anything
|
||||||
// Needed for both Okta and Tanflow logout endpoints
|
// Needed for both Okta and Tanflow logout endpoints
|
||||||
const idToken = TokenManager.getIdToken();
|
const idToken = TokenManager.getIdToken();
|
||||||
|
|
||||||
@ -609,7 +609,7 @@ function BackendAuthProvider({ children }: { children: ReactNode }) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Dev mode: tokens in localStorage
|
// Development mode: tokens in localStorage
|
||||||
const token = TokenManager.getAccessToken();
|
const token = TokenManager.getAccessToken();
|
||||||
if (token && !isTokenExpired(token)) {
|
if (token && !isTokenExpired(token)) {
|
||||||
return token;
|
return token;
|
||||||
@ -672,7 +672,7 @@ function BackendAuthProvider({ children }: { children: ReactNode }) {
|
|||||||
export function _Auth0AuthProvider({ children }: { children: ReactNode }) {
|
export function _Auth0AuthProvider({ children }: { children: ReactNode }) {
|
||||||
return (
|
return (
|
||||||
<Auth0Provider
|
<Auth0Provider
|
||||||
domain="{{IDP_DOMAIN}}/oauth2/default/v1"
|
domain="https://dev-830839.oktapreview.com/oauth2/default/v1"
|
||||||
clientId="0oa2j8slwj5S4bG5k0h8"
|
clientId="0oa2j8slwj5S4bG5k0h8"
|
||||||
authorizationParams={{
|
authorizationParams={{
|
||||||
redirect_uri: window.location.origin + '/login/callback',
|
redirect_uri: window.location.origin + '/login/callback',
|
||||||
|
|||||||
@ -31,14 +31,14 @@ export function StandardClosedRequestsFilters({
|
|||||||
searchTerm,
|
searchTerm,
|
||||||
priorityFilter,
|
priorityFilter,
|
||||||
statusFilter,
|
statusFilter,
|
||||||
templateTypeFilter: _templateTypeFilter,
|
// templateTypeFilter,
|
||||||
sortBy,
|
sortBy,
|
||||||
sortOrder,
|
sortOrder,
|
||||||
activeFiltersCount,
|
activeFiltersCount,
|
||||||
onSearchChange,
|
onSearchChange,
|
||||||
onPriorityChange,
|
onPriorityChange,
|
||||||
onStatusChange,
|
onStatusChange,
|
||||||
onTemplateTypeChange: _onTemplateTypeChange,
|
// onTemplateTypeChange,
|
||||||
onSortByChange,
|
onSortByChange,
|
||||||
onSortOrderChange,
|
onSortOrderChange,
|
||||||
onClearFilters,
|
onClearFilters,
|
||||||
@ -130,8 +130,8 @@ export function StandardClosedRequestsFilters({
|
|||||||
</SelectItem>
|
</SelectItem>
|
||||||
</SelectContent>
|
</SelectContent>
|
||||||
</Select>
|
</Select>
|
||||||
|
{/*
|
||||||
{/* <Select value={_templateTypeFilter} onValueChange={_onTemplateTypeChange}>
|
<Select value={templateTypeFilter} onValueChange={onTemplateTypeChange}>
|
||||||
<SelectTrigger className="h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white" data-testid="closed-requests-template-type-filter">
|
<SelectTrigger className="h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white" data-testid="closed-requests-template-type-filter">
|
||||||
<SelectValue placeholder="All Templates" />
|
<SelectValue placeholder="All Templates" />
|
||||||
</SelectTrigger>
|
</SelectTrigger>
|
||||||
|
|||||||
@ -31,13 +31,13 @@ export function StandardRequestsFilters({
|
|||||||
searchTerm,
|
searchTerm,
|
||||||
statusFilter,
|
statusFilter,
|
||||||
priorityFilter,
|
priorityFilter,
|
||||||
templateTypeFilter: _templateTypeFilter,
|
// templateTypeFilter,
|
||||||
sortBy,
|
sortBy,
|
||||||
sortOrder,
|
sortOrder,
|
||||||
onSearchChange,
|
onSearchChange,
|
||||||
onStatusFilterChange,
|
onStatusFilterChange,
|
||||||
onPriorityFilterChange,
|
onPriorityFilterChange,
|
||||||
onTemplateTypeFilterChange: _onTemplateTypeFilterChange,
|
// onTemplateTypeFilterChange,
|
||||||
onSortByChange,
|
onSortByChange,
|
||||||
onSortOrderChange,
|
onSortOrderChange,
|
||||||
onClearFilters,
|
onClearFilters,
|
||||||
|
|||||||
@ -87,7 +87,7 @@ export function StandardUserAllRequestsFilters({
|
|||||||
searchTerm,
|
searchTerm,
|
||||||
statusFilter,
|
statusFilter,
|
||||||
priorityFilter,
|
priorityFilter,
|
||||||
templateTypeFilter: _templateTypeFilter,
|
// templateTypeFilter,
|
||||||
departmentFilter,
|
departmentFilter,
|
||||||
slaComplianceFilter,
|
slaComplianceFilter,
|
||||||
initiatorFilter: _initiatorFilter,
|
initiatorFilter: _initiatorFilter,
|
||||||
@ -104,7 +104,7 @@ export function StandardUserAllRequestsFilters({
|
|||||||
onSearchChange,
|
onSearchChange,
|
||||||
onStatusChange,
|
onStatusChange,
|
||||||
onPriorityChange,
|
onPriorityChange,
|
||||||
onTemplateTypeChange: _onTemplateTypeChange,
|
// onTemplateTypeChange,
|
||||||
onDepartmentChange,
|
onDepartmentChange,
|
||||||
onSlaComplianceChange,
|
onSlaComplianceChange,
|
||||||
onInitiatorChange: _onInitiatorChange,
|
onInitiatorChange: _onInitiatorChange,
|
||||||
@ -180,7 +180,7 @@ export function StandardUserAllRequestsFilters({
|
|||||||
</SelectContent>
|
</SelectContent>
|
||||||
</Select>
|
</Select>
|
||||||
|
|
||||||
{/* <Select value={_templateTypeFilter} onValueChange={_onTemplateTypeChange}>
|
{/* <Select value={templateTypeFilter} onValueChange={onTemplateTypeChange}>
|
||||||
<SelectTrigger className="h-10" data-testid="template-type-filter">
|
<SelectTrigger className="h-10" data-testid="template-type-filter">
|
||||||
<SelectValue placeholder="All Templates" />
|
<SelectValue placeholder="All Templates" />
|
||||||
</SelectTrigger>
|
</SelectTrigger>
|
||||||
|
|||||||
@ -141,7 +141,7 @@ export function ClaimApproverSelectionStep({
|
|||||||
// Create new approver only if it doesn't exist
|
// Create new approver only if it doesn't exist
|
||||||
if (step.isAuto) {
|
if (step.isAuto) {
|
||||||
// System steps
|
// System steps
|
||||||
const systemEmail = step.level === 8 ? `finance@${import.meta.env.VITE_APP_DOMAIN}` : `system@${import.meta.env.VITE_APP_DOMAIN}`;
|
const systemEmail = step.level === 8 ? 'finance@royalenfield.com' : 'system@royalenfield.com';
|
||||||
const systemName = step.level === 8 ? 'System/Finance' : 'System';
|
const systemName = step.level === 8 ? 'System/Finance' : 'System';
|
||||||
newApprovers.push({
|
newApprovers.push({
|
||||||
email: systemEmail,
|
email: systemEmail,
|
||||||
@ -921,14 +921,16 @@ export function ClaimApproverSelectionStep({
|
|||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
|
|
||||||
<div className={`p-3 rounded-lg border-2 transition-all ${approver.email && approver.userId
|
<div className={`p-3 rounded-lg border-2 transition-all ${
|
||||||
|
approver.email && approver.userId
|
||||||
? 'border-green-200 bg-green-50'
|
? 'border-green-200 bg-green-50'
|
||||||
: isPreFilled
|
: isPreFilled
|
||||||
? 'border-blue-200 bg-blue-50'
|
? 'border-blue-200 bg-blue-50'
|
||||||
: 'border-gray-200 bg-gray-50'
|
: 'border-gray-200 bg-gray-50'
|
||||||
}`}>
|
}`}>
|
||||||
<div className="flex items-start gap-3">
|
<div className="flex items-start gap-3">
|
||||||
<div className={`w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0 ${approver.email && approver.userId
|
<div className={`w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0 ${
|
||||||
|
approver.email && approver.userId
|
||||||
? 'bg-green-600'
|
? 'bg-green-600'
|
||||||
: isPreFilled
|
: isPreFilled
|
||||||
? 'bg-blue-600'
|
? 'bg-blue-600'
|
||||||
@ -950,20 +952,14 @@ export function ClaimApproverSelectionStep({
|
|||||||
</div>
|
</div>
|
||||||
<p className="text-xs text-gray-600 mb-2">{step.description}</p>
|
<p className="text-xs text-gray-600 mb-2">{step.description}</p>
|
||||||
|
|
||||||
{isEditable && (() => {
|
{isEditable && (
|
||||||
const isVerified = !!(approver.email && approver.userId);
|
|
||||||
const isEmpty = !approver.email && !isPreFilled;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<div>
|
<div>
|
||||||
<div className="flex items-center justify-between mb-1">
|
<div className="flex items-center justify-between mb-1">
|
||||||
<Label htmlFor={`approver-${step.level}`} className={`text-xs font-bold ${isEmpty ? 'text-blue-900' : isVerified ? 'text-green-900' : 'text-gray-900'
|
<Label htmlFor={`approver-${step.level}`} className="text-xs font-medium">
|
||||||
}`}>
|
Email Address {!isPreFilled && '*'}
|
||||||
Approver Email {!isPreFilled && '*'}
|
|
||||||
{isEmpty && <span className="ml-2 text-[10px] font-semibold italic text-blue-600">(Required)</span>}
|
|
||||||
</Label>
|
</Label>
|
||||||
{isVerified && (
|
{approver.email && approver.userId && (
|
||||||
<Badge variant="outline" className="text-xs bg-green-50 text-green-700 border-green-300">
|
<Badge variant="outline" className="text-xs bg-green-50 text-green-700 border-green-300">
|
||||||
<CheckCircle className="w-3 h-3 mr-1" />
|
<CheckCircle className="w-3 h-3 mr-1" />
|
||||||
Verified
|
Verified
|
||||||
@ -974,7 +970,7 @@ export function ClaimApproverSelectionStep({
|
|||||||
<Input
|
<Input
|
||||||
id={`approver-${step.level}`}
|
id={`approver-${step.level}`}
|
||||||
type="text"
|
type="text"
|
||||||
placeholder={isPreFilled ? approver.email : "@username or email..."}
|
placeholder={isPreFilled ? approver.email : "@approver@royalenfield.com"}
|
||||||
value={approver.email || ''}
|
value={approver.email || ''}
|
||||||
onChange={(e) => {
|
onChange={(e) => {
|
||||||
const newValue = e.target.value;
|
const newValue = e.target.value;
|
||||||
@ -983,12 +979,7 @@ export function ClaimApproverSelectionStep({
|
|||||||
}
|
}
|
||||||
}}
|
}}
|
||||||
disabled={isPreFilled || step.isAuto}
|
disabled={isPreFilled || step.isAuto}
|
||||||
className={`h-9 border-2 transition-all mt-1 w-full text-sm ${isPreFilled
|
className="h-9 border-2 border-gray-300 focus:border-blue-500 mt-1 w-full text-sm"
|
||||||
? 'bg-gray-100/80 border-gray-300 text-gray-700 cursor-not-allowed font-medium'
|
|
||||||
: isVerified
|
|
||||||
? 'bg-green-50/50 border-green-600 focus:border-green-700 ring-offset-green-50 focus:ring-1 focus:ring-green-100 font-semibold text-gray-900'
|
|
||||||
: 'bg-white border-blue-300 shadow-sm shadow-blue-100/50 focus:border-blue-500 focus:ring-1 focus:ring-blue-100 text-gray-900'
|
|
||||||
}`}
|
|
||||||
/>
|
/>
|
||||||
{/* Search suggestions dropdown */}
|
{/* Search suggestions dropdown */}
|
||||||
{!isPreFilled && !step.isAuto && (userSearchLoading[step.level - 1] || (userSearchResults[step.level - 1]?.length || 0) > 0) && (
|
{!isPreFilled && !step.isAuto && (userSearchLoading[step.level - 1] || (userSearchResults[step.level - 1]?.length || 0) > 0) && (
|
||||||
@ -1023,8 +1014,7 @@ export function ClaimApproverSelectionStep({
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
<Label htmlFor={`tat-${step.level}`} className={`text-xs font-bold ${isEmpty ? 'text-blue-900' : isVerified ? 'text-green-900' : 'text-gray-900'
|
<Label htmlFor={`tat-${step.level}`} className="text-xs font-medium">
|
||||||
}`}>
|
|
||||||
TAT (Turn Around Time) *
|
TAT (Turn Around Time) *
|
||||||
</Label>
|
</Label>
|
||||||
<div className="flex items-center gap-2 mt-1">
|
<div className="flex items-center gap-2 mt-1">
|
||||||
@ -1037,24 +1027,14 @@ export function ClaimApproverSelectionStep({
|
|||||||
value={approver.tat || ''}
|
value={approver.tat || ''}
|
||||||
onChange={(e) => handleTatChange(step.level, parseInt(e.target.value) || '')}
|
onChange={(e) => handleTatChange(step.level, parseInt(e.target.value) || '')}
|
||||||
disabled={step.isAuto}
|
disabled={step.isAuto}
|
||||||
className={`h-9 border-2 transition-all flex-1 text-sm ${isPreFilled
|
className="h-9 border-2 border-gray-300 focus:border-blue-500 flex-1 text-sm"
|
||||||
? 'bg-gray-100/80 border-gray-300 text-gray-700 cursor-not-allowed font-medium'
|
|
||||||
: isVerified
|
|
||||||
? 'bg-green-50/50 border-green-600 focus:border-green-700 focus:ring-1 focus:ring-green-100 font-semibold text-gray-900'
|
|
||||||
: 'bg-white border-blue-300 shadow-sm shadow-blue-100/50 focus:border-blue-500 focus:ring-1 focus:ring-blue-100 text-gray-900'
|
|
||||||
}`}
|
|
||||||
/>
|
/>
|
||||||
<Select
|
<Select
|
||||||
value={approver.tatType || 'hours'}
|
value={approver.tatType || 'hours'}
|
||||||
onValueChange={(value) => handleTatTypeChange(step.level, value as 'hours' | 'days')}
|
onValueChange={(value) => handleTatTypeChange(step.level, value as 'hours' | 'days')}
|
||||||
disabled={step.isAuto}
|
disabled={step.isAuto}
|
||||||
>
|
>
|
||||||
<SelectTrigger className={`w-20 h-9 border-2 transition-all text-sm ${isPreFilled
|
<SelectTrigger className="w-20 h-9 border-2 border-gray-300 text-sm">
|
||||||
? 'bg-gray-100/80 border-gray-300 text-gray-700 cursor-not-allowed'
|
|
||||||
: isVerified
|
|
||||||
? 'bg-green-50/50 border-green-600 focus:border-green-700 focus:ring-1 focus:ring-green-100 text-gray-900 font-medium'
|
|
||||||
: 'bg-white border-blue-300 focus:border-blue-500 focus:ring-1 focus:ring-blue-100 text-gray-900'
|
|
||||||
}`}>
|
|
||||||
<SelectValue />
|
<SelectValue />
|
||||||
</SelectTrigger>
|
</SelectTrigger>
|
||||||
<SelectContent>
|
<SelectContent>
|
||||||
@ -1065,8 +1045,7 @@ export function ClaimApproverSelectionStep({
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
)}
|
||||||
})()}
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@ -29,7 +29,7 @@ import {
|
|||||||
} from 'lucide-react';
|
} from 'lucide-react';
|
||||||
import { format } from 'date-fns';
|
import { format } from 'date-fns';
|
||||||
import { toast } from 'sonner';
|
import { toast } from 'sonner';
|
||||||
import { verifyDealerLogin, searchExternalDealerByCode, type DealerInfo } from '@/services/dealerApi';
|
import { getAllDealers as fetchDealersFromAPI, verifyDealerLogin, type DealerInfo } from '@/services/dealerApi';
|
||||||
import { ClaimApproverSelectionStep } from './ClaimApproverSelectionStep';
|
import { ClaimApproverSelectionStep } from './ClaimApproverSelectionStep';
|
||||||
import { useAuth } from '@/contexts/AuthContext';
|
import { useAuth } from '@/contexts/AuthContext';
|
||||||
import { getPublicConfigurations, AdminConfiguration, getActivityTypes, type ActivityType } from '@/services/adminApi';
|
import { getPublicConfigurations, AdminConfiguration, getActivityTypes, type ActivityType } from '@/services/adminApi';
|
||||||
@ -194,26 +194,10 @@ export function ClaimManagementWizard({ onBack, onSubmit }: ClaimManagementWizar
|
|||||||
// Debounce search
|
// Debounce search
|
||||||
dealerSearchTimer.current = setTimeout(async () => {
|
dealerSearchTimer.current = setTimeout(async () => {
|
||||||
try {
|
try {
|
||||||
const result = await searchExternalDealerByCode(value);
|
const results = await fetchDealersFromAPI(value, 10); // Limit to 10 results
|
||||||
if (result) {
|
setDealerSearchResults(results);
|
||||||
// Map external API response to DealerInfo structure
|
|
||||||
const mappedDealer: DealerInfo = {
|
|
||||||
dealerId: result.dealer || result.dealer_code || value,
|
|
||||||
dealerCode: result.dealer || result.dealer_code || value,
|
|
||||||
dealerName: result['dealer name'] || result.dealer_name || 'Unknown Dealer',
|
|
||||||
displayName: result['dealer name'] || result.dealer_name || 'Unknown Dealer',
|
|
||||||
email: result['dealer email'] || '',
|
|
||||||
phone: result['dealer phone'] || '',
|
|
||||||
city: result['re city'] || result.city || '',
|
|
||||||
state: result['re state code'] || result.state || '',
|
|
||||||
isLoggedIn: true, // We'll verify this in the next step
|
|
||||||
};
|
|
||||||
setDealerSearchResults([mappedDealer]);
|
|
||||||
} else {
|
|
||||||
setDealerSearchResults([]);
|
|
||||||
}
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error searching external dealer:', error);
|
console.error('Error searching dealers:', error);
|
||||||
setDealerSearchResults([]);
|
setDealerSearchResults([]);
|
||||||
} finally {
|
} finally {
|
||||||
setDealerSearchLoading(false);
|
setDealerSearchLoading(false);
|
||||||
@ -898,7 +882,8 @@ export function ClaimManagementWizard({ onBack, onSubmit }: ClaimManagementWizar
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div key={`${approver.level}-${approver.email}`} className={`p-3 rounded-lg border ${approver.isAdditional ? 'bg-purple-50 border-purple-200' : 'bg-gray-50 border-gray-200'
|
<div key={`${approver.level}-${approver.email}`} className={`p-3 rounded-lg border ${
|
||||||
|
approver.isAdditional ? 'bg-purple-50 border-purple-200' : 'bg-gray-50 border-gray-200'
|
||||||
}`}>
|
}`}>
|
||||||
<div className="flex items-center justify-between">
|
<div className="flex items-center justify-between">
|
||||||
<div className="flex-1">
|
<div className="flex-1">
|
||||||
@ -1065,7 +1050,8 @@ export function ClaimManagementWizard({ onBack, onSubmit }: ClaimManagementWizar
|
|||||||
{STEP_NAMES.map((_name, index) => (
|
{STEP_NAMES.map((_name, index) => (
|
||||||
<span
|
<span
|
||||||
key={index}
|
key={index}
|
||||||
className={`text-xs sm:text-sm ${index + 1 <= currentStep ? 'text-blue-600 font-medium' : 'text-gray-400'
|
className={`text-xs sm:text-sm ${
|
||||||
|
index + 1 <= currentStep ? 'text-blue-600 font-medium' : 'text-gray-400'
|
||||||
}`}
|
}`}
|
||||||
>
|
>
|
||||||
{index + 1}
|
{index + 1}
|
||||||
@ -1099,7 +1085,8 @@ export function ClaimManagementWizard({ onBack, onSubmit }: ClaimManagementWizar
|
|||||||
{currentStep < totalSteps ? (
|
{currentStep < totalSteps ? (
|
||||||
<Button
|
<Button
|
||||||
onClick={nextStep}
|
onClick={nextStep}
|
||||||
className={`gap-2 w-full sm:w-auto order-1 sm:order-2 ${!isStepValid()
|
className={`gap-2 w-full sm:w-auto order-1 sm:order-2 ${
|
||||||
|
!isStepValid()
|
||||||
? 'opacity-50 cursor-pointer hover:opacity-60'
|
? 'opacity-50 cursor-pointer hover:opacity-60'
|
||||||
: ''
|
: ''
|
||||||
}`}
|
}`}
|
||||||
|
|||||||
@ -5,13 +5,13 @@
|
|||||||
* Located in: src/dealer-claim/components/request-detail/
|
* Located in: src/dealer-claim/components/request-detail/
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { useState, useEffect, useMemo } from 'react';
|
import { useState, useEffect } from 'react';
|
||||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { Input } from '@/components/ui/input';
|
import { Input } from '@/components/ui/input';
|
||||||
import { Label } from '@/components/ui/label';
|
import { Label } from '@/components/ui/label';
|
||||||
import { Badge } from '@/components/ui/badge';
|
import { Badge } from '@/components/ui/badge';
|
||||||
import { DollarSign, Download, CircleCheckBig, Target, CircleAlert } from 'lucide-react';
|
import { DollarSign, Download, CircleCheckBig, Target } from 'lucide-react';
|
||||||
import { toast } from 'sonner';
|
import { toast } from 'sonner';
|
||||||
import { validateIO, updateIODetails, getClaimDetails } from '@/services/dealerClaimApi';
|
import { validateIO, updateIODetails, getClaimDetails } from '@/services/dealerClaimApi';
|
||||||
import { useAuth } from '@/contexts/AuthContext';
|
import { useAuth } from '@/contexts/AuthContext';
|
||||||
@ -30,87 +30,95 @@ interface IOBlockedDetails {
|
|||||||
blockedDate: string;
|
blockedDate: string;
|
||||||
blockedBy: string; // User who blocked
|
blockedBy: string; // User who blocked
|
||||||
sapDocumentNumber: string;
|
sapDocumentNumber: string;
|
||||||
status: 'blocked' | 'released' | 'failed' | 'pending';
|
status: 'blocked' | 'released' | 'failed';
|
||||||
}
|
}
|
||||||
|
|
||||||
export function IOTab({ request, apiRequest, onRefresh }: IOTabProps) {
|
export function IOTab({ request, apiRequest, onRefresh }: IOTabProps) {
|
||||||
const { user } = useAuth();
|
const { user } = useAuth();
|
||||||
const requestId = apiRequest?.requestId || request?.requestId;
|
const requestId = apiRequest?.requestId || request?.requestId;
|
||||||
|
|
||||||
|
// Load existing IO data from apiRequest or request
|
||||||
|
const internalOrder = apiRequest?.internalOrder || apiRequest?.internal_order || null;
|
||||||
|
const existingIONumber = internalOrder?.ioNumber || internalOrder?.io_number || request?.ioNumber || '';
|
||||||
|
const existingBlockedAmount = internalOrder?.ioBlockedAmount || internalOrder?.io_blocked_amount || 0;
|
||||||
|
const existingAvailableBalance = internalOrder?.ioAvailableBalance || internalOrder?.io_available_balance || 0;
|
||||||
|
const existingRemainingBalance = internalOrder?.ioRemainingBalance || internalOrder?.io_remaining_balance || 0;
|
||||||
|
const sapDocNumber = internalOrder?.sapDocumentNumber || internalOrder?.sap_document_number || '';
|
||||||
// Get organizer user object from association (organizer) or fallback to organizedBy UUID
|
// Get organizer user object from association (organizer) or fallback to organizedBy UUID
|
||||||
|
const organizer = internalOrder?.organizer || null;
|
||||||
|
|
||||||
|
// Get estimated budget from proposal details
|
||||||
const proposalDetails = apiRequest?.proposalDetails || {};
|
const proposalDetails = apiRequest?.proposalDetails || {};
|
||||||
const claimDetails = apiRequest?.claimDetails || apiRequest || {};
|
const estimatedBudget = Number(proposalDetails?.totalEstimatedBudget || proposalDetails?.total_estimated_budget || 0);
|
||||||
|
|
||||||
// Calculate total base amount (needed for budget verification as requested)
|
const [ioNumber, setIoNumber] = useState(existingIONumber);
|
||||||
// This is the taxable amount excluding GST
|
|
||||||
const totalBaseAmount = useMemo(() => {
|
|
||||||
const costBreakupRaw = proposalDetails?.costBreakup || claimDetails?.costBreakup || [];
|
|
||||||
const costBreakup = Array.isArray(costBreakupRaw)
|
|
||||||
? costBreakupRaw
|
|
||||||
: (typeof costBreakupRaw === 'string'
|
|
||||||
? JSON.parse(costBreakupRaw)
|
|
||||||
: []);
|
|
||||||
|
|
||||||
if (!Array.isArray(costBreakup) || costBreakup.length === 0) {
|
|
||||||
return Number(claimDetails?.totalProposedTaxableAmount || proposalDetails?.totalEstimatedBudget || proposalDetails?.total_estimated_budget || 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
return costBreakup.reduce((sum: number, item: any) => {
|
|
||||||
const amount = typeof item === 'object' ? (item.amount || 0) : 0;
|
|
||||||
const quantity = typeof item === 'object' ? (item.quantity || 1) : 1;
|
|
||||||
return sum + (Number(amount) * Number(quantity));
|
|
||||||
}, 0);
|
|
||||||
}, [proposalDetails?.costBreakup, claimDetails?.costBreakup, claimDetails?.totalProposedTaxableAmount, proposalDetails?.totalEstimatedBudget]);
|
|
||||||
|
|
||||||
// Use base amount as the target budget for blocking
|
|
||||||
const estimatedBudget = totalBaseAmount;
|
|
||||||
|
|
||||||
// Budget status for signaling (Scenario 2)
|
|
||||||
// Use apiRequest as the primary source of truth, fall back to request
|
|
||||||
const budgetTracking = apiRequest?.budgetTracking || request?.budgetTracking || {};
|
|
||||||
const budgetStatus = budgetTracking?.budgetStatus || budgetTracking?.budget_status || '';
|
|
||||||
const internalOrdersList = apiRequest?.internalOrders || apiRequest?.internal_orders || request?.internalOrders || [];
|
|
||||||
const isAdditionalBlockingNeeded = budgetStatus === 'PROPOSED' && internalOrdersList.length > 0;
|
|
||||||
|
|
||||||
const [ioNumber, setIoNumber] = useState('');
|
|
||||||
const [fetchingAmount, setFetchingAmount] = useState(false);
|
const [fetchingAmount, setFetchingAmount] = useState(false);
|
||||||
const [fetchedAmount, setFetchedAmount] = useState<number | null>(null);
|
const [fetchedAmount, setFetchedAmount] = useState<number | null>(null);
|
||||||
const [amountToBlock, setAmountToBlock] = useState<string>('');
|
const [amountToBlock, setAmountToBlock] = useState<string>('');
|
||||||
const [blockedIOs, setBlockedIOs] = useState<IOBlockedDetails[]>([]);
|
const [blockedDetails, setBlockedDetails] = useState<IOBlockedDetails | null>(null);
|
||||||
const [blockingBudget, setBlockingBudget] = useState(false);
|
const [blockingBudget, setBlockingBudget] = useState(false);
|
||||||
|
|
||||||
// Load existing IO blocks
|
// Load existing IO block details from apiRequest
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (internalOrdersList.length > 0) {
|
if (internalOrder && existingIONumber) {
|
||||||
const formattedIOs = internalOrdersList.map((io: any) => {
|
// IMPORTANT: ioAvailableBalance is already the available balance BEFORE blocking
|
||||||
const org = io.organizer || null;
|
// We should NOT add blockedAmount to it - that would cause double deduction
|
||||||
const blockedByName = org?.displayName ||
|
// Backend stores: availableBalance (before block), blockedAmount, remainingBalance (after block)
|
||||||
org?.display_name ||
|
const availableBeforeBlock = Number(existingAvailableBalance) || 0;
|
||||||
org?.name ||
|
|
||||||
(org?.firstName && org?.lastName ? `${org.firstName} ${org.lastName}`.trim() : null) ||
|
|
||||||
org?.email ||
|
|
||||||
'Unknown User';
|
|
||||||
return {
|
|
||||||
ioNumber: io.ioNumber || io.io_number,
|
|
||||||
blockedAmount: Number(io.ioBlockedAmount || io.io_blocked_amount || 0),
|
|
||||||
availableBalance: Number(io.ioAvailableBalance || io.io_available_balance || 0),
|
|
||||||
remainingBalance: Number(io.ioRemainingBalance || io.io_remaining_balance || 0),
|
|
||||||
blockedDate: io.organizedAt || io.organized_at || new Date().toISOString(),
|
|
||||||
blockedBy: blockedByName,
|
|
||||||
sapDocumentNumber: io.sapDocumentNumber || io.sap_document_number || '',
|
|
||||||
status: (io.status === 'BLOCKED' ? 'blocked' :
|
|
||||||
io.status === 'RELEASED' ? 'released' :
|
|
||||||
io.status === 'PENDING' ? 'pending' : 'blocked') as any,
|
|
||||||
};
|
|
||||||
});
|
|
||||||
setBlockedIOs(formattedIOs);
|
|
||||||
|
|
||||||
// If we are not in Scenario 2 (additional blocking), set the IO number from the last block for convenience
|
// Get blocked by user name from organizer association (who blocked the amount)
|
||||||
if (!isAdditionalBlockingNeeded && formattedIOs.length > 0) {
|
// When amount is blocked, organizedBy stores the user who blocked it
|
||||||
setIoNumber(formattedIOs[formattedIOs.length - 1].ioNumber);
|
const blockedByName = organizer?.displayName ||
|
||||||
|
organizer?.display_name ||
|
||||||
|
organizer?.name ||
|
||||||
|
(organizer?.firstName && organizer?.lastName ? `${organizer.firstName} ${organizer.lastName}`.trim() : null) ||
|
||||||
|
organizer?.email ||
|
||||||
|
'Unknown User';
|
||||||
|
|
||||||
|
// Set IO number from existing data
|
||||||
|
setIoNumber(existingIONumber);
|
||||||
|
|
||||||
|
// Only set blocked details if amount is blocked
|
||||||
|
if (existingBlockedAmount > 0) {
|
||||||
|
const blockedAmt = Number(existingBlockedAmount) || 0;
|
||||||
|
const backendRemaining = Number(existingRemainingBalance) || 0;
|
||||||
|
|
||||||
|
// Calculate expected remaining balance for validation/debugging
|
||||||
|
// Formula: remaining = availableBeforeBlock - blockedAmount
|
||||||
|
const expectedRemaining = availableBeforeBlock - blockedAmt;
|
||||||
|
|
||||||
|
// Loading existing IO block
|
||||||
|
|
||||||
|
// Warn if remaining balance calculation seems incorrect (for backend debugging)
|
||||||
|
if (Math.abs(backendRemaining - expectedRemaining) > 0.01) {
|
||||||
|
console.warn('[IOTab] ⚠️ Remaining balance calculation issue detected!', {
|
||||||
|
availableBalance: availableBeforeBlock,
|
||||||
|
blockedAmount: blockedAmt,
|
||||||
|
expectedRemaining,
|
||||||
|
backendRemaining,
|
||||||
|
difference: backendRemaining - expectedRemaining,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
setBlockedDetails({
|
||||||
|
ioNumber: existingIONumber,
|
||||||
|
blockedAmount: blockedAmt,
|
||||||
|
availableBalance: availableBeforeBlock, // Available amount before block
|
||||||
|
remainingBalance: backendRemaining, // Use backend calculated value
|
||||||
|
blockedDate: internalOrder.organizedAt || internalOrder.organized_at || new Date().toISOString(),
|
||||||
|
blockedBy: blockedByName,
|
||||||
|
sapDocumentNumber: sapDocNumber,
|
||||||
|
status: (internalOrder.status === 'BLOCKED' ? 'blocked' :
|
||||||
|
internalOrder.status === 'RELEASED' ? 'released' : 'blocked') as 'blocked' | 'released' | 'failed',
|
||||||
|
});
|
||||||
|
|
||||||
|
// Set fetched amount if available balance exists
|
||||||
|
if (availableBeforeBlock > 0) {
|
||||||
|
setFetchedAmount(availableBeforeBlock);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}, [apiRequest, request, isAdditionalBlockingNeeded, internalOrdersList]);
|
}
|
||||||
|
}, [internalOrder, existingIONumber, existingBlockedAmount, existingAvailableBalance, existingRemainingBalance, sapDocNumber, organizer]);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Fetch available budget from SAP
|
* Fetch available budget from SAP
|
||||||
@ -135,22 +143,12 @@ export function IOTab({ request, apiRequest, onRefresh }: IOTabProps) {
|
|||||||
|
|
||||||
if (ioData.isValid && ioData.availableBalance > 0) {
|
if (ioData.isValid && ioData.availableBalance > 0) {
|
||||||
setFetchedAmount(ioData.availableBalance);
|
setFetchedAmount(ioData.availableBalance);
|
||||||
|
// Pre-fill amount to block with estimated budget (if available), otherwise use available balance
|
||||||
// Calculate total already blocked amount
|
if (estimatedBudget > 0) {
|
||||||
const totalAlreadyBlocked = blockedIOs.reduce((sum, io) => sum + io.blockedAmount, 0);
|
setAmountToBlock(String(estimatedBudget));
|
||||||
|
|
||||||
// Calculate remaining budget to block
|
|
||||||
const remainingToBlock = Math.max(0, estimatedBudget - totalAlreadyBlocked);
|
|
||||||
|
|
||||||
// Pre-fill amount to block with remaining budget, otherwise use available balance
|
|
||||||
if (remainingToBlock > 0) {
|
|
||||||
setAmountToBlock(String(remainingToBlock.toFixed(2)));
|
|
||||||
} else if (estimatedBudget > 0 && totalAlreadyBlocked === 0) {
|
|
||||||
setAmountToBlock(String(estimatedBudget.toFixed(2)));
|
|
||||||
} else {
|
} else {
|
||||||
setAmountToBlock(String(ioData.availableBalance.toFixed(2)));
|
setAmountToBlock(String(ioData.availableBalance));
|
||||||
}
|
}
|
||||||
|
|
||||||
toast.success(`IO fetched from SAP. Available balance: ₹${ioData.availableBalance.toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`);
|
toast.success(`IO fetched from SAP. Available balance: ₹${ioData.availableBalance.toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`);
|
||||||
} else {
|
} else {
|
||||||
toast.error('Invalid IO number or no available balance found');
|
toast.error('Invalid IO number or no available balance found');
|
||||||
@ -201,18 +199,11 @@ export function IOTab({ request, apiRequest, onRefresh }: IOTabProps) {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Validate that amount to block must exactly match estimated budget
|
||||||
// Calculate total already blocked
|
|
||||||
const totalAlreadyBlocked = blockedIOs.reduce((sum, io) => sum + io.blockedAmount, 0);
|
|
||||||
const totalPlanned = totalAlreadyBlocked + blockAmount;
|
|
||||||
|
|
||||||
// Validate that total planned must exactly match estimated budget
|
|
||||||
if (estimatedBudget > 0) {
|
if (estimatedBudget > 0) {
|
||||||
const roundedEstimatedBudget = parseFloat(estimatedBudget.toFixed(2));
|
const roundedEstimatedBudget = parseFloat(estimatedBudget.toFixed(2));
|
||||||
const roundedTotalPlanned = parseFloat(totalPlanned.toFixed(2));
|
if (Math.abs(blockAmount - roundedEstimatedBudget) > 0.01) {
|
||||||
|
toast.error(`Amount to block must be exactly equal to the estimated budget (₹${roundedEstimatedBudget.toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })})`);
|
||||||
if (Math.abs(roundedTotalPlanned - roundedEstimatedBudget) > 0.01) {
|
|
||||||
toast.error(`Total blocked amount (₹${roundedTotalPlanned.toLocaleString('en-IN')}) must be exactly equal to the estimated budget (₹${roundedEstimatedBudget.toLocaleString('en-IN')})`);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -288,9 +279,8 @@ export function IOTab({ request, apiRequest, onRefresh }: IOTabProps) {
|
|||||||
status: 'blocked',
|
status: 'blocked',
|
||||||
};
|
};
|
||||||
|
|
||||||
setBlockedIOs(prev => [...prev, blocked]);
|
setBlockedDetails(blocked);
|
||||||
setAmountToBlock(''); // Clear the input
|
setAmountToBlock(''); // Clear the input
|
||||||
setFetchedAmount(null); // Reset fetched state
|
|
||||||
toast.success('IO budget blocked successfully in SAP');
|
toast.success('IO budget blocked successfully in SAP');
|
||||||
|
|
||||||
// Refresh request details
|
// Refresh request details
|
||||||
@ -331,12 +321,12 @@ export function IOTab({ request, apiRequest, onRefresh }: IOTabProps) {
|
|||||||
placeholder="Enter IO number (e.g., IO-2024-12345)"
|
placeholder="Enter IO number (e.g., IO-2024-12345)"
|
||||||
value={ioNumber}
|
value={ioNumber}
|
||||||
onChange={(e) => setIoNumber(e.target.value)}
|
onChange={(e) => setIoNumber(e.target.value)}
|
||||||
disabled={fetchingAmount || (blockedIOs.length > 0 && !isAdditionalBlockingNeeded)}
|
disabled={fetchingAmount || !!blockedDetails}
|
||||||
className="flex-1"
|
className="flex-1"
|
||||||
/>
|
/>
|
||||||
<Button
|
<Button
|
||||||
onClick={handleFetchAmount}
|
onClick={handleFetchAmount}
|
||||||
disabled={!ioNumber.trim() || fetchingAmount || (blockedIOs.length > 0 && !isAdditionalBlockingNeeded)}
|
disabled={!ioNumber.trim() || fetchingAmount || !!blockedDetails}
|
||||||
className="bg-[#2d4a3e] hover:bg-[#1f3329]"
|
className="bg-[#2d4a3e] hover:bg-[#1f3329]"
|
||||||
>
|
>
|
||||||
<Download className="w-4 h-4 mr-2" />
|
<Download className="w-4 h-4 mr-2" />
|
||||||
@ -346,7 +336,7 @@ export function IOTab({ request, apiRequest, onRefresh }: IOTabProps) {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Instructions when IO number is entered but not fetched */}
|
{/* Instructions when IO number is entered but not fetched */}
|
||||||
{!fetchedAmount && blockedIOs.length === 0 && ioNumber.trim() && (
|
{!fetchedAmount && !blockedDetails && ioNumber.trim() && (
|
||||||
<div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
|
<div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
|
||||||
<p className="text-sm text-blue-800">
|
<p className="text-sm text-blue-800">
|
||||||
<strong>Next Step:</strong> Click "Fetch Amount" to validate the IO number and get available balance from SAP.
|
<strong>Next Step:</strong> Click "Fetch Amount" to validate the IO number and get available balance from SAP.
|
||||||
@ -355,7 +345,7 @@ export function IOTab({ request, apiRequest, onRefresh }: IOTabProps) {
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Fetched Amount Display */}
|
{/* Fetched Amount Display */}
|
||||||
{fetchedAmount !== null && (blockedIOs.length === 0 || isAdditionalBlockingNeeded) && (
|
{fetchedAmount !== null && !blockedDetails && (
|
||||||
<>
|
<>
|
||||||
<div className="bg-green-50 border-2 border-green-200 rounded-lg p-4">
|
<div className="bg-green-50 border-2 border-green-200 rounded-lg p-4">
|
||||||
<div className="flex items-center justify-between">
|
<div className="flex items-center justify-between">
|
||||||
@ -406,7 +396,7 @@ export function IOTab({ request, apiRequest, onRefresh }: IOTabProps) {
|
|||||||
!amountToBlock ||
|
!amountToBlock ||
|
||||||
parseFloat(amountToBlock) <= 0 ||
|
parseFloat(amountToBlock) <= 0 ||
|
||||||
parseFloat(amountToBlock) > fetchedAmount ||
|
parseFloat(amountToBlock) > fetchedAmount ||
|
||||||
(estimatedBudget > 0 && Math.abs((blockedIOs.reduce((s, i) => s + i.blockedAmount, 0) + parseFloat(amountToBlock)) - estimatedBudget) > 0.01)
|
(estimatedBudget > 0 && Math.abs(parseFloat(amountToBlock) - estimatedBudget) > 0.01)
|
||||||
}
|
}
|
||||||
className="w-full bg-[#2d4a3e] hover:bg-[#1f3329]"
|
className="w-full bg-[#2d4a3e] hover:bg-[#1f3329]"
|
||||||
>
|
>
|
||||||
@ -430,57 +420,71 @@ export function IOTab({ request, apiRequest, onRefresh }: IOTabProps) {
|
|||||||
</CardDescription>
|
</CardDescription>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent>
|
||||||
{blockedIOs.length > 0 ? (
|
{blockedDetails ? (
|
||||||
<div className="space-y-6">
|
<div className="space-y-4">
|
||||||
{isAdditionalBlockingNeeded && (
|
{/* Success Banner */}
|
||||||
<div className="bg-amber-50 border-2 border-amber-500 rounded-lg p-4 animate-pulse">
|
<div className="bg-green-50 border-2 border-green-500 rounded-lg p-4">
|
||||||
<div className="flex items-start gap-3">
|
<div className="flex items-start gap-3">
|
||||||
<CircleAlert className="w-6 h-6 text-amber-600 flex-shrink-0 mt-0.5" />
|
<CircleCheckBig className="w-6 h-6 text-green-600 flex-shrink-0 mt-0.5" />
|
||||||
<div>
|
<div>
|
||||||
<p className="font-semibold text-amber-900">Additional Budget Blocking Required</p>
|
<p className="font-semibold text-green-900">IO Blocked Successfully</p>
|
||||||
<p className="text-sm text-amber-700 mt-1">Actual expenses exceed the previously blocked amount. Please block an additional ₹{(estimatedBudget - blockedIOs.reduce((s, i) => s + i.blockedAmount, 0)).toLocaleString('en-IN', { minimumFractionDigits: 2 })}.</p>
|
<p className="text-sm text-green-700 mt-1">Budget has been reserved in SAP system</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
|
||||||
|
|
||||||
{blockedIOs.slice().reverse().map((io, idx) => (
|
{/* Blocked Details */}
|
||||||
<div key={idx} className="border rounded-lg overflow-hidden">
|
<div className="border rounded-lg divide-y">
|
||||||
<div className={`p-3 flex justify-between items-center ${idx === 0 ? 'bg-green-50' : 'bg-gray-50'}`}>
|
<div className="p-4">
|
||||||
<span className="font-semibold text-sm">IO: {io.ioNumber}</span>
|
<p className="text-xs text-gray-500 uppercase tracking-wide mb-1">IO Number</p>
|
||||||
<Badge className={
|
<p className="text-sm font-semibold text-gray-900">{blockedDetails.ioNumber}</p>
|
||||||
io.status === 'blocked' ? 'bg-green-100 text-green-800' :
|
</div>
|
||||||
io.status === 'pending' ? 'bg-amber-100 text-amber-800' :
|
<div className="p-4">
|
||||||
'bg-blue-100 text-blue-800'
|
<p className="text-xs text-gray-500 uppercase tracking-wide mb-1">SAP Document Number</p>
|
||||||
}>
|
<p className="text-sm font-semibold text-gray-900">{blockedDetails.sapDocumentNumber || 'N/A'}</p>
|
||||||
{io.status === 'blocked' ? 'Blocked' :
|
</div>
|
||||||
io.status === 'pending' ? 'Provisioned' : 'Released'}
|
<div className="p-4 bg-green-50">
|
||||||
|
<p className="text-xs text-gray-500 uppercase tracking-wide mb-1">Blocked Amount</p>
|
||||||
|
<p className="text-xl font-bold text-green-700">
|
||||||
|
₹{blockedDetails.blockedAmount.toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div className="p-4">
|
||||||
|
<p className="text-xs text-gray-500 uppercase tracking-wide mb-1">Available Amount (Before Block)</p>
|
||||||
|
<p className="text-sm font-medium text-gray-900">
|
||||||
|
₹{blockedDetails.availableBalance.toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div className="p-4 bg-blue-50">
|
||||||
|
<p className="text-xs text-gray-500 uppercase tracking-wide mb-1">Remaining Amount (After Block)</p>
|
||||||
|
<p className="text-sm font-bold text-blue-700">
|
||||||
|
₹{blockedDetails.remainingBalance.toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div className="p-4">
|
||||||
|
<p className="text-xs text-gray-500 uppercase tracking-wide mb-1">Blocked By</p>
|
||||||
|
<p className="text-sm font-medium text-gray-900">{blockedDetails.blockedBy}</p>
|
||||||
|
</div>
|
||||||
|
<div className="p-4">
|
||||||
|
<p className="text-xs text-gray-500 uppercase tracking-wide mb-1">Blocked At</p>
|
||||||
|
<p className="text-sm font-medium text-gray-900">
|
||||||
|
{new Date(blockedDetails.blockedDate).toLocaleString('en-IN', {
|
||||||
|
year: 'numeric',
|
||||||
|
month: 'short',
|
||||||
|
day: 'numeric',
|
||||||
|
hour: 'numeric',
|
||||||
|
minute: 'numeric',
|
||||||
|
hour12: true
|
||||||
|
})}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div className="p-4 bg-gray-50">
|
||||||
|
<p className="text-xs text-gray-500 uppercase tracking-wide mb-1">Status</p>
|
||||||
|
<Badge className="bg-green-100 text-green-800 border-green-200">
|
||||||
|
<CircleCheckBig className="w-3 h-3 mr-1" />
|
||||||
|
Blocked
|
||||||
</Badge>
|
</Badge>
|
||||||
</div>
|
</div>
|
||||||
<div className="grid grid-cols-2 divide-x divide-y">
|
|
||||||
<div className="p-3">
|
|
||||||
<p className="text-[10px] text-gray-500 uppercase">Amount</p>
|
|
||||||
<p className="text-sm font-bold text-green-700">₹{io.blockedAmount.toLocaleString('en-IN')}</p>
|
|
||||||
</div>
|
|
||||||
<div className="p-3">
|
|
||||||
<p className="text-[10px] text-gray-500 uppercase">SAP Doc</p>
|
|
||||||
<p className="text-sm font-medium">{io.sapDocumentNumber || 'N/A'}</p>
|
|
||||||
</div>
|
|
||||||
<div className="p-3">
|
|
||||||
<p className="text-[10px] text-gray-500 uppercase">Blocked By</p>
|
|
||||||
<p className="text-xs">{io.blockedBy}</p>
|
|
||||||
</div>
|
|
||||||
<div className="p-3">
|
|
||||||
<p className="text-[10px] text-gray-500 uppercase">Date</p>
|
|
||||||
<p className="text-[10px]">{new Date(io.blockedDate).toLocaleString()}</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
|
|
||||||
<div className="mt-4 p-4 bg-[#2d4a3e] text-white rounded-lg flex justify-between items-center">
|
|
||||||
<span className="font-bold">Total Blocked:</span>
|
|
||||||
<span className="text-xl font-bold">₹{blockedIOs.reduce((s, i) => s + i.blockedAmount, 0).toLocaleString('en-IN', { minimumFractionDigits: 2 })}</span>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
|
|||||||
@ -10,7 +10,7 @@ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/com
|
|||||||
import { Badge } from '@/components/ui/badge';
|
import { Badge } from '@/components/ui/badge';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { Progress } from '@/components/ui/progress';
|
import { Progress } from '@/components/ui/progress';
|
||||||
import { TrendingUp, Clock, CheckCircle, CircleCheckBig, Upload, Mail, Download, Receipt, Activity, AlertTriangle, AlertOctagon, XCircle, History, ChevronDown, ChevronUp, RefreshCw, RotateCw, Eye, FileSpreadsheet, X, Loader2 } from 'lucide-react';
|
import { TrendingUp, Clock, CheckCircle, CircleCheckBig, Upload, Mail, Download, Receipt, Activity, AlertTriangle, AlertOctagon, XCircle, History, ChevronDown, ChevronUp, RefreshCw, RotateCw, Eye } from 'lucide-react';
|
||||||
import { formatDateTime, formatDateDDMMYYYY } from '@/utils/dateFormatter';
|
import { formatDateTime, formatDateDDMMYYYY } from '@/utils/dateFormatter';
|
||||||
import { formatHoursMinutes } from '@/utils/slaTracker';
|
import { formatHoursMinutes } from '@/utils/slaTracker';
|
||||||
import {
|
import {
|
||||||
@ -29,7 +29,6 @@ import { toast } from 'sonner';
|
|||||||
import { submitProposal, updateIODetails, submitCompletion, updateEInvoice, sendCreditNoteToDealer } from '@/services/dealerClaimApi';
|
import { submitProposal, updateIODetails, submitCompletion, updateEInvoice, sendCreditNoteToDealer } from '@/services/dealerClaimApi';
|
||||||
import { getWorkflowDetails, approveLevel, rejectLevel, handleInitiatorAction, getWorkflowHistory } from '@/services/workflowApi';
|
import { getWorkflowDetails, approveLevel, rejectLevel, handleInitiatorAction, getWorkflowHistory } from '@/services/workflowApi';
|
||||||
import { uploadDocument } from '@/services/documentApi';
|
import { uploadDocument } from '@/services/documentApi';
|
||||||
import { TokenManager } from '@/utils/tokenManager';
|
|
||||||
|
|
||||||
interface DealerClaimWorkflowTabProps {
|
interface DealerClaimWorkflowTabProps {
|
||||||
request: any;
|
request: any;
|
||||||
@ -49,7 +48,7 @@ interface WorkflowStep {
|
|||||||
approver: string;
|
approver: string;
|
||||||
description: string;
|
description: string;
|
||||||
tatHours: number;
|
tatHours: number;
|
||||||
status: 'pending' | 'approved' | 'waiting' | 'rejected' | 'in_progress' | 'skipped';
|
status: 'pending' | 'approved' | 'waiting' | 'rejected' | 'in_progress';
|
||||||
comment?: string;
|
comment?: string;
|
||||||
approvedAt?: string;
|
approvedAt?: string;
|
||||||
elapsedHours?: number;
|
elapsedHours?: number;
|
||||||
@ -70,7 +69,6 @@ interface WorkflowStep {
|
|||||||
};
|
};
|
||||||
einvoiceUrl?: string;
|
einvoiceUrl?: string;
|
||||||
emailTemplateUrl?: string;
|
emailTemplateUrl?: string;
|
||||||
levelName?: string;
|
|
||||||
versionHistory?: {
|
versionHistory?: {
|
||||||
current: any;
|
current: any;
|
||||||
previous: any;
|
previous: any;
|
||||||
@ -109,8 +107,6 @@ const getStepIcon = (status: string) => {
|
|||||||
switch (status) {
|
switch (status) {
|
||||||
case 'approved':
|
case 'approved':
|
||||||
return <CircleCheckBig className="w-5 h-5 text-green-600" />;
|
return <CircleCheckBig className="w-5 h-5 text-green-600" />;
|
||||||
case 'skipped':
|
|
||||||
return <CheckCircle className="w-5 h-5 text-green-600" />;
|
|
||||||
case 'pending':
|
case 'pending':
|
||||||
return <Clock className="w-5 h-5 text-blue-600" />;
|
return <Clock className="w-5 h-5 text-blue-600" />;
|
||||||
case 'rejected':
|
case 'rejected':
|
||||||
@ -127,8 +123,6 @@ const getStepBadgeVariant = (status: string) => {
|
|||||||
switch (status) {
|
switch (status) {
|
||||||
case 'approved':
|
case 'approved':
|
||||||
return 'bg-green-100 text-green-800 border-green-200';
|
return 'bg-green-100 text-green-800 border-green-200';
|
||||||
case 'skipped':
|
|
||||||
return 'bg-green-50 text-green-700 border-green-200';
|
|
||||||
case 'pending':
|
case 'pending':
|
||||||
return 'bg-purple-100 text-purple-800 border-purple-200';
|
return 'bg-purple-100 text-purple-800 border-purple-200';
|
||||||
case 'rejected':
|
case 'rejected':
|
||||||
@ -145,7 +139,7 @@ const getStepCardStyle = (status: string, isActive: boolean) => {
|
|||||||
if (isActive && (status === 'pending' || status === 'in_progress')) {
|
if (isActive && (status === 'pending' || status === 'in_progress')) {
|
||||||
return 'border-purple-500 bg-purple-50 shadow-md';
|
return 'border-purple-500 bg-purple-50 shadow-md';
|
||||||
}
|
}
|
||||||
if (status === 'approved' || status === 'skipped') {
|
if (status === 'approved') {
|
||||||
return 'border-green-500 bg-green-50';
|
return 'border-green-500 bg-green-50';
|
||||||
}
|
}
|
||||||
if (status === 'rejected') {
|
if (status === 'rejected') {
|
||||||
@ -161,8 +155,6 @@ const getStepIconBg = (status: string) => {
|
|||||||
switch (status) {
|
switch (status) {
|
||||||
case 'approved':
|
case 'approved':
|
||||||
return 'bg-green-100';
|
return 'bg-green-100';
|
||||||
case 'skipped':
|
|
||||||
return 'bg-green-100';
|
|
||||||
case 'pending':
|
case 'pending':
|
||||||
return 'bg-purple-100';
|
return 'bg-purple-100';
|
||||||
case 'rejected':
|
case 'rejected':
|
||||||
@ -194,10 +186,7 @@ export function DealerClaimWorkflowTab({
|
|||||||
const [versionHistory, setVersionHistory] = useState<any[]>([]);
|
const [versionHistory, setVersionHistory] = useState<any[]>([]);
|
||||||
const [showHistory, setShowHistory] = useState(false);
|
const [showHistory, setShowHistory] = useState(false);
|
||||||
const [expandedVersionSteps, setExpandedVersionSteps] = useState<Set<number>>(new Set());
|
const [expandedVersionSteps, setExpandedVersionSteps] = useState<Set<number>>(new Set());
|
||||||
const [viewSnapshot, setViewSnapshot] = useState<{ data: any, type: 'PROPOSAL' | 'COMPLETION', title?: string } | null>(null);
|
const [viewSnapshot, setViewSnapshot] = useState<{data: any, type: 'PROPOSAL' | 'COMPLETION', title?: string} | null>(null);
|
||||||
const [invoicePdfUrl, setInvoicePdfUrl] = useState<string | null>(null);
|
|
||||||
const [showInvoicePdfModal, setShowInvoicePdfModal] = useState(false);
|
|
||||||
const [invoicePdfLoading, setInvoicePdfLoading] = useState(false);
|
|
||||||
|
|
||||||
// Load approval flows from real API
|
// Load approval flows from real API
|
||||||
const [approvalFlow, setApprovalFlow] = useState<any[]>([]);
|
const [approvalFlow, setApprovalFlow] = useState<any[]>([]);
|
||||||
@ -340,31 +329,19 @@ export function DealerClaimWorkflowTab({
|
|||||||
// Step title and description mapping based on actual step number (not array index)
|
// Step title and description mapping based on actual step number (not array index)
|
||||||
// This handles cases where approvers are added between steps
|
// This handles cases where approvers are added between steps
|
||||||
const getStepTitle = (stepNumber: number, levelName?: string, approverName?: string): string => {
|
const getStepTitle = (stepNumber: number, levelName?: string, approverName?: string): string => {
|
||||||
// Check if this is a legacy workflow (8 steps) or new workflow (5 steps)
|
|
||||||
// Legacy flows have system steps (Activity, E-Invoice, Credit Note) as approval levels
|
|
||||||
const isLegacyFlow = (request?.totalLevels || 0) > 5 || (request?.approvalLevels?.length || 0) > 5;
|
|
||||||
|
|
||||||
// Use levelName from backend if available (most accurate)
|
// Use levelName from backend if available (most accurate)
|
||||||
// Check if it's an "Additional Approver" - this indicates a dynamically added approver
|
// Check if it's an "Additional Approver" - this indicates a dynamically added approver
|
||||||
if (levelName && levelName.trim()) {
|
if (levelName && levelName.trim()) {
|
||||||
const levelNameLower = levelName.toLowerCase();
|
|
||||||
|
|
||||||
// If it starts with "Additional Approver", use it as-is (it's already formatted)
|
// If it starts with "Additional Approver", use it as-is (it's already formatted)
|
||||||
if (levelNameLower.includes('additional approver')) {
|
if (levelName.toLowerCase().includes('additional approver')) {
|
||||||
|
return levelName;
|
||||||
|
}
|
||||||
|
// Otherwise use the levelName from backend (preserved from original step)
|
||||||
return levelName;
|
return levelName;
|
||||||
}
|
}
|
||||||
|
|
||||||
// If levelName is NOT generic "Step X", return it
|
// Fallback to mapping based on step number
|
||||||
// This fixes the issue where backend sends "Step 1" instead of "Dealer Proposal Submission"
|
const stepTitleMap: Record<number, string> = {
|
||||||
if (!/^step\s+\d+$/i.test(levelName)) {
|
|
||||||
return levelName;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fallback to mapping based on step number and flow version
|
|
||||||
const stepTitleMap: Record<number, string> = isLegacyFlow
|
|
||||||
? {
|
|
||||||
// Legacy 8-step flow
|
|
||||||
1: 'Dealer - Proposal Submission',
|
1: 'Dealer - Proposal Submission',
|
||||||
2: 'Requestor Evaluation & Confirmation',
|
2: 'Requestor Evaluation & Confirmation',
|
||||||
3: 'Department Lead Approval',
|
3: 'Department Lead Approval',
|
||||||
@ -373,16 +350,6 @@ export function DealerClaimWorkflowTab({
|
|||||||
6: 'Requestor - Claim Approval',
|
6: 'Requestor - Claim Approval',
|
||||||
7: 'E-Invoice Generation',
|
7: 'E-Invoice Generation',
|
||||||
8: 'Credit Note from SAP',
|
8: 'Credit Note from SAP',
|
||||||
}
|
|
||||||
: {
|
|
||||||
// New 5-step flow
|
|
||||||
1: 'Dealer - Proposal Submission',
|
|
||||||
2: 'Requestor Evaluation & Confirmation',
|
|
||||||
3: 'Department Lead Approval',
|
|
||||||
4: 'Dealer - Completion Documents',
|
|
||||||
5: 'Requestor - Claim Approval',
|
|
||||||
6: 'E-Invoice Generation',
|
|
||||||
7: 'Credit Note from SAP',
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// If step number exists in map, use it
|
// If step number exists in map, use it
|
||||||
@ -410,9 +377,6 @@ export function DealerClaimWorkflowTab({
|
|||||||
return `Additional approver will review and approve this request.`;
|
return `Additional approver will review and approve this request.`;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check if this is a legacy workflow (8 steps) or new workflow (5 steps)
|
|
||||||
const isLegacyFlow = (request?.totalLevels || 0) > 5 || (request?.approvalLevels?.length || 0) > 5;
|
|
||||||
|
|
||||||
// Use levelName to determine description (handles shifted steps correctly)
|
// Use levelName to determine description (handles shifted steps correctly)
|
||||||
// This ensures descriptions shift with their steps when approvers are added
|
// This ensures descriptions shift with their steps when approvers are added
|
||||||
if (levelName && levelName.trim()) {
|
if (levelName && levelName.trim()) {
|
||||||
@ -428,7 +392,6 @@ export function DealerClaimWorkflowTab({
|
|||||||
if (levelNameLower.includes('department lead')) {
|
if (levelNameLower.includes('department lead')) {
|
||||||
return 'Department Lead approval. Decision point: Approved? (YES → Budget is blocked in the respective IO for the activity / NO → More clarification required → Request is cancelled)';
|
return 'Department Lead approval. Decision point: Approved? (YES → Budget is blocked in the respective IO for the activity / NO → More clarification required → Request is cancelled)';
|
||||||
}
|
}
|
||||||
// Re-added for legacy support
|
|
||||||
if (levelNameLower.includes('activity creation')) {
|
if (levelNameLower.includes('activity creation')) {
|
||||||
return 'Activity is created. Activity confirmation email is auto-triggered to dealer / requestor / Lead. IO confirmation to be made.';
|
return 'Activity is created. Activity confirmation email is auto-triggered to dealer / requestor / Lead. IO confirmation to be made.';
|
||||||
}
|
}
|
||||||
@ -438,36 +401,24 @@ export function DealerClaimWorkflowTab({
|
|||||||
if (levelNameLower.includes('requestor') && (levelNameLower.includes('claim') || levelNameLower.includes('approval'))) {
|
if (levelNameLower.includes('requestor') && (levelNameLower.includes('claim') || levelNameLower.includes('approval'))) {
|
||||||
return 'Requestor approves the claim in full or can modify the amount. If more information is required, can request additional details from dealer.';
|
return 'Requestor approves the claim in full or can modify the amount. If more information is required, can request additional details from dealer.';
|
||||||
}
|
}
|
||||||
if (levelNameLower.includes('e-invoice') || levelNameLower.includes('invoice generation') || levelNameLower.includes('dms')) {
|
if (levelNameLower.includes('e-invoice') || levelNameLower.includes('invoice generation')) {
|
||||||
return 'E-Invoice will be generated upon settlement initiation.';
|
return 'E-invoice will be generated through DMS.';
|
||||||
}
|
}
|
||||||
if (levelNameLower.includes('credit note') || levelNameLower.includes('sap')) {
|
if (levelNameLower.includes('credit note') || levelNameLower.includes('sap')) {
|
||||||
return 'Got credit note from SAP. Review and send to dealer to complete the claim management process.';
|
return 'Got credit note from SAP. Review and send to dealer to complete the claim management process.';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fallback to step number mapping depending on flow version
|
// Fallback to step number mapping (for backwards compatibility)
|
||||||
const stepDescriptionMap: Record<number, string> = isLegacyFlow
|
const stepDescriptionMap: Record<number, string> = {
|
||||||
? {
|
|
||||||
// Legacy 8-step flow
|
|
||||||
1: 'Dealer submits the proposal for the activity with comments including proposal document with requested details, cost break-up, timeline for closure, and other requests',
|
1: 'Dealer submits the proposal for the activity with comments including proposal document with requested details, cost break-up, timeline for closure, and other requests',
|
||||||
2: 'Requestor evaluates the request and confirms with comments. Decision point: Confirms? (YES → Continue to Dept Lead / NO → Request is cancelled)',
|
2: 'Requestor evaluates the request and confirms with comments. Decision point: Confirms? (YES → Continue to Dept Lead / NO → Request is cancelled)',
|
||||||
3: 'Department Lead approval. Decision point: Approved? (YES → Budget is blocked in the respective IO for the activity / NO → More clarification required → Request is cancelled)',
|
3: 'Department Lead approval. Decision point: Approved? (YES → Budget is blocked in the respective IO for the activity / NO → More clarification required → Request is cancelled)',
|
||||||
4: 'Activity is created. Activity confirmation email is auto-triggered to dealer / requestor / Lead. IO confirmation to be made.',
|
4: 'Activity is created. Activity confirmation email is auto-triggered to dealer / requestor / Lead. IO confirmation to be made.',
|
||||||
5: 'Dealer submits the necessary documents upon completion of the activity including document attachments (Zip Folder) and brief description',
|
5: 'Dealer submits the necessary documents upon completion of the activity including document attachments (Zip Folder) and brief description',
|
||||||
6: 'Requestor approves the claim in full or can modify the amount. If more information is required, can request additional details from dealer.',
|
6: 'Requestor approves the claim in full or can modify the amount. If more information is required, can request additional details from dealer.',
|
||||||
7: 'E-Invoice will be generated upon settlement initiation.',
|
7: 'E-invoice will be generated through DMS.',
|
||||||
8: 'Got credit note from SAP. Review and send to dealer to complete the claim management process.',
|
8: 'Got credit note from SAP. Review and send to dealer to complete the claim management process.',
|
||||||
}
|
|
||||||
: {
|
|
||||||
// New 5-step flow
|
|
||||||
1: 'Dealer submits the proposal for the activity with comments including proposal document with requested details, cost break-up, timeline for closure, and other requests',
|
|
||||||
2: 'Requestor evaluates the request and confirms with comments. Decision point: Confirms? (YES → Continue to Dept Lead / NO → Request is cancelled)',
|
|
||||||
3: 'Department Lead approval. Decision point: Approved? (YES → Budget is blocked in the respective IO for the activity / NO → More clarification required → Request is cancelled)',
|
|
||||||
4: 'Dealer submits the necessary documents upon completion of the activity including document attachments (Zip Folder) and brief description',
|
|
||||||
5: 'Requestor approves the claim in full or can modify the amount. If more information is required, can request additional details from dealer.',
|
|
||||||
6: 'E-Invoice will be generated upon settlement initiation.',
|
|
||||||
7: 'Got credit note from SAP. Review and send to dealer to complete the claim management process.',
|
|
||||||
};
|
};
|
||||||
|
|
||||||
if (stepDescriptionMap[stepNumber]) {
|
if (stepDescriptionMap[stepNumber]) {
|
||||||
@ -676,8 +627,6 @@ export function DealerClaimWorkflowTab({
|
|||||||
const approvalStatus = approval.status.toLowerCase();
|
const approvalStatus = approval.status.toLowerCase();
|
||||||
if (approvalStatus === 'approved') {
|
if (approvalStatus === 'approved') {
|
||||||
normalizedStatus = 'approved';
|
normalizedStatus = 'approved';
|
||||||
} else if (approvalStatus === 'skipped') {
|
|
||||||
normalizedStatus = 'skipped';
|
|
||||||
} else if (approvalStatus === 'rejected') {
|
} else if (approvalStatus === 'rejected') {
|
||||||
normalizedStatus = 'rejected';
|
normalizedStatus = 'rejected';
|
||||||
} else {
|
} else {
|
||||||
@ -776,7 +725,7 @@ export function DealerClaimWorkflowTab({
|
|||||||
// Note: Status normalization already handled in workflowSteps mapping above
|
// Note: Status normalization already handled in workflowSteps mapping above
|
||||||
// backendCurrentLevel is already calculated above before the map function
|
// backendCurrentLevel is already calculated above before the map function
|
||||||
|
|
||||||
//: If request is rejected or closed, no step should be active
|
// CRITICAL: If request is rejected or closed, no step should be active
|
||||||
let activeStep = null;
|
let activeStep = null;
|
||||||
let currentStep = 1;
|
let currentStep = 1;
|
||||||
|
|
||||||
@ -896,29 +845,13 @@ export function DealerClaimWorkflowTab({
|
|||||||
await uploadDocument(file, requestId, 'SUPPORTING');
|
await uploadDocument(file, requestId, 'SUPPORTING');
|
||||||
}
|
}
|
||||||
|
|
||||||
// Submit proposal using dealer claim API (calculate total from inclusive item totals)
|
// Submit proposal using dealer claim API
|
||||||
const totalBudget = data.costBreakup.reduce((sum, item: any) => sum + (item.totalAmt || item.amount || 0), 0);
|
const totalBudget = data.costBreakup.reduce((sum, item) => sum + item.amount, 0);
|
||||||
await submitProposal(requestId, {
|
await submitProposal(requestId, {
|
||||||
proposalDocument: data.proposalDocument || undefined,
|
proposalDocument: data.proposalDocument || undefined,
|
||||||
costBreakup: data.costBreakup.map((item: any) => ({
|
costBreakup: data.costBreakup.map(item => ({
|
||||||
description: item.description,
|
description: item.description,
|
||||||
amount: item.amount,
|
amount: item.amount,
|
||||||
gstRate: item.gstRate,
|
|
||||||
gstAmt: item.gstAmt,
|
|
||||||
cgstRate: item.cgstRate,
|
|
||||||
cgstAmt: item.cgstAmt,
|
|
||||||
sgstRate: item.sgstRate,
|
|
||||||
sgstAmt: item.sgstAmt,
|
|
||||||
igstRate: item.igstRate,
|
|
||||||
igstAmt: item.igstAmt,
|
|
||||||
utgstRate: item.utgstRate,
|
|
||||||
utgstAmt: item.utgstAmt,
|
|
||||||
cessRate: item.cessRate,
|
|
||||||
cessAmt: item.cessAmt,
|
|
||||||
totalAmt: item.totalAmt,
|
|
||||||
quantity: item.quantity,
|
|
||||||
hsnCode: item.hsnCode,
|
|
||||||
isService: item.isService
|
|
||||||
})),
|
})),
|
||||||
totalEstimatedBudget: totalBudget,
|
totalEstimatedBudget: totalBudget,
|
||||||
expectedCompletionDate: data.expectedCompletionDate,
|
expectedCompletionDate: data.expectedCompletionDate,
|
||||||
@ -1102,45 +1035,6 @@ export function DealerClaimWorkflowTab({
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Handle re-quotation request from Claim Approval step (Step 6)
|
|
||||||
const handleClaimReQuotation = async (comments: string) => {
|
|
||||||
try {
|
|
||||||
if (!request?.id && !request?.requestId) {
|
|
||||||
throw new Error('Request ID not found');
|
|
||||||
}
|
|
||||||
|
|
||||||
const requestId = request.id || request.requestId;
|
|
||||||
|
|
||||||
// Get workflow details to find the Requestor Claim Approval levelId dynamically
|
|
||||||
const details = await getWorkflowDetails(requestId);
|
|
||||||
const approvals = details?.approvalLevels || details?.approvals || [];
|
|
||||||
|
|
||||||
// Find the Requestor Claim Approval step
|
|
||||||
const claimApprovalLevel = approvals.find((level: any) => {
|
|
||||||
const levelName = (level.levelName || level.level_name || '').toLowerCase();
|
|
||||||
return levelName.includes('requestor claim') || levelName.includes('requestor - claim');
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!claimApprovalLevel?.levelId && !claimApprovalLevel?.level_id) {
|
|
||||||
throw new Error('Claim approval level not found');
|
|
||||||
}
|
|
||||||
|
|
||||||
const levelId = claimApprovalLevel.levelId || claimApprovalLevel.level_id;
|
|
||||||
|
|
||||||
// Reject the claim approval step with 'Revised Quotation Requested'
|
|
||||||
// This will trigger the backend to return the workflow to the Dealer Proposal step
|
|
||||||
await rejectLevel(requestId, levelId, 'Revised Quotation Requested', comments);
|
|
||||||
|
|
||||||
toast.success('Re-quotation requested. Request returned to dealer.');
|
|
||||||
handleRefresh();
|
|
||||||
} catch (error: any) {
|
|
||||||
console.error('Failed to request re-quotation:', error);
|
|
||||||
const errorMessage = error?.response?.data?.message || error?.message || 'Failed to request re-quotation. Please try again.';
|
|
||||||
toast.error(errorMessage);
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// Handle IO approval (Department Lead step - found dynamically)
|
// Handle IO approval (Department Lead step - found dynamically)
|
||||||
const handleIOApproval = async (data: {
|
const handleIOApproval = async (data: {
|
||||||
ioNumber: string;
|
ioNumber: string;
|
||||||
@ -1212,26 +1106,10 @@ export function DealerClaimWorkflowTab({
|
|||||||
|
|
||||||
const requestId = request.id || request.requestId;
|
const requestId = request.id || request.requestId;
|
||||||
|
|
||||||
// Transform expense items to match API format (include GST fields)
|
// Transform expense items to match API format
|
||||||
const closedExpenses = data.closedExpenses.map((item: any) => ({
|
const closedExpenses = data.closedExpenses.map(item => ({
|
||||||
description: item.description,
|
description: item.description,
|
||||||
amount: item.amount,
|
amount: item.amount,
|
||||||
gstRate: item.gstRate,
|
|
||||||
gstAmt: item.gstAmt,
|
|
||||||
cgstRate: item.cgstRate,
|
|
||||||
cgstAmt: item.cgstAmt,
|
|
||||||
sgstRate: item.sgstRate,
|
|
||||||
sgstAmt: item.sgstAmt,
|
|
||||||
igstRate: item.igstRate,
|
|
||||||
igstAmt: item.igstAmt,
|
|
||||||
utgstRate: item.utgstRate,
|
|
||||||
utgstAmt: item.utgstAmt,
|
|
||||||
cessRate: item.cessRate,
|
|
||||||
cessAmt: item.cessAmt,
|
|
||||||
totalAmt: item.totalAmt,
|
|
||||||
quantity: item.quantity,
|
|
||||||
hsnCode: item.hsnCode,
|
|
||||||
isService: item.isService
|
|
||||||
}));
|
}));
|
||||||
|
|
||||||
// Submit completion documents using dealer claim API
|
// Submit completion documents using dealer claim API
|
||||||
@ -1267,7 +1145,7 @@ export function DealerClaimWorkflowTab({
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// Handle E-Invoice generation (Step 6)
|
// Handle DMS push (Step 6)
|
||||||
const handleDMSPush = async (_comments: string) => {
|
const handleDMSPush = async (_comments: string) => {
|
||||||
try {
|
try {
|
||||||
if (!request?.id && !request?.requestId) {
|
if (!request?.id && !request?.requestId) {
|
||||||
@ -1284,18 +1162,11 @@ export function DealerClaimWorkflowTab({
|
|||||||
});
|
});
|
||||||
|
|
||||||
// Activity is logged by backend service - no need to create work note
|
// Activity is logged by backend service - no need to create work note
|
||||||
toast.success('E-Invoice generation initiated successfully.');
|
toast.success('Pushed to DMS successfully. E-invoice will be generated automatically.');
|
||||||
handleRefresh();
|
handleRefresh();
|
||||||
} catch (error: any) {
|
} catch (error: any) {
|
||||||
console.error('[DealerClaimWorkflowTab] Error generating e-invoice:', error);
|
console.error('[DealerClaimWorkflowTab] Error pushing to DMS:', error);
|
||||||
// Backend now translates PWC error codes to user-friendly messages in 'message' field
|
const errorMessage = error?.response?.data?.message || error?.message || 'Failed to push to DMS. Please try again.';
|
||||||
// Prefer 'message' (user-friendly) over 'error' (raw technical details)
|
|
||||||
const responseMessage = error?.response?.data?.message;
|
|
||||||
let errorMessage = responseMessage || error?.message || 'E-Invoice generation failed. Please try again.';
|
|
||||||
// Truncate very long error messages for toast display (keep first 300 chars)
|
|
||||||
if (errorMessage.length > 300) {
|
|
||||||
errorMessage = errorMessage.substring(0, 300) + '...';
|
|
||||||
}
|
|
||||||
toast.error(errorMessage);
|
toast.error(errorMessage);
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
@ -1510,115 +1381,10 @@ export function DealerClaimWorkflowTab({
|
|||||||
loadCompletionDocuments();
|
loadCompletionDocuments();
|
||||||
}, [request]);
|
}, [request]);
|
||||||
|
|
||||||
const handleDownloadCSV = async () => {
|
|
||||||
try {
|
|
||||||
const requestId = request.id || request.requestId;
|
|
||||||
if (!requestId) {
|
|
||||||
toast.error('Request ID not found');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const baseUrl = import.meta.env.VITE_API_BASE_URL || 'http://localhost:5000/api/v1';
|
|
||||||
const response = await fetch(`${baseUrl}/dealer-claims/${requestId}/e-invoice/csv`, {
|
|
||||||
headers: {
|
|
||||||
'Authorization': `Bearer ${TokenManager.getAccessToken()}`
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!response.ok) {
|
|
||||||
throw new Error('Failed to download CSV');
|
|
||||||
}
|
|
||||||
|
|
||||||
const blob = await response.blob();
|
|
||||||
const url = window.URL.createObjectURL(blob);
|
|
||||||
const a = document.createElement('a');
|
|
||||||
a.href = url;
|
|
||||||
a.download = `Invoice_${request.requestNumber || 'Export'}.csv`;
|
|
||||||
document.body.appendChild(a);
|
|
||||||
a.click();
|
|
||||||
window.URL.revokeObjectURL(url);
|
|
||||||
document.body.removeChild(a);
|
|
||||||
toast.success('CSV downloaded successfully');
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error downloading CSV:', error);
|
|
||||||
toast.error('Failed to download CSV');
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handlePreviewInvoice = async () => {
|
|
||||||
try {
|
|
||||||
const requestId = request.id || request.requestId;
|
|
||||||
if (!requestId) {
|
|
||||||
toast.error('Request ID not found');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check if invoice exists
|
|
||||||
if (!request.invoice && !request.irn) {
|
|
||||||
toast.error('Invoice not generated yet');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
setInvoicePdfLoading(true);
|
|
||||||
setShowInvoicePdfModal(true);
|
|
||||||
|
|
||||||
// Fetch PDF securely via Authorization header (not in URL query)
|
|
||||||
const baseUrl = import.meta.env.VITE_API_BASE_URL || 'http://localhost:5000/api/v1';
|
|
||||||
const response = await fetch(`${baseUrl}/dealer-claims/${requestId}/e-invoice/pdf`, {
|
|
||||||
headers: {
|
|
||||||
'Authorization': `Bearer ${TokenManager.getAccessToken()}`
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!response.ok) {
|
|
||||||
throw new Error('Failed to fetch invoice PDF');
|
|
||||||
}
|
|
||||||
|
|
||||||
const blob = await response.blob();
|
|
||||||
const blobUrl = window.URL.createObjectURL(blob);
|
|
||||||
|
|
||||||
// Revoke previous blob URL to prevent memory leaks
|
|
||||||
if (invoicePdfUrl) {
|
|
||||||
window.URL.revokeObjectURL(invoicePdfUrl);
|
|
||||||
}
|
|
||||||
|
|
||||||
setInvoicePdfUrl(blobUrl);
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Failed to preview invoice:', error);
|
|
||||||
toast.error('Failed to load invoice preview');
|
|
||||||
setShowInvoicePdfModal(false);
|
|
||||||
} finally {
|
|
||||||
setInvoicePdfLoading(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleCloseInvoicePdf = () => {
|
|
||||||
setShowInvoicePdfModal(false);
|
|
||||||
if (invoicePdfUrl) {
|
|
||||||
window.URL.revokeObjectURL(invoicePdfUrl);
|
|
||||||
setInvoicePdfUrl(null);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleDownloadInvoicePdf = () => {
|
|
||||||
if (invoicePdfUrl) {
|
|
||||||
const a = document.createElement('a');
|
|
||||||
a.href = invoicePdfUrl;
|
|
||||||
a.download = `Invoice_${request.requestNumber || 'Download'}.pdf`;
|
|
||||||
document.body.appendChild(a);
|
|
||||||
a.click();
|
|
||||||
document.body.removeChild(a);
|
|
||||||
toast.success('Invoice PDF downloaded');
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// Get dealer and activity info
|
// Get dealer and activity info
|
||||||
const dealerName = request?.claimDetails?.dealerName ||
|
const dealerName = request?.claimDetails?.dealerName ||
|
||||||
request?.dealerInfo?.name ||
|
request?.dealerInfo?.name ||
|
||||||
'Dealer';
|
'Dealer';
|
||||||
const dealerGSTIN = request?.claimDetails?.dealerGstin ||
|
|
||||||
request?.dealerInfo?.gstin ||
|
|
||||||
request?.dealerInfo?.dealerGSTIN;
|
|
||||||
const activityName = request?.claimDetails?.activityName ||
|
const activityName = request?.claimDetails?.activityName ||
|
||||||
request?.activityInfo?.activityName ||
|
request?.activityInfo?.activityName ||
|
||||||
request?.title ||
|
request?.title ||
|
||||||
@ -1683,7 +1449,7 @@ export function DealerClaimWorkflowTab({
|
|||||||
// - AND it matches the current step
|
// - AND it matches the current step
|
||||||
// - AND is pending/in_progress
|
// - AND is pending/in_progress
|
||||||
const isActive = isRequestActive && isPendingOrInProgress && matchesCurrentStep;
|
const isActive = isRequestActive && isPendingOrInProgress && matchesCurrentStep;
|
||||||
const isCompleted = step.status === 'approved' || step.status === 'skipped';
|
const isCompleted = step.status === 'approved';
|
||||||
|
|
||||||
// Find approval data for this step to get SLA information
|
// Find approval data for this step to get SLA information
|
||||||
// First find the corresponding level in approvalFlow to get levelId
|
// First find the corresponding level in approvalFlow to get levelId
|
||||||
@ -1747,40 +1513,6 @@ export function DealerClaimWorkflowTab({
|
|||||||
<Download className="w-3.5 h-3.5 text-green-600" />
|
<Download className="w-3.5 h-3.5 text-green-600" />
|
||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
{/* Invoice Preview Button (Requestor Claim Approval) */}
|
|
||||||
{(() => {
|
|
||||||
const isRequestorClaimStep = (step.levelName || step.title || '').toLowerCase().includes('requestor claim') ||
|
|
||||||
(step.levelName || step.title || '').toLowerCase().includes('requestor - claim');
|
|
||||||
const hasInvoice = request?.invoice || (request?.irn && step.status === 'approved');
|
|
||||||
return isRequestorClaimStep && hasInvoice && (
|
|
||||||
<Button
|
|
||||||
variant="ghost"
|
|
||||||
size="sm"
|
|
||||||
className="h-6 w-6 p-0 hover:bg-amber-100"
|
|
||||||
title="Preview Invoice"
|
|
||||||
onClick={handlePreviewInvoice}
|
|
||||||
>
|
|
||||||
<Receipt className="w-3.5 h-3.5 text-amber-600" />
|
|
||||||
</Button>
|
|
||||||
);
|
|
||||||
})()}
|
|
||||||
{/* CSV Export Button (Requestor Claim Approval) */}
|
|
||||||
{(() => {
|
|
||||||
const isRequestorClaimStep = (step.levelName || step.title || '').toLowerCase().includes('requestor claim') ||
|
|
||||||
(step.levelName || step.title || '').toLowerCase().includes('requestor - claim');
|
|
||||||
const hasInvoice = request?.invoice || (request?.irn && step.status === 'approved');
|
|
||||||
return isRequestorClaimStep && hasInvoice && (
|
|
||||||
<Button
|
|
||||||
variant="ghost"
|
|
||||||
size="sm"
|
|
||||||
className="h-6 w-6 p-0 hover:bg-emerald-100 ml-1"
|
|
||||||
title="Export CSV"
|
|
||||||
onClick={handleDownloadCSV}
|
|
||||||
>
|
|
||||||
<FileSpreadsheet className="w-3.5 h-3.5 text-emerald-600" />
|
|
||||||
</Button>
|
|
||||||
);
|
|
||||||
})()}
|
|
||||||
</div>
|
</div>
|
||||||
<p className="text-sm text-gray-600">{step.approver}</p>
|
<p className="text-sm text-gray-600">{step.approver}</p>
|
||||||
<p className="text-sm text-gray-500 mt-2 italic">{step.description}</p>
|
<p className="text-sm text-gray-500 mt-2 italic">{step.description}</p>
|
||||||
@ -1988,7 +1720,8 @@ export function DealerClaimWorkflowTab({
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Current Approver - Time Tracking */}
|
{/* Current Approver - Time Tracking */}
|
||||||
<div className={`border rounded-lg p-3 ${isPaused ? 'bg-gray-100 border-gray-300' :
|
<div className={`border rounded-lg p-3 ${
|
||||||
|
isPaused ? 'bg-gray-100 border-gray-300' :
|
||||||
(approval.sla.percentageUsed || 0) >= 100 ? 'bg-red-50 border-red-200' :
|
(approval.sla.percentageUsed || 0) >= 100 ? 'bg-red-50 border-red-200' :
|
||||||
(approval.sla.percentageUsed || 0) >= 75 ? 'bg-orange-50 border-orange-200' :
|
(approval.sla.percentageUsed || 0) >= 75 ? 'bg-orange-50 border-orange-200' :
|
||||||
(approval.sla.percentageUsed || 0) >= 50 ? 'bg-amber-50 border-amber-200' :
|
(approval.sla.percentageUsed || 0) >= 50 ? 'bg-amber-50 border-amber-200' :
|
||||||
@ -2124,25 +1857,25 @@ export function DealerClaimWorkflowTab({
|
|||||||
<div className="flex items-center gap-2 mb-2">
|
<div className="flex items-center gap-2 mb-2">
|
||||||
<Activity className="w-4 h-4 text-purple-600" />
|
<Activity className="w-4 h-4 text-purple-600" />
|
||||||
<p className="text-xs font-semibold text-purple-900 uppercase tracking-wide">
|
<p className="text-xs font-semibold text-purple-900 uppercase tracking-wide">
|
||||||
E-Invoice & Settlement Details
|
DMS Processing Details
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<div className="space-y-1.5">
|
<div className="space-y-1.5">
|
||||||
<div className="flex items-center justify-between">
|
<div className="flex items-center justify-between">
|
||||||
<span className="text-xs text-gray-600">Settlement ID:</span>
|
<span className="text-xs text-gray-600">DMS Number:</span>
|
||||||
<span className="text-sm font-semibold text-gray-900">
|
<span className="text-sm font-semibold text-gray-900">
|
||||||
{step.dmsDetails.dmsNumber}
|
{step.dmsDetails.dmsNumber}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
{step.dmsDetails.dmsRemarks && (
|
{step.dmsDetails.dmsRemarks && (
|
||||||
<div className="pt-1.5 border-t border-purple-100">
|
<div className="pt-1.5 border-t border-purple-100">
|
||||||
<p className="text-xs text-gray-600 mb-1">Settlement Remarks:</p>
|
<p className="text-xs text-gray-600 mb-1">DMS Remarks:</p>
|
||||||
<p className="text-sm text-gray-900">{step.dmsDetails.dmsRemarks}</p>
|
<p className="text-sm text-gray-900">{step.dmsDetails.dmsRemarks}</p>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
{step.dmsDetails.pushedAt && (
|
{step.dmsDetails.pushedAt && (
|
||||||
<div className="pt-1.5 border-t border-purple-100 text-xs text-gray-500">
|
<div className="pt-1.5 border-t border-purple-100 text-xs text-gray-500">
|
||||||
Initiated by {step.dmsDetails.pushedBy} on{' '}
|
Pushed by {step.dmsDetails.pushedBy} on{' '}
|
||||||
{formatDateSafe(step.dmsDetails.pushedAt)}
|
{formatDateSafe(step.dmsDetails.pushedAt)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
@ -2170,16 +1903,7 @@ export function DealerClaimWorkflowTab({
|
|||||||
})() && (
|
})() && (
|
||||||
<div className="mt-4 flex gap-2">
|
<div className="mt-4 flex gap-2">
|
||||||
{/* Step 1: Submit Proposal Button - Only for dealer or step 1 approver */}
|
{/* Step 1: Submit Proposal Button - Only for dealer or step 1 approver */}
|
||||||
{(() => {
|
{step.step === 1 && (isDealer || isStep1Approver) && (
|
||||||
// Check if this is Step 1 (Dealer Proposal Submission)
|
|
||||||
// Use levelName match or fallback to step 1
|
|
||||||
const levelName = (stepLevel?.levelName || step.title || '').toLowerCase();
|
|
||||||
const isProposalStep = step.step === 1 ||
|
|
||||||
levelName.includes('proposal') ||
|
|
||||||
levelName.includes('submission');
|
|
||||||
|
|
||||||
return isProposalStep && (isDealer || isStep1Approver);
|
|
||||||
})() && (
|
|
||||||
<Button
|
<Button
|
||||||
className="bg-purple-600 hover:bg-purple-700"
|
className="bg-purple-600 hover:bg-purple-700"
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
@ -2195,16 +1919,7 @@ export function DealerClaimWorkflowTab({
|
|||||||
{/* Use initiatorStepNumber to handle cases where approvers are added between steps */}
|
{/* Use initiatorStepNumber to handle cases where approvers are added between steps */}
|
||||||
{/* Step 2 (or shifted step): Review Request - Only for initiator or step approver */}
|
{/* Step 2 (or shifted step): Review Request - Only for initiator or step approver */}
|
||||||
{/* Use initiatorStepNumber to handle cases where approvers are added between steps */}
|
{/* Use initiatorStepNumber to handle cases where approvers are added between steps */}
|
||||||
{/* Step 2 (or shifted step): Review Request - Only for initiator or step approver */}
|
{step.step === initiatorStepNumber && (isInitiator || isStep2Approver) && (
|
||||||
{(() => {
|
|
||||||
// Check if this is the Requestor Evaluation step
|
|
||||||
const levelName = (stepLevel?.levelName || step.title || '').toLowerCase();
|
|
||||||
const isEvaluationStep = levelName.includes('requestor evaluation') ||
|
|
||||||
levelName.includes('confirmation') ||
|
|
||||||
step.step === initiatorStepNumber; // Fallback
|
|
||||||
|
|
||||||
return isEvaluationStep && (isInitiator || isStep2Approver);
|
|
||||||
})() && (
|
|
||||||
<Button
|
<Button
|
||||||
className="bg-blue-600 hover:bg-blue-700"
|
className="bg-blue-600 hover:bg-blue-700"
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
@ -2366,26 +2081,20 @@ export function DealerClaimWorkflowTab({
|
|||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<Activity className="w-4 h-4 mr-2" />
|
<Activity className="w-4 h-4 mr-2" />
|
||||||
Generate E-Invoice & Sync
|
Push to DMS
|
||||||
</Button>
|
</Button>
|
||||||
);
|
);
|
||||||
})()}
|
})()}
|
||||||
|
|
||||||
{/* Step 8: View & Send Credit Note - Only for finance approver or step 8 approver */}
|
{/* Step 8: View & Send Credit Note - Only for finance approver or step 8 approver */}
|
||||||
{(() => {
|
{step.step === 8 && (() => {
|
||||||
const levelName = (stepLevel?.levelName || step.title || '').toLowerCase();
|
const step8Level = approvalFlow.find((l: any) => (l.step || l.levelNumber || l.level_number) === 8);
|
||||||
// Check for "Credit Note" or "SAP" in level name, or fallback to step 8 if it's the last step
|
const step8ApproverEmail = (step8Level?.approverEmail || '').toLowerCase();
|
||||||
const isCreditNoteStep = levelName.includes('credit note') ||
|
const isStep8Approver = step8ApproverEmail && userEmail === step8ApproverEmail;
|
||||||
levelName.includes('sap') ||
|
|
||||||
(step.step === 8 && !levelName.includes('additional'));
|
|
||||||
|
|
||||||
const stepApproverEmail = (stepLevel?.approverEmail || '').toLowerCase();
|
|
||||||
const isStepApprover = stepApproverEmail && userEmail === stepApproverEmail;
|
|
||||||
// Also check if user has finance role
|
// Also check if user has finance role
|
||||||
const userRole = (user as any)?.role?.toUpperCase() || '';
|
const userRole = (user as any)?.role?.toUpperCase() || '';
|
||||||
const isFinanceUser = userRole === 'FINANCE' || userRole === 'ADMIN';
|
const isFinanceUser = userRole === 'FINANCE' || userRole === 'ADMIN';
|
||||||
|
return isStep8Approver || isFinanceUser;
|
||||||
return isCreditNoteStep && (isStepApprover || isFinanceUser);
|
|
||||||
})() && (
|
})() && (
|
||||||
<Button
|
<Button
|
||||||
className="bg-green-600 hover:bg-green-700"
|
className="bg-green-600 hover:bg-green-700"
|
||||||
@ -2405,21 +2114,35 @@ export function DealerClaimWorkflowTab({
|
|||||||
const levelName = (stepLevel?.levelName || step.title || '').toLowerCase();
|
const levelName = (stepLevel?.levelName || step.title || '').toLowerCase();
|
||||||
const isAdditionalApprover = levelName.includes('additional approver');
|
const isAdditionalApprover = levelName.includes('additional approver');
|
||||||
|
|
||||||
// Check if this step doesn't have any of the specific workflow action buttons above
|
|
||||||
// Check if this step doesn't have any of the specific workflow action buttons above
|
// Check if this step doesn't have any of the specific workflow action buttons above
|
||||||
const hasSpecificWorkflowAction =
|
const hasSpecificWorkflowAction =
|
||||||
// Proposal
|
step.step === 1 ||
|
||||||
(step.step === 1 || levelName.includes('proposal') || levelName.includes('submission')) ||
|
step.step === initiatorStepNumber ||
|
||||||
// Evaluation
|
(() => {
|
||||||
(levelName.includes('requestor evaluation') || levelName.includes('confirmation')) ||
|
const deptLeadStepLevel = approvalFlow.find((l: any) => {
|
||||||
// Dept Lead
|
const ln = (l.levelName || '').toLowerCase();
|
||||||
levelName.includes('department lead') ||
|
return ln.includes('department lead');
|
||||||
// Dealer Completion
|
});
|
||||||
(levelName.includes('dealer completion') || levelName.includes('completion documents')) ||
|
return deptLeadStepLevel &&
|
||||||
// Requestor Claim
|
(step.step === (deptLeadStepLevel.step || deptLeadStepLevel.levelNumber || deptLeadStepLevel.level_number));
|
||||||
(levelName.includes('requestor claim') || levelName.includes('requestor - claim')) ||
|
})() ||
|
||||||
// Credit Note
|
(() => {
|
||||||
(levelName.includes('credit note') || levelName.includes('sap'));
|
const stepLevel = approvalFlow.find((l: any) => (l.step || l.levelNumber || l.level_number) === step.step);
|
||||||
|
const stepApproverEmail = (stepLevel?.approverEmail || '').toLowerCase();
|
||||||
|
const isDealerForThisStep = isDealer && stepApproverEmail === dealerEmail;
|
||||||
|
const ln = (stepLevel?.levelName || step.title || '').toLowerCase();
|
||||||
|
const isDealerCompletionStep = ln.includes('dealer completion') || ln.includes('completion documents');
|
||||||
|
return isDealerForThisStep && isDealerCompletionStep;
|
||||||
|
})() ||
|
||||||
|
(() => {
|
||||||
|
const requestorClaimStepLevel = approvalFlow.find((l: any) => {
|
||||||
|
const ln = (l.levelName || '').toLowerCase();
|
||||||
|
return ln.includes('requestor claim') || ln.includes('requestor - claim');
|
||||||
|
});
|
||||||
|
return requestorClaimStepLevel &&
|
||||||
|
(step.step === (requestorClaimStepLevel.step || requestorClaimStepLevel.levelNumber || requestorClaimStepLevel.level_number));
|
||||||
|
})() ||
|
||||||
|
step.step === 8;
|
||||||
|
|
||||||
// Show "Review Request" button for additional approvers or steps without specific workflow actions
|
// Show "Review Request" button for additional approvers or steps without specific workflow actions
|
||||||
// Similar to the requestor approval step
|
// Similar to the requestor approval step
|
||||||
@ -2528,14 +2251,10 @@ export function DealerClaimWorkflowTab({
|
|||||||
onClose={() => setShowProposalModal(false)}
|
onClose={() => setShowProposalModal(false)}
|
||||||
onSubmit={handleProposalSubmit}
|
onSubmit={handleProposalSubmit}
|
||||||
dealerName={dealerName}
|
dealerName={dealerName}
|
||||||
dealerGSTIN={dealerGSTIN}
|
|
||||||
activityName={activityName}
|
activityName={activityName}
|
||||||
defaultGstRate={request?.claimDetails?.defaultGstRate}
|
|
||||||
requestId={request?.id || request?.requestId}
|
requestId={request?.id || request?.requestId}
|
||||||
previousProposalData={versionHistory?.find(v => v.snapshotType === 'PROPOSAL')?.snapshotData}
|
previousProposalData={versionHistory?.find(v => v.snapshotType === 'PROPOSAL')?.snapshotData}
|
||||||
documentPolicy={documentPolicy}
|
documentPolicy={documentPolicy}
|
||||||
taxationType={request?.claimDetails?.taxationType}
|
|
||||||
totalBlockedAmount={(request?.internalOrders || []).reduce((sum: number, io: any) => sum + (Number(io.ioBlockedAmount || io.io_blocked_amount || io.blockedAmount || 0)), 0)}
|
|
||||||
/>
|
/>
|
||||||
|
|
||||||
{/* Initiator Proposal Approval Modal */}
|
{/* Initiator Proposal Approval Modal */}
|
||||||
@ -2559,7 +2278,6 @@ export function DealerClaimWorkflowTab({
|
|||||||
// proposalSnapshots[1] is the previous proposal (last iteration - 1)
|
// proposalSnapshots[1] is the previous proposal (last iteration - 1)
|
||||||
return proposalSnapshots.length > 1 ? proposalSnapshots[1].snapshotData : null;
|
return proposalSnapshots.length > 1 ? proposalSnapshots[1].snapshotData : null;
|
||||||
})()}
|
})()}
|
||||||
taxationType={request?.claimDetails?.taxationType}
|
|
||||||
/>
|
/>
|
||||||
|
|
||||||
{/* Dept Lead IO Approval Modal */}
|
{/* Dept Lead IO Approval Modal */}
|
||||||
@ -2573,7 +2291,6 @@ export function DealerClaimWorkflowTab({
|
|||||||
preFilledIONumber={request?.internalOrder?.ioNumber || request?.internalOrder?.io_number || request?.internal_order?.ioNumber || request?.internal_order?.io_number || undefined}
|
preFilledIONumber={request?.internalOrder?.ioNumber || request?.internalOrder?.io_number || request?.internal_order?.ioNumber || request?.internal_order?.io_number || undefined}
|
||||||
preFilledBlockedAmount={request?.internalOrder?.ioBlockedAmount || request?.internalOrder?.io_blocked_amount || request?.internal_order?.ioBlockedAmount || request?.internal_order?.io_blocked_amount || undefined}
|
preFilledBlockedAmount={request?.internalOrder?.ioBlockedAmount || request?.internalOrder?.io_blocked_amount || request?.internal_order?.ioBlockedAmount || request?.internal_order?.io_blocked_amount || undefined}
|
||||||
preFilledRemainingBalance={request?.internalOrder?.ioRemainingBalance || request?.internalOrder?.io_remaining_balance || request?.internal_order?.ioRemainingBalance || request?.internal_order?.io_remaining_balance || undefined}
|
preFilledRemainingBalance={request?.internalOrder?.ioRemainingBalance || request?.internalOrder?.io_remaining_balance || request?.internal_order?.ioRemainingBalance || request?.internal_order?.io_remaining_balance || undefined}
|
||||||
taxationType={request?.claimDetails?.taxationType}
|
|
||||||
/>
|
/>
|
||||||
|
|
||||||
{/* Dealer Completion Documents Modal */}
|
{/* Dealer Completion Documents Modal */}
|
||||||
@ -2582,12 +2299,9 @@ export function DealerClaimWorkflowTab({
|
|||||||
onClose={() => setShowCompletionModal(false)}
|
onClose={() => setShowCompletionModal(false)}
|
||||||
onSubmit={handleCompletionSubmit}
|
onSubmit={handleCompletionSubmit}
|
||||||
dealerName={dealerName}
|
dealerName={dealerName}
|
||||||
dealerGSTIN={dealerGSTIN}
|
|
||||||
activityName={activityName}
|
activityName={activityName}
|
||||||
defaultGstRate={request?.claimDetails?.defaultGstRate}
|
|
||||||
requestId={request?.id || request?.requestId}
|
requestId={request?.id || request?.requestId}
|
||||||
documentPolicy={documentPolicy}
|
documentPolicy={documentPolicy}
|
||||||
taxationType={request?.claimDetails?.taxationType}
|
|
||||||
/>
|
/>
|
||||||
|
|
||||||
{/* DMS Push Modal */}
|
{/* DMS Push Modal */}
|
||||||
@ -2611,16 +2325,14 @@ export function DealerClaimWorkflowTab({
|
|||||||
completionDocuments={completionDocumentsData}
|
completionDocuments={completionDocumentsData}
|
||||||
requestTitle={request?.title}
|
requestTitle={request?.title}
|
||||||
requestNumber={request?.requestNumber || request?.request_number || request?.id}
|
requestNumber={request?.requestNumber || request?.request_number || request?.id}
|
||||||
taxationType={request?.claimDetails?.taxationType}
|
|
||||||
onReQuotation={handleClaimReQuotation}
|
|
||||||
/>
|
/>
|
||||||
|
|
||||||
{/* Credit Note from SAP Modal (Step 8) */}
|
{/* Credit Note from SAP Modal (Step 8) */}
|
||||||
<CreditNoteSAPModal
|
<CreditNoteSAPModal
|
||||||
isOpen={showCreditNoteModal}
|
isOpen={showCreditNoteModal}
|
||||||
onClose={() => setShowCreditNoteModal(false)}
|
onClose={() => setShowCreditNoteModal(false)}
|
||||||
taxationType={request?.claimDetails?.taxationType}
|
|
||||||
onDownload={async () => {
|
onDownload={async () => {
|
||||||
|
// TODO: Implement download functionality
|
||||||
toast.info('Download functionality will be implemented');
|
toast.info('Download functionality will be implemented');
|
||||||
}}
|
}}
|
||||||
onSendToDealer={async () => {
|
onSendToDealer={async () => {
|
||||||
@ -2691,7 +2403,7 @@ export function DealerClaimWorkflowTab({
|
|||||||
stepNumber={selectedStepForEmail?.stepNumber || 4}
|
stepNumber={selectedStepForEmail?.stepNumber || 4}
|
||||||
stepName={selectedStepForEmail?.stepName || 'Activity Creation'}
|
stepName={selectedStepForEmail?.stepName || 'Activity Creation'}
|
||||||
requestNumber={request?.requestNumber || request?.id || request?.request_number}
|
requestNumber={request?.requestNumber || request?.id || request?.request_number}
|
||||||
recipientEmail={`system@${import.meta.env.VITE_EMAIL_DOMAIN}`}
|
recipientEmail="system@royalenfield.com"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
{/* Additional Approver Review Modal */}
|
{/* Additional Approver Review Modal */}
|
||||||
@ -2925,65 +2637,6 @@ export function DealerClaimWorkflowTab({
|
|||||||
type={viewSnapshot?.type || 'PROPOSAL'}
|
type={viewSnapshot?.type || 'PROPOSAL'}
|
||||||
title={viewSnapshot?.title}
|
title={viewSnapshot?.title}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
{/* Invoice PDF Viewer Modal */}
|
|
||||||
{showInvoicePdfModal && (
|
|
||||||
<div className="fixed inset-0 z-50 flex items-center justify-center">
|
|
||||||
{/* Backdrop */}
|
|
||||||
<div className="absolute inset-0 bg-black/60" onClick={handleCloseInvoicePdf} />
|
|
||||||
{/* Modal */}
|
|
||||||
<div className="relative w-[95vw] max-w-5xl h-[90vh] bg-white rounded-xl shadow-2xl flex flex-col overflow-hidden">
|
|
||||||
{/* Header */}
|
|
||||||
<div className="flex items-center justify-between px-5 py-3 border-b bg-gray-50">
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<Receipt className="w-5 h-5 text-amber-600" />
|
|
||||||
<h3 className="font-semibold text-gray-900">Invoice Preview</h3>
|
|
||||||
<Badge className="bg-amber-100 text-amber-800 text-xs">{request.requestNumber}</Badge>
|
|
||||||
</div>
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
{invoicePdfUrl && (
|
|
||||||
<Button
|
|
||||||
variant="outline"
|
|
||||||
size="sm"
|
|
||||||
onClick={handleDownloadInvoicePdf}
|
|
||||||
className="gap-1.5 text-xs"
|
|
||||||
>
|
|
||||||
<Download className="w-3.5 h-3.5" />
|
|
||||||
Download
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
<Button
|
|
||||||
variant="ghost"
|
|
||||||
size="icon"
|
|
||||||
onClick={handleCloseInvoicePdf}
|
|
||||||
className="h-8 w-8 hover:bg-gray-200"
|
|
||||||
>
|
|
||||||
<X className="w-4 h-4" />
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
{/* Body */}
|
|
||||||
<div className="flex-1 overflow-hidden">
|
|
||||||
{invoicePdfLoading ? (
|
|
||||||
<div className="flex flex-col items-center justify-center h-full gap-3">
|
|
||||||
<Loader2 className="w-8 h-8 text-amber-600 animate-spin" />
|
|
||||||
<p className="text-sm text-gray-500">Loading invoice...</p>
|
|
||||||
</div>
|
|
||||||
) : invoicePdfUrl ? (
|
|
||||||
<iframe
|
|
||||||
src={invoicePdfUrl}
|
|
||||||
className="w-full h-full border-0"
|
|
||||||
title="Invoice PDF Preview"
|
|
||||||
/>
|
|
||||||
) : (
|
|
||||||
<div className="flex items-center justify-center h-full">
|
|
||||||
<p className="text-sm text-gray-500">Failed to load invoice</p>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -109,7 +109,7 @@ export function ActivityInformationCard({
|
|||||||
</label>
|
</label>
|
||||||
<p className="text-sm text-gray-900 font-medium mt-1 flex items-center gap-2">
|
<p className="text-sm text-gray-900 font-medium mt-1 flex items-center gap-2">
|
||||||
<DollarSign className="w-4 h-4 text-green-600" />
|
<DollarSign className="w-4 h-4 text-green-600" />
|
||||||
{activityInfo.estimatedBudget !== undefined && activityInfo.estimatedBudget !== null
|
{activityInfo.estimatedBudget
|
||||||
? formatCurrency(activityInfo.estimatedBudget)
|
? formatCurrency(activityInfo.estimatedBudget)
|
||||||
: 'TBD'}
|
: 'TBD'}
|
||||||
</p>
|
</p>
|
||||||
@ -123,11 +123,7 @@ export function ActivityInformationCard({
|
|||||||
</label>
|
</label>
|
||||||
<p className="text-sm text-gray-900 font-medium mt-1 flex items-center gap-2">
|
<p className="text-sm text-gray-900 font-medium mt-1 flex items-center gap-2">
|
||||||
<Receipt className="w-4 h-4 text-blue-600" />
|
<Receipt className="w-4 h-4 text-blue-600" />
|
||||||
{formatCurrency(
|
{formatCurrency(activityInfo.closedExpenses)}
|
||||||
activityInfo.closedExpensesBreakdown && activityInfo.closedExpensesBreakdown.length > 0
|
|
||||||
? activityInfo.closedExpensesBreakdown.reduce((sum, item: any) => sum + (item.totalAmt || (Number(item.amount) + Number(item.gstAmt || 0))), 0)
|
|
||||||
: activityInfo.closedExpenses
|
|
||||||
)}
|
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
@ -151,40 +147,23 @@ export function ActivityInformationCard({
|
|||||||
<label className="text-xs font-medium text-gray-500 uppercase tracking-wide mb-3 block">
|
<label className="text-xs font-medium text-gray-500 uppercase tracking-wide mb-3 block">
|
||||||
Closed Expenses Breakdown
|
Closed Expenses Breakdown
|
||||||
</label>
|
</label>
|
||||||
<div className="bg-blue-50 border border-blue-200 rounded-lg overflow-hidden">
|
<div className="bg-blue-50 border border-blue-200 rounded-lg p-3 space-y-2">
|
||||||
<table className="w-full text-xs sm:text-sm">
|
{activityInfo.closedExpensesBreakdown.map((item: { description: string; amount: number }, index: number) => (
|
||||||
<thead className="bg-blue-100/50">
|
<div key={index} className="flex justify-between items-center text-sm">
|
||||||
<tr>
|
<span className="text-gray-700">{item.description}</span>
|
||||||
<th className="px-3 py-2 text-left font-semibold text-blue-900">Description</th>
|
<span className="font-medium text-gray-900">
|
||||||
<th className="px-3 py-2 text-right font-semibold text-blue-900 w-24">Base</th>
|
{formatCurrency(item.amount)}
|
||||||
<th className="px-3 py-2 text-right font-semibold text-blue-900 w-24">GST</th>
|
</span>
|
||||||
<th className="px-3 py-2 text-right font-semibold text-blue-900 w-28">Total</th>
|
</div>
|
||||||
</tr>
|
|
||||||
</thead>
|
|
||||||
<tbody className="divide-y divide-blue-200/50">
|
|
||||||
{activityInfo.closedExpensesBreakdown.map((item: any, index: number) => (
|
|
||||||
<tr key={index} className="hover:bg-blue-100/30">
|
|
||||||
<td className="px-3 py-2 text-gray-700">
|
|
||||||
{item.description}
|
|
||||||
{item.gstRate ? <span className="text-[10px] text-gray-400 block">{item.gstRate}% GST</span> : null}
|
|
||||||
</td>
|
|
||||||
<td className="px-3 py-2 text-right text-gray-900">{formatCurrency(item.amount)}</td>
|
|
||||||
<td className="px-3 py-2 text-right text-gray-900">{formatCurrency(item.gstAmt || 0)}</td>
|
|
||||||
<td className="px-3 py-2 text-right font-medium text-gray-900">
|
|
||||||
{formatCurrency(item.totalAmt || (Number(item.amount) + Number(item.gstAmt || 0)))}
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
))}
|
))}
|
||||||
<tr className="bg-blue-100/50 font-bold">
|
<div className="pt-2 border-t border-blue-300 flex justify-between items-center">
|
||||||
<td colSpan={3} className="px-3 py-2 text-blue-900">Final Claim Amount</td>
|
<span className="font-semibold text-gray-900">Total</span>
|
||||||
<td className="px-3 py-2 text-right text-blue-700">
|
<span className="font-bold text-blue-600">
|
||||||
{formatCurrency(
|
{formatCurrency(
|
||||||
activityInfo.closedExpensesBreakdown.reduce((sum: number, item: any) => sum + (item.totalAmt || (Number(item.amount) + Number(item.gstAmt || 0))), 0)
|
activityInfo.closedExpensesBreakdown.reduce((sum: number, item: { description: string; amount: number }) => sum + item.amount, 0)
|
||||||
)}
|
)}
|
||||||
</td>
|
</span>
|
||||||
</tr>
|
</div>
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@ -1,6 +1,6 @@
|
|||||||
/**
|
/**
|
||||||
* ProcessDetailsCard Component
|
* ProcessDetailsCard Component
|
||||||
* Displays process-related details: IO Number, E-Invoice, Claim Amount, and Budget Breakdowns
|
* Displays process-related details: IO Number, DMS Number, Claim Amount, and Budget Breakdowns
|
||||||
* Visibility controlled by user role
|
* Visibility controlled by user role
|
||||||
*/
|
*/
|
||||||
|
|
||||||
@ -26,11 +26,6 @@ interface DMSDetails {
|
|||||||
remarks?: string;
|
remarks?: string;
|
||||||
createdByName?: string;
|
createdByName?: string;
|
||||||
createdAt?: string;
|
createdAt?: string;
|
||||||
// PWC fields
|
|
||||||
irn?: string;
|
|
||||||
ackNo?: string;
|
|
||||||
ackDate?: string;
|
|
||||||
signedInvoiceUrl?: string;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
interface ClaimAmountDetails {
|
interface ClaimAmountDetails {
|
||||||
@ -42,8 +37,6 @@ interface ClaimAmountDetails {
|
|||||||
interface CostBreakdownItem {
|
interface CostBreakdownItem {
|
||||||
description: string;
|
description: string;
|
||||||
amount: number;
|
amount: number;
|
||||||
gstAmt?: number;
|
|
||||||
totalAmt?: number;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
interface RoleBasedVisibility {
|
interface RoleBasedVisibility {
|
||||||
@ -92,7 +85,7 @@ export function ProcessDetailsCard({
|
|||||||
|
|
||||||
const calculateTotal = (items?: CostBreakdownItem[]) => {
|
const calculateTotal = (items?: CostBreakdownItem[]) => {
|
||||||
if (!items || items.length === 0) return 0;
|
if (!items || items.length === 0) return 0;
|
||||||
return items.reduce((sum, item) => sum + (item.totalAmt ?? (item.amount + (item.gstAmt ?? 0))), 0);
|
return items.reduce((sum, item) => sum + (item.amount ?? 0), 0);
|
||||||
};
|
};
|
||||||
|
|
||||||
// Don't render if nothing to show
|
// Don't render if nothing to show
|
||||||
@ -172,57 +165,27 @@ export function ProcessDetailsCard({
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* E-Invoice Details */}
|
{/* DMS Details */}
|
||||||
{visibility.showDMSDetails && dmsDetails && (
|
{visibility.showDMSDetails && dmsDetails && (
|
||||||
<div className="bg-white rounded-lg p-3 border border-purple-200">
|
<div className="bg-white rounded-lg p-3 border border-purple-200">
|
||||||
<div className="flex items-center gap-2 mb-2">
|
<div className="flex items-center gap-2 mb-2">
|
||||||
<Activity className="w-4 h-4 text-purple-600" />
|
<Activity className="w-4 h-4 text-purple-600" />
|
||||||
<Label className="text-xs font-semibold text-purple-900 uppercase tracking-wide">
|
<Label className="text-xs font-semibold text-purple-900 uppercase tracking-wide">
|
||||||
E-Invoice Details
|
DMS Number
|
||||||
</Label>
|
</Label>
|
||||||
</div>
|
</div>
|
||||||
|
<p className="font-bold text-gray-900 mb-2">{dmsDetails.dmsNumber}</p>
|
||||||
<div className="grid grid-cols-2 gap-3 mb-2">
|
|
||||||
|
|
||||||
{dmsDetails.ackNo && (
|
|
||||||
<div>
|
|
||||||
<p className="text-[10px] text-gray-500 uppercase">Ack No</p>
|
|
||||||
<p className="font-bold text-sm text-purple-700">{dmsDetails.ackNo}</p>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{dmsDetails.irn && (
|
|
||||||
<div className="mb-2 p-2 bg-purple-50 rounded border border-purple-100">
|
|
||||||
<p className="text-[10px] text-purple-600 uppercase font-semibold">IRN</p>
|
|
||||||
<p className="text-[10px] font-mono break-all text-gray-700 leading-tight">
|
|
||||||
{dmsDetails.irn}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{dmsDetails.signedInvoiceUrl && (
|
|
||||||
<Button
|
|
||||||
variant="outline"
|
|
||||||
size="sm"
|
|
||||||
className="w-full h-8 text-xs gap-2 mb-2 border-purple-200 text-purple-700 hover:bg-purple-50"
|
|
||||||
onClick={() => window.open(dmsDetails.signedInvoiceUrl, '_blank')}
|
|
||||||
>
|
|
||||||
<Receipt className="w-3.5 h-3.5" />
|
|
||||||
View E-Invoice
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{dmsDetails.remarks && (
|
{dmsDetails.remarks && (
|
||||||
<div className="pt-2 border-t border-purple-100">
|
<div className="pt-2 border-t border-purple-100">
|
||||||
<p className="text-[10px] text-gray-500 uppercase mb-1">Remarks</p>
|
<p className="text-xs text-gray-600 mb-1">Remarks:</p>
|
||||||
<p className="text-xs text-gray-900">{dmsDetails.remarks}</p>
|
<p className="text-xs text-gray-900">{dmsDetails.remarks}</p>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<div className="pt-2 border-t border-purple-100 mt-2">
|
<div className="pt-2 border-t border-purple-100 mt-2">
|
||||||
<p className="text-[10px] text-gray-500">By {dmsDetails.createdByName}</p>
|
<p className="text-xs text-gray-500">By {dmsDetails.createdByName}</p>
|
||||||
<p className="text-[10px] text-gray-500">{formatDate(dmsDetails.createdAt)}</p>
|
<p className="text-xs text-gray-500">{formatDate(dmsDetails.createdAt)}</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
@ -278,10 +241,10 @@ export function ProcessDetailsCard({
|
|||||||
</div>
|
</div>
|
||||||
<div className="space-y-1.5 pt-1">
|
<div className="space-y-1.5 pt-1">
|
||||||
{estimatedBudgetBreakdown.map((item, index) => (
|
{estimatedBudgetBreakdown.map((item, index) => (
|
||||||
<div key={index} className="flex justify-between items-center text-[10px] sm:text-xs">
|
<div key={index} className="flex justify-between items-center text-xs">
|
||||||
<div className="text-gray-700 truncate mr-2" title={item.description}>{item.description}</div>
|
<span className="text-gray-700">{item.description}</span>
|
||||||
<span className="font-medium text-gray-900 whitespace-nowrap">
|
<span className="font-medium text-gray-900">
|
||||||
{formatCurrency(item.totalAmt ?? (item.amount + (item.gstAmt ?? 0)))}
|
{formatCurrency(item.amount)}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
@ -306,10 +269,10 @@ export function ProcessDetailsCard({
|
|||||||
</div>
|
</div>
|
||||||
<div className="space-y-1.5 pt-1">
|
<div className="space-y-1.5 pt-1">
|
||||||
{closedExpensesBreakdown.map((item, index) => (
|
{closedExpensesBreakdown.map((item, index) => (
|
||||||
<div key={index} className="flex justify-between items-center text-[10px] sm:text-xs">
|
<div key={index} className="flex justify-between items-center text-xs">
|
||||||
<div className="text-gray-700 truncate mr-2" title={item.description}>{item.description}</div>
|
<span className="text-gray-700">{item.description}</span>
|
||||||
<span className="font-medium text-gray-900 whitespace-nowrap">
|
<span className="font-medium text-gray-900">
|
||||||
{formatCurrency(item.totalAmt ?? (item.amount + (item.gstAmt ?? 0)))}
|
{formatCurrency(item.amount)}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
|
|||||||
@ -11,19 +11,11 @@ import { format } from 'date-fns';
|
|||||||
interface ProposalCostItem {
|
interface ProposalCostItem {
|
||||||
description: string;
|
description: string;
|
||||||
amount?: number | null;
|
amount?: number | null;
|
||||||
gstRate?: number;
|
|
||||||
gstAmt?: number;
|
|
||||||
cgstAmt?: number;
|
|
||||||
sgstAmt?: number;
|
|
||||||
igstAmt?: number;
|
|
||||||
quantity?: number;
|
|
||||||
totalAmt?: number;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
interface ProposalDetails {
|
interface ProposalDetails {
|
||||||
costBreakup: ProposalCostItem[];
|
costBreakup: ProposalCostItem[];
|
||||||
estimatedBudgetTotal?: number | null;
|
estimatedBudgetTotal?: number | null;
|
||||||
totalEstimatedBudget?: number | null;
|
|
||||||
timelineForClosure?: string | null;
|
timelineForClosure?: string | null;
|
||||||
dealerComments?: string | null;
|
dealerComments?: string | null;
|
||||||
submittedOn?: string | null;
|
submittedOn?: string | null;
|
||||||
@ -37,18 +29,15 @@ interface ProposalDetailsCardProps {
|
|||||||
export function ProposalDetailsCard({ proposalDetails, className }: ProposalDetailsCardProps) {
|
export function ProposalDetailsCard({ proposalDetails, className }: ProposalDetailsCardProps) {
|
||||||
// Calculate estimated total from costBreakup if not provided
|
// Calculate estimated total from costBreakup if not provided
|
||||||
const calculateEstimatedTotal = () => {
|
const calculateEstimatedTotal = () => {
|
||||||
const total = proposalDetails.totalEstimatedBudget ?? proposalDetails.estimatedBudgetTotal;
|
if (proposalDetails.estimatedBudgetTotal !== undefined && proposalDetails.estimatedBudgetTotal !== null) {
|
||||||
if (total !== undefined && total !== null) {
|
return proposalDetails.estimatedBudgetTotal;
|
||||||
return total;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Calculate sum from costBreakup items
|
// Calculate sum from costBreakup items
|
||||||
if (proposalDetails.costBreakup && proposalDetails.costBreakup.length > 0) {
|
if (proposalDetails.costBreakup && proposalDetails.costBreakup.length > 0) {
|
||||||
const total = proposalDetails.costBreakup.reduce((sum, item) => {
|
const total = proposalDetails.costBreakup.reduce((sum, item) => {
|
||||||
const amount = item.amount || 0;
|
const amount = item.amount || 0;
|
||||||
const gst = item.gstAmt || 0;
|
return sum + (Number.isNaN(amount) ? 0 : amount);
|
||||||
const lineTotal = item.totalAmt || (Number(amount) + Number(gst));
|
|
||||||
return sum + (Number.isNaN(lineTotal) ? 0 : lineTotal);
|
|
||||||
}, 0);
|
}, 0);
|
||||||
return total;
|
return total;
|
||||||
}
|
}
|
||||||
@ -110,13 +99,7 @@ export function ProposalDetailsCard({ proposalDetails, className }: ProposalDeta
|
|||||||
Item Description
|
Item Description
|
||||||
</th>
|
</th>
|
||||||
<th className="px-4 py-2 text-right text-xs font-semibold text-gray-700 uppercase tracking-wide">
|
<th className="px-4 py-2 text-right text-xs font-semibold text-gray-700 uppercase tracking-wide">
|
||||||
Base Amount
|
Amount
|
||||||
</th>
|
|
||||||
<th className="px-4 py-2 text-right text-xs font-semibold text-gray-700 uppercase tracking-wide">
|
|
||||||
GST
|
|
||||||
</th>
|
|
||||||
<th className="px-4 py-2 text-right text-xs font-semibold text-gray-700 uppercase tracking-wide">
|
|
||||||
Total
|
|
||||||
</th>
|
</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
@ -124,27 +107,16 @@ export function ProposalDetailsCard({ proposalDetails, className }: ProposalDeta
|
|||||||
{(proposalDetails.costBreakup || []).map((item, index) => (
|
{(proposalDetails.costBreakup || []).map((item, index) => (
|
||||||
<tr key={index} className="hover:bg-gray-50">
|
<tr key={index} className="hover:bg-gray-50">
|
||||||
<td className="px-4 py-3 text-sm text-gray-900">
|
<td className="px-4 py-3 text-sm text-gray-900">
|
||||||
<div>{item.description}</div>
|
{item.description}
|
||||||
{item.gstRate ? (
|
|
||||||
<div className="text-[10px] text-gray-400">
|
|
||||||
{item.cgstAmt ? `CGST: ${item.gstRate / 2}%, SGST: ${item.gstRate / 2}%` : `IGST: ${item.gstRate}%`}
|
|
||||||
</div>
|
|
||||||
) : null}
|
|
||||||
</td>
|
|
||||||
<td className="px-4 py-3 text-sm text-gray-900 text-right">
|
|
||||||
{formatCurrency(item.amount)}
|
|
||||||
</td>
|
|
||||||
<td className="px-4 py-3 text-sm text-gray-900 text-right">
|
|
||||||
{formatCurrency(item.gstAmt)}
|
|
||||||
</td>
|
</td>
|
||||||
<td className="px-4 py-3 text-sm text-gray-900 text-right font-medium">
|
<td className="px-4 py-3 text-sm text-gray-900 text-right font-medium">
|
||||||
{formatCurrency(item.totalAmt || (Number(item.amount || 0) + Number(item.gstAmt || 0)))}
|
{formatCurrency(item.amount)}
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
))}
|
))}
|
||||||
<tr className="bg-green-50 font-semibold">
|
<tr className="bg-green-50 font-semibold">
|
||||||
<td colSpan={3} className="px-4 py-3 text-sm text-gray-900">
|
<td className="px-4 py-3 text-sm text-gray-900">
|
||||||
Estimated Budget (Total Inclusive of GST)
|
Estimated Budget (Total)
|
||||||
</td>
|
</td>
|
||||||
<td className="px-4 py-3 text-sm text-green-700 text-right">
|
<td className="px-4 py-3 text-sm text-green-700 text-right">
|
||||||
{formatCurrency(estimatedTotal)}
|
{formatCurrency(estimatedTotal)}
|
||||||
|
|||||||
@ -40,7 +40,6 @@ interface CreditNoteSAPModalProps {
|
|||||||
requestNumber?: string;
|
requestNumber?: string;
|
||||||
requestId?: string;
|
requestId?: string;
|
||||||
dueDate?: string;
|
dueDate?: string;
|
||||||
taxationType?: string | null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function CreditNoteSAPModal({
|
export function CreditNoteSAPModal({
|
||||||
@ -54,13 +53,10 @@ export function CreditNoteSAPModal({
|
|||||||
requestNumber,
|
requestNumber,
|
||||||
requestId: _requestId,
|
requestId: _requestId,
|
||||||
dueDate,
|
dueDate,
|
||||||
taxationType,
|
|
||||||
}: CreditNoteSAPModalProps) {
|
}: CreditNoteSAPModalProps) {
|
||||||
const [downloading, setDownloading] = useState(false);
|
const [downloading, setDownloading] = useState(false);
|
||||||
const [sending, setSending] = useState(false);
|
const [sending, setSending] = useState(false);
|
||||||
|
|
||||||
const isNonGst = taxationType === 'Non GST' || taxationType === 'Non-GST';
|
|
||||||
|
|
||||||
const hasCreditNote = creditNoteData?.creditNoteNumber && creditNoteData?.creditNoteNumber !== '';
|
const hasCreditNote = creditNoteData?.creditNoteNumber && creditNoteData?.creditNoteNumber !== '';
|
||||||
const creditNoteNumber = creditNoteData?.creditNoteNumber || '';
|
const creditNoteNumber = creditNoteData?.creditNoteNumber || '';
|
||||||
const creditNoteDate = creditNoteData?.creditNoteDate
|
const creditNoteDate = creditNoteData?.creditNoteDate
|
||||||
@ -122,16 +118,9 @@ export function CreditNoteSAPModal({
|
|||||||
<Dialog open={isOpen} onOpenChange={onClose}>
|
<Dialog open={isOpen} onOpenChange={onClose}>
|
||||||
<DialogContent className="sm:max-w-lg lg:max-w-[1000px] max-w-4xl max-h-[90vh] overflow-y-auto">
|
<DialogContent className="sm:max-w-lg lg:max-w-[1000px] max-w-4xl max-h-[90vh] overflow-y-auto">
|
||||||
<DialogHeader>
|
<DialogHeader>
|
||||||
<DialogTitle className="font-semibold flex items-center gap-2 text-2xl flex-wrap">
|
<DialogTitle className="font-semibold flex items-center gap-2 text-2xl">
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<Receipt className="w-6 h-6 text-[--re-green]" />
|
<Receipt className="w-6 h-6 text-[--re-green]" />
|
||||||
Credit Note from SAP
|
Credit Note from SAP
|
||||||
</div>
|
|
||||||
{taxationType && (
|
|
||||||
<Badge className={`ml-2 border-none shadow-sm ${!isNonGst ? 'bg-emerald-600 text-white hover:bg-emerald-700' : 'bg-indigo-600 text-white hover:bg-indigo-700'}`}>
|
|
||||||
{!isNonGst ? 'GST Claim' : 'Non-GST Claim'}
|
|
||||||
</Badge>
|
|
||||||
)}
|
|
||||||
</DialogTitle>
|
</DialogTitle>
|
||||||
<DialogDescription className="text-base">
|
<DialogDescription className="text-base">
|
||||||
Review and send credit note to dealer
|
Review and send credit note to dealer
|
||||||
|
|||||||
@ -1,16 +1,12 @@
|
|||||||
.settlement-push-modal {
|
.dms-push-modal {
|
||||||
width: 90vw !important;
|
width: 90vw !important;
|
||||||
max-width: 1000px !important;
|
max-width: 90vw !important;
|
||||||
min-width: 320px !important;
|
|
||||||
max-height: 95vh !important;
|
max-height: 95vh !important;
|
||||||
overflow: hidden;
|
|
||||||
display: flex;
|
|
||||||
flex-direction: column;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Mobile responsive */
|
/* Mobile responsive */
|
||||||
@media (max-width: 640px) {
|
@media (max-width: 640px) {
|
||||||
.settlement-push-modal {
|
.dms-push-modal {
|
||||||
width: 95vw !important;
|
width: 95vw !important;
|
||||||
max-width: 95vw !important;
|
max-width: 95vw !important;
|
||||||
max-height: 95vh !important;
|
max-height: 95vh !important;
|
||||||
@ -19,48 +15,25 @@
|
|||||||
|
|
||||||
/* Tablet and small desktop */
|
/* Tablet and small desktop */
|
||||||
@media (min-width: 641px) and (max-width: 1023px) {
|
@media (min-width: 641px) and (max-width: 1023px) {
|
||||||
.settlement-push-modal {
|
.dms-push-modal {
|
||||||
width: 90vw !important;
|
width: 90vw !important;
|
||||||
max-width: 900px !important;
|
max-width: 90vw !important;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Scrollable content area */
|
/* Large screens - fixed max-width for better readability */
|
||||||
.settlement-push-modal .flex-1 {
|
@media (min-width: 1024px) {
|
||||||
overflow-y: auto;
|
.dms-push-modal {
|
||||||
padding-right: 4px;
|
width: 90vw !important;
|
||||||
|
max-width: 1000px !important;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Custom scrollbar for the modal content */
|
/* Extra large screens */
|
||||||
.settlement-push-modal .flex-1::-webkit-scrollbar {
|
@media (min-width: 1536px) {
|
||||||
width: 6px;
|
.dms-push-modal {
|
||||||
|
width: 90vw !important;
|
||||||
|
max-width: 1000px !important;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
.settlement-push-modal .flex-1::-webkit-scrollbar-track {
|
|
||||||
background: transparent;
|
|
||||||
}
|
|
||||||
|
|
||||||
.settlement-push-modal .flex-1::-webkit-scrollbar-thumb {
|
|
||||||
background: #e2e8f0;
|
|
||||||
border-radius: 10px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.settlement-push-modal .flex-1::-webkit-scrollbar-thumb:hover {
|
|
||||||
background: #cbd5e1;
|
|
||||||
}
|
|
||||||
|
|
||||||
.file-preview-dialog {
|
|
||||||
width: 95vw !important;
|
|
||||||
max-width: 1200px !important;
|
|
||||||
max-height: 95vh !important;
|
|
||||||
padding: 0 !important;
|
|
||||||
display: flex;
|
|
||||||
flex-direction: column;
|
|
||||||
}
|
|
||||||
|
|
||||||
.file-preview-content {
|
|
||||||
display: flex;
|
|
||||||
flex-direction: column;
|
|
||||||
height: 100%;
|
|
||||||
width: 100%;
|
|
||||||
}
|
|
||||||
@ -27,7 +27,6 @@ import {
|
|||||||
Download,
|
Download,
|
||||||
Eye,
|
Eye,
|
||||||
Loader2,
|
Loader2,
|
||||||
RefreshCw,
|
|
||||||
} from 'lucide-react';
|
} from 'lucide-react';
|
||||||
import { toast } from 'sonner';
|
import { toast } from 'sonner';
|
||||||
import { getDocumentPreviewUrl, downloadDocument } from '@/services/workflowApi';
|
import { getDocumentPreviewUrl, downloadDocument } from '@/services/workflowApi';
|
||||||
@ -81,31 +80,23 @@ interface DMSPushModalProps {
|
|||||||
isOpen: boolean;
|
isOpen: boolean;
|
||||||
onClose: () => void;
|
onClose: () => void;
|
||||||
onPush: (comments: string) => Promise<void>;
|
onPush: (comments: string) => Promise<void>;
|
||||||
onReQuotation?: (comments: string) => Promise<void>;
|
|
||||||
completionDetails?: CompletionDetails | null;
|
completionDetails?: CompletionDetails | null;
|
||||||
ioDetails?: IODetails | null;
|
ioDetails?: IODetails | null;
|
||||||
completionDocuments?: CompletionDocuments | null;
|
completionDocuments?: CompletionDocuments | null;
|
||||||
requestTitle?: string;
|
requestTitle?: string;
|
||||||
requestNumber?: string;
|
requestNumber?: string;
|
||||||
taxationType?: string | null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function DMSPushModal({
|
export function DMSPushModal({
|
||||||
isOpen,
|
isOpen,
|
||||||
onClose,
|
onClose,
|
||||||
onPush,
|
onPush,
|
||||||
onReQuotation,
|
|
||||||
completionDetails,
|
completionDetails,
|
||||||
ioDetails,
|
ioDetails,
|
||||||
completionDocuments,
|
completionDocuments,
|
||||||
requestTitle,
|
requestTitle,
|
||||||
requestNumber,
|
requestNumber,
|
||||||
taxationType,
|
|
||||||
}: DMSPushModalProps) {
|
}: DMSPushModalProps) {
|
||||||
const isNonGst = useMemo(() => {
|
|
||||||
return taxationType === 'Non GST' || taxationType === 'Non-GST';
|
|
||||||
}, [taxationType]);
|
|
||||||
|
|
||||||
const [comments, setComments] = useState('');
|
const [comments, setComments] = useState('');
|
||||||
const [submitting, setSubmitting] = useState(false);
|
const [submitting, setSubmitting] = useState(false);
|
||||||
const [previewDocument, setPreviewDocument] = useState<{
|
const [previewDocument, setPreviewDocument] = useState<{
|
||||||
@ -127,9 +118,7 @@ export function DMSPushModal({
|
|||||||
if (completionDetails?.closedExpenses && Array.isArray(completionDetails.closedExpenses)) {
|
if (completionDetails?.closedExpenses && Array.isArray(completionDetails.closedExpenses)) {
|
||||||
return completionDetails.closedExpenses.reduce((sum, item) => {
|
return completionDetails.closedExpenses.reduce((sum, item) => {
|
||||||
const amount = typeof item === 'object' ? (item.amount || 0) : 0;
|
const amount = typeof item === 'object' ? (item.amount || 0) : 0;
|
||||||
const gst = typeof item === 'object' ? ((item as any).gstAmt || 0) : 0;
|
return sum + (Number(amount) || 0);
|
||||||
const total = (item as any).totalAmt || (amount + gst);
|
|
||||||
return sum + (Number(total) || 0);
|
|
||||||
}, 0);
|
}, 0);
|
||||||
}
|
}
|
||||||
return 0;
|
return 0;
|
||||||
@ -239,7 +228,7 @@ export function DMSPushModal({
|
|||||||
|
|
||||||
const handleSubmit = async () => {
|
const handleSubmit = async () => {
|
||||||
if (!comments.trim()) {
|
if (!comments.trim()) {
|
||||||
toast.error('Please provide comments before proceeding');
|
toast.error('Please provide comments before pushing to DMS');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -249,8 +238,8 @@ export function DMSPushModal({
|
|||||||
handleReset();
|
handleReset();
|
||||||
onClose();
|
onClose();
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to generate e-invoice:', error);
|
console.error('Failed to push to DMS:', error);
|
||||||
toast.error('Failed to generate e-invoice. Please try again.');
|
toast.error('Failed to push to DMS. Please try again.');
|
||||||
} finally {
|
} finally {
|
||||||
setSubmitting(false);
|
setSubmitting(false);
|
||||||
}
|
}
|
||||||
@ -260,30 +249,6 @@ export function DMSPushModal({
|
|||||||
setComments('');
|
setComments('');
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleReQuotation = async () => {
|
|
||||||
if (!comments.trim()) {
|
|
||||||
toast.error('Please provide comments (reason) for re-quotation request');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!onReQuotation) {
|
|
||||||
toast.error('Re-quotation handler not provided');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
setSubmitting(true);
|
|
||||||
await onReQuotation(comments.trim());
|
|
||||||
handleReset();
|
|
||||||
onClose();
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Failed to request re-quotation:', error);
|
|
||||||
// Error is handled in the parent handler
|
|
||||||
} finally {
|
|
||||||
setSubmitting(false);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleClose = () => {
|
const handleClose = () => {
|
||||||
if (!submitting) {
|
if (!submitting) {
|
||||||
handleReset();
|
handleReset();
|
||||||
@ -292,25 +257,19 @@ export function DMSPushModal({
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
|
||||||
<Dialog open={isOpen} onOpenChange={handleClose}>
|
<Dialog open={isOpen} onOpenChange={handleClose}>
|
||||||
<DialogContent className="settlement-push-modal overflow-hidden flex flex-col w-full max-w-none">
|
<DialogContent className="dms-push-modal overflow-hidden flex flex-col">
|
||||||
<DialogHeader className="px-6 pt-6 pb-3 flex-shrink-0">
|
<DialogHeader className="px-6 pt-6 pb-3 flex-shrink-0">
|
||||||
<div className="flex items-center gap-2 sm:gap-3 mb-2">
|
<div className="flex items-center gap-2 sm:gap-3 mb-2">
|
||||||
<div className="p-1.5 sm:p-2 rounded-lg bg-indigo-100">
|
<div className="p-1.5 sm:p-2 rounded-lg bg-indigo-100">
|
||||||
<Activity className="w-4 h-4 sm:w-5 sm:h-5 sm:w-6 sm:h-6 text-indigo-600" />
|
<Activity className="w-4 h-4 sm:w-5 sm:h-5 sm:w-6 sm:h-6 text-indigo-600" />
|
||||||
</div>
|
</div>
|
||||||
<div className="flex-1">
|
<div className="flex-1">
|
||||||
<DialogTitle className="font-semibold text-lg sm:text-xl flex items-center gap-2 flex-wrap">
|
<DialogTitle className="font-semibold text-lg sm:text-xl">
|
||||||
E-Invoice Generation & Sync
|
Push to DMS - Verification
|
||||||
{taxationType && (
|
|
||||||
<Badge className={`ml-2 border-none shadow-sm ${!isNonGst ? 'bg-emerald-600 text-white hover:bg-emerald-700' : 'bg-indigo-600 text-white hover:bg-indigo-700'}`}>
|
|
||||||
{!isNonGst ? 'GST Claim' : 'Non-GST Claim'}
|
|
||||||
</Badge>
|
|
||||||
)}
|
|
||||||
</DialogTitle>
|
</DialogTitle>
|
||||||
<DialogDescription className="text-xs sm:text-sm mt-1">
|
<DialogDescription className="text-xs sm:text-sm mt-1">
|
||||||
Review completion details and expenses before generating e-invoice and initiating SAP settlement
|
Review completion details and expenses before pushing to DMS for e-invoice generation
|
||||||
</DialogDescription>
|
</DialogDescription>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@ -335,7 +294,7 @@ export function DMSPushModal({
|
|||||||
<span className="font-medium text-xs sm:text-sm text-gray-600">Action:</span>
|
<span className="font-medium text-xs sm:text-sm text-gray-600">Action:</span>
|
||||||
<Badge className="bg-indigo-100 text-indigo-800 border-indigo-200 text-xs">
|
<Badge className="bg-indigo-100 text-indigo-800 border-indigo-200 text-xs">
|
||||||
<Activity className="w-3 h-3 mr-1" />
|
<Activity className="w-3 h-3 mr-1" />
|
||||||
SYNC TO SAP
|
PUSH TO DMS
|
||||||
</Badge>
|
</Badge>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@ -427,83 +386,38 @@ export function DMSPushModal({
|
|||||||
|
|
||||||
{/* Expense Breakdown Card */}
|
{/* Expense Breakdown Card */}
|
||||||
{completionDetails?.closedExpenses && completionDetails.closedExpenses.length > 0 && (
|
{completionDetails?.closedExpenses && completionDetails.closedExpenses.length > 0 && (
|
||||||
<Card className="md:col-span-2 lg:col-span-3">
|
<Card>
|
||||||
<CardHeader className="pb-3">
|
<CardHeader className="pb-3">
|
||||||
<CardTitle className="flex items-center gap-2 text-base sm:text-lg">
|
<CardTitle className="flex items-center gap-2 text-base sm:text-lg">
|
||||||
<DollarSign className="w-4 h-4 sm:w-5 sm:h-5 text-blue-600" />
|
<DollarSign className="w-4 h-4 sm:w-5 sm:h-5 text-blue-600" />
|
||||||
Expense Breakdown
|
Expense Breakdown
|
||||||
</CardTitle>
|
</CardTitle>
|
||||||
<CardDescription className="text-xs sm:text-sm">
|
<CardDescription className="text-xs sm:text-sm">
|
||||||
Review closed expenses breakdown (Base + GST)
|
Review closed expenses before pushing to DMS
|
||||||
</CardDescription>
|
</CardDescription>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent>
|
||||||
{/* Table Header */}
|
<div className="space-y-1.5 sm:space-y-2 max-h-[200px] overflow-y-auto">
|
||||||
<div className="grid grid-cols-12 gap-2 mb-2 px-3 text-xs font-medium text-gray-500 uppercase tracking-wider hidden sm:grid">
|
{completionDetails.closedExpenses.map((expense, index) => (
|
||||||
<div className={`${isNonGst ? 'col-span-8' : 'col-span-4'}`}>Description</div>
|
|
||||||
<div className="col-span-2 text-right">Base</div>
|
|
||||||
{!isNonGst && (
|
|
||||||
<>
|
|
||||||
<div className="col-span-2 text-right">GST Rate</div>
|
|
||||||
<div className="col-span-2 text-right">GST Amt</div>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
<div className="col-span-2 text-right">Total</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="space-y-2 max-h-[300px] overflow-y-auto">
|
|
||||||
{completionDetails.closedExpenses.map((expense, index) => {
|
|
||||||
const amount = typeof expense === 'object' ? (expense.amount || 0) : 0; // Base Amount
|
|
||||||
const gstRate = typeof expense === 'object' ? ((expense as any).gstRate || 0) : 0;
|
|
||||||
const gstAmt = typeof expense === 'object' ? ((expense as any).gstAmt || 0) : 0; // GST Amount
|
|
||||||
const total = typeof expense === 'object' ? ((expense as any).totalAmt || (amount + gstAmt)) : 0; // Total Amount
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div
|
<div
|
||||||
key={index}
|
key={index}
|
||||||
className="grid grid-cols-1 sm:grid-cols-12 gap-2 items-center py-2 px-3 bg-gray-50 rounded border text-xs sm:text-sm"
|
className="flex items-center justify-between py-1.5 sm:py-2 px-2 sm:px-3 bg-gray-50 rounded border"
|
||||||
>
|
>
|
||||||
{/* Mobile View: Stacked */}
|
<div className="flex-1 min-w-0 pr-2">
|
||||||
<div className="sm:hidden flex justify-between w-full mb-1">
|
<p className="text-xs sm:text-sm font-medium text-gray-900 truncate">
|
||||||
<span className="font-semibold text-gray-900">{expense.description || `Expense ${index + 1}`}</span>
|
|
||||||
<span className="font-bold text-gray-900">{formatCurrency(total)}</span>
|
|
||||||
</div>
|
|
||||||
<div className="sm:hidden flex justify-between w-full text-xs text-gray-500">
|
|
||||||
<span>Base: {formatCurrency(amount)}</span>
|
|
||||||
{!isNonGst && (
|
|
||||||
<span>GST: {gstRate}% ({formatCurrency(gstAmt)})</span>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* Desktop View: Grid */}
|
|
||||||
<div className={`hidden sm:block ${isNonGst ? 'col-span-8' : 'col-span-4'} min-w-0`}>
|
|
||||||
<p className="font-medium text-gray-900 truncate" title={expense.description}>
|
|
||||||
{expense.description || `Expense ${index + 1}`}
|
{expense.description || `Expense ${index + 1}`}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<div className="hidden sm:block col-span-2 text-right text-gray-600">
|
<div className="ml-2 flex-shrink-0">
|
||||||
{formatCurrency(amount)}
|
<p className="text-xs sm:text-sm font-semibold text-gray-900">
|
||||||
</div>
|
{formatCurrency(typeof expense === 'object' ? (expense.amount || 0) : 0)}
|
||||||
{!isNonGst && (
|
</p>
|
||||||
<>
|
|
||||||
<div className="hidden sm:block col-span-2 text-right text-gray-600">
|
|
||||||
{gstRate}%
|
|
||||||
</div>
|
|
||||||
<div className="hidden sm:block col-span-2 text-right text-gray-600">
|
|
||||||
{formatCurrency(gstAmt)}
|
|
||||||
</div>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
<div className="hidden sm:block col-span-2 text-right font-semibold text-gray-900">
|
|
||||||
{formatCurrency(total)}
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
))}
|
||||||
})}
|
|
||||||
</div>
|
</div>
|
||||||
|
<div className="flex items-center justify-between py-2 sm:py-3 px-2 sm:px-3 bg-blue-50 rounded border-2 border-blue-200 mt-2 sm:mt-3">
|
||||||
<div className="flex items-center justify-between py-2 sm:py-3 px-3 sm:px-4 bg-blue-50 rounded border-2 border-blue-200 mt-3 sm:mt-4">
|
<span className="text-xs sm:text-sm font-semibold text-gray-900">Total:</span>
|
||||||
<span className="text-xs sm:text-sm font-semibold text-gray-900">Total Closed Expenses:</span>
|
|
||||||
<span className="text-sm sm:text-base font-bold text-blue-700">
|
<span className="text-sm sm:text-base font-bold text-blue-700">
|
||||||
{formatCurrency(totalClosedExpenses)}
|
{formatCurrency(totalClosedExpenses)}
|
||||||
</span>
|
</span>
|
||||||
@ -786,10 +700,10 @@ export function DMSPushModal({
|
|||||||
<TriangleAlert className="w-4 h-4 sm:w-5 sm:h-5 text-yellow-600 flex-shrink-0 mt-0.5" />
|
<TriangleAlert className="w-4 h-4 sm:w-5 sm:h-5 text-yellow-600 flex-shrink-0 mt-0.5" />
|
||||||
<div>
|
<div>
|
||||||
<p className="text-xs sm:text-sm font-semibold text-yellow-900">
|
<p className="text-xs sm:text-sm font-semibold text-yellow-900">
|
||||||
Please verify all details before generation
|
Please verify all details before pushing to DMS
|
||||||
</p>
|
</p>
|
||||||
<p className="text-xs text-yellow-700 mt-1">
|
<p className="text-xs text-yellow-700 mt-1">
|
||||||
Once submitted, the system will generate an e-invoice and initiate the SAP settlement process.
|
Once pushed, the system will automatically generate an e-invoice and log it as an activity.
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@ -802,7 +716,7 @@ export function DMSPushModal({
|
|||||||
</Label>
|
</Label>
|
||||||
<Textarea
|
<Textarea
|
||||||
id="comment"
|
id="comment"
|
||||||
placeholder="Enter your comments about e-invoice generation (e.g., verified expenses, ready for settlement)..."
|
placeholder="Enter your comments about pushing to DMS (e.g., verified expenses, ready for invoice generation)..."
|
||||||
value={comments}
|
value={comments}
|
||||||
onChange={(e) => {
|
onChange={(e) => {
|
||||||
const value = e.target.value;
|
const value = e.target.value;
|
||||||
@ -832,40 +746,23 @@ export function DMSPushModal({
|
|||||||
>
|
>
|
||||||
Cancel
|
Cancel
|
||||||
</Button>
|
</Button>
|
||||||
{onReQuotation && (
|
|
||||||
<Button
|
|
||||||
variant="outline"
|
|
||||||
className="border-orange-500 text-orange-600 hover:bg-orange-50"
|
|
||||||
onClick={handleReQuotation}
|
|
||||||
disabled={!comments.trim() || submitting}
|
|
||||||
>
|
|
||||||
{submitting ? (
|
|
||||||
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
|
|
||||||
) : (
|
|
||||||
<RefreshCw className="w-4 h-4 mr-2" />
|
|
||||||
)}
|
|
||||||
Request Re-quotation
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
<Button
|
<Button
|
||||||
onClick={handleSubmit}
|
onClick={handleSubmit}
|
||||||
disabled={!comments.trim() || submitting}
|
disabled={!comments.trim() || submitting}
|
||||||
className="bg-indigo-600 hover:bg-indigo-700 text-white"
|
className="bg-indigo-600 hover:bg-indigo-700 text-white"
|
||||||
>
|
>
|
||||||
{submitting ? (
|
{submitting ? (
|
||||||
'Processing...'
|
'Pushing to DMS...'
|
||||||
) : (
|
) : (
|
||||||
<>
|
<>
|
||||||
<Activity className="w-4 h-4 mr-2" />
|
<Activity className="w-4 h-4 mr-2" />
|
||||||
Generate & Sync
|
Push to DMS
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</Button>
|
</Button>
|
||||||
</DialogFooter>
|
</DialogFooter>
|
||||||
</DialogContent>
|
</DialogContent>
|
||||||
|
|
||||||
</Dialog>
|
|
||||||
|
|
||||||
{/* File Preview Modal - Matching DocumentsTab style */}
|
{/* File Preview Modal - Matching DocumentsTab style */}
|
||||||
{previewDocument && (
|
{previewDocument && (
|
||||||
<Dialog
|
<Dialog
|
||||||
@ -969,7 +866,7 @@ export function DMSPushModal({
|
|||||||
</DialogContent>
|
</DialogContent>
|
||||||
</Dialog>
|
</Dialog>
|
||||||
)}
|
)}
|
||||||
</>
|
</Dialog>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -25,7 +25,7 @@
|
|||||||
@media (min-width: 1024px) {
|
@media (min-width: 1024px) {
|
||||||
.dealer-completion-documents-modal {
|
.dealer-completion-documents-modal {
|
||||||
width: 90vw !important;
|
width: 90vw !important;
|
||||||
max-width: 1200px !important;
|
max-width: 1000px !important;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -33,7 +33,7 @@
|
|||||||
@media (min-width: 1536px) {
|
@media (min-width: 1536px) {
|
||||||
.dealer-completion-documents-modal {
|
.dealer-completion-documents-modal {
|
||||||
width: 90vw !important;
|
width: 90vw !important;
|
||||||
max-width: 1200px !important;
|
max-width: 1000px !important;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -65,3 +65,4 @@
|
|||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
opacity: 1;
|
opacity: 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -19,34 +19,15 @@ import { Label } from '@/components/ui/label';
|
|||||||
import { Textarea } from '@/components/ui/textarea';
|
import { Textarea } from '@/components/ui/textarea';
|
||||||
import { Badge } from '@/components/ui/badge';
|
import { Badge } from '@/components/ui/badge';
|
||||||
import { CustomDatePicker } from '@/components/ui/date-picker';
|
import { CustomDatePicker } from '@/components/ui/date-picker';
|
||||||
import { Upload, Plus, X, Calendar, FileText, Image, Receipt, CircleAlert, CheckCircle2, Eye, Download, IndianRupee } from 'lucide-react';
|
import { Upload, Plus, X, Calendar, FileText, Image, Receipt, CircleAlert, CheckCircle2, Eye, Download } from 'lucide-react';
|
||||||
import { toast } from 'sonner';
|
import { toast } from 'sonner';
|
||||||
import { handleSecurityError } from '@/utils/securityToast';
|
|
||||||
import '@/components/common/FilePreview/FilePreview.css';
|
import '@/components/common/FilePreview/FilePreview.css';
|
||||||
import './DealerCompletionDocumentsModal.css';
|
import './DealerCompletionDocumentsModal.css';
|
||||||
import { validateHSNSAC } from '@/utils/validationUtils';
|
|
||||||
import { getStateCodeFromGSTIN, getActiveTaxComponents } from '@/utils/gstUtils';
|
|
||||||
|
|
||||||
interface ExpenseItem {
|
interface ExpenseItem {
|
||||||
id: string;
|
id: string;
|
||||||
description: string;
|
description: string;
|
||||||
amount: number;
|
amount: number;
|
||||||
gstRate: number;
|
|
||||||
gstAmt: number;
|
|
||||||
quantity: number;
|
|
||||||
hsnCode: string;
|
|
||||||
cgstRate: number;
|
|
||||||
cgstAmt: number;
|
|
||||||
sgstRate: number;
|
|
||||||
sgstAmt: number;
|
|
||||||
igstRate: number;
|
|
||||||
igstAmt: number;
|
|
||||||
utgstRate: number;
|
|
||||||
utgstAmt: number;
|
|
||||||
cessRate: number;
|
|
||||||
cessAmt: number;
|
|
||||||
totalAmt: number;
|
|
||||||
isService: boolean;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
interface DealerCompletionDocumentsModalProps {
|
interface DealerCompletionDocumentsModalProps {
|
||||||
@ -64,15 +45,12 @@ interface DealerCompletionDocumentsModalProps {
|
|||||||
completionDescription: string;
|
completionDescription: string;
|
||||||
}) => Promise<void>;
|
}) => Promise<void>;
|
||||||
dealerName?: string;
|
dealerName?: string;
|
||||||
dealerGSTIN?: string;
|
|
||||||
activityName?: string;
|
activityName?: string;
|
||||||
requestId?: string;
|
requestId?: string;
|
||||||
defaultGstRate?: number;
|
|
||||||
documentPolicy: {
|
documentPolicy: {
|
||||||
maxFileSizeMB: number;
|
maxFileSizeMB: number;
|
||||||
allowedFileTypes: string[];
|
allowedFileTypes: string[];
|
||||||
};
|
};
|
||||||
taxationType?: string | null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function DealerCompletionDocumentsModal({
|
export function DealerCompletionDocumentsModal({
|
||||||
@ -80,26 +58,12 @@ export function DealerCompletionDocumentsModal({
|
|||||||
onClose,
|
onClose,
|
||||||
onSubmit,
|
onSubmit,
|
||||||
dealerName = 'Jaipur Royal Enfield',
|
dealerName = 'Jaipur Royal Enfield',
|
||||||
dealerGSTIN,
|
|
||||||
activityName = 'Activity',
|
activityName = 'Activity',
|
||||||
requestId: _requestId,
|
requestId: _requestId,
|
||||||
defaultGstRate = 18,
|
|
||||||
documentPolicy,
|
documentPolicy,
|
||||||
taxationType,
|
|
||||||
}: DealerCompletionDocumentsModalProps) {
|
}: DealerCompletionDocumentsModalProps) {
|
||||||
const [activityCompletionDate, setActivityCompletionDate] = useState('');
|
const [activityCompletionDate, setActivityCompletionDate] = useState('');
|
||||||
const [numberOfParticipants, setNumberOfParticipants] = useState('');
|
const [numberOfParticipants, setNumberOfParticipants] = useState('');
|
||||||
|
|
||||||
// Determine active tax components based on dealer GSTIN
|
|
||||||
const taxConfig = useMemo(() => {
|
|
||||||
const stateCode = getStateCodeFromGSTIN(dealerGSTIN);
|
|
||||||
return getActiveTaxComponents(stateCode);
|
|
||||||
}, [dealerGSTIN]);
|
|
||||||
|
|
||||||
const isNonGst = useMemo(() => {
|
|
||||||
return taxationType === 'Non GST' || taxationType === 'Non-GST';
|
|
||||||
}, [taxationType]);
|
|
||||||
|
|
||||||
const [expenseItems, setExpenseItems] = useState<ExpenseItem[]>([]);
|
const [expenseItems, setExpenseItems] = useState<ExpenseItem[]>([]);
|
||||||
const [completionDocuments, setCompletionDocuments] = useState<File[]>([]);
|
const [completionDocuments, setCompletionDocuments] = useState<File[]>([]);
|
||||||
const [activityPhotos, setActivityPhotos] = useState<File[]>([]);
|
const [activityPhotos, setActivityPhotos] = useState<File[]>([]);
|
||||||
@ -137,33 +101,6 @@ export function DealerCompletionDocumentsModal({
|
|||||||
};
|
};
|
||||||
}, [previewFile]);
|
}, [previewFile]);
|
||||||
|
|
||||||
// Initialize with one empty row if none exist
|
|
||||||
useEffect(() => {
|
|
||||||
if (expenseItems.length === 0) {
|
|
||||||
setExpenseItems([{
|
|
||||||
id: '1',
|
|
||||||
description: '',
|
|
||||||
amount: 0,
|
|
||||||
gstRate: defaultGstRate || 0,
|
|
||||||
gstAmt: 0,
|
|
||||||
quantity: 1,
|
|
||||||
hsnCode: '',
|
|
||||||
isService: false,
|
|
||||||
cgstRate: 0,
|
|
||||||
cgstAmt: 0,
|
|
||||||
sgstRate: 0,
|
|
||||||
sgstAmt: 0,
|
|
||||||
igstRate: 0,
|
|
||||||
igstAmt: 0,
|
|
||||||
utgstRate: 0,
|
|
||||||
utgstAmt: 0,
|
|
||||||
cessRate: 0,
|
|
||||||
cessAmt: 0,
|
|
||||||
totalAmt: 0
|
|
||||||
}]);
|
|
||||||
}
|
|
||||||
}, [defaultGstRate]);
|
|
||||||
|
|
||||||
// Handle file preview
|
// Handle file preview
|
||||||
const handlePreviewFile = (file: File) => {
|
const handlePreviewFile = (file: File) => {
|
||||||
if (!canPreviewFile(file)) {
|
if (!canPreviewFile(file)) {
|
||||||
@ -192,36 +129,11 @@ export function DealerCompletionDocumentsModal({
|
|||||||
URL.revokeObjectURL(url);
|
URL.revokeObjectURL(url);
|
||||||
};
|
};
|
||||||
|
|
||||||
// Calculate total closed expenses (inclusive of GST)
|
// Calculate total closed expenses
|
||||||
const totalClosedExpenses = useMemo(() => {
|
const totalClosedExpenses = useMemo(() => {
|
||||||
return expenseItems.reduce((sum, item) => sum + (item.totalAmt || item.amount || 0), 0);
|
return expenseItems.reduce((sum, item) => sum + (item.amount || 0), 0);
|
||||||
}, [expenseItems]);
|
}, [expenseItems]);
|
||||||
|
|
||||||
// GST Calculation Helper
|
|
||||||
const calculateGST = (amount: number, rates: { cgstRate: number; sgstRate: number; igstRate: number; utgstRate: number }, quantity: number = 1) => {
|
|
||||||
const baseTotal = amount * quantity;
|
|
||||||
const cgstAmt = (baseTotal * (rates.cgstRate || 0)) / 100;
|
|
||||||
const sgstAmt = (baseTotal * (rates.sgstRate || 0)) / 100;
|
|
||||||
const utgstAmt = (baseTotal * (rates.utgstRate || 0)) / 100;
|
|
||||||
const igstAmt = (baseTotal * (rates.igstRate || 0)) / 100;
|
|
||||||
const gstAmt = cgstAmt + sgstAmt + utgstAmt + igstAmt;
|
|
||||||
const totalAmt = baseTotal + gstAmt;
|
|
||||||
|
|
||||||
return {
|
|
||||||
cgstRate: rates.cgstRate,
|
|
||||||
cgstAmt,
|
|
||||||
sgstRate: rates.sgstRate,
|
|
||||||
sgstAmt,
|
|
||||||
utgstRate: rates.utgstRate,
|
|
||||||
utgstAmt,
|
|
||||||
igstRate: rates.igstRate,
|
|
||||||
igstAmt,
|
|
||||||
gstAmt,
|
|
||||||
gstRate: (rates.cgstRate || 0) + (rates.sgstRate || 0) + (rates.utgstRate || 0) + (rates.igstRate || 0),
|
|
||||||
totalAmt
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
// Check if all required fields are filled
|
// Check if all required fields are filled
|
||||||
const isFormValid = useMemo(() => {
|
const isFormValid = useMemo(() => {
|
||||||
const hasCompletionDate = activityCompletionDate !== '';
|
const hasCompletionDate = activityCompletionDate !== '';
|
||||||
@ -229,13 +141,8 @@ export function DealerCompletionDocumentsModal({
|
|||||||
const hasPhotos = activityPhotos.length > 0;
|
const hasPhotos = activityPhotos.length > 0;
|
||||||
const hasDescription = completionDescription.trim().length > 0;
|
const hasDescription = completionDescription.trim().length > 0;
|
||||||
|
|
||||||
const hasHSNSACErrors = isNonGst ? false : expenseItems.some(item => {
|
return hasCompletionDate && hasDocuments && hasPhotos && hasDescription;
|
||||||
const { isValid } = validateHSNSAC(item.hsnCode, item.isService);
|
}, [activityCompletionDate, completionDocuments, activityPhotos, completionDescription]);
|
||||||
return !isValid;
|
|
||||||
});
|
|
||||||
|
|
||||||
return hasCompletionDate && hasDocuments && hasPhotos && hasDescription && !hasHSNSACErrors;
|
|
||||||
}, [activityCompletionDate, completionDocuments, activityPhotos, completionDescription, isNonGst, expenseItems]);
|
|
||||||
|
|
||||||
// Get today's date in YYYY-MM-DD format for max date
|
// Get today's date in YYYY-MM-DD format for max date
|
||||||
const maxDate = new Date().toISOString().split('T')[0];
|
const maxDate = new Date().toISOString().split('T')[0];
|
||||||
@ -243,110 +150,15 @@ export function DealerCompletionDocumentsModal({
|
|||||||
const handleAddExpense = () => {
|
const handleAddExpense = () => {
|
||||||
setExpenseItems([
|
setExpenseItems([
|
||||||
...expenseItems,
|
...expenseItems,
|
||||||
{
|
{ id: Date.now().toString(), description: '', amount: 0 },
|
||||||
id: Date.now().toString(),
|
|
||||||
description: '',
|
|
||||||
amount: 0,
|
|
||||||
gstRate: defaultGstRate || 0,
|
|
||||||
gstAmt: 0,
|
|
||||||
quantity: 1,
|
|
||||||
hsnCode: '',
|
|
||||||
isService: false,
|
|
||||||
cgstRate: 0,
|
|
||||||
cgstAmt: 0,
|
|
||||||
sgstRate: 0,
|
|
||||||
sgstAmt: 0,
|
|
||||||
igstRate: 0,
|
|
||||||
igstAmt: 0,
|
|
||||||
utgstRate: 0,
|
|
||||||
utgstAmt: 0,
|
|
||||||
cessRate: 0,
|
|
||||||
cessAmt: 0,
|
|
||||||
totalAmt: 0
|
|
||||||
},
|
|
||||||
]);
|
]);
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleExpenseChange = (id: string, field: string, value: any) => {
|
const handleExpenseChange = (id: string, field: 'description' | 'amount', value: string | number) => {
|
||||||
setExpenseItems(
|
setExpenseItems(
|
||||||
expenseItems.map((item) => {
|
expenseItems.map((item) =>
|
||||||
if (item.id === id) {
|
item.id === id ? { ...item, [field]: value } : item
|
||||||
let updatedItem = { ...item, [field]: value };
|
)
|
||||||
|
|
||||||
// Re-calculate GST if relevant fields change
|
|
||||||
if (['amount', 'gstRate', 'cgstRate', 'sgstRate', 'utgstRate', 'igstRate', 'quantity'].includes(field)) {
|
|
||||||
const amount = field === 'amount' ? parseFloat(value) || 0 : item.amount;
|
|
||||||
const quantity = field === 'quantity' ? parseInt(value) || 1 : item.quantity;
|
|
||||||
|
|
||||||
let cgstRate = item.cgstRate;
|
|
||||||
let sgstRate = item.sgstRate;
|
|
||||||
let utgstRate = item.utgstRate;
|
|
||||||
let igstRate = item.igstRate;
|
|
||||||
|
|
||||||
if (field === 'cgstRate') {
|
|
||||||
if (!taxConfig.isCGST) return item;
|
|
||||||
cgstRate = parseFloat(value) || 0;
|
|
||||||
// If UTGST is active for this dealer, sync with it
|
|
||||||
if (taxConfig.isUTGST) {
|
|
||||||
utgstRate = cgstRate;
|
|
||||||
sgstRate = 0;
|
|
||||||
} else {
|
|
||||||
sgstRate = cgstRate;
|
|
||||||
utgstRate = 0;
|
|
||||||
}
|
|
||||||
igstRate = 0;
|
|
||||||
} else if (field === 'sgstRate') {
|
|
||||||
if (!taxConfig.isSGST) return item;
|
|
||||||
sgstRate = parseFloat(value) || 0;
|
|
||||||
cgstRate = sgstRate;
|
|
||||||
utgstRate = 0;
|
|
||||||
igstRate = 0;
|
|
||||||
} else if (field === 'utgstRate') {
|
|
||||||
if (!taxConfig.isUTGST) return item;
|
|
||||||
utgstRate = parseFloat(value) || 0;
|
|
||||||
cgstRate = utgstRate;
|
|
||||||
sgstRate = 0;
|
|
||||||
igstRate = 0;
|
|
||||||
} else if (field === 'igstRate') {
|
|
||||||
if (!taxConfig.isIGST) return item;
|
|
||||||
igstRate = parseFloat(value) || 0;
|
|
||||||
cgstRate = 0;
|
|
||||||
sgstRate = 0;
|
|
||||||
utgstRate = 0;
|
|
||||||
} else if (field === 'gstRate') {
|
|
||||||
const totalRate = parseFloat(value) || 0;
|
|
||||||
if (taxConfig.isIGST) {
|
|
||||||
igstRate = totalRate;
|
|
||||||
cgstRate = 0;
|
|
||||||
sgstRate = 0;
|
|
||||||
utgstRate = 0;
|
|
||||||
} else {
|
|
||||||
cgstRate = totalRate / 2;
|
|
||||||
if (taxConfig.isUTGST) {
|
|
||||||
utgstRate = totalRate / 2;
|
|
||||||
sgstRate = 0;
|
|
||||||
} else {
|
|
||||||
sgstRate = totalRate / 2;
|
|
||||||
utgstRate = 0;
|
|
||||||
}
|
|
||||||
igstRate = 0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const calculation = calculateGST(amount, { cgstRate, sgstRate, igstRate, utgstRate }, quantity);
|
|
||||||
|
|
||||||
return {
|
|
||||||
...updatedItem,
|
|
||||||
amount,
|
|
||||||
quantity,
|
|
||||||
...calculation
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
return updatedItem;
|
|
||||||
}
|
|
||||||
return item;
|
|
||||||
})
|
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -528,21 +340,6 @@ export function DealerCompletionDocumentsModal({
|
|||||||
(item) => item.description.trim() !== '' && item.amount > 0
|
(item) => item.description.trim() !== '' && item.amount > 0
|
||||||
);
|
);
|
||||||
|
|
||||||
// Validation: Alert for 0% GST on taxable items (Skip for Non-GST)
|
|
||||||
const hasZeroGstItems = !isNonGst && validExpenses.some(item =>
|
|
||||||
item.description.trim() !== '' && item.amount > 0 && (item.gstRate === 0 || !item.gstRate)
|
|
||||||
);
|
|
||||||
|
|
||||||
if (hasZeroGstItems) {
|
|
||||||
const confirmZeroGst = window.confirm(
|
|
||||||
"One or more expenses have 0% GST. Are you sure you want to proceed? \n\nNote: If these items are taxable, please provide a valid GST rate to ensure correct E-Invoice generation."
|
|
||||||
);
|
|
||||||
if (!confirmZeroGst) {
|
|
||||||
setSubmitting(false);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
setSubmitting(true);
|
setSubmitting(true);
|
||||||
await onSubmit({
|
await onSubmit({
|
||||||
@ -560,9 +357,7 @@ export function DealerCompletionDocumentsModal({
|
|||||||
onClose();
|
onClose();
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to submit completion documents:', error);
|
console.error('Failed to submit completion documents:', error);
|
||||||
if (!handleSecurityError(error)) {
|
|
||||||
toast.error('Failed to submit completion documents. Please try again.');
|
toast.error('Failed to submit completion documents. Please try again.');
|
||||||
}
|
|
||||||
} finally {
|
} finally {
|
||||||
setSubmitting(false);
|
setSubmitting(false);
|
||||||
}
|
}
|
||||||
@ -576,27 +371,7 @@ export function DealerCompletionDocumentsModal({
|
|||||||
setPreviewFile(null);
|
setPreviewFile(null);
|
||||||
setActivityCompletionDate('');
|
setActivityCompletionDate('');
|
||||||
setNumberOfParticipants('');
|
setNumberOfParticipants('');
|
||||||
setExpenseItems([{
|
setExpenseItems([]);
|
||||||
id: '1',
|
|
||||||
description: '',
|
|
||||||
amount: 0,
|
|
||||||
gstRate: defaultGstRate || 0,
|
|
||||||
gstAmt: 0,
|
|
||||||
quantity: 1,
|
|
||||||
hsnCode: '',
|
|
||||||
isService: false,
|
|
||||||
cgstRate: 0,
|
|
||||||
cgstAmt: 0,
|
|
||||||
sgstRate: 0,
|
|
||||||
sgstAmt: 0,
|
|
||||||
igstRate: 0,
|
|
||||||
igstAmt: 0,
|
|
||||||
utgstRate: 0,
|
|
||||||
utgstAmt: 0,
|
|
||||||
cessRate: 0,
|
|
||||||
cessAmt: 0,
|
|
||||||
totalAmt: 0
|
|
||||||
}]);
|
|
||||||
setCompletionDocuments([]);
|
setCompletionDocuments([]);
|
||||||
setActivityPhotos([]);
|
setActivityPhotos([]);
|
||||||
setInvoicesReceipts([]);
|
setInvoicesReceipts([]);
|
||||||
@ -616,20 +391,12 @@ export function DealerCompletionDocumentsModal({
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
|
||||||
<Dialog open={isOpen} onOpenChange={handleClose}>
|
<Dialog open={isOpen} onOpenChange={handleClose}>
|
||||||
<DialogContent className="dealer-completion-documents-modal overflow-hidden flex flex-col">
|
<DialogContent className="dealer-completion-documents-modal overflow-hidden flex flex-col">
|
||||||
<DialogHeader className="px-6 pt-6 pb-3 flex-shrink-0">
|
<DialogHeader className="px-6 pt-6 pb-3 flex-shrink-0">
|
||||||
<DialogTitle className="font-semibold flex items-center gap-2 text-xl sm:text-2xl flex-wrap">
|
<DialogTitle className="font-semibold flex items-center gap-2 text-xl sm:text-2xl">
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<Upload className="w-5 h-5 sm:w-6 sm:h-6 text-[--re-green]" />
|
<Upload className="w-5 h-5 sm:w-6 sm:h-6 text-[--re-green]" />
|
||||||
Activity Completion Documents
|
Activity Completion Documents
|
||||||
</div>
|
|
||||||
{taxationType && (
|
|
||||||
<Badge className={`ml-2 border-none shadow-sm ${taxationType === 'GST' ? 'bg-emerald-600 text-white hover:bg-emerald-700' : 'bg-indigo-600 text-white hover:bg-indigo-700'}`}>
|
|
||||||
{taxationType === 'GST' ? 'GST Claim' : 'Non-GST Claim'}
|
|
||||||
</Badge>
|
|
||||||
)}
|
|
||||||
</DialogTitle>
|
</DialogTitle>
|
||||||
<DialogDescription className="text-sm sm:text-base">
|
<DialogDescription className="text-sm sm:text-base">
|
||||||
Step 5: Upload completion proof and final documents
|
Step 5: Upload completion proof and final documents
|
||||||
@ -648,7 +415,7 @@ export function DealerCompletionDocumentsModal({
|
|||||||
</DialogHeader>
|
</DialogHeader>
|
||||||
|
|
||||||
<div className="flex-1 overflow-y-auto overflow-x-hidden px-6 py-3">
|
<div className="flex-1 overflow-y-auto overflow-x-hidden px-6 py-3">
|
||||||
<div className="space-y-5 sm:space-y-6">
|
<div className="space-y-5 sm:space-y-6 max-w-4xl mx-auto">
|
||||||
{/* Activity Completion Date */}
|
{/* Activity Completion Date */}
|
||||||
<div className="space-y-1.5 sm:space-y-2">
|
<div className="space-y-1.5 sm:space-y-2">
|
||||||
<Label className="text-sm sm:text-base font-semibold flex items-center gap-2" htmlFor="completionDate">
|
<Label className="text-sm sm:text-base font-semibold flex items-center gap-2" htmlFor="completionDate">
|
||||||
@ -670,12 +437,8 @@ export function DealerCompletionDocumentsModal({
|
|||||||
<div className="flex items-center justify-between">
|
<div className="flex items-center justify-between">
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<h3 className="font-semibold text-base sm:text-lg">Closed Expenses</h3>
|
<h3 className="font-semibold text-base sm:text-lg">Closed Expenses</h3>
|
||||||
|
<Badge className="bg-secondary text-secondary-foreground text-xs">Optional</Badge>
|
||||||
</div>
|
</div>
|
||||||
{!isNonGst && (
|
|
||||||
<div className="text-[10px] text-gray-500 italic mt-0.5">
|
|
||||||
Tax fields are automatically toggled based on the dealer's state (Inter-state vs Intra-state).
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
<Button
|
<Button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={handleAddExpense}
|
onClick={handleAddExpense}
|
||||||
@ -686,192 +449,43 @@ export function DealerCompletionDocumentsModal({
|
|||||||
Add Expense
|
Add Expense
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
<div className="space-y-3 sm:space-y-4 max-h-[400px] overflow-y-auto pr-1">
|
<div className="space-y-2 sm:space-y-3">
|
||||||
{expenseItems.map((item) => (
|
{expenseItems.map((item) => (
|
||||||
<div key={item.id} className="p-4 border rounded-lg bg-gray-50/50 space-y-4 relative group">
|
<div key={item.id} className="flex gap-2 items-start">
|
||||||
<div className="flex gap-3 items-start w-full">
|
<div className="flex-1">
|
||||||
<div className={`${isNonGst ? 'flex-[3]' : 'flex-1'} min-w-0`}>
|
|
||||||
<Label className="text-[10px] uppercase text-gray-500 font-bold mb-1 block">Item description</Label>
|
|
||||||
<Input
|
<Input
|
||||||
placeholder="e.g., Venue rental, Refreshments"
|
placeholder="Item name (e.g., Venue rental, Refreshments, Printing)"
|
||||||
value={item.description}
|
value={item.description}
|
||||||
onChange={(e) =>
|
onChange={(e) =>
|
||||||
handleExpenseChange(item.id, 'description', e.target.value)
|
handleExpenseChange(item.id, 'description', e.target.value)
|
||||||
}
|
}
|
||||||
className="w-full bg-white text-sm"
|
className="text-sm"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
{isNonGst && (
|
<div className="w-32 sm:w-40">
|
||||||
<div className="w-28 sm:w-36 flex-shrink-0">
|
|
||||||
<Label className="text-[10px] uppercase text-gray-500 font-bold mb-1 block">Amount</Label>
|
|
||||||
<div className="relative">
|
|
||||||
<IndianRupee className="absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-gray-400" />
|
|
||||||
<Input
|
<Input
|
||||||
type="number"
|
type="number"
|
||||||
placeholder="0.00"
|
placeholder="Amount"
|
||||||
min="0"
|
min="0"
|
||||||
step="0.01"
|
step="0.01"
|
||||||
value={item.amount || ''}
|
value={item.amount || ''}
|
||||||
onChange={(e) =>
|
onChange={(e) =>
|
||||||
handleExpenseChange(item.id, 'amount', e.target.value)
|
handleExpenseChange(item.id, 'amount', parseFloat(e.target.value) || 0)
|
||||||
}
|
}
|
||||||
className="w-full bg-white text-sm pl-8"
|
className="text-sm"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{!isNonGst && (
|
|
||||||
<div className="w-28 sm:w-36 flex-shrink-0">
|
|
||||||
<Label className="text-[10px] uppercase text-gray-500 font-bold mb-1 block">Amount (Base)</Label>
|
|
||||||
<div className="relative">
|
|
||||||
<IndianRupee className="absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-gray-400" />
|
|
||||||
<Input
|
|
||||||
type="number"
|
|
||||||
placeholder="0.00"
|
|
||||||
min="0"
|
|
||||||
step="0.01"
|
|
||||||
value={item.amount || ''}
|
|
||||||
onChange={(e) =>
|
|
||||||
handleExpenseChange(item.id, 'amount', e.target.value)
|
|
||||||
}
|
|
||||||
className="w-full bg-white text-sm pl-8"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{!isNonGst && (
|
|
||||||
<>
|
|
||||||
<div className="w-20 sm:w-24 flex-shrink-0">
|
|
||||||
<Label className="text-[10px] uppercase text-gray-500 font-bold mb-1 block">HSN/SAC Code</Label>
|
|
||||||
<Input
|
|
||||||
placeholder="HSN/SAC Code"
|
|
||||||
value={item.hsnCode || ''}
|
|
||||||
onChange={(e) =>
|
|
||||||
handleExpenseChange(item.id, 'hsnCode', e.target.value)
|
|
||||||
}
|
|
||||||
className={`w-full bg-white text-sm ${!validateHSNSAC(item.hsnCode, item.isService).isValid ? 'border-red-500 focus-visible:ring-red-500' : ''}`}
|
|
||||||
/>
|
|
||||||
{!validateHSNSAC(item.hsnCode, item.isService).isValid && (
|
|
||||||
<span className="text-[9px] text-red-500 mt-1 block leading-tight">
|
|
||||||
{validateHSNSAC(item.hsnCode, item.isService).message}
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
<div className="w-24 sm:w-28 flex-shrink-0">
|
|
||||||
<Label className="text-[10px] uppercase text-gray-500 font-bold mb-1 block">Item Type</Label>
|
|
||||||
<select
|
|
||||||
value={item.isService ? 'SAC' : 'HSN'}
|
|
||||||
onChange={(e) =>
|
|
||||||
handleExpenseChange(item.id, 'isService', e.target.value === 'SAC')
|
|
||||||
}
|
|
||||||
className="flex h-9 w-full rounded-md border border-input bg-white px-3 py-1 text-sm shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50"
|
|
||||||
>
|
|
||||||
<option value="HSN">HSN (Goods)</option>
|
|
||||||
<option value="SAC">SAC (Service)</option>
|
|
||||||
</select>
|
|
||||||
</div>
|
|
||||||
<div className="w-14 sm:w-16 flex-shrink-0">
|
|
||||||
<Label className="text-[10px] uppercase text-gray-500 font-bold mb-1 block">CGST %</Label>
|
|
||||||
<Input
|
|
||||||
type="number"
|
|
||||||
placeholder="%"
|
|
||||||
min="0"
|
|
||||||
max="100"
|
|
||||||
step="0.1"
|
|
||||||
value={item.cgstRate || ''}
|
|
||||||
onChange={(e) =>
|
|
||||||
handleExpenseChange(item.id, 'cgstRate', e.target.value)
|
|
||||||
}
|
|
||||||
disabled={!taxConfig.isCGST}
|
|
||||||
className="w-full bg-white text-xs px-1 text-center disabled:bg-gray-100 disabled:text-gray-400"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="w-14 sm:w-16 flex-shrink-0">
|
|
||||||
<Label className="text-[10px] uppercase text-gray-500 font-bold mb-1 block">SGST %</Label>
|
|
||||||
<Input
|
|
||||||
type="number"
|
|
||||||
placeholder="%"
|
|
||||||
min="0"
|
|
||||||
max="100"
|
|
||||||
step="0.1"
|
|
||||||
value={item.sgstRate || ''}
|
|
||||||
onChange={(e) =>
|
|
||||||
handleExpenseChange(item.id, 'sgstRate', e.target.value)
|
|
||||||
}
|
|
||||||
disabled={!taxConfig.isSGST}
|
|
||||||
className="w-full bg-white text-xs px-1 text-center disabled:bg-gray-100 disabled:text-gray-400"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="w-14 sm:w-16 flex-shrink-0">
|
|
||||||
<Label className="text-[10px] uppercase text-gray-500 font-bold mb-1 block">UTGST %</Label>
|
|
||||||
<Input
|
|
||||||
type="number"
|
|
||||||
placeholder="%"
|
|
||||||
min="0"
|
|
||||||
max="100"
|
|
||||||
step="0.1"
|
|
||||||
value={item.utgstRate || ''}
|
|
||||||
onChange={(e) =>
|
|
||||||
handleExpenseChange(item.id, 'utgstRate', e.target.value)
|
|
||||||
}
|
|
||||||
disabled={!taxConfig.isUTGST}
|
|
||||||
className="w-full bg-white text-xs px-1 text-center disabled:bg-gray-100 disabled:text-gray-400"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="w-14 sm:w-16 flex-shrink-0">
|
|
||||||
<Label className="text-[10px] uppercase text-gray-500 font-bold mb-1 block">IGST %</Label>
|
|
||||||
<Input
|
|
||||||
type="number"
|
|
||||||
placeholder="%"
|
|
||||||
min="0"
|
|
||||||
max="100"
|
|
||||||
step="0.1"
|
|
||||||
value={item.igstRate || ''}
|
|
||||||
onChange={(e) =>
|
|
||||||
handleExpenseChange(item.id, 'igstRate', e.target.value)
|
|
||||||
}
|
|
||||||
disabled={!taxConfig.isIGST}
|
|
||||||
className="w-full bg-white text-xs px-1 text-center disabled:bg-gray-100 disabled:text-gray-400"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
<Button
|
<Button
|
||||||
type="button"
|
type="button"
|
||||||
variant="ghost"
|
variant="ghost"
|
||||||
size="sm"
|
size="sm"
|
||||||
className="mt-5 hover:bg-red-100 hover:text-red-700 flex-shrink-0 h-9 w-9 p-0"
|
className="mt-0.5 hover:bg-red-100 hover:text-red-700 h-9 w-9 p-0"
|
||||||
onClick={() => handleRemoveExpense(item.id)}
|
onClick={() => handleRemoveExpense(item.id)}
|
||||||
>
|
>
|
||||||
<X className="w-4 h-4" />
|
<X className="w-4 h-4" />
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className={`grid grid-cols-2 sm:grid-cols-5 gap-3 pt-3 border-t border-dashed border-gray-200 ${isNonGst ? 'items-center' : ''}`}>
|
|
||||||
{!isNonGst ? (
|
|
||||||
<>
|
|
||||||
<div className="flex flex-wrap gap-4 text-gray-500 font-medium">
|
|
||||||
<span>CGST: <span className="text-gray-900 font-semibold">₹{(item.cgstAmt || 0).toLocaleString('en-IN', { minimumFractionDigits: 1 })}</span></span>
|
|
||||||
{item.sgstAmt > 0 && <span>SGST: <span className="text-gray-900 font-semibold">₹{(item.sgstAmt || 0).toLocaleString('en-IN', { minimumFractionDigits: 1 })}</span></span>}
|
|
||||||
{item.utgstAmt > 0 && <span>UTGST: <span className="text-gray-900 font-semibold">₹{(item.utgstAmt || 0).toLocaleString('en-IN', { minimumFractionDigits: 1 })}</span></span>}
|
|
||||||
<span>IGST: <span className="text-gray-900 font-semibold">₹{(item.igstAmt || 0).toLocaleString('en-IN', { minimumFractionDigits: 1 })}</span></span>
|
|
||||||
</div>
|
|
||||||
<div className="flex flex-wrap gap-4 items-center sm:justify-end">
|
|
||||||
<span className="text-gray-500">GST Total: <span className="text-gray-900 font-bold">₹{(item.gstAmt || 0).toLocaleString('en-IN', { minimumFractionDigits: 1 })}</span></span>
|
|
||||||
<Badge className="bg-[#2d4a3e] text-white px-3 py-1 text-xs">Item Total: ₹{(item.totalAmt || 0).toLocaleString('en-IN', { minimumFractionDigits: 1 })}</Badge>
|
|
||||||
</div>
|
|
||||||
</>
|
|
||||||
) : (
|
|
||||||
<div className="col-span-4 invisible"></div>
|
|
||||||
)}
|
|
||||||
<div className="flex flex-col items-end">
|
|
||||||
<span className="text-[10px] text-gray-500 uppercase">Item Total</span>
|
|
||||||
<span className="text-sm font-bold text-[#2d4a3e]">₹{(item.amount || 0).toLocaleString('en-IN', { minimumFractionDigits: 2 })}</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
))}
|
))}
|
||||||
</div>
|
|
||||||
{expenseItems.length === 0 && (
|
{expenseItems.length === 0 && (
|
||||||
<p className="text-xs sm:text-sm text-gray-500 italic">
|
<p className="text-xs sm:text-sm text-gray-500 italic">
|
||||||
No expenses added. Click "Add Expense" to add expense items.
|
No expenses added. Click "Add Expense" to add expense items.
|
||||||
@ -909,7 +523,8 @@ export function DealerCompletionDocumentsModal({
|
|||||||
Upload documents proving activity completion (reports, certificates, etc.) - Can upload multiple files or ZIP folder
|
Upload documents proving activity completion (reports, certificates, etc.) - Can upload multiple files or ZIP folder
|
||||||
</p>
|
</p>
|
||||||
<div
|
<div
|
||||||
className={`border-2 border-dashed rounded-lg p-3 sm:p-4 transition-all duration-200 ${completionDocuments.length > 0
|
className={`border-2 border-dashed rounded-lg p-3 sm:p-4 transition-all duration-200 ${
|
||||||
|
completionDocuments.length > 0
|
||||||
? 'border-green-500 bg-green-50 hover:border-green-600'
|
? 'border-green-500 bg-green-50 hover:border-green-600'
|
||||||
: 'border-gray-300 hover:border-blue-500 bg-white'
|
: 'border-gray-300 hover:border-blue-500 bg-white'
|
||||||
}`}
|
}`}
|
||||||
@ -1014,7 +629,8 @@ export function DealerCompletionDocumentsModal({
|
|||||||
Upload photos from the completed activity (event photos, installations, etc.)
|
Upload photos from the completed activity (event photos, installations, etc.)
|
||||||
</p>
|
</p>
|
||||||
<div
|
<div
|
||||||
className={`border-2 border-dashed rounded-lg p-3 sm:p-4 transition-all duration-200 ${activityPhotos.length > 0
|
className={`border-2 border-dashed rounded-lg p-3 sm:p-4 transition-all duration-200 ${
|
||||||
|
activityPhotos.length > 0
|
||||||
? 'border-green-500 bg-green-50 hover:border-green-600'
|
? 'border-green-500 bg-green-50 hover:border-green-600'
|
||||||
: 'border-gray-300 hover:border-blue-500 bg-white'
|
: 'border-gray-300 hover:border-blue-500 bg-white'
|
||||||
}`}
|
}`}
|
||||||
@ -1129,7 +745,8 @@ export function DealerCompletionDocumentsModal({
|
|||||||
Upload invoices and receipts for expenses incurred
|
Upload invoices and receipts for expenses incurred
|
||||||
</p>
|
</p>
|
||||||
<div
|
<div
|
||||||
className={`border-2 border-dashed rounded-lg p-3 sm:p-4 transition-all duration-200 ${invoicesReceipts.length > 0
|
className={`border-2 border-dashed rounded-lg p-3 sm:p-4 transition-all duration-200 ${
|
||||||
|
invoicesReceipts.length > 0
|
||||||
? 'border-blue-500 bg-blue-50 hover:border-blue-600'
|
? 'border-blue-500 bg-blue-50 hover:border-blue-600'
|
||||||
: 'border-gray-300 hover:border-blue-500 bg-white'
|
: 'border-gray-300 hover:border-blue-500 bg-white'
|
||||||
}`}
|
}`}
|
||||||
@ -1232,7 +849,8 @@ export function DealerCompletionDocumentsModal({
|
|||||||
Upload attendance records or participant lists (if applicable)
|
Upload attendance records or participant lists (if applicable)
|
||||||
</p>
|
</p>
|
||||||
<div
|
<div
|
||||||
className={`border-2 border-dashed rounded-lg p-3 sm:p-4 transition-all duration-200 ${attendanceSheet
|
className={`border-2 border-dashed rounded-lg p-3 sm:p-4 transition-all duration-200 ${
|
||||||
|
attendanceSheet
|
||||||
? 'border-blue-500 bg-blue-50 hover:border-blue-600'
|
? 'border-blue-500 bg-blue-50 hover:border-blue-600'
|
||||||
: 'border-gray-300 hover:border-blue-500 bg-white'
|
: 'border-gray-300 hover:border-blue-500 bg-white'
|
||||||
}`}
|
}`}
|
||||||
@ -1353,6 +971,7 @@ export function DealerCompletionDocumentsModal({
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<DialogFooter className="flex flex-col-reverse sm:flex-row sm:justify-end gap-2 px-6 pt-3 pb-6 border-t flex-shrink-0">
|
<DialogFooter className="flex flex-col-reverse sm:flex-row sm:justify-end gap-2 px-6 pt-3 pb-6 border-t flex-shrink-0">
|
||||||
<Button
|
<Button
|
||||||
@ -1372,11 +991,9 @@ export function DealerCompletionDocumentsModal({
|
|||||||
</Button>
|
</Button>
|
||||||
</DialogFooter>
|
</DialogFooter>
|
||||||
</DialogContent>
|
</DialogContent>
|
||||||
</Dialog >
|
|
||||||
|
|
||||||
{/* File Preview Modal - Matching DocumentsTab style */}
|
{/* File Preview Modal - Matching DocumentsTab style */}
|
||||||
{
|
{previewFile && (
|
||||||
previewFile && (
|
|
||||||
<Dialog
|
<Dialog
|
||||||
open={!!previewFile}
|
open={!!previewFile}
|
||||||
onOpenChange={() => {
|
onOpenChange={() => {
|
||||||
@ -1463,8 +1080,7 @@ export function DealerCompletionDocumentsModal({
|
|||||||
</div>
|
</div>
|
||||||
</DialogContent>
|
</DialogContent>
|
||||||
</Dialog>
|
</Dialog>
|
||||||
)
|
)}
|
||||||
}
|
</Dialog>
|
||||||
</>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@ -25,7 +25,7 @@
|
|||||||
@media (min-width: 1024px) {
|
@media (min-width: 1024px) {
|
||||||
.dealer-proposal-modal {
|
.dealer-proposal-modal {
|
||||||
width: 90vw !important;
|
width: 90vw !important;
|
||||||
max-width: 1200px !important;
|
max-width: 1000px !important;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -33,7 +33,7 @@
|
|||||||
@media (min-width: 1536px) {
|
@media (min-width: 1536px) {
|
||||||
.dealer-proposal-modal {
|
.dealer-proposal-modal {
|
||||||
width: 90vw !important;
|
width: 90vw !important;
|
||||||
max-width: 1200px !important;
|
max-width: 1000px !important;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -65,3 +65,4 @@
|
|||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
opacity: 1;
|
opacity: 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@ -37,7 +37,6 @@ interface DeptLeadIOApprovalModalProps {
|
|||||||
preFilledIONumber?: string;
|
preFilledIONumber?: string;
|
||||||
preFilledBlockedAmount?: number;
|
preFilledBlockedAmount?: number;
|
||||||
preFilledRemainingBalance?: number;
|
preFilledRemainingBalance?: number;
|
||||||
taxationType?: string | null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function DeptLeadIOApprovalModal({
|
export function DeptLeadIOApprovalModal({
|
||||||
@ -50,16 +49,11 @@ export function DeptLeadIOApprovalModal({
|
|||||||
preFilledIONumber,
|
preFilledIONumber,
|
||||||
preFilledBlockedAmount,
|
preFilledBlockedAmount,
|
||||||
preFilledRemainingBalance,
|
preFilledRemainingBalance,
|
||||||
taxationType,
|
|
||||||
}: DeptLeadIOApprovalModalProps) {
|
}: DeptLeadIOApprovalModalProps) {
|
||||||
const [actionType, setActionType] = useState<'approve' | 'reject'>('approve');
|
const [actionType, setActionType] = useState<'approve' | 'reject'>('approve');
|
||||||
const [comments, setComments] = useState('');
|
const [comments, setComments] = useState('');
|
||||||
const [submitting, setSubmitting] = useState(false);
|
const [submitting, setSubmitting] = useState(false);
|
||||||
|
|
||||||
const isNonGst = useMemo(() => {
|
|
||||||
return taxationType === 'Non GST' || taxationType === 'Non-GST';
|
|
||||||
}, [taxationType]);
|
|
||||||
|
|
||||||
// Get IO number from props (read-only, from IO table)
|
// Get IO number from props (read-only, from IO table)
|
||||||
const ioNumber = preFilledIONumber || '';
|
const ioNumber = preFilledIONumber || '';
|
||||||
|
|
||||||
@ -144,13 +138,8 @@ export function DeptLeadIOApprovalModal({
|
|||||||
<CircleCheckBig className="w-5 h-5 lg:w-6 lg:h-6 text-green-600" />
|
<CircleCheckBig className="w-5 h-5 lg:w-6 lg:h-6 text-green-600" />
|
||||||
</div>
|
</div>
|
||||||
<div className="flex-1">
|
<div className="flex-1">
|
||||||
<DialogTitle className="font-semibold text-lg lg:text-xl flex items-center gap-2 flex-wrap">
|
<DialogTitle className="font-semibold text-lg lg:text-xl">
|
||||||
Review and Approve
|
Review and Approve
|
||||||
{taxationType && (
|
|
||||||
<Badge className={`ml-2 border-none shadow-sm ${!isNonGst ? 'bg-emerald-600 text-white hover:bg-emerald-700' : 'bg-indigo-600 text-white hover:bg-indigo-700'}`}>
|
|
||||||
{!isNonGst ? 'GST Claim' : 'Non-GST Claim'}
|
|
||||||
</Badge>
|
|
||||||
)}
|
|
||||||
</DialogTitle>
|
</DialogTitle>
|
||||||
<DialogDescription className="text-xs lg:text-sm mt-1">
|
<DialogDescription className="text-xs lg:text-sm mt-1">
|
||||||
Review IO details and provide your approval comments
|
Review IO details and provide your approval comments
|
||||||
@ -185,7 +174,8 @@ export function DeptLeadIOApprovalModal({
|
|||||||
<Button
|
<Button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={() => setActionType('approve')}
|
onClick={() => setActionType('approve')}
|
||||||
className={`flex-1 text-sm lg:text-base ${actionType === 'approve'
|
className={`flex-1 text-sm lg:text-base ${
|
||||||
|
actionType === 'approve'
|
||||||
? 'bg-green-600 text-white shadow-sm'
|
? 'bg-green-600 text-white shadow-sm'
|
||||||
: 'text-gray-700 hover:bg-gray-200'
|
: 'text-gray-700 hover:bg-gray-200'
|
||||||
}`}
|
}`}
|
||||||
@ -197,7 +187,8 @@ export function DeptLeadIOApprovalModal({
|
|||||||
<Button
|
<Button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={() => setActionType('reject')}
|
onClick={() => setActionType('reject')}
|
||||||
className={`flex-1 text-sm lg:text-base ${actionType === 'reject'
|
className={`flex-1 text-sm lg:text-base ${
|
||||||
|
actionType === 'reject'
|
||||||
? 'bg-red-600 text-white shadow-sm'
|
? 'bg-red-600 text-white shadow-sm'
|
||||||
: 'text-gray-700 hover:bg-gray-200'
|
: 'text-gray-700 hover:bg-gray-200'
|
||||||
}`}
|
}`}
|
||||||
@ -318,7 +309,8 @@ export function DeptLeadIOApprovalModal({
|
|||||||
<Button
|
<Button
|
||||||
onClick={handleSubmit}
|
onClick={handleSubmit}
|
||||||
disabled={!isFormValid || submitting}
|
disabled={!isFormValid || submitting}
|
||||||
className={`text-sm lg:text-base ${actionType === 'approve'
|
className={`text-sm lg:text-base ${
|
||||||
|
actionType === 'approve'
|
||||||
? 'bg-green-600 hover:bg-green-700'
|
? 'bg-green-600 hover:bg-green-700'
|
||||||
: 'bg-red-600 hover:bg-red-700'
|
: 'bg-red-600 hover:bg-red-700'
|
||||||
} text-white`}
|
} text-white`}
|
||||||
|
|||||||
@ -32,7 +32,7 @@ export function EmailNotificationTemplateModal({
|
|||||||
stepNumber,
|
stepNumber,
|
||||||
stepName,
|
stepName,
|
||||||
requestNumber = 'RE-REQ-2024-CM-101',
|
requestNumber = 'RE-REQ-2024-CM-101',
|
||||||
recipientEmail = `system@${import.meta.env.VITE_EMAIL_DOMAIN}`,
|
recipientEmail = 'system@royalenfield.com',
|
||||||
subject,
|
subject,
|
||||||
emailBody,
|
emailBody,
|
||||||
}: EmailNotificationTemplateModalProps) {
|
}: EmailNotificationTemplateModalProps) {
|
||||||
|
|||||||
@ -39,7 +39,6 @@ interface CostItem {
|
|||||||
id: string;
|
id: string;
|
||||||
description: string;
|
description: string;
|
||||||
amount: number;
|
amount: number;
|
||||||
quantity?: number;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
interface ProposalData {
|
interface ProposalData {
|
||||||
@ -71,7 +70,6 @@ interface InitiatorProposalApprovalModalProps {
|
|||||||
requestId?: string;
|
requestId?: string;
|
||||||
request?: any; // Request object to check IO blocking status
|
request?: any; // Request object to check IO blocking status
|
||||||
previousProposalData?: any;
|
previousProposalData?: any;
|
||||||
taxationType?: string | null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function InitiatorProposalApprovalModal({
|
export function InitiatorProposalApprovalModal({
|
||||||
@ -86,18 +84,25 @@ export function InitiatorProposalApprovalModal({
|
|||||||
requestId: _requestId, // Prefix with _ to indicate intentionally unused
|
requestId: _requestId, // Prefix with _ to indicate intentionally unused
|
||||||
request,
|
request,
|
||||||
previousProposalData,
|
previousProposalData,
|
||||||
taxationType,
|
|
||||||
}: InitiatorProposalApprovalModalProps) {
|
}: InitiatorProposalApprovalModalProps) {
|
||||||
const isNonGst = useMemo(() => {
|
|
||||||
return taxationType === 'Non GST' || taxationType === 'Non-GST';
|
|
||||||
}, [taxationType]);
|
|
||||||
|
|
||||||
const [comments, setComments] = useState('');
|
const [comments, setComments] = useState('');
|
||||||
const [submitting, setSubmitting] = useState(false);
|
const [submitting, setSubmitting] = useState(false);
|
||||||
const [actionType, setActionType] = useState<'approve' | 'reject' | 'revision' | null>(null);
|
const [actionType, setActionType] = useState<'approve' | 'reject' | 'revision' | null>(null);
|
||||||
const [showPreviousProposal, setShowPreviousProposal] = useState(false);
|
const [showPreviousProposal, setShowPreviousProposal] = useState(false);
|
||||||
|
|
||||||
// Calculate total budget (needed for display)
|
// Check if IO is blocked (IO blocking moved to Requestor Evaluation level)
|
||||||
|
const internalOrder = request?.internalOrder || request?.internal_order;
|
||||||
|
const ioBlockedAmount = internalOrder?.ioBlockedAmount || internalOrder?.io_blocked_amount || 0;
|
||||||
|
const isIOBlocked = ioBlockedAmount > 0;
|
||||||
|
const [previewDoc, setPreviewDoc] = useState<{
|
||||||
|
name: string;
|
||||||
|
url: string;
|
||||||
|
type?: string;
|
||||||
|
size?: number;
|
||||||
|
id?: string;
|
||||||
|
} | null>(null);
|
||||||
|
|
||||||
|
// Calculate total budget
|
||||||
const totalBudget = useMemo(() => {
|
const totalBudget = useMemo(() => {
|
||||||
if (!proposalData?.costBreakup) return 0;
|
if (!proposalData?.costBreakup) return 0;
|
||||||
|
|
||||||
@ -112,65 +117,10 @@ export function InitiatorProposalApprovalModal({
|
|||||||
|
|
||||||
return costBreakup.reduce((sum: number, item: any) => {
|
return costBreakup.reduce((sum: number, item: any) => {
|
||||||
const amount = typeof item === 'object' ? (item.amount || 0) : 0;
|
const amount = typeof item === 'object' ? (item.amount || 0) : 0;
|
||||||
const quantity = typeof item === 'object' ? (item.quantity || 1) : 1;
|
return sum + (Number(amount) || 0);
|
||||||
const baseTotal = amount * quantity;
|
|
||||||
const gst = typeof item === 'object' ? (item.gstAmt || 0) : 0;
|
|
||||||
const total = item.totalAmt || (baseTotal + gst);
|
|
||||||
return sum + (Number(total) || 0);
|
|
||||||
}, 0);
|
}, 0);
|
||||||
}, [proposalData]);
|
}, [proposalData]);
|
||||||
|
|
||||||
// Calculate total base amount (needed for budget verification as requested)
|
|
||||||
// This is the taxable amount excluding GST
|
|
||||||
const totalBaseAmount = useMemo(() => {
|
|
||||||
if (!proposalData?.costBreakup) return 0;
|
|
||||||
|
|
||||||
const costBreakup = Array.isArray(proposalData.costBreakup)
|
|
||||||
? proposalData.costBreakup
|
|
||||||
: (typeof proposalData.costBreakup === 'string'
|
|
||||||
? JSON.parse(proposalData.costBreakup)
|
|
||||||
: []);
|
|
||||||
|
|
||||||
if (!Array.isArray(costBreakup)) return 0;
|
|
||||||
|
|
||||||
return costBreakup.reduce((sum: number, item: any) => {
|
|
||||||
const amount = typeof item === 'object' ? (item.amount || 0) : 0;
|
|
||||||
const quantity = typeof item === 'object' ? (item.quantity || 1) : 1;
|
|
||||||
return sum + (Number(amount) * Number(quantity));
|
|
||||||
}, 0);
|
|
||||||
}, [proposalData]);
|
|
||||||
|
|
||||||
// Check if IO is blocked (IO blocking moved to Requestor Evaluation level)
|
|
||||||
// Sum up all successful blocks from internalOrders array
|
|
||||||
const totalBlockedAmount = useMemo(() => {
|
|
||||||
const internalOrders = request?.internalOrders || request?.internal_orders || [];
|
|
||||||
|
|
||||||
// If we have an array, sum the blocked amounts
|
|
||||||
if (Array.isArray(internalOrders) && internalOrders.length > 0) {
|
|
||||||
return internalOrders.reduce((sum: number, io: any) => {
|
|
||||||
const amt = Number(io.ioBlockedAmount || io.io_blocked_amount || 0);
|
|
||||||
return sum + amt;
|
|
||||||
}, 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Fallback to single internalOrder object for backward compatibility
|
|
||||||
const singleIO = request?.internalOrder || request?.internal_order;
|
|
||||||
return Number(singleIO?.ioBlockedAmount || singleIO?.io_blocked_amount || 0);
|
|
||||||
}, [request?.internalOrders, request?.internal_orders, request?.internalOrder, request?.internal_order]);
|
|
||||||
|
|
||||||
// Budget is considered blocked only if the total blocked amount matches or exceeds the proposed base amount
|
|
||||||
// Allow a small margin for floating point comparison if needed, but here simple >= should suffice
|
|
||||||
const isIOBlocked = totalBlockedAmount >= (totalBaseAmount - 0.01);
|
|
||||||
const remainingBaseToBlock = Math.max(0, totalBaseAmount - totalBlockedAmount);
|
|
||||||
|
|
||||||
const [previewDoc, setPreviewDoc] = useState<{
|
|
||||||
name: string;
|
|
||||||
url: string;
|
|
||||||
type?: string;
|
|
||||||
size?: number;
|
|
||||||
id?: string;
|
|
||||||
} | null>(null);
|
|
||||||
|
|
||||||
// Format date
|
// Format date
|
||||||
const formatDate = (dateString: string) => {
|
const formatDate = (dateString: string) => {
|
||||||
if (!dateString) return '—';
|
if (!dateString) return '—';
|
||||||
@ -323,16 +273,9 @@ export function InitiatorProposalApprovalModal({
|
|||||||
<Dialog open={isOpen} onOpenChange={handleClose}>
|
<Dialog open={isOpen} onOpenChange={handleClose}>
|
||||||
<DialogContent className="dealer-proposal-modal overflow-hidden flex flex-col">
|
<DialogContent className="dealer-proposal-modal overflow-hidden flex flex-col">
|
||||||
<DialogHeader className="flex-shrink-0 pb-3 lg:pb-4 px-6 pt-4 lg:pt-6 border-b">
|
<DialogHeader className="flex-shrink-0 pb-3 lg:pb-4 px-6 pt-4 lg:pt-6 border-b">
|
||||||
<DialogTitle className="flex items-center gap-2 text-lg lg:text-xl flex-wrap">
|
<DialogTitle className="flex items-center gap-2 text-lg lg:text-xl">
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<CheckCircle className="w-4 h-4 lg:w-5 lg:h-5 text-green-600" />
|
<CheckCircle className="w-4 h-4 lg:w-5 lg:h-5 text-green-600" />
|
||||||
Requestor Evaluation & Confirmation
|
Requestor Evaluation & Confirmation
|
||||||
</div>
|
|
||||||
{taxationType && (
|
|
||||||
<Badge className={`ml-2 border-none shadow-sm ${!isNonGst ? 'bg-emerald-600 text-white hover:bg-emerald-700' : 'bg-indigo-600 text-white hover:bg-indigo-700'}`}>
|
|
||||||
{!isNonGst ? 'GST Claim' : 'Non-GST Claim'}
|
|
||||||
</Badge>
|
|
||||||
)}
|
|
||||||
</DialogTitle>
|
</DialogTitle>
|
||||||
<DialogDescription className="text-xs lg:text-sm">
|
<DialogDescription className="text-xs lg:text-sm">
|
||||||
Step 2: Review dealer proposal and make a decision
|
Step 2: Review dealer proposal and make a decision
|
||||||
@ -660,43 +603,17 @@ export function InitiatorProposalApprovalModal({
|
|||||||
<>
|
<>
|
||||||
<div className="border rounded-lg overflow-hidden max-h-[200px] lg:max-h-[180px] overflow-y-auto">
|
<div className="border rounded-lg overflow-hidden max-h-[200px] lg:max-h-[180px] overflow-y-auto">
|
||||||
<div className="bg-gray-50 px-3 lg:px-4 py-2 border-b sticky top-0">
|
<div className="bg-gray-50 px-3 lg:px-4 py-2 border-b sticky top-0">
|
||||||
<div className={`grid ${isNonGst ? 'grid-cols-3' : 'grid-cols-4'} gap-4 text-xs lg:text-sm font-semibold text-gray-700`}>
|
<div className="grid grid-cols-2 gap-4 text-xs lg:text-sm font-semibold text-gray-700">
|
||||||
<div className="col-span-1">Item Description</div>
|
<div>Item Description</div>
|
||||||
<div className="text-right">Base</div>
|
<div className="text-right">Amount</div>
|
||||||
{!isNonGst && <div className="text-right">GST</div>}
|
|
||||||
<div className="text-right">Total</div>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="divide-y">
|
<div className="divide-y">
|
||||||
{costBreakup.map((item: any, index: number) => (
|
{costBreakup.map((item: any, index: number) => (
|
||||||
<div key={item?.id || item?.description || index} className={`px-3 lg:px-4 py-2 lg:py-3 grid ${isNonGst ? 'grid-cols-3' : 'grid-cols-4'} gap-4`}>
|
<div key={item?.id || item?.description || index} className="px-3 lg:px-4 py-2 lg:py-3 grid grid-cols-2 gap-4">
|
||||||
<div className="col-span-1 text-xs lg:text-sm text-gray-700">
|
<div className="text-xs lg:text-sm text-gray-700">{item?.description || 'N/A'}</div>
|
||||||
<div className="flex items-center gap-1.5 mb-0.5">
|
|
||||||
<span className="font-medium">
|
|
||||||
{item?.description?.startsWith('[ADDITIONAL]')
|
|
||||||
? item.description.replace('[ADDITIONAL]', '').trim()
|
|
||||||
: (item?.description || 'N/A')}
|
|
||||||
</span>
|
|
||||||
{costBreakup.some((i: any) => i?.description?.startsWith('[ADDITIONAL]')) && (
|
|
||||||
item?.description?.startsWith('[ADDITIONAL]') ? (
|
|
||||||
<Badge className="text-[9px] h-3.5 px-1 bg-amber-100 text-amber-700 hover:bg-amber-100 border-none leading-none">ADDITIONAL</Badge>
|
|
||||||
) : (
|
|
||||||
<Badge className="text-[9px] h-3.5 px-1 bg-gray-100 text-gray-600 hover:bg-gray-100 border-none leading-none">ORIGINAL</Badge>
|
|
||||||
)
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
{!isNonGst && item?.gstRate ? <span className="block text-[10px] text-gray-400">{item.gstRate}% GST</span> : null}
|
|
||||||
</div>
|
|
||||||
<div className="text-xs lg:text-sm text-gray-900 text-right">
|
|
||||||
₹{(Number(item?.amount) || 0).toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
|
|
||||||
</div>
|
|
||||||
{!isNonGst && (
|
|
||||||
<div className="text-xs lg:text-sm text-gray-900 text-right">
|
|
||||||
₹{(Number(item?.gstAmt) || 0).toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
<div className="text-xs lg:text-sm font-semibold text-gray-900 text-right">
|
<div className="text-xs lg:text-sm font-semibold text-gray-900 text-right">
|
||||||
₹{(Number(item?.totalAmt || ((item?.amount || 0) * (item?.quantity || 1) + (item?.gstAmt || 0))) || 0).toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
|
₹{(Number(item?.amount) || 0).toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
@ -839,10 +756,8 @@ export function InitiatorProposalApprovalModal({
|
|||||||
</div>
|
</div>
|
||||||
{/* Warning for IO not blocked - shown below Approve button */}
|
{/* Warning for IO not blocked - shown below Approve button */}
|
||||||
{!isIOBlocked && (
|
{!isIOBlocked && (
|
||||||
<p className="text-xs text-red-600 text-center sm:text-left font-medium">
|
<p className="text-xs text-red-600 text-center sm:text-left">
|
||||||
{totalBlockedAmount > 0
|
Please block IO budget in the IO Tab before approving
|
||||||
? `Pending block: ₹${remainingBaseToBlock.toLocaleString('en-IN', { minimumFractionDigits: 2 })} more needs to be blocked in the IO Tab.`
|
|
||||||
: "Please block IO budget in the IO Tab before approving."}
|
|
||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@ -41,7 +41,7 @@ import { downloadDocument } from '@/services/workflowApi';
|
|||||||
import { getPublicConfigurations, AdminConfiguration } from '@/services/adminApi';
|
import { getPublicConfigurations, AdminConfiguration } from '@/services/adminApi';
|
||||||
import { PolicyViolationModal } from '@/components/modals/PolicyViolationModal';
|
import { PolicyViolationModal } from '@/components/modals/PolicyViolationModal';
|
||||||
import { getSocket, joinUserRoom } from '@/utils/socket';
|
import { getSocket, joinUserRoom } from '@/utils/socket';
|
||||||
|
import { isClaimManagementRequest } from '@/utils/claimRequestUtils';
|
||||||
|
|
||||||
// Dealer Claim Components (import from index to get properly aliased exports)
|
// Dealer Claim Components (import from index to get properly aliased exports)
|
||||||
import { DealerClaimOverviewTab, DealerClaimWorkflowTab, IOTab } from '../index';
|
import { DealerClaimOverviewTab, DealerClaimWorkflowTab, IOTab } from '../index';
|
||||||
@ -155,12 +155,8 @@ function DealerClaimRequestDetailInner({ requestId: propRequestId, onBack, dynam
|
|||||||
const currentUserId = (user as any)?.userId || '';
|
const currentUserId = (user as any)?.userId || '';
|
||||||
|
|
||||||
// IO tab visibility for dealer claims
|
// IO tab visibility for dealer claims
|
||||||
// Restricted: Hide from Dealers, show for internal roles (Initiator, Dept Lead, Finance, Admin)
|
// Show IO tab for initiator (Requestor Evaluation level) - initiator can now fetch and block IO
|
||||||
const isDealer = (user as any)?.jobTitle === 'Dealer' || (user as any)?.designation === 'Dealer';
|
const showIOTab = isInitiator;
|
||||||
const isClaimManagement = request?.workflowType === 'CLAIM_MANAGEMENT' ||
|
|
||||||
apiRequest?.workflowType === 'CLAIM_MANAGEMENT' ||
|
|
||||||
request?.templateType === 'claim-management';
|
|
||||||
const showIOTab = isClaimManagement && !isDealer;
|
|
||||||
|
|
||||||
const {
|
const {
|
||||||
mergedMessages,
|
mergedMessages,
|
||||||
@ -677,7 +673,7 @@ function DealerClaimRequestDetailInner({ requestId: propRequestId, onBack, dynam
|
|||||||
request={request}
|
request={request}
|
||||||
isInitiator={isInitiator}
|
isInitiator={isInitiator}
|
||||||
isSpectator={isSpectator}
|
isSpectator={isSpectator}
|
||||||
currentApprovalLevel={currentApprovalLevel}
|
currentApprovalLevel={isClaimManagementRequest(apiRequest) ? null : currentApprovalLevel}
|
||||||
onAddApprover={() => setShowAddApproverModal(true)}
|
onAddApprover={() => setShowAddApproverModal(true)}
|
||||||
onAddSpectator={() => setShowAddSpectatorModal(true)}
|
onAddSpectator={() => setShowAddSpectatorModal(true)}
|
||||||
onApprove={() => setShowApproveModal(true)}
|
onApprove={() => setShowApproveModal(true)}
|
||||||
|
|||||||
@ -2,7 +2,6 @@ import { useState, useEffect } from 'react';
|
|||||||
import { uploadDocument } from '@/services/documentApi';
|
import { uploadDocument } from '@/services/documentApi';
|
||||||
import { getPublicConfigurations, AdminConfiguration } from '@/services/adminApi';
|
import { getPublicConfigurations, AdminConfiguration } from '@/services/adminApi';
|
||||||
import { toast } from 'sonner';
|
import { toast } from 'sonner';
|
||||||
import { handleSecurityError } from '@/utils/securityToast';
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Custom Hook: useDocumentUpload
|
* Custom Hook: useDocumentUpload
|
||||||
@ -202,10 +201,8 @@ export function useDocumentUpload(
|
|||||||
} catch (error: any) {
|
} catch (error: any) {
|
||||||
console.error('[useDocumentUpload] Upload error:', error);
|
console.error('[useDocumentUpload] Upload error:', error);
|
||||||
|
|
||||||
// Show security-specific red toast for scan errors, or generic error toast
|
// Error feedback with backend error message if available
|
||||||
if (!handleSecurityError(error)) {
|
toast.error(error?.response?.data?.error || 'Failed to upload document');
|
||||||
toast.error(error?.response?.data?.message || 'Failed to upload document');
|
|
||||||
}
|
|
||||||
} finally {
|
} finally {
|
||||||
setUploadingDocument(false);
|
setUploadingDocument(false);
|
||||||
|
|
||||||
|
|||||||
@ -1,6 +1,8 @@
|
|||||||
import { useState, useEffect, useMemo, useCallback } from 'react';
|
import { useState, useEffect, useMemo, useCallback } from 'react';
|
||||||
import workflowApi, { getPauseDetails } from '@/services/workflowApi';
|
import workflowApi, { getPauseDetails } from '@/services/workflowApi';
|
||||||
import apiClient from '@/services/authApi';
|
import apiClient from '@/services/authApi';
|
||||||
|
import { CUSTOM_REQUEST_DATABASE } from '@/utils/customRequestDatabase';
|
||||||
|
import { CLAIM_MANAGEMENT_DATABASE } from '@/utils/claimManagementDatabase';
|
||||||
import { getSocket } from '@/utils/socket';
|
import { getSocket } from '@/utils/socket';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -238,7 +240,6 @@ export function useRequestDetails(
|
|||||||
let proposalDetails = null;
|
let proposalDetails = null;
|
||||||
let completionDetails = null;
|
let completionDetails = null;
|
||||||
let internalOrder = null;
|
let internalOrder = null;
|
||||||
let internalOrders = [];
|
|
||||||
|
|
||||||
if (wf.workflowType === 'CLAIM_MANAGEMENT' || wf.templateType === 'claim-management') {
|
if (wf.workflowType === 'CLAIM_MANAGEMENT' || wf.templateType === 'claim-management') {
|
||||||
try {
|
try {
|
||||||
@ -251,7 +252,6 @@ export function useRequestDetails(
|
|||||||
proposalDetails = claimData.proposalDetails || claimData.proposal_details;
|
proposalDetails = claimData.proposalDetails || claimData.proposal_details;
|
||||||
completionDetails = claimData.completionDetails || claimData.completion_details;
|
completionDetails = claimData.completionDetails || claimData.completion_details;
|
||||||
internalOrder = claimData.internalOrder || claimData.internal_order || null;
|
internalOrder = claimData.internalOrder || claimData.internal_order || null;
|
||||||
internalOrders = claimData.internalOrders || claimData.internal_orders || [];
|
|
||||||
// New normalized tables
|
// New normalized tables
|
||||||
const budgetTracking = claimData.budgetTracking || claimData.budget_tracking || null;
|
const budgetTracking = claimData.budgetTracking || claimData.budget_tracking || null;
|
||||||
const invoice = claimData.invoice || null;
|
const invoice = claimData.invoice || null;
|
||||||
@ -328,7 +328,6 @@ export function useRequestDetails(
|
|||||||
proposalDetails: proposalDetails || null,
|
proposalDetails: proposalDetails || null,
|
||||||
completionDetails: completionDetails || null,
|
completionDetails: completionDetails || null,
|
||||||
internalOrder: internalOrder || null,
|
internalOrder: internalOrder || null,
|
||||||
internalOrders: internalOrders || [],
|
|
||||||
// New normalized tables (also available via claimDetails for backward compatibility)
|
// New normalized tables (also available via claimDetails for backward compatibility)
|
||||||
budgetTracking: (claimDetails as any)?.budgetTracking || null,
|
budgetTracking: (claimDetails as any)?.budgetTracking || null,
|
||||||
invoice: (claimDetails as any)?.invoice || null,
|
invoice: (claimDetails as any)?.invoice || null,
|
||||||
@ -520,7 +519,6 @@ export function useRequestDetails(
|
|||||||
let proposalDetails = null;
|
let proposalDetails = null;
|
||||||
let completionDetails = null;
|
let completionDetails = null;
|
||||||
let internalOrder = null;
|
let internalOrder = null;
|
||||||
let internalOrders = [];
|
|
||||||
|
|
||||||
if (wf.workflowType === 'CLAIM_MANAGEMENT' || wf.templateType === 'claim-management') {
|
if (wf.workflowType === 'CLAIM_MANAGEMENT' || wf.templateType === 'claim-management') {
|
||||||
try {
|
try {
|
||||||
@ -532,7 +530,6 @@ export function useRequestDetails(
|
|||||||
proposalDetails = claimData.proposalDetails || claimData.proposal_details;
|
proposalDetails = claimData.proposalDetails || claimData.proposal_details;
|
||||||
completionDetails = claimData.completionDetails || claimData.completion_details;
|
completionDetails = claimData.completionDetails || claimData.completion_details;
|
||||||
internalOrder = claimData.internalOrder || claimData.internal_order || null;
|
internalOrder = claimData.internalOrder || claimData.internal_order || null;
|
||||||
internalOrders = claimData.internalOrders || claimData.internal_orders || [];
|
|
||||||
// New normalized tables
|
// New normalized tables
|
||||||
const budgetTracking = claimData.budgetTracking || claimData.budget_tracking || null;
|
const budgetTracking = claimData.budgetTracking || claimData.budget_tracking || null;
|
||||||
const invoice = claimData.invoice || null;
|
const invoice = claimData.invoice || null;
|
||||||
@ -596,7 +593,6 @@ export function useRequestDetails(
|
|||||||
proposalDetails: proposalDetails || null,
|
proposalDetails: proposalDetails || null,
|
||||||
completionDetails: completionDetails || null,
|
completionDetails: completionDetails || null,
|
||||||
internalOrder: internalOrder || null,
|
internalOrder: internalOrder || null,
|
||||||
internalOrders: internalOrders || [],
|
|
||||||
// New normalized tables (also available via claimDetails for backward compatibility)
|
// New normalized tables (also available via claimDetails for backward compatibility)
|
||||||
budgetTracking: (claimDetails as any)?.budgetTracking || null,
|
budgetTracking: (claimDetails as any)?.budgetTracking || null,
|
||||||
invoice: (claimDetails as any)?.invoice || null,
|
invoice: (claimDetails as any)?.invoice || null,
|
||||||
@ -655,13 +651,21 @@ export function useRequestDetails(
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Computed: Get final request object with fallback to static databases
|
* Computed: Get final request object with fallback to static databases
|
||||||
* Priority: API data → Custom Database → Claim Database → Dynamic props → null
|
* Priority: API data → Custom DB → Claim DB → Dynamic props → null
|
||||||
*/
|
*/
|
||||||
const request = useMemo(() => {
|
const request = useMemo(() => {
|
||||||
// Primary source: API data
|
// Primary source: API data
|
||||||
if (apiRequest) return apiRequest;
|
if (apiRequest) return apiRequest;
|
||||||
|
|
||||||
// Fallback: Dynamic requests passed as props
|
// Fallback 1: Static custom request database
|
||||||
|
const customRequest = CUSTOM_REQUEST_DATABASE[requestIdentifier];
|
||||||
|
if (customRequest) return customRequest;
|
||||||
|
|
||||||
|
// Fallback 2: Static claim management database
|
||||||
|
const claimRequest = CLAIM_MANAGEMENT_DATABASE[requestIdentifier];
|
||||||
|
if (claimRequest) return claimRequest;
|
||||||
|
|
||||||
|
// Fallback 3: Dynamic requests passed as props
|
||||||
const dynamicRequest = dynamicRequests.find((req: any) =>
|
const dynamicRequest = dynamicRequests.find((req: any) =>
|
||||||
req.id === requestIdentifier ||
|
req.id === requestIdentifier ||
|
||||||
req.requestNumber === requestIdentifier ||
|
req.requestNumber === requestIdentifier ||
|
||||||
|
|||||||
@ -41,21 +41,21 @@ export function Auth() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// const handleTanflowLogin = () => {
|
/* const handleTanflowLogin = () => {
|
||||||
// // Clear any existing session data
|
// Clear any existing session data
|
||||||
// localStorage.clear();
|
localStorage.clear();
|
||||||
// sessionStorage.clear();
|
sessionStorage.clear();
|
||||||
|
|
||||||
// setTanflowLoading(true);
|
setTanflowLoading(true);
|
||||||
// try {
|
try {
|
||||||
// initiateTanflowLogin();
|
initiateTanflowLogin();
|
||||||
// } catch (loginError) {
|
} catch (loginError) {
|
||||||
// console.error('========================================');
|
console.error('========================================');
|
||||||
// console.error('TANFLOW LOGIN ERROR');
|
console.error('TANFLOW LOGIN ERROR');
|
||||||
// console.error('Error details:', loginError);
|
console.error('Error details:', loginError);
|
||||||
// setTanflowLoading(false);
|
setTanflowLoading(false);
|
||||||
// }
|
}
|
||||||
// };
|
}; */
|
||||||
|
|
||||||
if (error) {
|
if (error) {
|
||||||
console.error('Auth Error in Auth Component:', {
|
console.error('Auth Error in Auth Component:', {
|
||||||
@ -123,8 +123,8 @@ export function Auth() {
|
|||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</Button>
|
</Button>
|
||||||
|
{/*
|
||||||
{/* <div className="relative">
|
<div className="relative">
|
||||||
<div className="absolute inset-0 flex items-center">
|
<div className="absolute inset-0 flex items-center">
|
||||||
<span className="w-full border-t border-gray-700"></span>
|
<span className="w-full border-t border-gray-700"></span>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@ -29,14 +29,14 @@ export function ClosedRequestsFilters({
|
|||||||
searchTerm,
|
searchTerm,
|
||||||
priorityFilter,
|
priorityFilter,
|
||||||
statusFilter,
|
statusFilter,
|
||||||
templateTypeFilter,
|
// templateTypeFilter,
|
||||||
sortBy,
|
sortBy,
|
||||||
sortOrder,
|
sortOrder,
|
||||||
activeFiltersCount,
|
activeFiltersCount,
|
||||||
onSearchChange,
|
onSearchChange,
|
||||||
onPriorityChange,
|
onPriorityChange,
|
||||||
onStatusChange,
|
onStatusChange,
|
||||||
onTemplateTypeChange,
|
// onTemplateTypeChange,
|
||||||
onSortByChange,
|
onSortByChange,
|
||||||
onSortOrderChange,
|
onSortOrderChange,
|
||||||
onClearFilters,
|
onClearFilters,
|
||||||
@ -129,7 +129,7 @@ export function ClosedRequestsFilters({
|
|||||||
</SelectContent>
|
</SelectContent>
|
||||||
</Select>
|
</Select>
|
||||||
|
|
||||||
<Select value={templateTypeFilter} onValueChange={onTemplateTypeChange}>
|
{/* <Select value={templateTypeFilter} onValueChange={onTemplateTypeChange}>
|
||||||
<SelectTrigger className="h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white" data-testid="closed-requests-template-type-filter">
|
<SelectTrigger className="h-9 sm:h-10 md:h-11 text-sm sm:text-base bg-gray-50 border-gray-200 focus:bg-white" data-testid="closed-requests-template-type-filter">
|
||||||
<SelectValue placeholder="All Templates" />
|
<SelectValue placeholder="All Templates" />
|
||||||
</SelectTrigger>
|
</SelectTrigger>
|
||||||
@ -138,7 +138,7 @@ export function ClosedRequestsFilters({
|
|||||||
<SelectItem value="CUSTOM">Non-Templatized</SelectItem>
|
<SelectItem value="CUSTOM">Non-Templatized</SelectItem>
|
||||||
<SelectItem value="DEALER CLAIM">Dealer Claim</SelectItem>
|
<SelectItem value="DEALER CLAIM">Dealer Claim</SelectItem>
|
||||||
</SelectContent>
|
</SelectContent>
|
||||||
</Select>
|
</Select> */}
|
||||||
|
|
||||||
<div className="flex gap-2">
|
<div className="flex gap-2">
|
||||||
<Select value={sortBy} onValueChange={(value) => onSortByChange(value as 'created' | 'due' | 'priority')}>
|
<Select value={sortBy} onValueChange={(value) => onSortByChange(value as 'created' | 'due' | 'priority')}>
|
||||||
|
|||||||
@ -22,11 +22,11 @@ export function MyRequestsFilters({
|
|||||||
searchTerm,
|
searchTerm,
|
||||||
statusFilter,
|
statusFilter,
|
||||||
priorityFilter,
|
priorityFilter,
|
||||||
templateTypeFilter: _templateTypeFilter,
|
// templateTypeFilter,
|
||||||
onSearchChange,
|
onSearchChange,
|
||||||
onStatusChange,
|
onStatusChange,
|
||||||
onPriorityChange,
|
onPriorityChange,
|
||||||
onTemplateTypeChange: _onTemplateTypeChange,
|
// onTemplateTypeChange,
|
||||||
}: MyRequestsFiltersProps) {
|
}: MyRequestsFiltersProps) {
|
||||||
return (
|
return (
|
||||||
<Card className="border-gray-200" data-testid="my-requests-filters">
|
<Card className="border-gray-200" data-testid="my-requests-filters">
|
||||||
@ -76,7 +76,7 @@ export function MyRequestsFilters({
|
|||||||
</SelectContent>
|
</SelectContent>
|
||||||
</Select>
|
</Select>
|
||||||
|
|
||||||
{/* <Select value={_templateTypeFilter} onValueChange={_onTemplateTypeChange}>
|
{/* <Select value={templateTypeFilter} onValueChange={onTemplateTypeChange}>
|
||||||
<SelectTrigger
|
<SelectTrigger
|
||||||
className="flex-1 md:w-28 lg:w-32 text-xs sm:text-sm bg-white border-gray-300 hover:border-gray-400 focus:border-blue-400 focus:ring-1 focus:ring-blue-200 h-9 sm:h-10"
|
className="flex-1 md:w-28 lg:w-32 text-xs sm:text-sm bg-white border-gray-300 hover:border-gray-400 focus:border-blue-400 focus:ring-1 focus:ring-blue-200 h-9 sm:h-10"
|
||||||
data-testid="template-type-filter"
|
data-testid="template-type-filter"
|
||||||
|
|||||||
@ -184,10 +184,7 @@ export function OverviewTab({
|
|||||||
{pauseInfo.pauseReason && (
|
{pauseInfo.pauseReason && (
|
||||||
<div>
|
<div>
|
||||||
<label className="text-xs font-medium text-gray-700 uppercase tracking-wide">Reason</label>
|
<label className="text-xs font-medium text-gray-700 uppercase tracking-wide">Reason</label>
|
||||||
<FormattedDescription
|
<p className="text-sm text-gray-900 mt-1">{pauseInfo.pauseReason}</p>
|
||||||
content={pauseInfo.pauseReason}
|
|
||||||
className="text-sm text-gray-900 mt-1"
|
|
||||||
/>
|
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
@ -334,15 +331,18 @@ export function OverviewTab({
|
|||||||
{/* Conclusion Remark Section */}
|
{/* Conclusion Remark Section */}
|
||||||
{needsClosure && (
|
{needsClosure && (
|
||||||
<Card data-testid="conclusion-remark-card">
|
<Card data-testid="conclusion-remark-card">
|
||||||
<CardHeader className={`bg-gradient-to-r border-b ${request.status === 'rejected'
|
<CardHeader className={`bg-gradient-to-r border-b ${
|
||||||
|
request.status === 'rejected'
|
||||||
? 'from-red-50 to-rose-50 border-red-200'
|
? 'from-red-50 to-rose-50 border-red-200'
|
||||||
: 'from-green-50 to-emerald-50 border-green-200'
|
: 'from-green-50 to-emerald-50 border-green-200'
|
||||||
}`}>
|
}`}>
|
||||||
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
|
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
|
||||||
<div>
|
<div>
|
||||||
<CardTitle className={`flex items-center gap-2 text-base sm:text-lg ${request.status === 'rejected' ? 'text-red-700' : 'text-green-700'
|
<CardTitle className={`flex items-center gap-2 text-base sm:text-lg ${
|
||||||
|
request.status === 'rejected' ? 'text-red-700' : 'text-green-700'
|
||||||
}`}>
|
}`}>
|
||||||
<CheckCircle className={`w-5 h-5 ${request.status === 'rejected' ? 'text-red-600' : 'text-green-600'
|
<CheckCircle className={`w-5 h-5 ${
|
||||||
|
request.status === 'rejected' ? 'text-red-600' : 'text-green-600'
|
||||||
}`} />
|
}`} />
|
||||||
Conclusion Remark - Final Step
|
Conclusion Remark - Final Step
|
||||||
</CardTitle>
|
</CardTitle>
|
||||||
|
|||||||
@ -163,14 +163,7 @@ export function SummaryTab({ summary, loading, onShare, isInitiator }: SummaryTa
|
|||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<p className="text-xs text-gray-500 mb-1">Remarks</p>
|
<p className="text-xs text-gray-500 mb-1">Remarks</p>
|
||||||
{approver.remarks ? (
|
<p className="text-sm text-gray-700">{approver.remarks || '—'}</p>
|
||||||
<FormattedDescription
|
|
||||||
content={approver.remarks}
|
|
||||||
className="text-sm text-gray-700"
|
|
||||||
/>
|
|
||||||
) : (
|
|
||||||
<p className="text-sm text-gray-700">—</p>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
|
|||||||
@ -11,6 +11,7 @@ import { useAppSelector } from '@/redux/hooks';
|
|||||||
import { Pagination } from '@/components/common/Pagination';
|
import { Pagination } from '@/components/common/Pagination';
|
||||||
import type { DateRange } from '@/services/dashboard.service';
|
import type { DateRange } from '@/services/dashboard.service';
|
||||||
import dashboardService from '@/services/dashboard.service';
|
import dashboardService from '@/services/dashboard.service';
|
||||||
|
import userApi from '@/services/userApi';
|
||||||
|
|
||||||
// Components
|
// Components
|
||||||
import { RequestsHeader } from './components/RequestsHeader';
|
import { RequestsHeader } from './components/RequestsHeader';
|
||||||
@ -69,6 +70,7 @@ export function Requests({ onViewRequest }: RequestsProps) {
|
|||||||
const [backendStats, setBackendStats] = useState<BackendStats | null>(null);
|
const [backendStats, setBackendStats] = useState<BackendStats | null>(null);
|
||||||
const [departments, setDepartments] = useState<string[]>([]);
|
const [departments, setDepartments] = useState<string[]>([]);
|
||||||
const [loadingDepartments, setLoadingDepartments] = useState(false);
|
const [loadingDepartments, setLoadingDepartments] = useState(false);
|
||||||
|
const [allUsers, setAllUsers] = useState<Array<{ userId: string; email: string; displayName?: string }>>([]);
|
||||||
|
|
||||||
// Pagination (currentPage now in Redux)
|
// Pagination (currentPage now in Redux)
|
||||||
const [totalPages, setTotalPages] = useState(1);
|
const [totalPages, setTotalPages] = useState(1);
|
||||||
@ -77,15 +79,15 @@ export function Requests({ onViewRequest }: RequestsProps) {
|
|||||||
|
|
||||||
// User search hooks
|
// User search hooks
|
||||||
const initiatorSearch = useUserSearch({
|
const initiatorSearch = useUserSearch({
|
||||||
|
allUsers,
|
||||||
filterValue: filters.initiatorFilter,
|
filterValue: filters.initiatorFilter,
|
||||||
onFilterChange: filters.setInitiatorFilter,
|
onFilterChange: filters.setInitiatorFilter
|
||||||
source: 'local'
|
|
||||||
});
|
});
|
||||||
|
|
||||||
const approverSearch = useUserSearch({
|
const approverSearch = useUserSearch({
|
||||||
|
allUsers,
|
||||||
filterValue: filters.approverFilter,
|
filterValue: filters.approverFilter,
|
||||||
onFilterChange: filters.setApproverFilter,
|
onFilterChange: filters.setApproverFilter
|
||||||
source: 'local'
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// Fetch backend stats
|
// Fetch backend stats
|
||||||
@ -98,7 +100,6 @@ export function Requests({ onViewRequest }: RequestsProps) {
|
|||||||
statsEndDate?: Date,
|
statsEndDate?: Date,
|
||||||
filtersWithoutStatus?: {
|
filtersWithoutStatus?: {
|
||||||
priority?: string;
|
priority?: string;
|
||||||
templateType?: string;
|
|
||||||
department?: string;
|
department?: string;
|
||||||
initiator?: string;
|
initiator?: string;
|
||||||
approver?: string;
|
approver?: string;
|
||||||
@ -184,7 +185,7 @@ export function Requests({ onViewRequest }: RequestsProps) {
|
|||||||
statsEndDate ? statsEndDate.toISOString() : undefined,
|
statsEndDate ? statsEndDate.toISOString() : undefined,
|
||||||
undefined, // status - All Requests stats show all statuses, not filtered by status
|
undefined, // status - All Requests stats show all statuses, not filtered by status
|
||||||
filtersWithoutStatus?.priority,
|
filtersWithoutStatus?.priority,
|
||||||
filtersWithoutStatus?.templateType,
|
undefined, // templateType
|
||||||
filtersWithoutStatus?.department,
|
filtersWithoutStatus?.department,
|
||||||
filtersWithoutStatus?.initiator,
|
filtersWithoutStatus?.initiator,
|
||||||
filtersWithoutStatus?.approver,
|
filtersWithoutStatus?.approver,
|
||||||
@ -225,6 +226,20 @@ export function Requests({ onViewRequest }: RequestsProps) {
|
|||||||
}
|
}
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
// Fetch users
|
||||||
|
const fetchUsers = useCallback(async () => {
|
||||||
|
try {
|
||||||
|
const usersData = await userApi.getAllUsers();
|
||||||
|
const usersList = usersData.map((user: any) => ({
|
||||||
|
userId: user.userId,
|
||||||
|
email: user.email,
|
||||||
|
displayName: user.displayName || user.email
|
||||||
|
}));
|
||||||
|
setAllUsers(usersList);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to fetch users:', error);
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
// Use refs to store stable callbacks to prevent infinite loops
|
// Use refs to store stable callbacks to prevent infinite loops
|
||||||
const filtersRef = useRef(filters);
|
const filtersRef = useRef(filters);
|
||||||
@ -317,7 +332,8 @@ export function Requests({ onViewRequest }: RequestsProps) {
|
|||||||
// Initial fetch
|
// Initial fetch
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
fetchDepartments();
|
fetchDepartments();
|
||||||
}, [fetchDepartments]);
|
fetchUsers();
|
||||||
|
}, [fetchDepartments, fetchUsers]);
|
||||||
|
|
||||||
// Fetch backend stats when filters change (excluding status)
|
// Fetch backend stats when filters change (excluding status)
|
||||||
// Stats should reflect priority, department, initiator, approver, search, and date range filters
|
// Stats should reflect priority, department, initiator, approver, search, and date range filters
|
||||||
|
|||||||
@ -11,6 +11,7 @@ import { useEffect, useState, useCallback, useMemo, useRef } from 'react';
|
|||||||
import { Pagination } from '@/components/common/Pagination';
|
import { Pagination } from '@/components/common/Pagination';
|
||||||
import dashboardService from '@/services/dashboard.service';
|
import dashboardService from '@/services/dashboard.service';
|
||||||
import type { DateRange } from '@/services/dashboard.service';
|
import type { DateRange } from '@/services/dashboard.service';
|
||||||
|
import userApi from '@/services/userApi';
|
||||||
|
|
||||||
// Components
|
// Components
|
||||||
import { RequestsHeader } from './components/RequestsHeader';
|
import { RequestsHeader } from './components/RequestsHeader';
|
||||||
@ -95,6 +96,7 @@ export function UserAllRequests({ onViewRequest }: RequestsProps) {
|
|||||||
const [backendStats, setBackendStats] = useState<BackendStats | null>(null); // Stats from backend API
|
const [backendStats, setBackendStats] = useState<BackendStats | null>(null); // Stats from backend API
|
||||||
const [departments, setDepartments] = useState<string[]>([]);
|
const [departments, setDepartments] = useState<string[]>([]);
|
||||||
const [loadingDepartments, setLoadingDepartments] = useState(false);
|
const [loadingDepartments, setLoadingDepartments] = useState(false);
|
||||||
|
const [allUsers, setAllUsers] = useState<Array<{ userId: string; email: string; displayName?: string }>>([]);
|
||||||
|
|
||||||
// Pagination (currentPage now in Redux)
|
// Pagination (currentPage now in Redux)
|
||||||
const [totalPages, setTotalPages] = useState(1);
|
const [totalPages, setTotalPages] = useState(1);
|
||||||
@ -103,15 +105,15 @@ export function UserAllRequests({ onViewRequest }: RequestsProps) {
|
|||||||
|
|
||||||
// User search hooks
|
// User search hooks
|
||||||
const initiatorSearch = useUserSearch({
|
const initiatorSearch = useUserSearch({
|
||||||
|
allUsers,
|
||||||
filterValue: filters.initiatorFilter,
|
filterValue: filters.initiatorFilter,
|
||||||
onFilterChange: filters.setInitiatorFilter,
|
onFilterChange: filters.setInitiatorFilter
|
||||||
source: 'local'
|
|
||||||
});
|
});
|
||||||
|
|
||||||
const approverSearch = useUserSearch({
|
const approverSearch = useUserSearch({
|
||||||
|
allUsers,
|
||||||
filterValue: filters.approverFilter,
|
filterValue: filters.approverFilter,
|
||||||
onFilterChange: filters.setApproverFilter,
|
onFilterChange: filters.setApproverFilter
|
||||||
source: 'local'
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// Fetch backend stats using dashboard API
|
// Fetch backend stats using dashboard API
|
||||||
@ -178,6 +180,20 @@ export function UserAllRequests({ onViewRequest }: RequestsProps) {
|
|||||||
}
|
}
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
// Fetch users
|
||||||
|
const fetchUsers = useCallback(async () => {
|
||||||
|
try {
|
||||||
|
const usersData = await userApi.getAllUsers();
|
||||||
|
const usersList = usersData.map((user: any) => ({
|
||||||
|
userId: user.userId,
|
||||||
|
email: user.email,
|
||||||
|
displayName: user.displayName || user.email
|
||||||
|
}));
|
||||||
|
setAllUsers(usersList);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to fetch users:', error);
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
// Use refs to store stable callbacks to prevent infinite loops
|
// Use refs to store stable callbacks to prevent infinite loops
|
||||||
const filtersRef = useRef(filters);
|
const filtersRef = useRef(filters);
|
||||||
@ -237,7 +253,8 @@ export function UserAllRequests({ onViewRequest }: RequestsProps) {
|
|||||||
// Initial fetch
|
// Initial fetch
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
fetchDepartments();
|
fetchDepartments();
|
||||||
}, [fetchDepartments]);
|
fetchUsers();
|
||||||
|
}, [fetchDepartments, fetchUsers]);
|
||||||
|
|
||||||
// Fetch backend stats when filters change (except status filter)
|
// Fetch backend stats when filters change (except status filter)
|
||||||
// OPTIMIZED: Uses backend stats API instead of fetching 100 records
|
// OPTIMIZED: Uses backend stats API instead of fetching 100 records
|
||||||
|
|||||||
@ -4,44 +4,30 @@
|
|||||||
|
|
||||||
import { useState, useCallback, useRef, useEffect } from 'react';
|
import { useState, useCallback, useRef, useEffect } from 'react';
|
||||||
import type { User } from '../types/requests.types';
|
import type { User } from '../types/requests.types';
|
||||||
import { userApi } from '@/services/userApi';
|
|
||||||
|
|
||||||
interface UseUserSearchOptions {
|
interface UseUserSearchOptions {
|
||||||
|
allUsers: User[];
|
||||||
filterValue: string;
|
filterValue: string;
|
||||||
onFilterChange: (userId: string) => void;
|
onFilterChange: (userId: string) => void;
|
||||||
source?: 'local' | 'okta' | 'default';
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useUserSearch({ filterValue, onFilterChange, source = 'default' }: UseUserSearchOptions) {
|
export function useUserSearch({ allUsers, filterValue, onFilterChange }: UseUserSearchOptions) {
|
||||||
const [searchQuery, setSearchQuery] = useState('');
|
const [searchQuery, setSearchQuery] = useState('');
|
||||||
const [searchResults, setSearchResults] = useState<User[]>([]);
|
const [searchResults, setSearchResults] = useState<User[]>([]);
|
||||||
const [showResults, setShowResults] = useState(false);
|
const [showResults, setShowResults] = useState(false);
|
||||||
const [selectedUser, setSelectedUser] = useState<User | null>(null);
|
const [selectedUser, setSelectedUser] = useState<User | null>(null);
|
||||||
const [searching, setSearching] = useState(false);
|
|
||||||
const searchTimer = useRef<NodeJS.Timeout | null>(null);
|
const searchTimer = useRef<NodeJS.Timeout | null>(null);
|
||||||
|
|
||||||
// Initialize selected user details if we only have the ID (filterValue)
|
// Initialize selected user from filter value
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
async function fetchUserDetail() {
|
if (filterValue !== 'all' && allUsers.length > 0) {
|
||||||
if (filterValue !== 'all' && !selectedUser) {
|
const user = allUsers.find(u => u.userId === filterValue);
|
||||||
try {
|
|
||||||
// Fetch specific user details by ID
|
|
||||||
const user = await userApi.getUserById(filterValue);
|
|
||||||
if (user) {
|
if (user) {
|
||||||
setSelectedUser(user);
|
setSelectedUser(user);
|
||||||
setSearchQuery(user.displayName || user.email);
|
setSearchQuery(user.displayName || user.email);
|
||||||
}
|
}
|
||||||
} catch (err) {
|
|
||||||
console.error('Failed to fetch user detail for search:', err);
|
|
||||||
}
|
}
|
||||||
} else if (filterValue === 'all') {
|
}, [filterValue, allUsers]);
|
||||||
setSelectedUser(null);
|
|
||||||
setSearchQuery('');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fetchUserDetail();
|
|
||||||
}, [filterValue]);
|
|
||||||
|
|
||||||
// Cleanup timer
|
// Cleanup timer
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@ -65,22 +51,17 @@ export function useUserSearch({ filterValue, onFilterChange, source = 'default'
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
searchTimer.current = setTimeout(async () => {
|
searchTimer.current = setTimeout(() => {
|
||||||
setSearching(true);
|
const searchLower = query.toLowerCase().trim();
|
||||||
try {
|
const filtered = allUsers.filter((user) => {
|
||||||
const response = await userApi.searchUsers(query.trim(), 10, source);
|
const email = (user.email || '').toLowerCase();
|
||||||
const users = response.data?.data || [];
|
const displayName = (user.displayName || '').toLowerCase();
|
||||||
setSearchResults(users);
|
return email.includes(searchLower) || displayName.includes(searchLower);
|
||||||
setShowResults(users.length > 0);
|
});
|
||||||
} catch (err) {
|
setSearchResults(filtered.slice(0, 10));
|
||||||
console.error('Search API failed:', err);
|
setShowResults(filtered.length > 0);
|
||||||
setSearchResults([]);
|
}, 300);
|
||||||
setShowResults(false);
|
}, [allUsers]);
|
||||||
} finally {
|
|
||||||
setSearching(false);
|
|
||||||
}
|
|
||||||
}, 400); // Slightly longer debounce for API calls
|
|
||||||
}, [source]);
|
|
||||||
|
|
||||||
const handleSelect = useCallback((user: User) => {
|
const handleSelect = useCallback((user: User) => {
|
||||||
setSelectedUser(user);
|
setSelectedUser(user);
|
||||||
@ -103,7 +84,6 @@ export function useUserSearch({ filterValue, onFilterChange, source = 'default'
|
|||||||
searchResults,
|
searchResults,
|
||||||
showResults,
|
showResults,
|
||||||
selectedUser,
|
selectedUser,
|
||||||
searching,
|
|
||||||
handleSearch,
|
handleSearch,
|
||||||
handleSelect,
|
handleSelect,
|
||||||
handleClear,
|
handleClear,
|
||||||
|
|||||||
@ -1,67 +0,0 @@
|
|||||||
import { useNavigate } from 'react-router-dom';
|
|
||||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
|
||||||
import { Button } from '@/components/ui/button';
|
|
||||||
import { ArrowLeft, Lock, Key } from 'lucide-react';
|
|
||||||
import { ApiTokenManager } from '@/components/settings/ApiTokenManager';
|
|
||||||
|
|
||||||
export function SecuritySettings() {
|
|
||||||
const navigate = useNavigate();
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="max-w-7xl mx-auto space-y-6 pb-8">
|
|
||||||
{/* Header */}
|
|
||||||
<div className="flex items-center gap-4 mb-6">
|
|
||||||
<Button variant="ghost" size="icon" onClick={() => navigate('/settings')}>
|
|
||||||
<ArrowLeft className="w-5 h-5" />
|
|
||||||
</Button>
|
|
||||||
<div>
|
|
||||||
<h1 className="text-2xl font-bold text-gray-900">Security Settings</h1>
|
|
||||||
<p className="text-gray-500">Manage your account security and access tokens</p>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="grid grid-cols-1 gap-6">
|
|
||||||
{/* Password Section */}
|
|
||||||
<Card className="shadow-md">
|
|
||||||
<CardHeader>
|
|
||||||
<div className="flex items-center gap-3">
|
|
||||||
<div className="p-2 bg-blue-100 rounded-md">
|
|
||||||
<Lock className="w-5 h-5 text-blue-600" />
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<CardTitle>Password</CardTitle>
|
|
||||||
<CardDescription>Manage your sign-in password</CardDescription>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent>
|
|
||||||
<div className="p-4 bg-gray-50 rounded-md border border-gray-200">
|
|
||||||
<p className="text-sm text-gray-600">
|
|
||||||
Your password is managed through your organization's Single Sign-On (SSO) provider.
|
|
||||||
Please contact your IT administrator to reset or change your password.
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
|
|
||||||
{/* API Tokens Section */}
|
|
||||||
<Card className="shadow-md">
|
|
||||||
<CardHeader>
|
|
||||||
<div className="flex items-center gap-3">
|
|
||||||
<div className="p-2 bg-purple-100 rounded-md">
|
|
||||||
<Key className="w-5 h-5 text-purple-600" />
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<CardTitle>API Tokens</CardTitle>
|
|
||||||
<CardDescription>Manage personal access tokens for external integrations</CardDescription>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent>
|
|
||||||
<ApiTokenManager />
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@ -19,13 +19,10 @@ import { UserRoleManager } from '@/components/admin/UserRoleManager';
|
|||||||
import { ActivityTypeManager } from '@/components/admin/ActivityTypeManager';
|
import { ActivityTypeManager } from '@/components/admin/ActivityTypeManager';
|
||||||
import { NotificationStatusModal } from '@/components/settings/NotificationStatusModal';
|
import { NotificationStatusModal } from '@/components/settings/NotificationStatusModal';
|
||||||
import { NotificationPreferencesModal } from '@/components/settings/NotificationPreferencesModal';
|
import { NotificationPreferencesModal } from '@/components/settings/NotificationPreferencesModal';
|
||||||
// import { ApiTokenManager } from '@/components/settings/ApiTokenManager'; // Removed: Moved to dedicated page
|
|
||||||
import { useState, useEffect } from 'react';
|
import { useState, useEffect } from 'react';
|
||||||
import { useNavigate } from 'react-router-dom';
|
|
||||||
import { getUserSubscriptions } from '@/services/notificationApi';
|
import { getUserSubscriptions } from '@/services/notificationApi';
|
||||||
|
|
||||||
export function Settings() {
|
export function Settings() {
|
||||||
const navigate = useNavigate();
|
|
||||||
const { user } = useAuth();
|
const { user } = useAuth();
|
||||||
const isAdmin = checkIsAdmin(user);
|
const isAdmin = checkIsAdmin(user);
|
||||||
const [showNotificationModal, setShowNotificationModal] = useState(false);
|
const [showNotificationModal, setShowNotificationModal] = useState(false);
|
||||||
@ -274,18 +271,9 @@ export function Settings() {
|
|||||||
</div>
|
</div>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent>
|
||||||
<div className="space-y-6">
|
<div className="space-y-4">
|
||||||
<div className="p-4 bg-gradient-to-br from-gray-50 to-gray-100 rounded-md border border-gray-200">
|
<div className="p-4 bg-gradient-to-br from-gray-50 to-gray-100 rounded-md border border-gray-200">
|
||||||
<p className="text-sm text-gray-600 mb-4">
|
<p className="text-sm text-gray-600 text-center">Security settings will be available soon</p>
|
||||||
Manage your password, API tokens, and other security preferences.
|
|
||||||
</p>
|
|
||||||
<Button
|
|
||||||
onClick={() => navigate('/settings/security')}
|
|
||||||
className="w-full bg-re-green hover:bg-re-green/90 text-white shadow-md hover:shadow-lg transition-all"
|
|
||||||
>
|
|
||||||
<Lock className="w-4 h-4 mr-2" />
|
|
||||||
Manage Security
|
|
||||||
</Button>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
@ -336,9 +324,6 @@ export function Settings() {
|
|||||||
</Button>
|
</Button>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
|
|
||||||
{/* Additional Settings if needed */}
|
|
||||||
</div>
|
</div>
|
||||||
</TabsContent>
|
</TabsContent>
|
||||||
|
|
||||||
@ -506,18 +491,9 @@ export function Settings() {
|
|||||||
</div>
|
</div>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent>
|
||||||
<div className="space-y-6">
|
<div className="space-y-4">
|
||||||
<div className="p-4 bg-gradient-to-br from-gray-50 to-gray-100 rounded-md border border-gray-200">
|
<div className="p-4 bg-gradient-to-br from-gray-50 to-gray-100 rounded-md border border-gray-200">
|
||||||
<p className="text-sm text-gray-600 mb-4">
|
<p className="text-sm text-gray-600 text-center">Security settings will be available soon</p>
|
||||||
Manage your password, API tokens, and other security preferences.
|
|
||||||
</p>
|
|
||||||
<Button
|
|
||||||
onClick={() => navigate('/settings/security')}
|
|
||||||
className="w-full bg-re-green hover:bg-re-green/90 text-white shadow-md hover:shadow-lg transition-all"
|
|
||||||
>
|
|
||||||
<Lock className="w-4 h-4 mr-2" />
|
|
||||||
Manage Security
|
|
||||||
</Button>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
@ -569,8 +545,6 @@ export function Settings() {
|
|||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Additional sections if needed */}
|
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@ -135,7 +135,7 @@ export const bulkImportHolidays = async (holidays: Partial<Holiday>[]): Promise<
|
|||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get all active activity types (requires authentication)
|
* Get all activity types (public endpoint - no auth required)
|
||||||
*/
|
*/
|
||||||
export const getActivityTypes = async (): Promise<ActivityType[]> => {
|
export const getActivityTypes = async (): Promise<ActivityType[]> => {
|
||||||
const response = await apiClient.get('/config/activity-types');
|
const response = await apiClient.get('/config/activity-types');
|
||||||
|
|||||||
@ -6,7 +6,7 @@
|
|||||||
import axios, { AxiosInstance } from 'axios';
|
import axios, { AxiosInstance } from 'axios';
|
||||||
import { TokenManager } from '../utils/tokenManager';
|
import { TokenManager } from '../utils/tokenManager';
|
||||||
|
|
||||||
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || '';
|
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:5000/api/v1';
|
||||||
|
|
||||||
// Create axios instance with default config
|
// Create axios instance with default config
|
||||||
const apiClient: AxiosInstance = axios.create({
|
const apiClient: AxiosInstance = axios.create({
|
||||||
@ -27,13 +27,13 @@ apiClient.interceptors.request.use(
|
|||||||
const isProduction = import.meta.env.PROD || import.meta.env.MODE === 'production';
|
const isProduction = import.meta.env.PROD || import.meta.env.MODE === 'production';
|
||||||
|
|
||||||
if (!isProduction) {
|
if (!isProduction) {
|
||||||
// Dev: Get token from localStorage and add to header
|
// Development: Get token from localStorage and add to header
|
||||||
const token = TokenManager.getAccessToken();
|
const token = TokenManager.getAccessToken();
|
||||||
if (token) {
|
if (token) {
|
||||||
config.headers.Authorization = `Bearer ${token}`;
|
config.headers.Authorization = `Bearer ${token}`;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Prod: Cookies handle authentication automatically
|
// Production: Cookies handle authentication automatically
|
||||||
|
|
||||||
return config;
|
return config;
|
||||||
},
|
},
|
||||||
@ -183,11 +183,11 @@ export async function exchangeCodeForTokens(
|
|||||||
// SECURITY: In production, tokens are ONLY in httpOnly cookies (not in response body)
|
// SECURITY: In production, tokens are ONLY in httpOnly cookies (not in response body)
|
||||||
// In development, backend returns tokens for cross-port setup
|
// In development, backend returns tokens for cross-port setup
|
||||||
if (result.accessToken && result.refreshToken) {
|
if (result.accessToken && result.refreshToken) {
|
||||||
// Dev mode: Backend returned tokens, store them
|
// Development mode: Backend returned tokens, store them
|
||||||
TokenManager.setAccessToken(result.accessToken);
|
TokenManager.setAccessToken(result.accessToken);
|
||||||
TokenManager.setRefreshToken(result.refreshToken);
|
TokenManager.setRefreshToken(result.refreshToken);
|
||||||
}
|
}
|
||||||
// Prod mode: No tokens in response - they're in httpOnly cookies
|
// Production mode: No tokens in response - they're in httpOnly cookies
|
||||||
// TokenManager.setAccessToken/setRefreshToken are no-ops in production anyway
|
// TokenManager.setAccessToken/setRefreshToken are no-ops in production anyway
|
||||||
|
|
||||||
return result;
|
return result;
|
||||||
@ -255,7 +255,7 @@ export async function getCurrentUser() {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Logout user
|
* Logout user
|
||||||
* IMPORTANT: This endpoint MUST clear httpOnly cookies set by backend
|
* CRITICAL: This endpoint MUST clear httpOnly cookies set by backend
|
||||||
* Note: TokenManager.clearAll() is called in AuthContext.logout()
|
* Note: TokenManager.clearAll() is called in AuthContext.logout()
|
||||||
* We don't call it here to avoid double clearing
|
* We don't call it here to avoid double clearing
|
||||||
*/
|
*/
|
||||||
|
|||||||
@ -105,16 +105,3 @@ export async function verifyDealerLogin(dealerCode: string): Promise<DealerInfo>
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Search dealer by code from external Royal Enfield API
|
|
||||||
* @param dealerCode - The code to search for
|
|
||||||
*/
|
|
||||||
export async function searchExternalDealerByCode(dealerCode: string): Promise<any | null> {
|
|
||||||
try {
|
|
||||||
const res = await apiClient.get(`/dealers-external/search/${dealerCode}`);
|
|
||||||
return res.data?.data || res.data || null;
|
|
||||||
} catch (error) {
|
|
||||||
console.error('[DealerAPI] Error searching external dealer:', error);
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@ -78,22 +78,7 @@ export async function submitProposal(
|
|||||||
requestId: string,
|
requestId: string,
|
||||||
proposalData: {
|
proposalData: {
|
||||||
proposalDocument?: File;
|
proposalDocument?: File;
|
||||||
costBreakup?: Array<{
|
costBreakup?: Array<{ description: string; amount: number }>;
|
||||||
description: string;
|
|
||||||
amount: number;
|
|
||||||
hsnCode?: string;
|
|
||||||
isService?: boolean;
|
|
||||||
quantity?: number;
|
|
||||||
gstRate?: number;
|
|
||||||
gstAmt?: number;
|
|
||||||
cgstRate?: number;
|
|
||||||
cgstAmt?: number;
|
|
||||||
sgstRate?: number;
|
|
||||||
sgstAmt?: number;
|
|
||||||
igstRate?: number;
|
|
||||||
igstAmt?: number;
|
|
||||||
totalAmt?: number;
|
|
||||||
}>;
|
|
||||||
totalEstimatedBudget?: number;
|
totalEstimatedBudget?: number;
|
||||||
timelineMode?: 'date' | 'days';
|
timelineMode?: 'date' | 'days';
|
||||||
expectedCompletionDate?: string;
|
expectedCompletionDate?: string;
|
||||||
@ -154,16 +139,7 @@ export async function submitCompletion(
|
|||||||
completionData: {
|
completionData: {
|
||||||
activityCompletionDate: string; // ISO date string
|
activityCompletionDate: string; // ISO date string
|
||||||
numberOfParticipants?: number;
|
numberOfParticipants?: number;
|
||||||
closedExpenses?: Array<{
|
closedExpenses?: Array<{ description: string; amount: number }>;
|
||||||
description: string;
|
|
||||||
amount: number;
|
|
||||||
hsnCode?: string;
|
|
||||||
isService?: boolean;
|
|
||||||
quantity?: number;
|
|
||||||
gstRate?: number;
|
|
||||||
gstAmt?: number;
|
|
||||||
totalAmt?: number;
|
|
||||||
}>;
|
|
||||||
totalClosedExpenses?: number;
|
totalClosedExpenses?: number;
|
||||||
completionDocuments?: File[];
|
completionDocuments?: File[];
|
||||||
activityPhotos?: File[];
|
activityPhotos?: File[];
|
||||||
|
|||||||
@ -6,8 +6,8 @@
|
|||||||
import { TokenManager } from '../utils/tokenManager';
|
import { TokenManager } from '../utils/tokenManager';
|
||||||
import axios from 'axios';
|
import axios from 'axios';
|
||||||
|
|
||||||
const TANFLOW_BASE_URL = import.meta.env.VITE_TANFLOW_BASE_URL || '';
|
const TANFLOW_BASE_URL = import.meta.env.VITE_TANFLOW_BASE_URL || 'https://ssodev.rebridge.co.in/realms/RE';
|
||||||
const TANFLOW_CLIENT_ID = import.meta.env.VITE_TANFLOW_CLIENT_ID || '';
|
const TANFLOW_CLIENT_ID = import.meta.env.VITE_TANFLOW_CLIENT_ID || 'REFLOW';
|
||||||
const TANFLOW_REDIRECT_URI = `${window.location.origin}/login/callback`;
|
const TANFLOW_REDIRECT_URI = `${window.location.origin}/login/callback`;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -63,7 +63,7 @@ export async function exchangeTanflowCodeForTokens(
|
|||||||
idToken: string;
|
idToken: string;
|
||||||
user: any;
|
user: any;
|
||||||
}> {
|
}> {
|
||||||
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || '';
|
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:5000/api/v1';
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await axios.post(
|
const response = await axios.post(
|
||||||
@ -112,7 +112,7 @@ export async function exchangeTanflowCodeForTokens(
|
|||||||
* Refresh access token using refresh token
|
* Refresh access token using refresh token
|
||||||
*/
|
*/
|
||||||
export async function refreshTanflowToken(): Promise<string> {
|
export async function refreshTanflowToken(): Promise<string> {
|
||||||
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || '';
|
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:5000/api/v1';
|
||||||
const refreshToken = TokenManager.getRefreshToken();
|
const refreshToken = TokenManager.getRefreshToken();
|
||||||
|
|
||||||
if (!refreshToken) {
|
if (!refreshToken) {
|
||||||
|
|||||||
@ -24,8 +24,8 @@ export interface UserSummary {
|
|||||||
isActive?: boolean;
|
isActive?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function searchUsers(query: string, limit: number = 10, source: 'local' | 'okta' | 'default' = 'default') {
|
export async function searchUsers(query: string, limit: number = 10) {
|
||||||
const res = await apiClient.get('/users/search', { params: { q: query, limit, source } });
|
const res = await apiClient.get('/users/search', { params: { q: query, limit } });
|
||||||
// ResponseHandler.success returns { success: true, data: array }
|
// ResponseHandler.success returns { success: true, data: array }
|
||||||
return res;
|
return res;
|
||||||
}
|
}
|
||||||
@ -102,14 +102,6 @@ export async function getRoleStatistics() {
|
|||||||
return await apiClient.get('/admin/users/role-statistics');
|
return await apiClient.get('/admin/users/role-statistics');
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Get user by ID
|
|
||||||
*/
|
|
||||||
export async function getUserById(userId: string) {
|
|
||||||
const res = await apiClient.get(`/users/${userId}`);
|
|
||||||
return res.data?.data || res.data;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get all users from database (for filtering purposes)
|
* Get all users from database (for filtering purposes)
|
||||||
*/
|
*/
|
||||||
@ -121,7 +113,6 @@ export async function getAllUsers() {
|
|||||||
|
|
||||||
export const userApi = {
|
export const userApi = {
|
||||||
searchUsers,
|
searchUsers,
|
||||||
getUserById,
|
|
||||||
ensureUserExists,
|
ensureUserExists,
|
||||||
assignRole,
|
assignRole,
|
||||||
updateUserRole,
|
updateUserRole,
|
||||||
|
|||||||
@ -362,12 +362,12 @@ export async function getPauseDetails(requestId: string) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function getWorkNoteAttachmentPreviewUrl(attachmentId: string): string {
|
export function getWorkNoteAttachmentPreviewUrl(attachmentId: string): string {
|
||||||
const baseURL = import.meta.env.VITE_BASE_URL || '';
|
const baseURL = import.meta.env.VITE_BASE_URL || 'http://localhost:5000';
|
||||||
return `${baseURL}/api/v1/workflows/work-notes/attachments/${attachmentId}/preview`;
|
return `${baseURL}/api/v1/workflows/work-notes/attachments/${attachmentId}/preview`;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function getDocumentPreviewUrl(documentId: string): string {
|
export function getDocumentPreviewUrl(documentId: string): string {
|
||||||
const baseURL = import.meta.env.VITE_BASE_URL || '';
|
const baseURL = import.meta.env.VITE_BASE_URL || 'http://localhost:5000';
|
||||||
return `${baseURL}/api/v1/workflows/documents/${documentId}/preview`;
|
return `${baseURL}/api/v1/workflows/documents/${documentId}/preview`;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -404,7 +404,7 @@ function extractFilenameFromContentDisposition(contentDisposition: string | null
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function downloadDocument(documentId: string): Promise<void> {
|
export async function downloadDocument(documentId: string): Promise<void> {
|
||||||
const baseURL = import.meta.env.VITE_BASE_URL || '';
|
const baseURL = import.meta.env.VITE_BASE_URL || 'http://localhost:5000';
|
||||||
const downloadUrl = `${baseURL}/api/v1/workflows/documents/${documentId}/download`;
|
const downloadUrl = `${baseURL}/api/v1/workflows/documents/${documentId}/download`;
|
||||||
const isProduction = import.meta.env.PROD || import.meta.env.MODE === 'production';
|
const isProduction = import.meta.env.PROD || import.meta.env.MODE === 'production';
|
||||||
|
|
||||||
@ -449,7 +449,7 @@ export async function downloadDocument(documentId: string): Promise<void> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function downloadWorkNoteAttachment(attachmentId: string): Promise<void> {
|
export async function downloadWorkNoteAttachment(attachmentId: string): Promise<void> {
|
||||||
const downloadBaseURL = import.meta.env.VITE_BASE_URL || '';
|
const downloadBaseURL = import.meta.env.VITE_BASE_URL || 'http://localhost:5000';
|
||||||
const downloadUrl = `${downloadBaseURL}/api/v1/workflows/work-notes/attachments/${attachmentId}/download`;
|
const downloadUrl = `${downloadBaseURL}/api/v1/workflows/work-notes/attachments/${attachmentId}/download`;
|
||||||
const isProduction = import.meta.env.PROD || import.meta.env.MODE === 'production';
|
const isProduction = import.meta.env.PROD || import.meta.env.MODE === 'production';
|
||||||
|
|
||||||
|
|||||||
@ -26,17 +26,7 @@ export interface ClaimManagementRequest {
|
|||||||
};
|
};
|
||||||
estimatedBudget?: number;
|
estimatedBudget?: number;
|
||||||
closedExpenses?: number;
|
closedExpenses?: number;
|
||||||
defaultGstRate?: number;
|
closedExpensesBreakdown?: Array<{ description: string; amount: number }>;
|
||||||
closedExpensesBreakdown?: Array<{
|
|
||||||
description: string;
|
|
||||||
amount: number;
|
|
||||||
gstRate?: number;
|
|
||||||
gstAmt?: number;
|
|
||||||
cgstAmt?: number;
|
|
||||||
sgstAmt?: number;
|
|
||||||
igstAmt?: number;
|
|
||||||
totalAmt?: number;
|
|
||||||
}>;
|
|
||||||
description?: string;
|
description?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -52,16 +42,7 @@ export interface ClaimManagementRequest {
|
|||||||
// Proposal Details (Step 1)
|
// Proposal Details (Step 1)
|
||||||
proposalDetails?: {
|
proposalDetails?: {
|
||||||
proposalDocumentUrl?: string;
|
proposalDocumentUrl?: string;
|
||||||
costBreakup: Array<{
|
costBreakup: Array<{ description: string; amount: number }>;
|
||||||
description: string;
|
|
||||||
amount: number;
|
|
||||||
gstRate?: number;
|
|
||||||
gstAmt?: number;
|
|
||||||
cgstAmt?: number;
|
|
||||||
sgstAmt?: number;
|
|
||||||
igstAmt?: number;
|
|
||||||
totalAmt?: number;
|
|
||||||
}>;
|
|
||||||
totalEstimatedBudget: number;
|
totalEstimatedBudget: number;
|
||||||
timelineMode?: 'date' | 'days';
|
timelineMode?: 'date' | 'days';
|
||||||
expectedCompletionDate?: string;
|
expectedCompletionDate?: string;
|
||||||
@ -89,12 +70,6 @@ export interface ClaimManagementRequest {
|
|||||||
creditNoteNumber?: string;
|
creditNoteNumber?: string;
|
||||||
creditNoteDate?: string;
|
creditNoteDate?: string;
|
||||||
creditNoteAmount?: number;
|
creditNoteAmount?: number;
|
||||||
// PWC Fields
|
|
||||||
irn?: string;
|
|
||||||
ackNo?: string;
|
|
||||||
ackDate?: string;
|
|
||||||
signedInvoiceUrl?: string;
|
|
||||||
taxBreakdown?: any;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// Claim Amount
|
// Claim Amount
|
||||||
@ -154,19 +129,19 @@ export function mapToClaimManagementRequest(
|
|||||||
// Activity fields mapped
|
// Activity fields mapped
|
||||||
|
|
||||||
// Get budget values from budgetTracking table (new source of truth)
|
// Get budget values from budgetTracking table (new source of truth)
|
||||||
const estimatedBudget = budgetTracking.proposalEstimatedBudget ??
|
const estimatedBudget = budgetTracking.proposalEstimatedBudget ||
|
||||||
budgetTracking.proposal_estimated_budget ??
|
budgetTracking.proposal_estimated_budget ||
|
||||||
budgetTracking.initialEstimatedBudget ??
|
budgetTracking.initialEstimatedBudget ||
|
||||||
budgetTracking.initial_estimated_budget ??
|
budgetTracking.initial_estimated_budget ||
|
||||||
claimDetails.estimatedBudget ??
|
claimDetails.estimatedBudget ||
|
||||||
claimDetails.estimated_budget;
|
claimDetails.estimated_budget;
|
||||||
|
|
||||||
// Get closed expenses - check multiple sources with proper number conversion
|
// Get closed expenses - check multiple sources with proper number conversion
|
||||||
const closedExpensesRaw = budgetTracking?.closedExpenses ??
|
const closedExpensesRaw = budgetTracking?.closedExpenses ||
|
||||||
budgetTracking?.closed_expenses ??
|
budgetTracking?.closed_expenses ||
|
||||||
completionDetails?.totalClosedExpenses ??
|
completionDetails?.totalClosedExpenses ||
|
||||||
completionDetails?.total_closed_expenses ??
|
completionDetails?.total_closed_expenses ||
|
||||||
claimDetails?.closedExpenses ??
|
claimDetails?.closedExpenses ||
|
||||||
claimDetails?.closed_expenses;
|
claimDetails?.closed_expenses;
|
||||||
// Convert to number and handle 0 as valid value
|
// Convert to number and handle 0 as valid value
|
||||||
const closedExpenses = closedExpensesRaw !== null && closedExpensesRaw !== undefined
|
const closedExpenses = closedExpensesRaw !== null && closedExpensesRaw !== undefined
|
||||||
@ -176,14 +151,8 @@ export function mapToClaimManagementRequest(
|
|||||||
// Get closed expenses breakdown from new completionExpenses table
|
// Get closed expenses breakdown from new completionExpenses table
|
||||||
const closedExpensesBreakdown = Array.isArray(completionExpenses) && completionExpenses.length > 0
|
const closedExpensesBreakdown = Array.isArray(completionExpenses) && completionExpenses.length > 0
|
||||||
? completionExpenses.map((exp: any) => ({
|
? completionExpenses.map((exp: any) => ({
|
||||||
description: exp.description || exp.itemDescription || exp.item_description || '',
|
description: exp.description || exp.itemDescription || '',
|
||||||
amount: Number(exp.amount) || 0,
|
amount: Number(exp.amount) || 0
|
||||||
gstRate: exp.gstRate ?? exp.gst_rate,
|
|
||||||
gstAmt: exp.gstAmt ?? exp.gst_amt,
|
|
||||||
cgstAmt: exp.cgstAmt ?? exp.cgst_amt,
|
|
||||||
sgstAmt: exp.sgstAmt ?? exp.sgst_amt,
|
|
||||||
igstAmt: exp.igstAmt ?? exp.igst_amt,
|
|
||||||
totalAmt: exp.totalAmt ?? exp.total_amt
|
|
||||||
}))
|
}))
|
||||||
: (completionDetails?.closedExpenses ||
|
: (completionDetails?.closedExpenses ||
|
||||||
completionDetails?.closed_expenses ||
|
completionDetails?.closed_expenses ||
|
||||||
@ -193,7 +162,6 @@ export function mapToClaimManagementRequest(
|
|||||||
const activityInfo = {
|
const activityInfo = {
|
||||||
activityName,
|
activityName,
|
||||||
activityType,
|
activityType,
|
||||||
defaultGstRate: claimDetails.defaultGstRate || 18,
|
|
||||||
requestedDate: claimDetails.activityDate || claimDetails.activity_date || apiRequest.createdAt, // Use activityDate as requestedDate, fallback to createdAt
|
requestedDate: claimDetails.activityDate || claimDetails.activity_date || apiRequest.createdAt, // Use activityDate as requestedDate, fallback to createdAt
|
||||||
location,
|
location,
|
||||||
period: (periodStartDate && periodEndDate) ? {
|
period: (periodStartDate && periodEndDate) ? {
|
||||||
@ -232,29 +200,7 @@ export function mapToClaimManagementRequest(
|
|||||||
const expectedCompletionDate = proposalDetails?.expectedCompletionDate || proposalDetails?.expected_completion_date;
|
const expectedCompletionDate = proposalDetails?.expectedCompletionDate || proposalDetails?.expected_completion_date;
|
||||||
const proposal = proposalDetails ? {
|
const proposal = proposalDetails ? {
|
||||||
proposalDocumentUrl: proposalDetails.proposalDocumentUrl || proposalDetails.proposal_document_url,
|
proposalDocumentUrl: proposalDetails.proposalDocumentUrl || proposalDetails.proposal_document_url,
|
||||||
costBreakup: Array.isArray(proposalDetails.costItems || proposalDetails.cost_items)
|
costBreakup: proposalDetails.costBreakup || proposalDetails.cost_breakup || [],
|
||||||
? (proposalDetails.costItems || proposalDetails.cost_items).map((item: any) => ({
|
|
||||||
description: item.description || item.itemDescription || item.item_description || '',
|
|
||||||
amount: Number(item.amount) || 0,
|
|
||||||
gstRate: Number(item.gstRate ?? item.gst_rate ?? 0),
|
|
||||||
gstAmt: Number(item.gstAmt ?? item.gst_amt ?? 0),
|
|
||||||
cgstAmt: Number(item.cgstAmt ?? item.cgst_amt ?? 0),
|
|
||||||
sgstAmt: Number(item.sgstAmt ?? item.sgst_amt ?? 0),
|
|
||||||
igstAmt: Number(item.igstAmt ?? item.igst_amt ?? 0),
|
|
||||||
totalAmt: Number(item.totalAmt ?? item.total_amt ?? 0)
|
|
||||||
}))
|
|
||||||
: Array.isArray(proposalDetails.costBreakup || proposalDetails.cost_breakup)
|
|
||||||
? (proposalDetails.costBreakup || proposalDetails.cost_breakup).map((item: any) => ({
|
|
||||||
description: item.description || item.itemDescription || item.item_description || '',
|
|
||||||
amount: Number(item.amount) || 0,
|
|
||||||
gstRate: item.gstRate ?? item.gst_rate,
|
|
||||||
gstAmt: item.gstAmt ?? item.gst_amt,
|
|
||||||
cgstAmt: item.cgstAmt ?? item.cgst_amt,
|
|
||||||
sgstAmt: item.sgstAmt ?? item.sgst_amt,
|
|
||||||
igstAmt: item.igstAmt ?? item.igst_amt,
|
|
||||||
totalAmt: item.totalAmt ?? item.total_amt
|
|
||||||
}))
|
|
||||||
: [],
|
|
||||||
totalEstimatedBudget: proposalDetails.totalEstimatedBudget || proposalDetails.total_estimated_budget || 0,
|
totalEstimatedBudget: proposalDetails.totalEstimatedBudget || proposalDetails.total_estimated_budget || 0,
|
||||||
timelineMode: proposalDetails.timelineMode || proposalDetails.timeline_mode,
|
timelineMode: proposalDetails.timelineMode || proposalDetails.timeline_mode,
|
||||||
expectedCompletionDate: expectedCompletionDate,
|
expectedCompletionDate: expectedCompletionDate,
|
||||||
@ -292,12 +238,6 @@ export function mapToClaimManagementRequest(
|
|||||||
(creditNote.creditNoteAmount ? Number(creditNote.creditNoteAmount) :
|
(creditNote.creditNoteAmount ? Number(creditNote.creditNoteAmount) :
|
||||||
(claimDetails.creditNoteAmount ? Number(claimDetails.creditNoteAmount) :
|
(claimDetails.creditNoteAmount ? Number(claimDetails.creditNoteAmount) :
|
||||||
(claimDetails.credit_note_amount ? Number(claimDetails.credit_note_amount) : undefined)))),
|
(claimDetails.credit_note_amount ? Number(claimDetails.credit_note_amount) : undefined)))),
|
||||||
// PWC fields
|
|
||||||
irn: invoice.irn || claimDetails.irn,
|
|
||||||
ackNo: invoice.ackNo || claimDetails.ackNo,
|
|
||||||
ackDate: invoice.ackDate || claimDetails.ackDate,
|
|
||||||
signedInvoiceUrl: invoice.signedInvoiceUrl || claimDetails.signedInvoiceUrl,
|
|
||||||
taxBreakdown: invoice.taxBreakdown || claimDetails.taxBreakdown,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// Map claim amounts
|
// Map claim amounts
|
||||||
|
|||||||
@ -2,7 +2,166 @@
|
|||||||
// This database is exclusively for claim management requests created via ClaimManagementWizard
|
// This database is exclusively for claim management requests created via ClaimManagementWizard
|
||||||
// Template: Claim Management (8-step workflow)
|
// Template: Claim Management (8-step workflow)
|
||||||
|
|
||||||
export const CLAIM_MANAGEMENT_DATABASE: any = {};
|
export const CLAIM_MANAGEMENT_DATABASE: any = {
|
||||||
|
'RE-REQ-2024-CM-001': {
|
||||||
|
id: 'RE-REQ-2024-CM-001',
|
||||||
|
title: 'Dealer Marketing Activity Claim - Diwali Festival Campaign',
|
||||||
|
description: 'Claim request for dealer-led Diwali festival marketing campaign including showroom decoration, test ride events, customer engagement activities, and promotional merchandise distribution. Activity conducted at Royal Motors Mumbai dealership.',
|
||||||
|
category: 'Dealer Operations',
|
||||||
|
subcategory: 'Claim Management',
|
||||||
|
status: 'pending',
|
||||||
|
priority: 'standard',
|
||||||
|
amount: 'TBD',
|
||||||
|
slaProgress: 35,
|
||||||
|
slaRemaining: '4 days 12 hours',
|
||||||
|
slaEndDate: 'Oct 16, 2024 5:00 PM',
|
||||||
|
currentStep: 1,
|
||||||
|
totalSteps: 8,
|
||||||
|
template: 'claim-management',
|
||||||
|
templateName: 'Claim Management',
|
||||||
|
initiator: {
|
||||||
|
name: 'Sneha Patil',
|
||||||
|
role: 'Regional Marketing Coordinator',
|
||||||
|
department: 'Marketing - West Zone',
|
||||||
|
email: 'sneha.patil@royalenfield.com',
|
||||||
|
phone: '+91 98765 43250',
|
||||||
|
avatar: 'SP'
|
||||||
|
},
|
||||||
|
department: 'Marketing - West Zone',
|
||||||
|
createdAt: 'Oct 7, 2024 9:30 AM',
|
||||||
|
updatedAt: 'Oct 7, 2024 9:30 AM',
|
||||||
|
dueDate: '2024-10-16T17:00:00Z',
|
||||||
|
conclusionRemark: '',
|
||||||
|
claimDetails: {
|
||||||
|
activityName: 'Diwali Festival Campaign 2024',
|
||||||
|
activityType: 'Marketing Activity',
|
||||||
|
activityDate: 'Oct 5, 2024',
|
||||||
|
location: 'Mumbai, Maharashtra',
|
||||||
|
dealerCode: 'RE-MH-001',
|
||||||
|
dealerName: 'Royal Motors Mumbai',
|
||||||
|
dealerEmail: 'dealer@royalmotorsmumbai.com',
|
||||||
|
dealerPhone: '+91 98765 12345',
|
||||||
|
dealerAddress: '123 Main Street, Andheri West, Mumbai, Maharashtra 400053',
|
||||||
|
requestDescription: 'Marketing campaign for Diwali festival including showroom decoration, test ride events, customer engagement activities, and promotional merchandise distribution at Royal Motors Mumbai dealership.',
|
||||||
|
estimatedBudget: '₹2,45,000',
|
||||||
|
periodStart: 'Oct 1, 2024',
|
||||||
|
periodEnd: 'Oct 10, 2024'
|
||||||
|
},
|
||||||
|
approvalFlow: [
|
||||||
|
{
|
||||||
|
step: 1,
|
||||||
|
approver: 'Royal Motors Mumbai (Dealer)',
|
||||||
|
role: 'Dealer - Document Upload',
|
||||||
|
status: 'pending',
|
||||||
|
tatHours: 72,
|
||||||
|
elapsedHours: 12,
|
||||||
|
assignedAt: '2024-10-07T09:30:00Z',
|
||||||
|
comment: null,
|
||||||
|
timestamp: null,
|
||||||
|
description: 'Dealer uploads proposal document, cost breakup, timeline for closure, and other supporting documents'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
step: 2,
|
||||||
|
approver: 'Sneha Patil (Initiator)',
|
||||||
|
role: 'Initiator Evaluation',
|
||||||
|
status: 'waiting',
|
||||||
|
tatHours: 48,
|
||||||
|
elapsedHours: 0,
|
||||||
|
assignedAt: null,
|
||||||
|
comment: null,
|
||||||
|
timestamp: null,
|
||||||
|
description: 'Initiator reviews dealer documents and approves or requests modifications'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
step: 3,
|
||||||
|
approver: 'System Auto-Process',
|
||||||
|
role: 'IO Confirmation',
|
||||||
|
status: 'waiting',
|
||||||
|
tatHours: 1,
|
||||||
|
elapsedHours: 0,
|
||||||
|
assignedAt: null,
|
||||||
|
comment: null,
|
||||||
|
timestamp: null,
|
||||||
|
description: 'Automatic IO (Internal Order) confirmation generated upon initiator approval'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
step: 4,
|
||||||
|
approver: 'Rajesh Kumar',
|
||||||
|
role: 'Department Lead Approval',
|
||||||
|
status: 'waiting',
|
||||||
|
tatHours: 72,
|
||||||
|
elapsedHours: 0,
|
||||||
|
assignedAt: null,
|
||||||
|
comment: null,
|
||||||
|
timestamp: null,
|
||||||
|
description: 'Department head approves and blocks budget in IO for this activity'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
step: 5,
|
||||||
|
approver: 'Royal Motors Mumbai (Dealer)',
|
||||||
|
role: 'Dealer - Completion Documents',
|
||||||
|
status: 'waiting',
|
||||||
|
tatHours: 120,
|
||||||
|
elapsedHours: 0,
|
||||||
|
assignedAt: null,
|
||||||
|
comment: null,
|
||||||
|
timestamp: null,
|
||||||
|
description: 'Dealer submits activity completion documents and description'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
step: 6,
|
||||||
|
approver: 'Sneha Patil (Initiator)',
|
||||||
|
role: 'Initiator Verification',
|
||||||
|
status: 'waiting',
|
||||||
|
tatHours: 48,
|
||||||
|
elapsedHours: 0,
|
||||||
|
assignedAt: null,
|
||||||
|
comment: null,
|
||||||
|
timestamp: null,
|
||||||
|
description: 'Initiator verifies completion documents and can modify approved amount'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
step: 7,
|
||||||
|
approver: 'System Auto-Process',
|
||||||
|
role: 'E-Invoice Generation',
|
||||||
|
status: 'waiting',
|
||||||
|
tatHours: 1,
|
||||||
|
elapsedHours: 0,
|
||||||
|
assignedAt: null,
|
||||||
|
comment: null,
|
||||||
|
timestamp: null,
|
||||||
|
description: 'Auto-generate e-invoice based on final approved amount'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
step: 8,
|
||||||
|
approver: 'Meera Patel',
|
||||||
|
role: 'Finance - Credit Note Issuance',
|
||||||
|
status: 'waiting',
|
||||||
|
tatHours: 48,
|
||||||
|
elapsedHours: 0,
|
||||||
|
assignedAt: null,
|
||||||
|
comment: null,
|
||||||
|
timestamp: null,
|
||||||
|
description: 'Finance team issues credit note to dealer'
|
||||||
|
}
|
||||||
|
],
|
||||||
|
documents: [
|
||||||
|
{ name: 'Claim_Proposal_Diwali_2024.pdf', size: '1.8 MB', type: 'PDF', uploadedBy: 'Sneha Patil', uploadedAt: 'Oct 7, 2024 9:35 AM' },
|
||||||
|
{ name: 'Cost_Breakup_Detailed.xlsx', size: '450 KB', type: 'Excel', uploadedBy: 'Sneha Patil', uploadedAt: 'Oct 7, 2024 9:38 AM' },
|
||||||
|
{ name: 'Activity_Timeline.pdf', size: '320 KB', type: 'PDF', uploadedBy: 'Sneha Patil', uploadedAt: 'Oct 7, 2024 9:40 AM' }
|
||||||
|
],
|
||||||
|
spectators: [
|
||||||
|
{ name: 'Arjun Menon', role: 'Brand Manager', avatar: 'AM' },
|
||||||
|
{ name: 'Finance Team', role: 'Budget Monitoring', avatar: 'FT' }
|
||||||
|
],
|
||||||
|
auditTrail: [
|
||||||
|
{ type: 'created', action: 'Claim Request Created', details: 'Diwali festival campaign claim initiated using Claim Management template', user: 'Sneha Patil', timestamp: 'Oct 7, 2024 9:30 AM' },
|
||||||
|
{ type: 'assignment', action: 'Assigned to Dealer', details: 'Dealer Royal Motors Mumbai assigned for document upload', user: 'System', timestamp: 'Oct 7, 2024 9:31 AM' },
|
||||||
|
{ type: 'status_change', action: 'Workflow Started', details: 'Step 1: Dealer document upload phase initiated', user: 'System', timestamp: 'Oct 7, 2024 9:31 AM' }
|
||||||
|
],
|
||||||
|
tags: ['claim-management', 'dealer-activity', 'marketing', 'diwali-campaign', 'template']
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
// API Endpoints for Claim Management (to be implemented with backend)
|
// API Endpoints for Claim Management (to be implemented with backend)
|
||||||
export const CLAIM_MANAGEMENT_API_ENDPOINTS = {
|
export const CLAIM_MANAGEMENT_API_ENDPOINTS = {
|
||||||
|
|||||||
@ -2,7 +2,720 @@
|
|||||||
// This database is exclusively for custom requests created via NewRequestWizard
|
// This database is exclusively for custom requests created via NewRequestWizard
|
||||||
// Users define their own workflow, approvers, spectators, and tagged participants
|
// Users define their own workflow, approvers, spectators, and tagged participants
|
||||||
|
|
||||||
export const CUSTOM_REQUEST_DATABASE: any = {};
|
export const CUSTOM_REQUEST_DATABASE: any = {
|
||||||
|
'RE-REQ-2024-001': {
|
||||||
|
id: 'RE-REQ-2024-001',
|
||||||
|
title: 'Himalayan 450 Launch Campaign - Digital Media Blitz',
|
||||||
|
description: 'Comprehensive digital marketing campaign for Himalayan 450 adventure motorcycle launch. Includes social media campaigns, influencer partnerships, performance marketing, content creation, and digital advertising across platforms. Target: Reach 10M adventure enthusiasts across India.\n\nEquipment Specifications:\n• 10x MacBook Pro 16-inch (M2 Pro chip)\n• 5x Professional Camera Kits (Canon EOS R5)\n• Video Editing Workstations\n• Social Media Management Tools',
|
||||||
|
category: 'Marketing & Campaigns',
|
||||||
|
subcategory: 'Digital Marketing',
|
||||||
|
status: 'pending',
|
||||||
|
priority: 'express',
|
||||||
|
amount: '₹3,75,00,000',
|
||||||
|
slaProgress: 65,
|
||||||
|
slaRemaining: '8 hours 45 minutes',
|
||||||
|
slaEndDate: 'Oct 9, 2024 5:00 PM',
|
||||||
|
currentStep: 1,
|
||||||
|
totalSteps: 3,
|
||||||
|
template: 'custom',
|
||||||
|
initiator: {
|
||||||
|
name: 'Priya Sharma',
|
||||||
|
role: 'Senior Digital Marketing Manager',
|
||||||
|
department: 'Marketing',
|
||||||
|
email: 'priya.sharma@royalenfield.com',
|
||||||
|
phone: '+91 98765 43210',
|
||||||
|
avatar: 'PS'
|
||||||
|
},
|
||||||
|
department: 'Marketing',
|
||||||
|
createdAt: 'Oct 6, 2024 10:30 AM',
|
||||||
|
updatedAt: 'Oct 7, 2024 2:15 PM',
|
||||||
|
dueDate: '2024-10-09T17:00:00Z',
|
||||||
|
conclusionRemark: '',
|
||||||
|
approvalFlow: [
|
||||||
|
{
|
||||||
|
step: 1,
|
||||||
|
approver: 'Rajesh Kumar',
|
||||||
|
role: 'Marketing Director - India',
|
||||||
|
status: 'pending',
|
||||||
|
tatHours: 24,
|
||||||
|
elapsedHours: 22,
|
||||||
|
assignedAt: '2024-10-06T10:30:00Z',
|
||||||
|
comment: null,
|
||||||
|
timestamp: null
|
||||||
|
},
|
||||||
|
{
|
||||||
|
step: 2,
|
||||||
|
approver: 'Amit Desai',
|
||||||
|
role: 'VP Product Marketing',
|
||||||
|
status: 'waiting',
|
||||||
|
tatHours: 48,
|
||||||
|
elapsedHours: 0,
|
||||||
|
assignedAt: null,
|
||||||
|
comment: null,
|
||||||
|
timestamp: null
|
||||||
|
},
|
||||||
|
{
|
||||||
|
step: 3,
|
||||||
|
approver: 'Deepika Sharma',
|
||||||
|
role: 'VP Sales & Marketing',
|
||||||
|
status: 'waiting',
|
||||||
|
tatHours: 72,
|
||||||
|
elapsedHours: 0,
|
||||||
|
assignedAt: null,
|
||||||
|
comment: null,
|
||||||
|
timestamp: null
|
||||||
|
}
|
||||||
|
],
|
||||||
|
documents: [
|
||||||
|
{ name: 'Himalayan_450_Digital_Strategy.pdf', size: '5.2 MB', type: 'PDF', uploadedBy: 'Priya Sharma', uploadedAt: 'Oct 6, 2024 10:45 AM' },
|
||||||
|
{ name: 'Budget_Breakdown_Q4_2024.xlsx', size: '980 KB', type: 'Excel', uploadedBy: 'Priya Sharma', uploadedAt: 'Oct 6, 2024 11:15 AM' },
|
||||||
|
{ name: 'Influencer_Partnership_List.xlsx', size: '450 KB', type: 'Excel', uploadedBy: 'Marketing Team', uploadedAt: 'Oct 6, 2024 2:30 PM' },
|
||||||
|
{ name: 'Creative_Campaign_Assets.zip', size: '125 MB', type: 'ZIP', uploadedBy: 'Creative Team', uploadedAt: 'Oct 6, 2024 4:15 PM' }
|
||||||
|
],
|
||||||
|
spectators: [
|
||||||
|
{ name: 'Sarah Khan', role: 'Brand Strategy Lead', avatar: 'SK' },
|
||||||
|
{ name: 'Finance Team', role: 'Budget Approval', avatar: 'FT' }
|
||||||
|
],
|
||||||
|
auditTrail: [
|
||||||
|
{ type: 'created', action: 'Request Created', details: 'New digital marketing campaign request submitted', user: 'Priya Sharma', timestamp: 'Oct 6, 2024 10:30 AM' },
|
||||||
|
{ type: 'assignment', action: 'Assigned to Rajesh Kumar', details: 'Forwarded to Marketing Director for review', user: 'System', timestamp: 'Oct 6, 2024 10:31 AM' },
|
||||||
|
{ type: 'comment', action: 'Work Note Added', details: 'Reviewed budget allocation and target metrics', user: 'Rajesh Kumar', timestamp: 'Oct 7, 2024 2:15 PM' },
|
||||||
|
{ type: 'reminder', action: 'SLA Reminder', details: 'TAT approaching - 8 hours remaining', user: 'System', timestamp: 'Oct 7, 2024 8:15 AM' }
|
||||||
|
],
|
||||||
|
tags: ['digital-marketing', 'launch-campaign', 'himalayan-450', 'high-priority']
|
||||||
|
},
|
||||||
|
|
||||||
|
'RE-REQ-2024-002': {
|
||||||
|
id: 'RE-REQ-2024-002',
|
||||||
|
title: 'New Laptop Procurement - Design Team Expansion',
|
||||||
|
description: 'Purchase of 10 high-performance laptops for the newly expanded Product Design team. Required specifications: Latest generation processor, 32GB RAM, dedicated graphics card for 3D modeling and rendering work.',
|
||||||
|
category: 'IT & Infrastructure',
|
||||||
|
subcategory: 'Hardware Procurement',
|
||||||
|
status: 'in-review',
|
||||||
|
priority: 'standard',
|
||||||
|
amount: '₹12,50,000',
|
||||||
|
slaProgress: 45,
|
||||||
|
slaRemaining: '2 days 8 hours',
|
||||||
|
slaEndDate: 'Oct 11, 2024 5:00 PM',
|
||||||
|
currentStep: 2,
|
||||||
|
totalSteps: 3,
|
||||||
|
template: 'custom',
|
||||||
|
initiator: {
|
||||||
|
name: 'Vikram Singh',
|
||||||
|
role: 'Head - IT Operations',
|
||||||
|
department: 'Information Technology',
|
||||||
|
email: 'vikram.singh@royalenfield.com',
|
||||||
|
phone: '+91 98765 43221',
|
||||||
|
avatar: 'VS'
|
||||||
|
},
|
||||||
|
department: 'Information Technology',
|
||||||
|
createdAt: 'Oct 5, 2024 9:15 AM',
|
||||||
|
updatedAt: 'Oct 7, 2024 3:45 PM',
|
||||||
|
dueDate: '2024-10-11T17:00:00Z',
|
||||||
|
conclusionRemark: '',
|
||||||
|
approvalFlow: [
|
||||||
|
{
|
||||||
|
step: 1,
|
||||||
|
approver: 'Meera Patel',
|
||||||
|
role: 'IT Manager',
|
||||||
|
status: 'approved',
|
||||||
|
tatHours: 24,
|
||||||
|
actualHours: 18,
|
||||||
|
assignedAt: '2024-10-05T09:15:00Z',
|
||||||
|
comment: 'Technical specifications verified. Hardware meets design team requirements.',
|
||||||
|
timestamp: '2024-10-06T03:15:00Z'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
step: 2,
|
||||||
|
approver: 'Anil Kapoor',
|
||||||
|
role: 'Finance Manager',
|
||||||
|
status: 'in-review',
|
||||||
|
tatHours: 48,
|
||||||
|
elapsedHours: 32,
|
||||||
|
assignedAt: '2024-10-06T03:15:00Z',
|
||||||
|
comment: null,
|
||||||
|
timestamp: null
|
||||||
|
},
|
||||||
|
{
|
||||||
|
step: 3,
|
||||||
|
approver: 'Ramesh Kulkarni',
|
||||||
|
role: 'VP Operations',
|
||||||
|
status: 'waiting',
|
||||||
|
tatHours: 72,
|
||||||
|
elapsedHours: 0,
|
||||||
|
assignedAt: null,
|
||||||
|
comment: null,
|
||||||
|
timestamp: null
|
||||||
|
}
|
||||||
|
],
|
||||||
|
documents: [
|
||||||
|
{ name: 'Laptop_Specifications.pdf', size: '850 KB', type: 'PDF', uploadedBy: 'Vikram Singh', uploadedAt: 'Oct 5, 2024 9:20 AM' },
|
||||||
|
{ name: 'Vendor_Quotations.xlsx', size: '1.2 MB', type: 'Excel', uploadedBy: 'Procurement Team', uploadedAt: 'Oct 5, 2024 11:45 AM' },
|
||||||
|
{ name: 'Team_Expansion_Plan.pdf', size: '620 KB', type: 'PDF', uploadedBy: 'Design Team', uploadedAt: 'Oct 5, 2024 2:30 PM' }
|
||||||
|
],
|
||||||
|
spectators: [
|
||||||
|
{ name: 'Design Team Lead', role: 'End Users', avatar: 'DT' },
|
||||||
|
{ name: 'Procurement Team', role: 'Vendor Management', avatar: 'PT' }
|
||||||
|
],
|
||||||
|
auditTrail: [
|
||||||
|
{ type: 'created', action: 'Request Created', details: 'Laptop procurement request for design team', user: 'Vikram Singh', timestamp: 'Oct 5, 2024 9:15 AM' },
|
||||||
|
{ type: 'assignment', action: 'Assigned to Meera Patel', details: 'IT Manager to verify specifications', user: 'System', timestamp: 'Oct 5, 2024 9:16 AM' },
|
||||||
|
{ type: 'approval', action: 'Approved by Meera Patel', details: 'Technical specifications approved', user: 'Meera Patel', timestamp: 'Oct 6, 2024 3:15 AM' },
|
||||||
|
{ type: 'assignment', action: 'Assigned to Anil Kapoor', details: 'Forwarded to Finance for budget approval', user: 'System', timestamp: 'Oct 6, 2024 3:15 AM' }
|
||||||
|
],
|
||||||
|
tags: ['hardware', 'procurement', 'design-team', 'laptops']
|
||||||
|
},
|
||||||
|
|
||||||
|
'RE-REQ-2024-003': {
|
||||||
|
id: 'RE-REQ-2024-003',
|
||||||
|
title: 'Annual Service Center Expansion - Western Region',
|
||||||
|
description: 'Proposal for opening 15 new authorized service centers across tier-2 cities in Western region. Includes infrastructure setup, technician training, spare parts inventory, and marketing support. Expected to improve service accessibility by 35% in the target region.',
|
||||||
|
category: 'Operations & Expansion',
|
||||||
|
subcategory: 'Service Network',
|
||||||
|
status: 'pending',
|
||||||
|
priority: 'standard',
|
||||||
|
amount: '₹8,75,00,000',
|
||||||
|
slaProgress: 78,
|
||||||
|
slaRemaining: '1 day 4 hours',
|
||||||
|
slaEndDate: 'Oct 10, 2024 5:00 PM',
|
||||||
|
currentStep: 1,
|
||||||
|
totalSteps: 4,
|
||||||
|
template: 'custom',
|
||||||
|
initiator: {
|
||||||
|
name: 'Sanjay Reddy',
|
||||||
|
role: 'Regional Service Manager - West',
|
||||||
|
department: 'After Sales Service',
|
||||||
|
email: 'sanjay.reddy@royalenfield.com',
|
||||||
|
phone: '+91 98765 43232',
|
||||||
|
avatar: 'SR'
|
||||||
|
},
|
||||||
|
department: 'After Sales Service',
|
||||||
|
createdAt: 'Oct 3, 2024 8:45 AM',
|
||||||
|
updatedAt: 'Oct 6, 2024 5:45 PM',
|
||||||
|
dueDate: '2024-10-10T17:00:00Z',
|
||||||
|
conclusionRemark: '',
|
||||||
|
approvalFlow: [
|
||||||
|
{
|
||||||
|
step: 1,
|
||||||
|
approver: 'Ramesh Kulkarni',
|
||||||
|
role: 'Head - After Sales Service',
|
||||||
|
status: 'pending',
|
||||||
|
tatHours: 72,
|
||||||
|
elapsedHours: 85,
|
||||||
|
assignedAt: '2024-10-03T08:45:00Z',
|
||||||
|
comment: null,
|
||||||
|
timestamp: null
|
||||||
|
},
|
||||||
|
{
|
||||||
|
step: 2,
|
||||||
|
approver: 'Finance Team',
|
||||||
|
role: 'Budget Allocation',
|
||||||
|
status: 'waiting',
|
||||||
|
tatHours: 96,
|
||||||
|
elapsedHours: 0,
|
||||||
|
assignedAt: null,
|
||||||
|
comment: null,
|
||||||
|
timestamp: null
|
||||||
|
},
|
||||||
|
{
|
||||||
|
step: 3,
|
||||||
|
approver: 'Legal Team',
|
||||||
|
role: 'Compliance Review',
|
||||||
|
status: 'waiting',
|
||||||
|
tatHours: 120,
|
||||||
|
elapsedHours: 0,
|
||||||
|
assignedAt: null,
|
||||||
|
comment: null,
|
||||||
|
timestamp: null
|
||||||
|
},
|
||||||
|
{
|
||||||
|
step: 4,
|
||||||
|
approver: 'Deepika Sharma',
|
||||||
|
role: 'VP Sales & Marketing',
|
||||||
|
status: 'waiting',
|
||||||
|
tatHours: 72,
|
||||||
|
elapsedHours: 0,
|
||||||
|
assignedAt: null,
|
||||||
|
comment: null,
|
||||||
|
timestamp: null
|
||||||
|
}
|
||||||
|
],
|
||||||
|
documents: [
|
||||||
|
{ name: 'Western_Region_Expansion_Plan.pdf', size: '7.5 MB', type: 'PDF', uploadedBy: 'Sanjay Reddy', uploadedAt: 'Oct 3, 2024 9:00 AM' },
|
||||||
|
{ name: 'Service_Center_Requirements.xlsx', size: '2.8 MB', type: 'Excel', uploadedBy: 'Planning Team', uploadedAt: 'Oct 3, 2024 11:30 AM' },
|
||||||
|
{ name: 'Customer_Demand_Analysis.pptx', size: '4.2 MB', type: 'PowerPoint', uploadedBy: 'Analytics Team', uploadedAt: 'Oct 4, 2024 2:15 PM' },
|
||||||
|
{ name: 'ROI_Projections_Service_Network.xlsx', size: '1.9 MB', type: 'Excel', uploadedBy: 'Finance Team', uploadedAt: 'Oct 5, 2024 10:45 AM' }
|
||||||
|
],
|
||||||
|
spectators: [
|
||||||
|
{ name: 'Regional Managers', role: 'Service Operations', avatar: 'RM' },
|
||||||
|
{ name: 'Training Team', role: 'Technician Development', avatar: 'TT' }
|
||||||
|
],
|
||||||
|
auditTrail: [
|
||||||
|
{ type: 'created', action: 'Request Created', details: 'Service center expansion proposal submitted', user: 'Sanjay Reddy', timestamp: 'Oct 3, 2024 8:45 AM' },
|
||||||
|
{ type: 'assignment', action: 'Assigned to Ramesh Kulkarni', details: 'Forwarded to Head of After Sales Service', user: 'System', timestamp: 'Oct 3, 2024 8:46 AM' },
|
||||||
|
{ type: 'reminder', action: 'Reminder Sent', details: 'TAT breach reminder sent to approver', user: 'System', timestamp: 'Oct 6, 2024 5:45 PM' },
|
||||||
|
{ type: 'updated', action: 'Additional Documents', details: 'ROI projections added by finance team', user: 'Finance Team', timestamp: 'Oct 5, 2024 10:45 AM' }
|
||||||
|
],
|
||||||
|
tags: ['service-expansion', 'western-region', 'tier2-cities', 'overdue']
|
||||||
|
},
|
||||||
|
|
||||||
|
'RE-REQ-2024-004': {
|
||||||
|
id: 'RE-REQ-2024-004',
|
||||||
|
title: 'Employee Training Program - Advanced Motorcycle Mechanics',
|
||||||
|
description: 'Comprehensive training program for 50 service center technicians covering advanced diagnostics, electrical systems, fuel injection troubleshooting, and customer service excellence. Program duration: 3 weeks. Includes certification upon completion.',
|
||||||
|
category: 'Human Resources',
|
||||||
|
subcategory: 'Training & Development',
|
||||||
|
status: 'approved',
|
||||||
|
priority: 'standard',
|
||||||
|
amount: '₹18,50,000',
|
||||||
|
slaProgress: 100,
|
||||||
|
slaRemaining: 'Completed',
|
||||||
|
slaEndDate: 'Oct 5, 2024 5:00 PM',
|
||||||
|
currentStep: 3,
|
||||||
|
totalSteps: 3,
|
||||||
|
template: 'custom',
|
||||||
|
initiator: {
|
||||||
|
name: 'Kavita Menon',
|
||||||
|
role: 'Training Manager',
|
||||||
|
department: 'Human Resources',
|
||||||
|
email: 'kavita.menon@royalenfield.com',
|
||||||
|
phone: '+91 98765 43243',
|
||||||
|
avatar: 'KM'
|
||||||
|
},
|
||||||
|
department: 'Human Resources',
|
||||||
|
createdAt: 'Sep 28, 2024 11:00 AM',
|
||||||
|
updatedAt: 'Oct 5, 2024 4:30 PM',
|
||||||
|
dueDate: '2024-10-05T17:00:00Z',
|
||||||
|
submittedDate: '2024-09-28T11:00:00Z',
|
||||||
|
estimatedCompletion: 'Oct 5, 2024',
|
||||||
|
currentApprover: 'Completed',
|
||||||
|
approverLevel: '3 of 3',
|
||||||
|
conclusionRemark: 'All approvals completed. Training program scheduled for November 2024.',
|
||||||
|
approvalFlow: [
|
||||||
|
{
|
||||||
|
step: 1,
|
||||||
|
approver: 'Ramesh Kulkarni',
|
||||||
|
role: 'Head - After Sales Service',
|
||||||
|
status: 'approved',
|
||||||
|
tatHours: 48,
|
||||||
|
actualHours: 36,
|
||||||
|
assignedAt: '2024-09-28T11:00:00Z',
|
||||||
|
comment: 'Excellent initiative. Training content approved.',
|
||||||
|
timestamp: 'Sep 29, 2024 11:00 PM'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
step: 2,
|
||||||
|
approver: 'Anil Kapoor',
|
||||||
|
role: 'Finance Manager',
|
||||||
|
status: 'approved',
|
||||||
|
tatHours: 72,
|
||||||
|
actualHours: 48,
|
||||||
|
assignedAt: '2024-09-29T23:00:00Z',
|
||||||
|
comment: 'Budget approved. Cost per participant is reasonable.',
|
||||||
|
timestamp: 'Oct 1, 2024 11:00 PM'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
step: 3,
|
||||||
|
approver: 'Deepika Sharma',
|
||||||
|
role: 'VP Sales & Marketing',
|
||||||
|
status: 'approved',
|
||||||
|
tatHours: 96,
|
||||||
|
actualHours: 72,
|
||||||
|
assignedAt: '2024-10-01T23:00:00Z',
|
||||||
|
comment: 'Final approval granted. Proceed with program execution.',
|
||||||
|
timestamp: 'Oct 5, 2024 4:30 PM'
|
||||||
|
}
|
||||||
|
],
|
||||||
|
documents: [
|
||||||
|
{ name: 'Training_Curriculum.pdf', size: '3.2 MB', type: 'PDF', uploadedBy: 'Kavita Menon', uploadedAt: 'Sep 28, 2024 11:15 AM' },
|
||||||
|
{ name: 'Trainer_Profiles.pdf', size: '1.8 MB', type: 'PDF', uploadedBy: 'HR Team', uploadedAt: 'Sep 28, 2024 2:45 PM' },
|
||||||
|
{ name: 'Budget_Training_Program.xlsx', size: '680 KB', type: 'Excel', uploadedBy: 'Finance Team', uploadedAt: 'Sep 29, 2024 10:30 AM' }
|
||||||
|
],
|
||||||
|
spectators: [
|
||||||
|
{ name: 'Service Center Managers', role: 'Participant Coordination', avatar: 'SC' },
|
||||||
|
{ name: 'Quality Assurance', role: 'Training Quality', avatar: 'QA' }
|
||||||
|
],
|
||||||
|
auditTrail: [
|
||||||
|
{ type: 'created', action: 'Request Created', details: 'Training program proposal submitted', user: 'Kavita Menon', timestamp: 'Sep 28, 2024 11:00 AM' },
|
||||||
|
{ type: 'assignment', action: 'Assigned to Ramesh Kulkarni', details: 'Forwarded to After Sales Service Head', user: 'System', timestamp: 'Sep 28, 2024 11:01 AM' },
|
||||||
|
{ type: 'approval', action: 'Approved by Ramesh Kulkarni', details: 'Level 1 approval completed', user: 'Ramesh Kulkarni', timestamp: 'Sep 29, 2024 11:00 PM' },
|
||||||
|
{ type: 'assignment', action: 'Assigned to Anil Kapoor', details: 'Forwarded to Finance Manager', user: 'System', timestamp: 'Sep 29, 2024 11:01 PM' },
|
||||||
|
{ type: 'approval', action: 'Approved by Anil Kapoor', details: 'Budget approval completed', user: 'Anil Kapoor', timestamp: 'Oct 1, 2024 11:00 PM' },
|
||||||
|
{ type: 'assignment', action: 'Assigned to Deepika Sharma', details: 'Forwarded to VP for final approval', user: 'System', timestamp: 'Oct 1, 2024 11:01 PM' },
|
||||||
|
{ type: 'approval', action: 'Approved by Deepika Sharma', details: 'Final approval - Request completed', user: 'Deepika Sharma', timestamp: 'Oct 5, 2024 4:30 PM' },
|
||||||
|
{ type: 'completed', action: 'Request Completed', details: 'All approvals obtained. Training scheduled.', user: 'System', timestamp: 'Oct 5, 2024 4:31 PM' }
|
||||||
|
],
|
||||||
|
tags: ['training', 'technicians', 'approved', 'completed']
|
||||||
|
},
|
||||||
|
|
||||||
|
'RE-REQ-2024-005': {
|
||||||
|
id: 'RE-REQ-2024-005',
|
||||||
|
title: 'Showroom Renovation - Chennai Flagship Store',
|
||||||
|
description: 'Complete renovation of Chennai flagship showroom including modern interior design, interactive display zones, customer lounge upgrade, motorcycle test ride facility, and digital experience center. Project timeline: 8 weeks.',
|
||||||
|
category: 'Infrastructure',
|
||||||
|
subcategory: 'Retail & Showroom',
|
||||||
|
status: 'rejected',
|
||||||
|
priority: 'standard',
|
||||||
|
amount: '₹65,00,000',
|
||||||
|
slaProgress: 100,
|
||||||
|
slaRemaining: 'Rejected',
|
||||||
|
slaEndDate: 'Oct 4, 2024 5:00 PM',
|
||||||
|
currentStep: 2,
|
||||||
|
totalSteps: 4,
|
||||||
|
template: 'custom',
|
||||||
|
initiator: {
|
||||||
|
name: 'Arjun Nair',
|
||||||
|
role: 'Showroom Manager - South',
|
||||||
|
department: 'Retail Operations',
|
||||||
|
email: 'arjun.nair@royalenfield.com',
|
||||||
|
phone: '+91 98765 43254',
|
||||||
|
avatar: 'AN'
|
||||||
|
},
|
||||||
|
department: 'Retail Operations',
|
||||||
|
createdAt: 'Oct 1, 2024 9:30 AM',
|
||||||
|
updatedAt: 'Oct 4, 2024 3:15 PM',
|
||||||
|
dueDate: '2024-10-04T17:00:00Z',
|
||||||
|
submittedDate: '2024-10-01T09:30:00Z',
|
||||||
|
estimatedCompletion: 'N/A',
|
||||||
|
currentApprover: 'Rejected by Anil Kapoor',
|
||||||
|
approverLevel: '2 of 4',
|
||||||
|
conclusionRemark: 'Request rejected due to insufficient budget justification. Please revise with detailed ROI analysis.',
|
||||||
|
approvalFlow: [
|
||||||
|
{
|
||||||
|
step: 1,
|
||||||
|
approver: 'Suresh Iyer',
|
||||||
|
role: 'Regional Manager - South',
|
||||||
|
status: 'approved',
|
||||||
|
tatHours: 48,
|
||||||
|
actualHours: 24,
|
||||||
|
assignedAt: '2024-10-01T09:30:00Z',
|
||||||
|
comment: 'Renovation is necessary. Current showroom needs upgrade.',
|
||||||
|
timestamp: 'Oct 2, 2024 9:30 AM'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
step: 2,
|
||||||
|
approver: 'Anil Kapoor',
|
||||||
|
role: 'Finance Manager',
|
||||||
|
status: 'rejected',
|
||||||
|
tatHours: 72,
|
||||||
|
actualHours: 48,
|
||||||
|
assignedAt: '2024-10-02T09:30:00Z',
|
||||||
|
comment: 'Budget allocation not justified. Need detailed ROI analysis and comparison with alternative renovation options. Please revise and resubmit with comprehensive financial projections.',
|
||||||
|
timestamp: 'Oct 4, 2024 3:15 PM'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
step: 3,
|
||||||
|
approver: 'Legal Team',
|
||||||
|
role: 'Compliance & Contracts',
|
||||||
|
status: 'cancelled',
|
||||||
|
tatHours: 96,
|
||||||
|
elapsedHours: 0,
|
||||||
|
assignedAt: null,
|
||||||
|
comment: null,
|
||||||
|
timestamp: null
|
||||||
|
},
|
||||||
|
{
|
||||||
|
step: 4,
|
||||||
|
approver: 'Ramesh Kulkarni',
|
||||||
|
role: 'VP Operations',
|
||||||
|
status: 'cancelled',
|
||||||
|
tatHours: 72,
|
||||||
|
elapsedHours: 0,
|
||||||
|
assignedAt: null,
|
||||||
|
comment: null,
|
||||||
|
timestamp: null
|
||||||
|
}
|
||||||
|
],
|
||||||
|
documents: [
|
||||||
|
{ name: 'Showroom_Renovation_Plan.pdf', size: '12.5 MB', type: 'PDF', uploadedBy: 'Arjun Nair', uploadedAt: 'Oct 1, 2024 9:45 AM' },
|
||||||
|
{ name: 'Interior_Design_Mockups.zip', size: '85 MB', type: 'ZIP', uploadedBy: 'Design Team', uploadedAt: 'Oct 1, 2024 2:30 PM' },
|
||||||
|
{ name: 'Contractor_Quotations.xlsx', size: '2.1 MB', type: 'Excel', uploadedBy: 'Procurement Team', uploadedAt: 'Oct 2, 2024 11:15 AM' }
|
||||||
|
],
|
||||||
|
spectators: [
|
||||||
|
{ name: 'Marketing Team', role: 'Brand Experience', avatar: 'MT' },
|
||||||
|
{ name: 'Customer Experience', role: 'Feedback & Analysis', avatar: 'CX' }
|
||||||
|
],
|
||||||
|
auditTrail: [
|
||||||
|
{ type: 'created', action: 'Request Created', details: 'Showroom renovation request submitted', user: 'Arjun Nair', timestamp: 'Oct 1, 2024 9:30 AM' },
|
||||||
|
{ type: 'assignment', action: 'Assigned to Suresh Iyer', details: 'Forwarded to Regional Manager', user: 'System', timestamp: 'Oct 1, 2024 9:31 AM' },
|
||||||
|
{ type: 'approval', action: 'Approved by Suresh Iyer', details: 'Level 1 approval completed', user: 'Suresh Iyer', timestamp: 'Oct 2, 2024 9:30 AM' },
|
||||||
|
{ type: 'assignment', action: 'Assigned to Anil Kapoor', details: 'Forwarded to Finance Manager', user: 'System', timestamp: 'Oct 2, 2024 9:31 AM' },
|
||||||
|
{ type: 'rejection', action: 'Rejected by Anil Kapoor', details: 'Budget justification insufficient', user: 'Anil Kapoor', timestamp: 'Oct 4, 2024 3:15 PM' },
|
||||||
|
{ type: 'completed', action: 'Request Rejected', details: 'Workflow terminated. Requires resubmission with revisions.', user: 'System', timestamp: 'Oct 4, 2024 3:16 PM' }
|
||||||
|
],
|
||||||
|
tags: ['showroom', 'renovation', 'rejected', 'south-region']
|
||||||
|
},
|
||||||
|
|
||||||
|
'RE-REQ-2024-006': {
|
||||||
|
id: 'RE-REQ-2024-006',
|
||||||
|
title: 'Spare Parts Inventory Optimization System',
|
||||||
|
description: 'Implementation of AI-powered inventory management system for spare parts across all service centers. Features include demand forecasting, automated reordering, stock level optimization, and real-time tracking. Expected to reduce inventory costs by 20% and improve part availability.',
|
||||||
|
category: 'Technology & Innovation',
|
||||||
|
subcategory: 'Software Implementation',
|
||||||
|
status: 'pending',
|
||||||
|
priority: 'express',
|
||||||
|
amount: '₹42,00,000',
|
||||||
|
slaProgress: 35,
|
||||||
|
slaRemaining: '1 day 16 hours',
|
||||||
|
slaEndDate: 'Oct 12, 2024 5:00 PM',
|
||||||
|
currentStep: 1,
|
||||||
|
totalSteps: 4,
|
||||||
|
template: 'custom',
|
||||||
|
initiator: {
|
||||||
|
name: 'Rahul Deshmukh',
|
||||||
|
role: 'Head - Supply Chain Technology',
|
||||||
|
department: 'Supply Chain',
|
||||||
|
email: 'rahul.deshmukh@royalenfield.com',
|
||||||
|
phone: '+91 98765 43265',
|
||||||
|
avatar: 'RD'
|
||||||
|
},
|
||||||
|
department: 'Supply Chain',
|
||||||
|
createdAt: 'Oct 7, 2024 10:00 AM',
|
||||||
|
updatedAt: 'Oct 8, 2024 9:15 AM',
|
||||||
|
dueDate: '2024-10-12T17:00:00Z',
|
||||||
|
submittedDate: '2024-10-07T10:00:00Z',
|
||||||
|
estimatedCompletion: 'Oct 12, 2024',
|
||||||
|
currentApprover: 'Vikram Singh',
|
||||||
|
approverLevel: '1 of 4',
|
||||||
|
conclusionRemark: '',
|
||||||
|
approvalFlow: [
|
||||||
|
{
|
||||||
|
step: 1,
|
||||||
|
approver: 'Vikram Singh',
|
||||||
|
role: 'Head - IT Operations',
|
||||||
|
status: 'pending',
|
||||||
|
tatHours: 48,
|
||||||
|
elapsedHours: 23,
|
||||||
|
assignedAt: '2024-10-07T10:00:00Z',
|
||||||
|
comment: null,
|
||||||
|
timestamp: null
|
||||||
|
},
|
||||||
|
{
|
||||||
|
step: 2,
|
||||||
|
approver: 'Supply Chain Director',
|
||||||
|
role: 'Operations Approval',
|
||||||
|
status: 'waiting',
|
||||||
|
tatHours: 72,
|
||||||
|
elapsedHours: 0,
|
||||||
|
assignedAt: null,
|
||||||
|
comment: null,
|
||||||
|
timestamp: null
|
||||||
|
},
|
||||||
|
{
|
||||||
|
step: 3,
|
||||||
|
approver: 'Anil Kapoor',
|
||||||
|
role: 'Finance Manager',
|
||||||
|
status: 'waiting',
|
||||||
|
tatHours: 96,
|
||||||
|
elapsedHours: 0,
|
||||||
|
assignedAt: null,
|
||||||
|
comment: null,
|
||||||
|
timestamp: null
|
||||||
|
},
|
||||||
|
{
|
||||||
|
step: 4,
|
||||||
|
approver: 'Ramesh Kulkarni',
|
||||||
|
role: 'VP Operations',
|
||||||
|
status: 'waiting',
|
||||||
|
tatHours: 72,
|
||||||
|
elapsedHours: 0,
|
||||||
|
assignedAt: null,
|
||||||
|
comment: null,
|
||||||
|
timestamp: null
|
||||||
|
}
|
||||||
|
],
|
||||||
|
documents: [
|
||||||
|
{ name: 'AI_Inventory_System_Proposal.pdf', size: '8.9 MB', type: 'PDF', uploadedBy: 'Rahul Deshmukh', uploadedAt: 'Oct 7, 2024 10:15 AM' },
|
||||||
|
{ name: 'Vendor_Comparison_Analysis.xlsx', size: '3.4 MB', type: 'Excel', uploadedBy: 'IT Procurement', uploadedAt: 'Oct 7, 2024 2:45 PM' },
|
||||||
|
{ name: 'Cost_Benefit_Analysis.pptx', size: '6.2 MB', type: 'PowerPoint', uploadedBy: 'Analytics Team', uploadedAt: 'Oct 7, 2024 4:30 PM' },
|
||||||
|
{ name: 'Implementation_Timeline.pdf', size: '1.5 MB', type: 'PDF', uploadedBy: 'Project Management', uploadedAt: 'Oct 8, 2024 9:15 AM' }
|
||||||
|
],
|
||||||
|
spectators: [
|
||||||
|
{ name: 'Service Center Network', role: 'End Users', avatar: 'SN' },
|
||||||
|
{ name: 'Data Analytics Team', role: 'System Integration', avatar: 'DA' }
|
||||||
|
],
|
||||||
|
auditTrail: [
|
||||||
|
{ type: 'created', action: 'Request Created', details: 'AI inventory system proposal submitted', user: 'Rahul Deshmukh', timestamp: 'Oct 7, 2024 10:00 AM' },
|
||||||
|
{ type: 'assignment', action: 'Assigned to Vikram Singh', details: 'Forwarded to IT Operations Head', user: 'System', timestamp: 'Oct 7, 2024 10:01 AM' },
|
||||||
|
{ type: 'updated', action: 'Documents Added', details: 'Implementation timeline document uploaded', user: 'Project Management', timestamp: 'Oct 8, 2024 9:15 AM' }
|
||||||
|
],
|
||||||
|
tags: ['technology', 'ai', 'inventory', 'supply-chain', 'high-priority']
|
||||||
|
},
|
||||||
|
|
||||||
|
'RE-REQ-2024-007': {
|
||||||
|
id: 'RE-REQ-2024-007',
|
||||||
|
title: 'Dealer Network Meeting - Q4 Business Review',
|
||||||
|
description: 'Quarterly business review meeting for all authorized dealers across India. Venue: Bangalore. Topics include Q3 performance review, Q4 targets, new model launches, marketing initiatives, service excellence programs, and dealer support policies. Expected attendance: 250 dealers.',
|
||||||
|
category: 'Events & Conferences',
|
||||||
|
subcategory: 'Dealer Meetings',
|
||||||
|
status: 'in-review',
|
||||||
|
priority: 'standard',
|
||||||
|
amount: '₹28,50,000',
|
||||||
|
slaProgress: 58,
|
||||||
|
slaRemaining: '1 day 12 hours',
|
||||||
|
slaEndDate: 'Oct 11, 2024 5:00 PM',
|
||||||
|
currentStep: 2,
|
||||||
|
totalSteps: 3,
|
||||||
|
template: 'custom',
|
||||||
|
initiator: {
|
||||||
|
name: 'Neha Kapoor',
|
||||||
|
role: 'Dealer Network Manager',
|
||||||
|
department: 'Sales & Distribution',
|
||||||
|
email: 'neha.kapoor@royalenfield.com',
|
||||||
|
phone: '+91 98765 43276',
|
||||||
|
avatar: 'NK'
|
||||||
|
},
|
||||||
|
department: 'Sales & Distribution',
|
||||||
|
createdAt: 'Oct 6, 2024 2:00 PM',
|
||||||
|
updatedAt: 'Oct 8, 2024 11:30 AM',
|
||||||
|
dueDate: '2024-10-11T17:00:00Z',
|
||||||
|
submittedDate: '2024-10-06T14:00:00Z',
|
||||||
|
estimatedCompletion: 'Oct 11, 2024',
|
||||||
|
currentApprover: 'Anil Kapoor',
|
||||||
|
approverLevel: '2 of 3',
|
||||||
|
conclusionRemark: '',
|
||||||
|
approvalFlow: [
|
||||||
|
{
|
||||||
|
step: 1,
|
||||||
|
approver: 'Suresh Mehta',
|
||||||
|
role: 'Sales Director',
|
||||||
|
status: 'approved',
|
||||||
|
tatHours: 48,
|
||||||
|
actualHours: 36,
|
||||||
|
assignedAt: '2024-10-06T14:00:00Z',
|
||||||
|
comment: 'Dealer meeting approved. Agenda looks comprehensive.',
|
||||||
|
timestamp: 'Oct 8, 2024 2:00 AM'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
step: 2,
|
||||||
|
approver: 'Anil Kapoor',
|
||||||
|
role: 'Finance Manager',
|
||||||
|
status: 'in-review',
|
||||||
|
tatHours: 72,
|
||||||
|
elapsedHours: 33,
|
||||||
|
assignedAt: '2024-10-08T02:00:00Z',
|
||||||
|
comment: null,
|
||||||
|
timestamp: null
|
||||||
|
},
|
||||||
|
{
|
||||||
|
step: 3,
|
||||||
|
approver: 'Deepika Sharma',
|
||||||
|
role: 'VP Sales & Marketing',
|
||||||
|
status: 'waiting',
|
||||||
|
tatHours: 48,
|
||||||
|
elapsedHours: 0,
|
||||||
|
assignedAt: null,
|
||||||
|
comment: null,
|
||||||
|
timestamp: null
|
||||||
|
}
|
||||||
|
],
|
||||||
|
documents: [
|
||||||
|
{ name: 'Q4_Dealer_Meeting_Agenda.pdf', size: '2.8 MB', type: 'PDF', uploadedBy: 'Neha Kapoor', uploadedAt: 'Oct 6, 2024 2:15 PM' },
|
||||||
|
{ name: 'Venue_Booking_Confirmation.pdf', size: '980 KB', type: 'PDF', uploadedBy: 'Events Team', uploadedAt: 'Oct 6, 2024 4:45 PM' },
|
||||||
|
{ name: 'Event_Budget_Breakdown.xlsx', size: '1.2 MB', type: 'Excel', uploadedBy: 'Finance Team', uploadedAt: 'Oct 7, 2024 10:30 AM' },
|
||||||
|
{ name: 'Dealer_Invitations_List.xlsx', size: '580 KB', type: 'Excel', uploadedBy: 'Sales Team', uploadedAt: 'Oct 7, 2024 3:15 PM' }
|
||||||
|
],
|
||||||
|
spectators: [
|
||||||
|
{ name: 'Marketing Team', role: 'Presentation Support', avatar: 'MT' },
|
||||||
|
{ name: 'Events Management', role: 'Logistics Coordination', avatar: 'EM' }
|
||||||
|
],
|
||||||
|
auditTrail: [
|
||||||
|
{ type: 'created', action: 'Request Created', details: 'Dealer meeting proposal submitted', user: 'Neha Kapoor', timestamp: 'Oct 6, 2024 2:00 PM' },
|
||||||
|
{ type: 'assignment', action: 'Assigned to Suresh Mehta', details: 'Forwarded to Sales Director', user: 'System', timestamp: 'Oct 6, 2024 2:01 PM' },
|
||||||
|
{ type: 'approval', action: 'Approved by Suresh Mehta', details: 'Sales approval completed', user: 'Suresh Mehta', timestamp: 'Oct 8, 2024 2:00 AM' },
|
||||||
|
{ type: 'assignment', action: 'Assigned to Anil Kapoor', details: 'Forwarded to Finance Manager', user: 'System', timestamp: 'Oct 8, 2024 2:01 AM' },
|
||||||
|
{ type: 'updated', action: 'Documents Added', details: 'Dealer invitations list uploaded', user: 'Sales Team', timestamp: 'Oct 7, 2024 3:15 PM' }
|
||||||
|
],
|
||||||
|
tags: ['dealer-meeting', 'q4-review', 'event', 'bangalore']
|
||||||
|
},
|
||||||
|
|
||||||
|
'RE-REQ-2024-008': {
|
||||||
|
id: 'RE-REQ-2024-008',
|
||||||
|
title: 'Cybersecurity Infrastructure Upgrade',
|
||||||
|
description: 'Comprehensive upgrade of cybersecurity infrastructure including next-gen firewall, intrusion detection system, endpoint protection for 500+ devices, security information and event management (SIEM) system, and employee security awareness training. Critical for protecting customer data and business operations.',
|
||||||
|
category: 'IT & Infrastructure',
|
||||||
|
subcategory: 'Security & Compliance',
|
||||||
|
status: 'pending',
|
||||||
|
priority: 'urgent',
|
||||||
|
amount: '₹52,00,000',
|
||||||
|
slaProgress: 82,
|
||||||
|
slaRemaining: '4 hours 20 minutes',
|
||||||
|
slaEndDate: 'Oct 8, 2024 6:00 PM',
|
||||||
|
currentStep: 2,
|
||||||
|
totalSteps: 3,
|
||||||
|
template: 'custom',
|
||||||
|
initiator: {
|
||||||
|
name: 'Sameer Joshi',
|
||||||
|
role: 'Chief Information Security Officer',
|
||||||
|
department: 'Information Technology',
|
||||||
|
email: 'sameer.joshi@royalenfield.com',
|
||||||
|
phone: '+91 98765 43287',
|
||||||
|
avatar: 'SJ'
|
||||||
|
},
|
||||||
|
department: 'Information Technology',
|
||||||
|
createdAt: 'Oct 5, 2024 11:30 AM',
|
||||||
|
updatedAt: 'Oct 8, 2024 12:45 PM',
|
||||||
|
dueDate: '2024-10-08T18:00:00Z',
|
||||||
|
submittedDate: '2024-10-05T11:30:00Z',
|
||||||
|
estimatedCompletion: 'Oct 8, 2024',
|
||||||
|
currentApprover: 'Anil Kapoor',
|
||||||
|
approverLevel: '2 of 3',
|
||||||
|
conclusionRemark: '',
|
||||||
|
approvalFlow: [
|
||||||
|
{
|
||||||
|
step: 1,
|
||||||
|
approver: 'Vikram Singh',
|
||||||
|
role: 'Head - IT Operations',
|
||||||
|
status: 'approved',
|
||||||
|
tatHours: 24,
|
||||||
|
actualHours: 18,
|
||||||
|
assignedAt: '2024-10-05T11:30:00Z',
|
||||||
|
comment: 'Critical security upgrade. Approve immediately.',
|
||||||
|
timestamp: 'Oct 6, 2024 5:30 AM'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
step: 2,
|
||||||
|
approver: 'Anil Kapoor',
|
||||||
|
role: 'Finance Manager',
|
||||||
|
status: 'pending',
|
||||||
|
tatHours: 48,
|
||||||
|
elapsedHours: 55,
|
||||||
|
assignedAt: '2024-10-06T05:30:00Z',
|
||||||
|
comment: null,
|
||||||
|
timestamp: null
|
||||||
|
},
|
||||||
|
{
|
||||||
|
step: 3,
|
||||||
|
approver: 'Ramesh Kulkarni',
|
||||||
|
role: 'VP Operations',
|
||||||
|
status: 'waiting',
|
||||||
|
tatHours: 72,
|
||||||
|
elapsedHours: 0,
|
||||||
|
assignedAt: null,
|
||||||
|
comment: null,
|
||||||
|
timestamp: null
|
||||||
|
}
|
||||||
|
],
|
||||||
|
documents: [
|
||||||
|
{ name: 'Security_Assessment_Report.pdf', size: '15.3 MB', type: 'PDF', uploadedBy: 'Sameer Joshi', uploadedAt: 'Oct 5, 2024 11:45 AM' },
|
||||||
|
{ name: 'Vendor_Solutions_Comparison.xlsx', size: '4.8 MB', type: 'Excel', uploadedBy: 'IT Security Team', uploadedAt: 'Oct 5, 2024 3:30 PM' },
|
||||||
|
{ name: 'Implementation_Roadmap.pptx', size: '7.6 MB', type: 'PowerPoint', uploadedBy: 'Project Management', uploadedAt: 'Oct 6, 2024 10:15 AM' },
|
||||||
|
{ name: 'Risk_Analysis_Report.pdf', size: '5.9 MB', type: 'PDF', uploadedBy: 'Security Consultant', uploadedAt: 'Oct 6, 2024 4:45 PM' }
|
||||||
|
],
|
||||||
|
spectators: [
|
||||||
|
{ name: 'Legal & Compliance', role: 'Data Protection', avatar: 'LC' },
|
||||||
|
{ name: 'IT Infrastructure', role: 'System Integration', avatar: 'IT' }
|
||||||
|
],
|
||||||
|
auditTrail: [
|
||||||
|
{ type: 'created', action: 'Request Created', details: 'Cybersecurity upgrade proposal submitted', user: 'Sameer Joshi', timestamp: 'Oct 5, 2024 11:30 AM' },
|
||||||
|
{ type: 'assignment', action: 'Assigned to Vikram Singh', details: 'Forwarded to IT Operations Head', user: 'System', timestamp: 'Oct 5, 2024 11:31 AM' },
|
||||||
|
{ type: 'approval', action: 'Approved by Vikram Singh', details: 'IT approval - marked as critical', user: 'Vikram Singh', timestamp: 'Oct 6, 2024 5:30 AM' },
|
||||||
|
{ type: 'assignment', action: 'Assigned to Anil Kapoor', details: 'Forwarded to Finance Manager', user: 'System', timestamp: 'Oct 6, 2024 5:31 AM' },
|
||||||
|
{ type: 'reminder', action: 'Urgent Reminder', details: 'TAT breach warning - 4 hours remaining', user: 'System', timestamp: 'Oct 8, 2024 12:45 PM' }
|
||||||
|
],
|
||||||
|
tags: ['cybersecurity', 'urgent', 'critical', 'infrastructure', 'overdue']
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
// API Endpoints for Custom Requests (to be implemented with backend)
|
// API Endpoints for Custom Requests (to be implemented with backend)
|
||||||
export const CUSTOM_REQUEST_API_ENDPOINTS = {
|
export const CUSTOM_REQUEST_API_ENDPOINTS = {
|
||||||
|
|||||||
188
src/utils/dealerDatabase.ts
Normal file
188
src/utils/dealerDatabase.ts
Normal file
@ -0,0 +1,188 @@
|
|||||||
|
// Mock Dealer Database - In production, this would be fetched from API
|
||||||
|
export interface DealerInfo {
|
||||||
|
code: string;
|
||||||
|
name: string;
|
||||||
|
email: string;
|
||||||
|
phone: string;
|
||||||
|
address: string;
|
||||||
|
city: string;
|
||||||
|
state: string;
|
||||||
|
region: string;
|
||||||
|
managerName: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const DEALER_DATABASE: Record<string, DealerInfo> = {
|
||||||
|
'RE-MH-001': {
|
||||||
|
code: 'RE-MH-001',
|
||||||
|
name: 'Royal Motors Mumbai',
|
||||||
|
email: 'dealer@royalmotorsmumbai.com',
|
||||||
|
phone: '+91 98765 12345',
|
||||||
|
address: 'Shop No. 12-15, Central Avenue, Andheri West',
|
||||||
|
city: 'Mumbai',
|
||||||
|
state: 'Maharashtra',
|
||||||
|
region: 'West',
|
||||||
|
managerName: 'Rahul Deshmukh'
|
||||||
|
},
|
||||||
|
'RE-DL-002': {
|
||||||
|
code: 'RE-DL-002',
|
||||||
|
name: 'Delhi Enfield Center',
|
||||||
|
email: 'contact@delhienfield.com',
|
||||||
|
phone: '+91 98765 23456',
|
||||||
|
address: '45-48, Rajouri Garden, Main Market',
|
||||||
|
city: 'New Delhi',
|
||||||
|
state: 'Delhi',
|
||||||
|
region: 'North',
|
||||||
|
managerName: 'Vikram Singh'
|
||||||
|
},
|
||||||
|
'RE-BLR-003': {
|
||||||
|
code: 'RE-BLR-003',
|
||||||
|
name: 'Bangalore Royal Bikes',
|
||||||
|
email: 'info@bangaloreroyalbikes.com',
|
||||||
|
phone: '+91 98765 34567',
|
||||||
|
address: '123, MG Road, Near Trinity Metro',
|
||||||
|
city: 'Bangalore',
|
||||||
|
state: 'Karnataka',
|
||||||
|
region: 'South',
|
||||||
|
managerName: 'Suresh Kumar'
|
||||||
|
},
|
||||||
|
'RE-CHN-004': {
|
||||||
|
code: 'RE-CHN-004',
|
||||||
|
name: 'Chennai Enfield Hub',
|
||||||
|
email: 'chennai@enfieldhub.com',
|
||||||
|
phone: '+91 98765 45678',
|
||||||
|
address: '78-80, Anna Salai, T Nagar',
|
||||||
|
city: 'Chennai',
|
||||||
|
state: 'Tamil Nadu',
|
||||||
|
region: 'South',
|
||||||
|
managerName: 'Venkat Ramanan'
|
||||||
|
},
|
||||||
|
'RE-HYD-005': {
|
||||||
|
code: 'RE-HYD-005',
|
||||||
|
name: 'Hyderabad Royal Motorcycles',
|
||||||
|
email: 'hyderabad@royalmotorcycles.com',
|
||||||
|
phone: '+91 98765 56789',
|
||||||
|
address: '234, Banjara Hills, Road No. 12',
|
||||||
|
city: 'Hyderabad',
|
||||||
|
state: 'Telangana',
|
||||||
|
region: 'South',
|
||||||
|
managerName: 'Anil Reddy'
|
||||||
|
},
|
||||||
|
'RE-KOL-006': {
|
||||||
|
code: 'RE-KOL-006',
|
||||||
|
name: 'Kolkata Enfield Motors',
|
||||||
|
email: 'kolkata@enfieldmotors.com',
|
||||||
|
phone: '+91 98765 67890',
|
||||||
|
address: '56-58, Park Street, Near Park Hotel',
|
||||||
|
city: 'Kolkata',
|
||||||
|
state: 'West Bengal',
|
||||||
|
region: 'East',
|
||||||
|
managerName: 'Amit Chatterjee'
|
||||||
|
},
|
||||||
|
'RE-PUN-007': {
|
||||||
|
code: 'RE-PUN-007',
|
||||||
|
name: 'Pune Royal Dealership',
|
||||||
|
email: 'pune@royaldealership.com',
|
||||||
|
phone: '+91 98765 78901',
|
||||||
|
address: '345, FC Road, Deccan Gymkhana',
|
||||||
|
city: 'Pune',
|
||||||
|
state: 'Maharashtra',
|
||||||
|
region: 'West',
|
||||||
|
managerName: 'Sandeep Patil'
|
||||||
|
},
|
||||||
|
'RE-AHM-008': {
|
||||||
|
code: 'RE-AHM-008',
|
||||||
|
name: 'Ahmedabad Enfield Plaza',
|
||||||
|
email: 'ahmedabad@enfieldplaza.com',
|
||||||
|
phone: '+91 98765 89012',
|
||||||
|
address: '123, CG Road, Navrangpura',
|
||||||
|
city: 'Ahmedabad',
|
||||||
|
state: 'Gujarat',
|
||||||
|
region: 'West',
|
||||||
|
managerName: 'Kiran Patel'
|
||||||
|
},
|
||||||
|
'RE-JP-009': {
|
||||||
|
code: 'RE-JP-009',
|
||||||
|
name: 'Jaipur Royal Enfield',
|
||||||
|
email: 'jaipur@royalenfield.com',
|
||||||
|
phone: '+91 98765 90123',
|
||||||
|
address: '67, MI Road, C-Scheme',
|
||||||
|
city: 'Jaipur',
|
||||||
|
state: 'Rajasthan',
|
||||||
|
region: 'North',
|
||||||
|
managerName: 'Rajesh Sharma'
|
||||||
|
},
|
||||||
|
'RE-LKO-010': {
|
||||||
|
code: 'RE-LKO-010',
|
||||||
|
name: 'Lucknow Enfield Showroom',
|
||||||
|
email: 'lucknow@enfieldshowroom.com',
|
||||||
|
phone: '+91 98765 01234',
|
||||||
|
address: '89, Hazratganj, Near Halwasiya Crossing',
|
||||||
|
city: 'Lucknow',
|
||||||
|
state: 'Uttar Pradesh',
|
||||||
|
region: 'North',
|
||||||
|
managerName: 'Ankit Verma'
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get dealer information by dealer code
|
||||||
|
* @param dealerCode - The dealer code (e.g., 'RE-MH-001')
|
||||||
|
* @returns DealerInfo object or null if not found
|
||||||
|
*/
|
||||||
|
export function getDealerInfo(dealerCode: string): DealerInfo | null {
|
||||||
|
return DEALER_DATABASE[dealerCode] || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get all dealers for a specific region
|
||||||
|
* @param region - Region name (North, South, East, West)
|
||||||
|
* @returns Array of DealerInfo objects
|
||||||
|
*/
|
||||||
|
export function getDealersByRegion(region: string): DealerInfo[] {
|
||||||
|
return Object.values(DEALER_DATABASE).filter(
|
||||||
|
dealer => dealer.region.toLowerCase() === region.toLowerCase()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get all dealers for a specific state
|
||||||
|
* @param state - State name
|
||||||
|
* @returns Array of DealerInfo objects
|
||||||
|
*/
|
||||||
|
export function getDealersByState(state: string): DealerInfo[] {
|
||||||
|
return Object.values(DEALER_DATABASE).filter(
|
||||||
|
dealer => dealer.state.toLowerCase() === state.toLowerCase()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get all dealers as an array (for dropdowns, etc.)
|
||||||
|
* @returns Array of DealerInfo objects
|
||||||
|
*/
|
||||||
|
export function getAllDealers(): DealerInfo[] {
|
||||||
|
return Object.values(DEALER_DATABASE);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Search dealers by name or code
|
||||||
|
* @param searchTerm - Search term
|
||||||
|
* @returns Array of matching DealerInfo objects
|
||||||
|
*/
|
||||||
|
export function searchDealers(searchTerm: string): DealerInfo[] {
|
||||||
|
const term = searchTerm.toLowerCase();
|
||||||
|
return Object.values(DEALER_DATABASE).filter(
|
||||||
|
dealer =>
|
||||||
|
dealer.name.toLowerCase().includes(term) ||
|
||||||
|
dealer.code.toLowerCase().includes(term) ||
|
||||||
|
dealer.city.toLowerCase().includes(term)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Format dealer address for display
|
||||||
|
* @param dealer - DealerInfo object
|
||||||
|
* @returns Formatted address string
|
||||||
|
*/
|
||||||
|
export function formatDealerAddress(dealer: DealerInfo): string {
|
||||||
|
return `${dealer.address}, ${dealer.city}, ${dealer.state}`;
|
||||||
|
}
|
||||||
@ -1,122 +0,0 @@
|
|||||||
/**
|
|
||||||
* GST Utility for state validation and tax calculations
|
|
||||||
* Contains state codes and helper functions for determining GST components
|
|
||||||
*/
|
|
||||||
|
|
||||||
export const STATE_CODES: Record<string, string> = {
|
|
||||||
'01': 'Jammu and Kashmir',
|
|
||||||
'02': 'Himachal Pradesh',
|
|
||||||
'03': 'Punjab',
|
|
||||||
'04': 'Chandigarh',
|
|
||||||
'05': 'Uttarakhand',
|
|
||||||
'06': 'Haryana',
|
|
||||||
'07': 'Delhi',
|
|
||||||
'08': 'Rajasthan',
|
|
||||||
'09': 'Uttar Pradesh',
|
|
||||||
'10': 'Bihar',
|
|
||||||
'11': 'Sikkim',
|
|
||||||
'12': 'Arunachal Pradesh',
|
|
||||||
'13': 'Nagaland',
|
|
||||||
'14': 'Manipur',
|
|
||||||
'15': 'Mizoram',
|
|
||||||
'16': 'Tripura',
|
|
||||||
'17': 'Meghalaya',
|
|
||||||
'18': 'Assam',
|
|
||||||
'19': 'West Bengal',
|
|
||||||
'20': 'Jharkhand',
|
|
||||||
'21': 'Odisha',
|
|
||||||
'22': 'Chhattisgarh',
|
|
||||||
'23': 'Madhya Pradesh',
|
|
||||||
'24': 'Gujarat',
|
|
||||||
'25': 'Daman and Diu',
|
|
||||||
'26': 'Dadra and Nagar Haveli',
|
|
||||||
'27': 'Maharashtra',
|
|
||||||
'29': 'Karnataka',
|
|
||||||
'30': 'Goa',
|
|
||||||
'31': 'Lakshadweep Islands',
|
|
||||||
'32': 'Kerala',
|
|
||||||
'33': 'Tamil Nadu',
|
|
||||||
'34': 'Pondicherry',
|
|
||||||
'35': 'Andaman and Nicobar',
|
|
||||||
'36': 'Telangana',
|
|
||||||
'37': 'Andhra Pradesh',
|
|
||||||
'38': 'Ladakh',
|
|
||||||
'97': 'Others',
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Royal Enfield State Code (Tamil Nadu)
|
|
||||||
*/
|
|
||||||
export const COMPANY_STATE_CODE = '33';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* State codes that use UTGST instead of SGST
|
|
||||||
* Andaman and Nicobar Islands, Chandigarh, Dadra and Nagar Haveli and Daman and Diu, Ladakh, Lakshadweep
|
|
||||||
*/
|
|
||||||
export const UT_STATE_CODES = new Set(['04', '25', '26', '31', '35', '38']);
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Extracts state code from GSTIN
|
|
||||||
* @param gstin The 15-digit GSTIN string
|
|
||||||
* @returns 2-digit state code or null
|
|
||||||
*/
|
|
||||||
export const getStateCodeFromGSTIN = (gstin: string | undefined | null): string | null => {
|
|
||||||
if (!gstin || gstin.length < 2) return null;
|
|
||||||
const stateCode = gstin.substring(0, 2);
|
|
||||||
return STATE_CODES[stateCode] ? stateCode : null;
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Checks if a state code corresponds to a Union Territory (requiring UTGST)
|
|
||||||
* @param stateCode 2-digit state code
|
|
||||||
* @returns boolean
|
|
||||||
*/
|
|
||||||
export const isUnionTerritory = (stateCode: string | undefined | null): boolean => {
|
|
||||||
if (!stateCode) return false;
|
|
||||||
return UT_STATE_CODES.has(stateCode);
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Determines if a transaction is Inter-state (IGST) or Intra-state (CGST+SGST/UTGST)
|
|
||||||
* @param dealerStateCode 2-digit state code of the dealer
|
|
||||||
* @returns true if IGST, false if CGST+SGST/UTGST
|
|
||||||
*/
|
|
||||||
export const isInterState = (dealerStateCode: string | undefined | null): boolean => {
|
|
||||||
if (!dealerStateCode) return false; // Default to intra-state if unknown
|
|
||||||
return dealerStateCode !== COMPANY_STATE_CODE;
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Gets the tax components for a given dealer state
|
|
||||||
* @param dealerStateCode 2-digit state code of the dealer
|
|
||||||
* @returns Object indicating which tax components are active
|
|
||||||
*/
|
|
||||||
export const getActiveTaxComponents = (dealerStateCode: string | undefined | null) => {
|
|
||||||
if (!dealerStateCode) {
|
|
||||||
return {
|
|
||||||
isIGST: false,
|
|
||||||
isCGST: true,
|
|
||||||
isSGST: true,
|
|
||||||
isUTGST: false,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
const isInter = isInterState(dealerStateCode);
|
|
||||||
|
|
||||||
if (isInter) {
|
|
||||||
return {
|
|
||||||
isIGST: true,
|
|
||||||
isCGST: false,
|
|
||||||
isSGST: false,
|
|
||||||
isUTGST: false,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
const isUT = isUnionTerritory(dealerStateCode);
|
|
||||||
return {
|
|
||||||
isIGST: false,
|
|
||||||
isCGST: true,
|
|
||||||
isSGST: !isUT,
|
|
||||||
isUTGST: isUT,
|
|
||||||
};
|
|
||||||
};
|
|
||||||
@ -21,8 +21,5 @@ export function sanitizeHTML(html: string): string {
|
|||||||
// 5. Remove meta and link tags (except for purely visual ones if needed, but safer to remove)
|
// 5. Remove meta and link tags (except for purely visual ones if needed, but safer to remove)
|
||||||
sanitized = sanitized.replace(/<(meta|link|iframe|object|embed|applet)[^>]*>/gi, '');
|
sanitized = sanitized.replace(/<(meta|link|iframe|object|embed|applet)[^>]*>/gi, '');
|
||||||
|
|
||||||
// 6. Explicitly remove <a> tags to prevent HTML injection of links (VAPT compliance)
|
|
||||||
sanitized = sanitized.replace(/<a[^>]*>([\s\S]*?)<\/a>/gi, '$1');
|
|
||||||
|
|
||||||
return sanitized;
|
return sanitized;
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,82 +0,0 @@
|
|||||||
/**
|
|
||||||
* Security Toast Helper
|
|
||||||
* Shows distinct, styled toast messages for antivirus/security scan errors.
|
|
||||||
* Each error type (malware, file validation, XSS, scan unavailable) gets
|
|
||||||
* its own clear message so the user knows exactly what happened.
|
|
||||||
*/
|
|
||||||
|
|
||||||
import { toast } from 'sonner';
|
|
||||||
|
|
||||||
// Security error codes returned by the backend
|
|
||||||
const SECURITY_ERROR_CODES = [
|
|
||||||
'MALWARE_DETECTED',
|
|
||||||
'FILE_VALIDATION_FAILED',
|
|
||||||
'CONTENT_THREAT_DETECTED',
|
|
||||||
'SCAN_UNAVAILABLE',
|
|
||||||
'SCAN_ERROR',
|
|
||||||
] as const;
|
|
||||||
|
|
||||||
type SecurityErrorCode = typeof SECURITY_ERROR_CODES[number];
|
|
||||||
|
|
||||||
interface SecurityErrorResponse {
|
|
||||||
error?: string;
|
|
||||||
message?: string;
|
|
||||||
details?: {
|
|
||||||
errors?: string[];
|
|
||||||
warnings?: string[];
|
|
||||||
scanEngine?: string;
|
|
||||||
signatures?: string[];
|
|
||||||
scanType?: string;
|
|
||||||
threats?: Array<{ description: string; severity: string }>;
|
|
||||||
};
|
|
||||||
scanEventId?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
// User-friendly titles for each error type
|
|
||||||
const ERROR_TITLES: Record<SecurityErrorCode, string> = {
|
|
||||||
MALWARE_DETECTED: '🛑 Malware Detected',
|
|
||||||
FILE_VALIDATION_FAILED: '⛔ File Rejected',
|
|
||||||
CONTENT_THREAT_DETECTED: '⚠️ Malicious Content Detected',
|
|
||||||
SCAN_UNAVAILABLE: '🔒 Security Scan Unavailable',
|
|
||||||
SCAN_ERROR: '❌ Security Scan Error',
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Check if an API error response is a security/scan error.
|
|
||||||
* Returns true if it was handled (showed a toast), false otherwise.
|
|
||||||
*/
|
|
||||||
export function handleSecurityError(error: any): boolean {
|
|
||||||
const responseData: SecurityErrorResponse = error?.response?.data;
|
|
||||||
if (!responseData?.error) return false;
|
|
||||||
|
|
||||||
const errorCode = responseData.error as SecurityErrorCode;
|
|
||||||
if (!SECURITY_ERROR_CODES.includes(errorCode)) return false;
|
|
||||||
|
|
||||||
const title = ERROR_TITLES[errorCode] || 'Security Error';
|
|
||||||
const message = responseData.message || 'File was blocked by security scan';
|
|
||||||
|
|
||||||
// Build detail text
|
|
||||||
let detailText = '';
|
|
||||||
if (responseData.details) {
|
|
||||||
if (responseData.details.signatures?.length) {
|
|
||||||
detailText = `Virus: ${responseData.details.signatures.join(', ')}`;
|
|
||||||
} else if (responseData.details.errors?.length) {
|
|
||||||
detailText = responseData.details.errors[0] || '';
|
|
||||||
} else if (responseData.details.threats?.length) {
|
|
||||||
detailText = responseData.details.threats.map(t => t.description).join(', ');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Show custom styled toast
|
|
||||||
toast.error(title, {
|
|
||||||
description: detailText || message,
|
|
||||||
duration: 8000,
|
|
||||||
style: {
|
|
||||||
background: '#fef2f2',
|
|
||||||
border: '1px solid #fca5a5',
|
|
||||||
color: '#991b1b',
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
@ -30,7 +30,7 @@ async function ensureConfigLoaded() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Initialize config on first import (non-blocking)
|
// Initialize config on first import (non-blocking)
|
||||||
ensureConfigLoaded().catch(() => { });
|
ensureConfigLoaded().catch(() => {});
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Check if current time is within working hours
|
* Check if current time is within working hours
|
||||||
@ -54,6 +54,7 @@ export function isWorkingTime(date: Date = new Date(), priority: string = 'stand
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO: Add holiday check if holiday API is available
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|||||||
@ -19,8 +19,9 @@ export function getSocketBaseUrl(): string {
|
|||||||
return apiBaseUrl.replace(/\/api\/v1\/?$/, '');
|
return apiBaseUrl.replace(/\/api\/v1\/?$/, '');
|
||||||
}
|
}
|
||||||
|
|
||||||
// Dev fallback
|
// Development fallback
|
||||||
return '';
|
console.warn('[Socket] No VITE_BASE_URL or VITE_API_BASE_URL found, using localhost:5000');
|
||||||
|
return 'http://localhost:5000';
|
||||||
}
|
}
|
||||||
|
|
||||||
export function getSocket(baseUrl?: string): Socket {
|
export function getSocket(baseUrl?: string): Socket {
|
||||||
|
|||||||
@ -75,37 +75,53 @@ export const cookieUtils = {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Token Manager - Handles token storage and retrieval
|
||||||
|
*
|
||||||
|
* SECURITY MODES:
|
||||||
|
* - Production: Tokens stored in httpOnly cookies by backend only
|
||||||
|
* Frontend does NOT store access/refresh tokens anywhere
|
||||||
|
* All API requests rely on cookies being sent automatically
|
||||||
|
*
|
||||||
|
* - Development: Tokens stored in localStorage for debugging
|
||||||
|
* Needed because frontend/backend run on different ports
|
||||||
|
*/
|
||||||
export class TokenManager {
|
export class TokenManager {
|
||||||
/**
|
/**
|
||||||
* Store access token
|
* Store access token
|
||||||
|
* In production: No-op (backend handles via httpOnly cookies)
|
||||||
|
* In development: Store in localStorage for Authorization header
|
||||||
*/
|
*/
|
||||||
static setAccessToken(token: string): void {
|
static setAccessToken(token: string): void {
|
||||||
|
// SECURITY: In production, don't store tokens client-side
|
||||||
|
// Backend sets httpOnly cookies that are sent automatically
|
||||||
if (isProduction()) {
|
if (isProduction()) {
|
||||||
return; // No-op - rely on httpOnly cookies
|
return; // No-op - rely on httpOnly cookies
|
||||||
}
|
}
|
||||||
|
|
||||||
// Dev only: Store for debugging and cross-port requests
|
// Development only: Store for debugging and cross-port requests
|
||||||
localStorage.setItem(ACCESS_TOKEN_KEY, token);
|
localStorage.setItem(ACCESS_TOKEN_KEY, token);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get access token
|
* Get access token
|
||||||
*
|
* In production: Returns null (cookies are sent automatically)
|
||||||
|
* In development: Returns from localStorage
|
||||||
*/
|
*/
|
||||||
static getAccessToken(): string | null {
|
static getAccessToken(): string | null {
|
||||||
|
// SECURITY: In production, return null - cookies are used instead
|
||||||
if (isProduction()) {
|
if (isProduction()) {
|
||||||
return null;
|
return null; // API calls use cookies via withCredentials: true
|
||||||
}
|
}
|
||||||
|
|
||||||
// Dev: Return from localStorage
|
// Development: Return from localStorage
|
||||||
return localStorage.getItem(ACCESS_TOKEN_KEY);
|
return localStorage.getItem(ACCESS_TOKEN_KEY);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Store refresh token
|
* Store refresh token
|
||||||
|
* In production: No-op (backend handles via httpOnly cookies)
|
||||||
|
* In development: Store in localStorage
|
||||||
*/
|
*/
|
||||||
static setRefreshToken(token: string): void {
|
static setRefreshToken(token: string): void {
|
||||||
// SECURITY: In production, don't store tokens client-side
|
// SECURITY: In production, don't store tokens client-side
|
||||||
@ -113,12 +129,14 @@ export class TokenManager {
|
|||||||
return; // No-op - rely on httpOnly cookies
|
return; // No-op - rely on httpOnly cookies
|
||||||
}
|
}
|
||||||
|
|
||||||
// Dev only
|
// Development only
|
||||||
localStorage.setItem(REFRESH_TOKEN_KEY, token);
|
localStorage.setItem(REFRESH_TOKEN_KEY, token);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get refresh token
|
* Get refresh token
|
||||||
|
* In production: Returns null (cookies are used)
|
||||||
|
* In development: Returns from localStorage
|
||||||
*/
|
*/
|
||||||
static getRefreshToken(): string | null {
|
static getRefreshToken(): string | null {
|
||||||
// SECURITY: In production, return null - backend reads from cookie
|
// SECURITY: In production, return null - backend reads from cookie
|
||||||
@ -129,6 +147,10 @@ export class TokenManager {
|
|||||||
return localStorage.getItem(REFRESH_TOKEN_KEY);
|
return localStorage.getItem(REFRESH_TOKEN_KEY);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Store ID token (from Okta) - needed for logout
|
||||||
|
* Stored in sessionStorage (cleared when tab closes)
|
||||||
|
*/
|
||||||
static setIdToken(token: string): void {
|
static setIdToken(token: string): void {
|
||||||
// ID token is needed for Okta logout, use sessionStorage (more secure than localStorage)
|
// ID token is needed for Okta logout, use sessionStorage (more secure than localStorage)
|
||||||
sessionStorage.setItem(ID_TOKEN_KEY, token);
|
sessionStorage.setItem(ID_TOKEN_KEY, token);
|
||||||
@ -161,9 +183,20 @@ export class TokenManager {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Clear all tokens and user data
|
||||||
|
*
|
||||||
|
* PRODUCTION MODE:
|
||||||
|
* - Clears user data from localStorage
|
||||||
|
* - Clears ID token from sessionStorage
|
||||||
|
* - Backend logout endpoint clears httpOnly cookies
|
||||||
|
*
|
||||||
|
* DEVELOPMENT MODE:
|
||||||
|
* - Clears all localStorage and sessionStorage
|
||||||
|
* - Clears client-side cookies
|
||||||
|
*/
|
||||||
static clearAll(): void {
|
static clearAll(): void {
|
||||||
//: Set logout flag in sessionStorage FIRST (before clearing)
|
// CRITICAL: Set logout flag in sessionStorage FIRST (before clearing)
|
||||||
// This flag survives the redirect and prevents auto-authentication
|
// This flag survives the redirect and prevents auto-authentication
|
||||||
try {
|
try {
|
||||||
sessionStorage.setItem('__logout_in_progress__', 'true');
|
sessionStorage.setItem('__logout_in_progress__', 'true');
|
||||||
@ -193,7 +226,7 @@ export class TokenManager {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Dev MODE: Clear everything
|
// DEVELOPMENT MODE: Clear everything
|
||||||
const authKeys = [
|
const authKeys = [
|
||||||
ACCESS_TOKEN_KEY,
|
ACCESS_TOKEN_KEY,
|
||||||
REFRESH_TOKEN_KEY,
|
REFRESH_TOKEN_KEY,
|
||||||
@ -263,7 +296,11 @@ export class TokenManager {
|
|||||||
return !!this.getAccessToken();
|
return !!this.getAccessToken();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if refresh token exists
|
||||||
|
* In production: Always returns true if user data exists
|
||||||
|
* In development: Checks localStorage
|
||||||
|
*/
|
||||||
static hasRefreshToken(): boolean {
|
static hasRefreshToken(): boolean {
|
||||||
if (isProduction()) {
|
if (isProduction()) {
|
||||||
return !!this.getUserData();
|
return !!this.getUserData();
|
||||||
|
|||||||
@ -1,50 +0,0 @@
|
|||||||
/**
|
|
||||||
* Validation utilities for HSN and SAC codes
|
|
||||||
*/
|
|
||||||
|
|
||||||
export interface ValidationResult {
|
|
||||||
isValid: boolean;
|
|
||||||
message: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Validates HSN or SAC code based on GST rules
|
|
||||||
* @param code The HSN/SAC code string
|
|
||||||
* @param isService Boolean indicating if it's a Service (SAC) or Goods (HSN)
|
|
||||||
* @returns ValidationResult object
|
|
||||||
*/
|
|
||||||
export const validateHSNSAC = (code: string, isService: boolean): ValidationResult => {
|
|
||||||
if (!code) return { isValid: true, message: '' };
|
|
||||||
|
|
||||||
const cleanCode = code.trim();
|
|
||||||
|
|
||||||
// Basic check for digits only
|
|
||||||
if (!/^\d+$/.test(cleanCode)) {
|
|
||||||
return { isValid: false, message: 'Code must contain only digits' };
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isService) {
|
|
||||||
// SAC (Services Accounting Code)
|
|
||||||
// Must start with 99 and typically has 6 digits
|
|
||||||
if (!cleanCode.startsWith('99')) {
|
|
||||||
return { isValid: false, message: 'SAC (Service) code must start with 99' };
|
|
||||||
}
|
|
||||||
if (cleanCode.length !== 6) {
|
|
||||||
return { isValid: false, message: 'SAC code must be exactly 6 digits' };
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// HSN (Harmonized System of Nomenclature) for Goods
|
|
||||||
// Usually 4, 6, or 8 digits in India
|
|
||||||
const validHSNLengths = [4, 6, 8];
|
|
||||||
if (!validHSNLengths.includes(cleanCode.length)) {
|
|
||||||
return { isValid: false, message: 'HSN code must be 4, 6, or 8 digits' };
|
|
||||||
}
|
|
||||||
|
|
||||||
// HSN codes for goods should generally not start with 99 (that's reserved for SAC)
|
|
||||||
if (cleanCode.startsWith('99')) {
|
|
||||||
return { isValid: false, message: 'HSN code should not start with 99 (use SAC type for services)' };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return { isValid: true, message: '' };
|
|
||||||
};
|
|
||||||
2
src/vite-env.d.ts
vendored
2
src/vite-env.d.ts
vendored
@ -7,8 +7,6 @@ interface ImportMetaEnv {
|
|||||||
readonly VITE_APP_VERSION: string;
|
readonly VITE_APP_VERSION: string;
|
||||||
readonly VITE_ENABLE_ANALYTICS: string;
|
readonly VITE_ENABLE_ANALYTICS: string;
|
||||||
readonly VITE_ENABLE_DEBUG: string;
|
readonly VITE_ENABLE_DEBUG: string;
|
||||||
readonly VITE_TANFLOW_BASE_URL: string;
|
|
||||||
readonly VITE_TANFLOW_CLIENT_ID: string;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
interface ImportMeta {
|
interface ImportMeta {
|
||||||
|
|||||||
@ -60,24 +60,9 @@ const ensureChunkOrder = () => {
|
|||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
// Plugin to replace axios localhost fallback for VAPT compliance
|
|
||||||
const replaceAxiosLocalhost = () => {
|
|
||||||
return {
|
|
||||||
name: 'replace-axios-localhost',
|
|
||||||
transform(code: string, id: string) {
|
|
||||||
// Target the specific utils.js file in axios where the localhost string exists
|
|
||||||
if (id.includes('node_modules') && id.includes('axios') && id.includes('utils.js')) {
|
|
||||||
// Replace 'http://localhost' with empty string
|
|
||||||
return code.replace(/'http:\/\/localhost'/g, "''");
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
},
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
// https://vitejs.dev/config/
|
// https://vitejs.dev/config/
|
||||||
export default defineConfig({
|
export default defineConfig({
|
||||||
plugins: [react(), suppressCssWarnings(), ensureChunkOrder(), replaceAxiosLocalhost()],
|
plugins: [react(), suppressCssWarnings(), ensureChunkOrder()],
|
||||||
resolve: {
|
resolve: {
|
||||||
alias: {
|
alias: {
|
||||||
'@': path.resolve(__dirname, './src'),
|
'@': path.resolve(__dirname, './src'),
|
||||||
@ -93,7 +78,7 @@ export default defineConfig({
|
|||||||
},
|
},
|
||||||
build: {
|
build: {
|
||||||
outDir: 'dist',
|
outDir: 'dist',
|
||||||
sourcemap: false,
|
sourcemap: true,
|
||||||
// CSS minification warning is harmless - it's a known issue with certain Tailwind class combinations
|
// CSS minification warning is harmless - it's a known issue with certain Tailwind class combinations
|
||||||
// Re-enable minification with settings that preserve initialization order
|
// Re-enable minification with settings that preserve initialization order
|
||||||
// The "Cannot access 'React' before initialization" error is fixed by keeping React in main bundle
|
// The "Cannot access 'React' before initialization" error is fixed by keeping React in main bundle
|
||||||
@ -134,7 +119,7 @@ export default defineConfig({
|
|||||||
chunkFileNames: 'assets/[name]-[hash].js',
|
chunkFileNames: 'assets/[name]-[hash].js',
|
||||||
// Explicitly define chunk order - React must load before Radix UI
|
// Explicitly define chunk order - React must load before Radix UI
|
||||||
manualChunks(id) {
|
manualChunks(id) {
|
||||||
// IMPORTANT: Keep React in main bundle OR ensure it loads first
|
// CRITICAL FIX: Keep React in main bundle OR ensure it loads first
|
||||||
// The "Cannot access 'React' before initialization" error occurs when
|
// The "Cannot access 'React' before initialization" error occurs when
|
||||||
// Radix UI components try to access React before it's initialized
|
// Radix UI components try to access React before it's initialized
|
||||||
// Option 1: Don't split React - keep it in main bundle (most reliable)
|
// Option 1: Don't split React - keep it in main bundle (most reliable)
|
||||||
@ -143,7 +128,7 @@ export default defineConfig({
|
|||||||
// For now, let's keep React in main bundle to avoid initialization issues
|
// For now, let's keep React in main bundle to avoid initialization issues
|
||||||
// Only split other vendors
|
// Only split other vendors
|
||||||
|
|
||||||
// Radix UI - IMPORTANT: ALL Radix packages MUST stay together in ONE chunk
|
// Radix UI - CRITICAL: ALL Radix packages MUST stay together in ONE chunk
|
||||||
// This chunk will import React from the main bundle, avoiding initialization issues
|
// This chunk will import React from the main bundle, avoiding initialization issues
|
||||||
if (id.includes('node_modules/@radix-ui')) {
|
if (id.includes('node_modules/@radix-ui')) {
|
||||||
return 'radix-vendor';
|
return 'radix-vendor';
|
||||||
@ -187,7 +172,7 @@ export default defineConfig({
|
|||||||
chunkSizeWarningLimit: 1500, // Increased limit since we have manual chunks
|
chunkSizeWarningLimit: 1500, // Increased limit since we have manual chunks
|
||||||
},
|
},
|
||||||
esbuild: {
|
esbuild: {
|
||||||
//: Strip all legal comments to prevent "Suspicious Comments" alerts (e.g. from Redux docs)
|
// CRITICAL: Strip all legal comments to prevent "Suspicious Comments" alerts (e.g. from Redux docs)
|
||||||
legalComments: 'none',
|
legalComments: 'none',
|
||||||
},
|
},
|
||||||
optimizeDeps: {
|
optimizeDeps: {
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user