SAP response from credit note and debit note

This commit is contained in:
Aaditya Jaiswal 2026-03-18 11:32:48 +05:30
parent 85ddb72143
commit def22be1b1
10 changed files with 1120 additions and 96 deletions

View File

@ -28,6 +28,7 @@ import { CreateAdminRequest } from '@/pages/CreateAdminRequest/CreateAdminReques
import { Admin } from '@/pages/Admin/Admin'; import { Admin } from '@/pages/Admin/Admin';
import { Form16CreditNotes } from '@/pages/Form16/Form16CreditNotes'; import { Form16CreditNotes } from '@/pages/Form16/Form16CreditNotes';
import { Form16CreditNoteDetail } from '@/pages/Form16/Form16CreditNoteDetail'; import { Form16CreditNoteDetail } from '@/pages/Form16/Form16CreditNoteDetail';
import { Form16DebitNotes } from '@/pages/Form16/Form16DebitNotes';
import { Form16Submit } from '@/pages/Form16/Form16Submit'; import { Form16Submit } from '@/pages/Form16/Form16Submit';
import { Form16SubmissionResult } from '@/pages/Form16/Form16SubmissionResult'; import { Form16SubmissionResult } from '@/pages/Form16/Form16SubmissionResult';
import { Form16_26AS } from '@/pages/Form16/Form16_26AS'; import { Form16_26AS } from '@/pages/Form16/Form16_26AS';
@ -532,6 +533,16 @@ function AppRoutes({ onLogout }: AppProps) {
} }
/> />
{/* Form 16 Debit Notes (RE) */}
<Route
path="/form16/debit-notes"
element={
<PageLayout currentPage="form16-debit-notes" onNavigate={handleNavigate} onNewRequest={handleNewRequest} onLogout={onLogout}>
<Form16DebitNotes />
</PageLayout>
}
/>
{/* Form 16 Submit (dealer) */} {/* Form 16 Submit (dealer) */}
<Route <Route
path="/form16/submit" path="/form16/submit"

View File

@ -122,9 +122,13 @@ export function Form16AdminConfig() {
const [reminderDays, setReminderDays] = useState(7); const [reminderDays, setReminderDays] = useState(7);
const [notification26AsDataAdded, setNotification26AsDataAdded] = useState<Form16Notification26AsItem>(default26AsNotif()); const [notification26AsDataAdded, setNotification26AsDataAdded] = useState<Form16Notification26AsItem>(default26AsNotif());
const [reminder26AsUploadEnabled, setReminder26AsUploadEnabled] = useState(true);
const [reminder26AsUploadAfterQuarterEndDays, setReminder26AsUploadAfterQuarterEndDays] = useState(0);
const [notificationForm16SuccessCreditNote, setNotificationForm16SuccessCreditNote] = useState<Form16NotificationItem>(defaultNotif(true, 'Form 16 submitted successfully. Credit note: [CreditNoteRef].')); const [notificationForm16SuccessCreditNote, setNotificationForm16SuccessCreditNote] = useState<Form16NotificationItem>(defaultNotif(true, 'Form 16 submitted successfully. Credit note: [CreditNoteRef].'));
const [notificationForm16Unsuccessful, setNotificationForm16Unsuccessful] = useState<Form16NotificationItem>(defaultNotif(true, 'Form 16 submission was unsuccessful. Issue: [Issue]. Please review.')); const [notificationForm16Unsuccessful, setNotificationForm16Unsuccessful] = useState<Form16NotificationItem>(defaultNotif(true, 'Form 16 submission was unsuccessful. Issue: [Issue]. Please review.'));
const [alertSubmitForm16Enabled, setAlertSubmitForm16Enabled] = useState(true); const [alertSubmitForm16Enabled, setAlertSubmitForm16Enabled] = useState(true);
const [alertSubmitForm16AfterQuarterEndDays, setAlertSubmitForm16AfterQuarterEndDays] = useState(0);
const [alertSubmitForm16EveryDays, setAlertSubmitForm16EveryDays] = useState(7);
const [alertSubmitForm16FrequencyDays, setAlertSubmitForm16FrequencyDays] = useState(0); const [alertSubmitForm16FrequencyDays, setAlertSubmitForm16FrequencyDays] = useState(0);
const [alertSubmitForm16FrequencyHours, setAlertSubmitForm16FrequencyHours] = useState(24); const [alertSubmitForm16FrequencyHours, setAlertSubmitForm16FrequencyHours] = useState(24);
const [alertSubmitForm16RunAtTime, setAlertSubmitForm16RunAtTime] = useState('09:00'); const [alertSubmitForm16RunAtTime, setAlertSubmitForm16RunAtTime] = useState('09:00');
@ -152,9 +156,13 @@ export function Form16AdminConfig() {
templateDealers: n.templateDealers ?? default26AsNotif().templateDealers, templateDealers: n.templateDealers ?? default26AsNotif().templateDealers,
}); });
} }
setReminder26AsUploadEnabled(config.reminder26AsUploadEnabled ?? true);
setReminder26AsUploadAfterQuarterEndDays(typeof config.reminder26AsUploadAfterQuarterEndDays === 'number' ? config.reminder26AsUploadAfterQuarterEndDays : 0);
if (config.notificationForm16SuccessCreditNote) setNotificationForm16SuccessCreditNote(config.notificationForm16SuccessCreditNote); if (config.notificationForm16SuccessCreditNote) setNotificationForm16SuccessCreditNote(config.notificationForm16SuccessCreditNote);
if (config.notificationForm16Unsuccessful) setNotificationForm16Unsuccessful(config.notificationForm16Unsuccessful); if (config.notificationForm16Unsuccessful) setNotificationForm16Unsuccessful(config.notificationForm16Unsuccessful);
setAlertSubmitForm16Enabled(config.alertSubmitForm16Enabled ?? true); setAlertSubmitForm16Enabled(config.alertSubmitForm16Enabled ?? true);
setAlertSubmitForm16AfterQuarterEndDays(typeof config.alertSubmitForm16AfterQuarterEndDays === 'number' ? config.alertSubmitForm16AfterQuarterEndDays : 0);
setAlertSubmitForm16EveryDays(typeof config.alertSubmitForm16EveryDays === 'number' ? config.alertSubmitForm16EveryDays : 7);
setAlertSubmitForm16FrequencyDays(config.alertSubmitForm16FrequencyDays ?? 0); setAlertSubmitForm16FrequencyDays(config.alertSubmitForm16FrequencyDays ?? 0);
setAlertSubmitForm16FrequencyHours(config.alertSubmitForm16FrequencyHours ?? 24); setAlertSubmitForm16FrequencyHours(config.alertSubmitForm16FrequencyHours ?? 24);
setAlertSubmitForm16RunAtTime(config.alertSubmitForm16RunAtTime !== undefined && config.alertSubmitForm16RunAtTime !== null ? config.alertSubmitForm16RunAtTime : '09:00'); setAlertSubmitForm16RunAtTime(config.alertSubmitForm16RunAtTime !== undefined && config.alertSubmitForm16RunAtTime !== null ? config.alertSubmitForm16RunAtTime : '09:00');
@ -185,9 +193,13 @@ export function Form16AdminConfig() {
reminderEnabled, reminderEnabled,
reminderDays: Math.max(1, Math.min(365, reminderDays)) || 7, reminderDays: Math.max(1, Math.min(365, reminderDays)) || 7,
notification26AsDataAdded, notification26AsDataAdded,
reminder26AsUploadEnabled,
reminder26AsUploadAfterQuarterEndDays: Math.max(0, Math.min(365, reminder26AsUploadAfterQuarterEndDays)),
notificationForm16SuccessCreditNote, notificationForm16SuccessCreditNote,
notificationForm16Unsuccessful, notificationForm16Unsuccessful,
alertSubmitForm16Enabled, alertSubmitForm16Enabled,
alertSubmitForm16AfterQuarterEndDays: Math.max(0, Math.min(365, alertSubmitForm16AfterQuarterEndDays)),
alertSubmitForm16EveryDays: Math.max(1, Math.min(365, alertSubmitForm16EveryDays)),
alertSubmitForm16FrequencyDays: Math.max(0, Math.min(365, alertSubmitForm16FrequencyDays)), alertSubmitForm16FrequencyDays: Math.max(0, Math.min(365, alertSubmitForm16FrequencyDays)),
alertSubmitForm16FrequencyHours: Math.max(0, Math.min(168, alertSubmitForm16FrequencyHours)), alertSubmitForm16FrequencyHours: Math.max(0, Math.min(168, alertSubmitForm16FrequencyHours)),
alertSubmitForm16RunAtTime: alertSubmitForm16RunAtTime ?? '', alertSubmitForm16RunAtTime: alertSubmitForm16RunAtTime ?? '',
@ -257,6 +269,39 @@ export function Form16AdminConfig() {
</div> </div>
</div> </div>
{/* Quarter calendar explain quarter-based reminders */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Database className="w-5 h-5 text-re-green" />
Quarter calendar (how reminders/alerts work)
</CardTitle>
<CardDescription>
Form 16 schedules are quarter-based. Reminders/alerts are intended to be sent after the quarter end date (quarter end + N days) if required data is missing.
</CardDescription>
</CardHeader>
<CardContent>
<div className="grid grid-cols-1 md:grid-cols-2 gap-3 text-sm">
<div className="rounded-md border p-3">
<p className="font-medium">Q1</p>
<p className="text-muted-foreground">1 Apr 30 Jun</p>
</div>
<div className="rounded-md border p-3">
<p className="font-medium">Q2</p>
<p className="text-muted-foreground">1 Jul 30 Sep</p>
</div>
<div className="rounded-md border p-3">
<p className="font-medium">Q3</p>
<p className="text-muted-foreground">1 Oct 31 Dec</p>
</div>
<div className="rounded-md border p-3">
<p className="font-medium">Q4</p>
<p className="text-muted-foreground">1 Jan 31 Mar</p>
</div>
</div>
</CardContent>
</Card>
{/* Submission data viewers */} {/* Submission data viewers */}
<Card> <Card>
<CardHeader> <CardHeader>
@ -345,6 +390,36 @@ export function Form16AdminConfig() {
<div className="space-y-3"> <div className="space-y-3">
<h4 className="font-medium">Form 16 notifications recipient and trigger</h4> <h4 className="font-medium">Form 16 notifications recipient and trigger</h4>
{/* 26AS upload reminder (RE) */}
<div className="flex items-start justify-between gap-4 p-4 bg-muted/50 rounded-lg">
<div className="flex-1 min-w-0 space-y-2">
<p className="font-medium">Reminder upload 26AS (RE)</p>
<p className="text-sm text-muted-foreground">
<span className="font-medium text-foreground">Sent to:</span> RE users listed in <span className="font-medium text-foreground">26AS viewers (RE)</span>.{' '}
<span className="font-medium text-foreground">When:</span> Quarter end + N days if 26AS is missing for the most recently ended quarter.
</p>
<div className="flex flex-wrap items-center gap-3">
<div className="flex items-center gap-2">
<Label htmlFor="re-26as-after-days" className="text-sm whitespace-nowrap">Start after (days):</Label>
<Input
id="re-26as-after-days"
type="number"
min={0}
max={365}
value={reminder26AsUploadAfterQuarterEndDays}
onChange={(e) => setReminder26AsUploadAfterQuarterEndDays(parseInt(e.target.value || '0', 10) || 0)}
className="w-24"
/>
</div>
<span className="text-xs text-muted-foreground">Stops automatically once 26AS is uploaded for that quarter.</span>
</div>
</div>
<Switch
checked={reminder26AsUploadEnabled}
onCheckedChange={setReminder26AsUploadEnabled}
/>
</div>
{/* 26AS data added separate message for RE users and for dealers */} {/* 26AS data added separate message for RE users and for dealers */}
<div className="flex items-start justify-between gap-4 p-4 bg-muted/50 rounded-lg"> <div className="flex items-start justify-between gap-4 p-4 bg-muted/50 rounded-lg">
<div className="flex-1 min-w-0 space-y-3"> <div className="flex-1 min-w-0 space-y-3">
@ -362,6 +437,47 @@ export function Form16AdminConfig() {
/> />
</div> </div>
{/* Dealer reminder to submit Form 16A (quarter-ended based) */}
<div className="flex items-start justify-between gap-4 p-4 bg-muted/50 rounded-lg">
<div className="flex-1 min-w-0 space-y-2">
<p className="font-medium">Reminder submit Form 16A (Dealers)</p>
<p className="text-sm text-muted-foreground">
<span className="font-medium text-foreground">Sent to:</span> Dealers who have not submitted Form 16A for the most recently ended quarter.{' '}
<span className="font-medium text-foreground">When:</span> Quarter end + N days, then repeat every X days (until submitted).
</p>
<div className="flex flex-wrap items-center gap-3">
<div className="flex items-center gap-2">
<Label htmlFor="dealer-submit-after-days" className="text-sm whitespace-nowrap">Start after (days):</Label>
<Input
id="dealer-submit-after-days"
type="number"
min={0}
max={365}
value={alertSubmitForm16AfterQuarterEndDays}
onChange={(e) => setAlertSubmitForm16AfterQuarterEndDays(parseInt(e.target.value || '0', 10) || 0)}
className="w-24"
/>
</div>
<div className="flex items-center gap-2">
<Label htmlFor="dealer-submit-every-days" className="text-sm whitespace-nowrap">Repeat every (days):</Label>
<Input
id="dealer-submit-every-days"
type="number"
min={1}
max={365}
value={alertSubmitForm16EveryDays}
onChange={(e) => setAlertSubmitForm16EveryDays(parseInt(e.target.value || '7', 10) || 7)}
className="w-24"
/>
</div>
</div>
</div>
<Switch
checked={alertSubmitForm16Enabled}
onCheckedChange={setAlertSubmitForm16Enabled}
/>
</div>
{/* Successful Form 16 with credit note */} {/* Successful Form 16 with credit note */}
<div className="flex items-start justify-between gap-4 p-4 bg-muted/50 rounded-lg"> <div className="flex items-start justify-between gap-4 p-4 bg-muted/50 rounded-lg">
<div className="flex-1 min-w-0"> <div className="flex-1 min-w-0">
@ -396,69 +512,6 @@ export function Form16AdminConfig() {
/> />
</div> </div>
{/* Alert to submit Form 16 (auto, configurable) */}
<div className="flex items-start justify-between gap-4 p-4 bg-muted/50 rounded-lg">
<div className="flex-1 min-w-0">
<p className="font-medium">Alert submit Form 16 (to dealers who havent submitted)</p>
<p className="text-sm text-muted-foreground">
<span className="font-medium text-foreground">Sent to:</span> Dealers who have not yet submitted Form 16 for the current FY. <span className="font-medium text-foreground">When:</span> Daily at the time below (server timezone). All settings are API-driven from this config.
</p>
<div className="mt-2 space-y-2">
<div className="flex flex-wrap items-center gap-3">
<div className="flex items-center gap-2">
<Label htmlFor="alert-run-at" className="text-sm whitespace-nowrap">Run daily at (optional):</Label>
<Input
id="alert-run-at"
type="time"
value={alertSubmitForm16RunAtTime}
onChange={(e) => setAlertSubmitForm16RunAtTime(e.target.value)}
className="w-28"
/>
{alertSubmitForm16RunAtTime ? (
<Button type="button" variant="ghost" size="sm" className="text-muted-foreground" onClick={() => setAlertSubmitForm16RunAtTime('')}>
Clear
</Button>
) : null}
</div>
<span className="text-xs text-muted-foreground">24h, server TZ. Leave empty to disable daily run.</span>
</div>
<div className="flex flex-wrap items-center gap-3">
<div className="flex items-center gap-2">
<Label htmlFor="alert-freq-days" className="text-sm whitespace-nowrap">Frequency (days):</Label>
<Input
id="alert-freq-days"
type="number"
min={0}
max={365}
value={alertSubmitForm16FrequencyDays}
onChange={(e) => setAlertSubmitForm16FrequencyDays(Math.max(0, parseInt(e.target.value, 10) || 0))}
className="w-20"
/>
</div>
<div className="flex items-center gap-2">
<Label htmlFor="alert-freq-hours" className="text-sm whitespace-nowrap">Hours:</Label>
<Input
id="alert-freq-hours"
type="number"
min={0}
max={168}
value={alertSubmitForm16FrequencyHours}
onChange={(e) => setAlertSubmitForm16FrequencyHours(Math.max(0, parseInt(e.target.value, 10) || 0))}
className="w-20"
/>
</div>
</div>
<p className="text-xs text-muted-foreground">
Alert message content is fixed and managed by the system.
</p>
</div>
</div>
<Switch
checked={alertSubmitForm16Enabled}
onCheckedChange={setAlertSubmitForm16Enabled}
/>
</div>
{/* Reminder notification (pending Form 16) */} {/* Reminder notification (pending Form 16) */}
<div className="flex items-start justify-between gap-4 p-4 bg-muted/50 rounded-lg"> <div className="flex items-start justify-between gap-4 p-4 bg-muted/50 rounded-lg">
<div className="flex-1 min-w-0"> <div className="flex-1 min-w-0">

View File

@ -126,7 +126,7 @@ export function PageLayout({ children, currentPage = 'dashboard', onNavigate, on
const canView26AS = !!form16Permissions?.canView26AS; const canView26AS = !!form16Permissions?.canView26AS;
// Keep Form 16 expanded when on a Form 16 page (dealer or RE) // Keep Form 16 expanded when on a Form 16 page (dealer or RE)
const isForm16Page = currentPage === 'form16-credit-notes' || currentPage === 'form16-submit' || currentPage === 'form16-pending-submissions' || currentPage === 'form16-26as' || currentPage === 'form16-non-submitted-dealers'; const isForm16Page = currentPage === 'form16-credit-notes' || currentPage === 'form16-debit-notes' || currentPage === 'form16-submit' || currentPage === 'form16-pending-submissions' || currentPage === 'form16-26as' || currentPage === 'form16-non-submitted-dealers';
const form16ExpandedOrActive = form16Expanded || isForm16Page; const form16ExpandedOrActive = form16Expanded || isForm16Page;
const toggleSidebar = () => { const toggleSidebar = () => {
@ -413,6 +413,21 @@ export function PageLayout({ children, currentPage = 'dashboard', onNavigate, on
<Receipt className="w-3.5 h-3.5 shrink-0" /> <Receipt className="w-3.5 h-3.5 shrink-0" />
<span className="truncate">Non-submitted Dealers</span> <span className="truncate">Non-submitted Dealers</span>
</button> </button>
<button
type="button"
onClick={() => {
onNavigate?.('/form16/debit-notes');
if (window.innerWidth < 768) setSidebarOpen(false);
}}
className={`w-full flex items-center gap-2 px-2 py-1.5 rounded-md text-sm transition-colors ${
currentPage === 'form16-debit-notes'
? 'bg-re-green/80 text-white font-medium'
: 'text-gray-400 hover:bg-gray-800 hover:text-white'
}`}
>
<Receipt className="w-3.5 h-3.5 shrink-0" />
<span className="truncate">Debit Notes</span>
</button>
<button <button
type="button" type="button"
onClick={() => { onClick={() => {

View File

@ -4,9 +4,11 @@ import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/com
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge'; import { Badge } from '@/components/ui/badge';
import { ArrowLeft, Mail, Download, Loader2 } from 'lucide-react'; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { getCreditNoteById, type CreditNoteDetailResponse } from '@/services/form16Api'; import { ArrowLeft, Mail, Download, Loader2, RefreshCw, FileText, IndianRupee, CalendarClock } from 'lucide-react';
import { getCreditNoteById, getCreditNoteDownloadUrl, type CreditNoteDetailResponse } from '@/services/form16Api';
import { toast } from 'sonner'; import { toast } from 'sonner';
import apiClient from '@/services/authApi';
function formatDate(value: string | null | undefined): string { function formatDate(value: string | null | undefined): string {
if (!value) return ''; if (!value) return '';
@ -23,11 +25,65 @@ function formatAmount(value: number | null | undefined): string {
return new Intl.NumberFormat('en-IN', { style: 'currency', currency: 'INR', maximumFractionDigits: 0 }).format(value); return new Intl.NumberFormat('en-IN', { style: 'currency', currency: 'INR', maximumFractionDigits: 0 }).format(value);
} }
function buildAbsoluteBackendUrl(url: string): string {
if (!url) return url;
if (/^https?:\/\//i.test(url)) return url;
const apiBase = ((import.meta as any).env?.VITE_API_BASE_URL as string | undefined) || 'http://localhost:5000/api/v1';
const origin = apiBase.replace(/\/api\/v1\/?$/i, '');
return `${origin}${url.startsWith('/') ? '' : '/'}${url}`;
}
function parseSapResponseCsv(rawCsv: string): Record<string, string> | null {
const lines = rawCsv
.split(/\r?\n/)
.map((l) => l.trim())
.filter(Boolean);
if (lines.length < 2) return null;
const header = lines[0]!.split('|').map((h) => h.trim());
const isUsefulRow = (values: string[]) => {
const obj: Record<string, string> = {};
header.forEach((h, idx) => (obj[h] = (values[idx] || '').trim()));
const trns = (obj.TRNS_UNIQ_NO || '').trim();
const docNo = (obj.DOC_NO || '').trim();
const msgTyp = (obj.MSG_TYP || '').trim();
const tdsId = (obj.TDS_TRNS_ID || '').trim();
if (trns) return true;
if (tdsId && (docNo || msgTyp) && tdsId.toUpperCase() !== 'MSG_TYP' && tdsId.toUpperCase() !== 'MESSAGE') return true;
return false;
};
for (let i = lines.length - 1; i >= 1; i--) {
const values = lines[i]!.split('|');
if (isUsefulRow(values)) {
const obj: Record<string, string> = {};
header.forEach((h, idx) => (obj[h] = (values[idx] || '').trim()));
return obj;
}
}
return null;
}
function formatIssuedAt(value: string | null | undefined): string {
if (!value) return '';
try {
const d = new Date(value);
return Number.isNaN(d.getTime())
? value
: d.toLocaleString('en-IN', { day: '2-digit', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit' });
} catch {
return value;
}
}
export function Form16CreditNoteDetail() { export function Form16CreditNoteDetail() {
const navigate = useNavigate(); const navigate = useNavigate();
const { id } = useParams<{ id: string }>(); const { id } = useParams<{ id: string }>();
const [data, setData] = useState<CreditNoteDetailResponse | null>(null); const [data, setData] = useState<CreditNoteDetailResponse | null>(null);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [pulling, setPulling] = useState(false);
const [previewOpen, setPreviewOpen] = useState(false);
const [previewLoading, setPreviewLoading] = useState(false);
const [previewRow, setPreviewRow] = useState<Record<string, string> | null>(null);
const [previewCsv, setPreviewCsv] = useState<string>('');
useEffect(() => { useEffect(() => {
const numId = id ? parseInt(id, 10) : NaN; const numId = id ? parseInt(id, 10) : NaN;
@ -58,8 +114,47 @@ export function Form16CreditNoteDetail() {
toast.info('Resend to dealer integration pending'); toast.info('Resend to dealer integration pending');
}; };
const handleDownload = () => { const handlePull = async () => {
toast.info('Download credit note integration pending'); const numId = id ? parseInt(id, 10) : NaN;
if (Number.isNaN(numId)) return;
setPulling(true);
try {
const res = await getCreditNoteById(numId);
setData(res);
if (res.creditNote?.sapResponseAvailable) toast.success('Credit note is available to download.');
else toast.info('Credit note is being generated. Please wait.');
} catch (e: any) {
toast.error(e instanceof Error ? e.message : 'Failed to pull credit note');
} finally {
setPulling(false);
}
};
const handleDownload = async () => {
const numId = id ? parseInt(id, 10) : NaN;
if (Number.isNaN(numId)) return;
try {
const url = await getCreditNoteDownloadUrl(numId);
setPreviewOpen(true);
setPreviewLoading(true);
setPreviewRow(null);
setPreviewCsv('');
const absUrl = buildAbsoluteBackendUrl(url);
const res = await apiClient.get<Blob>(absUrl, { responseType: 'blob' });
const rawCsv = await res.data.text();
const row = parseSapResponseCsv(rawCsv);
if (!row) throw new Error('Could not parse SAP response CSV');
setPreviewRow(row);
setPreviewCsv(rawCsv);
} catch (e: any) {
const msg =
e?.response?.status === 409
? 'The credit note is being generated, wait.'
: (e instanceof Error ? e.message : 'Failed to download');
toast.error(String(msg));
} finally {
setPreviewLoading(false);
}
}; };
if (loading) { if (loading) {
@ -83,6 +178,117 @@ export function Form16CreditNoteDetail() {
return ( return (
<div className="space-y-6 min-h-screen bg-gray-50 p-4 md:p-6 w-full"> <div className="space-y-6 min-h-screen bg-gray-50 p-4 md:p-6 w-full">
<Dialog
open={previewOpen}
onOpenChange={(open) => {
setPreviewOpen(open);
if (!open) {
setPreviewRow(null);
setPreviewCsv('');
}
}}
>
<DialogContent className="sm:max-w-2xl">
<DialogHeader>
<DialogTitle>SAP Response</DialogTitle>
<DialogDescription>
{previewLoading ? 'Loading SAP response CSV…' : 'Review SAP response details and download the CSV.'}
</DialogDescription>
</DialogHeader>
{previewLoading ? (
<div className="py-8 flex items-center justify-center gap-2 text-gray-600">
<Loader2 className="w-5 h-5 animate-spin" />
Loading SAP response
</div>
) : previewRow ? (
<div className="space-y-4">
{/* Card 1 (GREEN): SAP identifiers only */}
<div className="rounded-xl border border-emerald-200 bg-emerald-50/70 p-4">
<div className="flex items-center gap-2">
<FileText className="w-4 h-4 text-emerald-700" />
<p className="text-xs font-semibold text-emerald-800 tracking-wide uppercase">SAP Response Identifiers</p>
</div>
<div className="mt-3 grid grid-cols-1 sm:grid-cols-2 gap-3">
<div className="rounded-lg border border-emerald-200 bg-white/70 p-3">
<p className="text-xs text-emerald-700 uppercase tracking-wide">TRNS_UNIQ_NO</p>
<p className="text-sm font-semibold text-emerald-900 break-all mt-1">{previewRow['TRNS_UNIQ_NO'] || ''}</p>
</div>
<div className="rounded-lg border border-emerald-200 bg-white/70 p-3">
<p className="text-xs text-emerald-700 uppercase tracking-wide">TDS_TRNS_ID</p>
<p className="text-sm font-semibold text-emerald-900 break-all mt-1">{previewRow['TDS_TRNS_ID'] || ''}</p>
</div>
</div>
</div>
{/* Card 2: Details */}
<div className="rounded-xl border border-amber-200 bg-amber-50/70 p-4">
<div className="flex items-center gap-2 mb-3">
<IndianRupee className="w-4 h-4 text-amber-700" />
<p className="text-xs font-semibold text-amber-800 tracking-wide uppercase">Credit Note Details</p>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
<div className="rounded-lg border border-amber-200 bg-white/70 p-3">
<p className="text-xs text-amber-700 uppercase tracking-wide flex items-center gap-2">
<IndianRupee className="w-4 h-4" /> Amount
</p>
<p className="text-base font-semibold text-amber-900 mt-1">{formatAmount(creditNote.amount)}</p>
</div>
<div className="rounded-lg border border-amber-200 bg-white/70 p-3">
<p className="text-xs text-amber-700 uppercase tracking-wide flex items-center gap-2">
<CalendarClock className="w-4 h-4" /> Issued Date
</p>
<p className="text-base font-semibold text-amber-900 mt-1">{formatIssuedAt(creditNote.issueDate)}</p>
</div>
<div className="rounded-lg border border-amber-200 bg-white/70 p-3">
<p className="text-xs text-amber-700 uppercase tracking-wide">DOC_NO</p>
<p className="text-sm font-semibold text-amber-900 break-all mt-1">{previewRow['DOC_NO'] || ''}</p>
</div>
<div className="rounded-lg border border-amber-200 bg-white/70 p-3">
<p className="text-xs text-amber-700 uppercase tracking-wide">MSG_TYP</p>
<p className="text-sm font-semibold text-amber-900 break-all mt-1">{previewRow['MSG_TYP'] || ''}</p>
</div>
</div>
<div className="rounded-lg border border-amber-200 bg-white/70 p-3 mt-3">
<p className="text-xs text-amber-700 uppercase tracking-wide">MESSAGE</p>
<p className="text-sm font-medium text-amber-900 break-words mt-1">{previewRow['MESSAGE'] || ''}</p>
</div>
</div>
</div>
) : (
<div className="py-8 text-sm text-gray-600">No preview available.</div>
)}
<DialogFooter className="gap-2 sm:gap-0">
<Button variant="outline" onClick={() => setPreviewOpen(false)}>
Close
</Button>
<Button
onClick={() => {
if (!previewCsv) return;
const fileName = `${creditNote.creditNoteNumber || `credit-note-${id}`}.csv`;
const blob = new Blob([previewCsv], { type: 'text/csv;charset=utf-8' });
const href = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = href;
a.download = fileName;
document.body.appendChild(a);
a.click();
a.remove();
URL.revokeObjectURL(href);
}}
disabled={!previewRow || previewLoading}
>
<Download className="w-4 h-4 mr-2" />
Download CSV
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
<div className="w-full min-w-0"> <div className="w-full min-w-0">
<div className="flex flex-wrap items-center justify-between gap-4 mb-6"> <div className="flex flex-wrap items-center justify-between gap-4 mb-6">
<Button <Button
@ -99,10 +305,6 @@ export function Form16CreditNoteDetail() {
<Mail className="w-4 h-4 mr-2" /> <Mail className="w-4 h-4 mr-2" />
Resend to Dealer Resend to Dealer
</Button> </Button>
<Button variant="outline" size="sm" onClick={handleDownload}>
<Download className="w-4 h-4 mr-2" />
Download Credit Note
</Button>
</div> </div>
</div> </div>
@ -128,6 +330,20 @@ export function Form16CreditNoteDetail() {
</p> </p>
</div> </div>
</div> </div>
<div className="flex justify-end gap-2 mt-4">
{creditNote.sapResponseAvailable ? (
<Button variant="outline" size="sm" onClick={handleDownload}>
<Download className="w-4 h-4 mr-2" />
Download Credit Note
</Button>
) : (
<Button variant="outline" size="sm" onClick={handlePull} disabled={pulling}>
{pulling ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : <RefreshCw className="w-4 h-4 mr-2" />}
Pull Credit Note
</Button>
)}
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 mt-6 pt-6 border-t border-gray-100"> <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 mt-6 pt-6 border-t border-gray-100">
<div> <div>
<p className="text-xs text-gray-500 uppercase tracking-wide">Dealer Name</p> <p className="text-xs text-gray-500 uppercase tracking-wide">Dealer Name</p>

View File

@ -1,18 +1,20 @@
import { useState, useEffect, useCallback, useMemo } from 'react'; import { useState, useEffect, useCallback, useMemo } from 'react';
import { useNavigate } from 'react-router-dom';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card'; import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge'; import { Badge } from '@/components/ui/badge';
import { Input } from '@/components/ui/input'; import { Input } from '@/components/ui/input';
import { Search, Loader2, Receipt } from 'lucide-react'; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Search, Loader2, Receipt, Download, RefreshCw, FileText, IndianRupee, CalendarClock } from 'lucide-react';
import { import {
listCreditNotes, listCreditNotes,
getCreditNoteDownloadUrl,
type Form16CreditNoteItem, type Form16CreditNoteItem,
type ListCreditNotesParams, type ListCreditNotesParams,
type ListCreditNotesSummary, type ListCreditNotesSummary,
} from '@/services/form16Api'; } from '@/services/form16Api';
import { toast } from 'sonner'; import { toast } from 'sonner';
import apiClient from '@/services/authApi';
function formatDate(value: string | null | undefined): string { function formatDate(value: string | null | undefined): string {
if (!value) return ''; if (!value) return '';
@ -35,12 +37,76 @@ const DEFAULT_SUMMARY: ListCreditNotesSummary = {
activeDealersCount: 0, activeDealersCount: 0,
}; };
type SapResponsePreview = {
fileUrl: string;
fileName: string;
rawCsv: string;
row: Record<string, string>;
meta: {
amountText: string;
issuedAtText: string;
};
};
function buildAbsoluteBackendUrl(url: string): string {
if (!url) return url;
if (/^https?:\/\//i.test(url)) return url;
const apiBase = ((import.meta as any).env?.VITE_API_BASE_URL as string | undefined) || 'http://localhost:5000/api/v1';
const origin = apiBase.replace(/\/api\/v1\/?$/i, '');
return `${origin}${url.startsWith('/') ? '' : '/'}${url}`;
}
function parseSapResponseCsv(rawCsv: string): Record<string, string> | null {
const lines = rawCsv
.split(/\r?\n/)
.map((l) => l.trim())
.filter(Boolean);
if (lines.length < 2) return null;
const header = lines[0]!.split('|').map((h) => h.trim());
const isUsefulRow = (values: string[]) => {
const obj: Record<string, string> = {};
header.forEach((h, idx) => (obj[h] = (values[idx] || '').trim()));
const trns = (obj.TRNS_UNIQ_NO || '').trim();
const docNo = (obj.DOC_NO || '').trim();
const msgTyp = (obj.MSG_TYP || '').trim();
const tdsId = (obj.TDS_TRNS_ID || '').trim();
if (trns) return true;
if (tdsId && (docNo || msgTyp) && tdsId.toUpperCase() !== 'MSG_TYP' && tdsId.toUpperCase() !== 'MESSAGE') return true;
return false;
};
for (let i = lines.length - 1; i >= 1; i--) {
const values = lines[i]!.split('|');
if (isUsefulRow(values)) {
const obj: Record<string, string> = {};
header.forEach((h, idx) => (obj[h] = (values[idx] || '').trim()));
return obj;
}
}
return null;
}
function formatIssuedAt(value: string | null | undefined): string {
if (!value) return '';
try {
const d = new Date(value);
return Number.isNaN(d.getTime())
? value
: d.toLocaleString('en-IN', { day: '2-digit', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit' });
} catch {
return value;
}
}
export function Form16CreditNotes() { export function Form16CreditNotes() {
const navigate = useNavigate();
const [creditNotes, setCreditNotes] = useState<Form16CreditNoteItem[]>([]); const [creditNotes, setCreditNotes] = useState<Form16CreditNoteItem[]>([]);
const [summary, setSummary] = useState<ListCreditNotesSummary>(DEFAULT_SUMMARY); const [summary, setSummary] = useState<ListCreditNotesSummary>(DEFAULT_SUMMARY);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [searchQuery, setSearchQuery] = useState(''); const [searchQuery, setSearchQuery] = useState('');
const [previewOpen, setPreviewOpen] = useState(false);
const [previewLoading, setPreviewLoading] = useState(false);
const [preview, setPreview] = useState<SapResponsePreview | null>(null);
const fetchNotes = useCallback(async (params?: ListCreditNotesParams) => { const fetchNotes = useCallback(async (params?: ListCreditNotesParams) => {
try { try {
@ -62,6 +128,52 @@ export function Form16CreditNotes() {
fetchNotes(); fetchNotes();
}, [fetchNotes]); }, [fetchNotes]);
const openSapPreview = useCallback(async (noteId: number, creditNoteNumber?: string | null) => {
setPreviewOpen(true);
setPreviewLoading(true);
setPreview(null);
try {
const url = await getCreditNoteDownloadUrl(noteId);
const absUrl = buildAbsoluteBackendUrl(url);
const fileName = (creditNoteNumber || `credit-note-${noteId}`).trim() + '.csv';
const res = await apiClient.get<Blob>(absUrl, { responseType: 'blob' });
const blob = res.data;
const rawCsv = await blob.text();
const row = parseSapResponseCsv(rawCsv);
if (!row) throw new Error('Could not parse SAP response CSV');
// Enrich with UI meta (amount/date from listing row when available)
const note = creditNotes.find((n) => Number(n.id) === Number(noteId));
const amountText = formatAmount(note?.amount ?? null);
const issuedAtText = formatIssuedAt(note?.issueDate ?? null);
setPreview({ fileUrl: absUrl, fileName, rawCsv, row, meta: { amountText, issuedAtText } });
} catch (e: any) {
const msg =
e?.response?.status === 409
? 'The credit note is being generated, wait.'
: (e instanceof Error ? e.message : 'Failed to load SAP response');
toast.error(String(msg));
setPreviewOpen(false);
} finally {
setPreviewLoading(false);
}
}, [creditNotes]);
const downloadPreviewCsv = useCallback(async () => {
if (!preview) return;
const blob = new Blob([preview.rawCsv], { type: 'text/csv;charset=utf-8' });
const href = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = href;
a.download = preview.fileName;
document.body.appendChild(a);
a.click();
a.remove();
URL.revokeObjectURL(href);
}, [preview]);
const filteredNotes = useMemo(() => { const filteredNotes = useMemo(() => {
if (!searchQuery.trim()) return creditNotes; if (!searchQuery.trim()) return creditNotes;
const q = searchQuery.trim().toLowerCase(); const q = searchQuery.trim().toLowerCase();
@ -76,6 +188,99 @@ export function Form16CreditNotes() {
return ( return (
<div className="space-y-6 min-h-screen bg-gray-50 p-4 md:p-6 w-full"> <div className="space-y-6 min-h-screen bg-gray-50 p-4 md:p-6 w-full">
<Dialog
open={previewOpen}
onOpenChange={(open) => {
setPreviewOpen(open);
if (!open) setPreview(null);
}}
>
<DialogContent className="sm:max-w-2xl">
<DialogHeader>
<DialogTitle>SAP Response</DialogTitle>
<DialogDescription>
{previewLoading ? 'Loading SAP response CSV…' : 'Review SAP response details and download the CSV.'}
</DialogDescription>
</DialogHeader>
{previewLoading ? (
<div className="py-8 flex items-center justify-center gap-2 text-gray-600">
<Loader2 className="w-5 h-5 animate-spin" />
Loading SAP response
</div>
) : preview ? (
<div className="space-y-4">
{/* Card 1 (GREEN): SAP identifiers only */}
<div className="rounded-xl border border-emerald-200 bg-emerald-50/70 p-4">
<div className="flex items-center gap-2">
<FileText className="w-4 h-4 text-emerald-700" />
<p className="text-xs font-semibold text-emerald-800 tracking-wide uppercase">SAP Response Identifiers</p>
</div>
<div className="mt-3 grid grid-cols-1 sm:grid-cols-2 gap-3">
<div className="rounded-lg border border-emerald-200 bg-white/70 p-3">
<p className="text-xs text-emerald-700 uppercase tracking-wide">TRNS_UNIQ_NO</p>
<p className="text-sm font-semibold text-emerald-900 break-all mt-1">{preview.row['TRNS_UNIQ_NO'] || ''}</p>
</div>
<div className="rounded-lg border border-emerald-200 bg-white/70 p-3">
<p className="text-xs text-emerald-700 uppercase tracking-wide">TDS_TRNS_ID</p>
<p className="text-sm font-semibold text-emerald-900 break-all mt-1">{preview.row['TDS_TRNS_ID'] || ''}</p>
</div>
</div>
</div>
{/* Card 2: Amount + date + ids */}
<div className="rounded-xl border border-amber-200 bg-amber-50/70 p-4">
<div className="flex items-center gap-2 mb-3">
<IndianRupee className="w-4 h-4 text-amber-700" />
<p className="text-xs font-semibold text-amber-800 tracking-wide uppercase">Credit Note Details</p>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
<div className="rounded-lg border border-amber-200 bg-white/70 p-3">
<p className="text-xs text-amber-700 uppercase tracking-wide flex items-center gap-2">
<IndianRupee className="w-4 h-4" /> Amount
</p>
<p className="text-base font-semibold text-amber-900 mt-1">{preview.meta.amountText}</p>
</div>
<div className="rounded-lg border border-amber-200 bg-white/70 p-3">
<p className="text-xs text-amber-700 uppercase tracking-wide flex items-center gap-2">
<CalendarClock className="w-4 h-4" /> Issued Date
</p>
<p className="text-base font-semibold text-amber-900 mt-1">{preview.meta.issuedAtText}</p>
</div>
<div className="rounded-lg border border-amber-200 bg-white/70 p-3">
<p className="text-xs text-amber-700 uppercase tracking-wide">DOC_NO</p>
<p className="text-sm font-semibold text-amber-900 break-all mt-1">{preview.row['DOC_NO'] || ''}</p>
</div>
<div className="rounded-lg border border-amber-200 bg-white/70 p-3">
<p className="text-xs text-amber-700 uppercase tracking-wide">MSG_TYP</p>
<p className="text-sm font-semibold text-amber-900 break-all mt-1">{preview.row['MSG_TYP'] || ''}</p>
</div>
</div>
<div className="rounded-lg border border-amber-200 bg-white/70 p-3 mt-3">
<p className="text-xs text-amber-700 uppercase tracking-wide">MESSAGE</p>
<p className="text-sm font-medium text-amber-900 break-words mt-1">{preview.row['MESSAGE'] || ''}</p>
</div>
</div>
</div>
) : (
<div className="py-8 text-sm text-gray-600">No preview available.</div>
)}
<DialogFooter className="gap-2 sm:gap-0">
<Button variant="outline" onClick={() => setPreviewOpen(false)}>
Close
</Button>
<Button onClick={downloadPreviewCsv} disabled={!preview || previewLoading}>
<Download className="w-4 h-4 mr-2" />
Download CSV
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
<div className="w-full min-w-0"> <div className="w-full min-w-0">
<div className="mb-6"> <div className="mb-6">
<h1 className="text-2xl sm:text-3xl font-bold text-gray-900 mb-2">Credit Notes</h1> <h1 className="text-2xl sm:text-3xl font-bold text-gray-900 mb-2">Credit Notes</h1>
@ -114,9 +319,8 @@ export function Form16CreditNotes() {
<Card> <Card>
<CardHeader> <CardHeader>
<CardTitle>All Credit Notes</CardTitle> <CardTitle>All Credit Notes</CardTitle>
<CardDescription className="flex flex-col gap-2"> <CardDescription>Search by credit note number, dealer name, or Form 16A number</CardDescription>
<span>Search by credit note number, dealer name, or Form 16A number</span> <div className="relative max-w-md mt-2">
<div className="relative max-w-md">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" /> <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
<Input <Input
type="search" type="search"
@ -126,7 +330,6 @@ export function Form16CreditNotes() {
className="pl-9" className="pl-9"
/> />
</div> </div>
</CardDescription>
</CardHeader> </CardHeader>
<CardContent> <CardContent>
<div className="rounded-lg border overflow-hidden"> <div className="rounded-lg border overflow-hidden">
@ -188,13 +391,38 @@ export function Form16CreditNotes() {
</Badge> </Badge>
</TableCell> </TableCell>
<TableCell className="text-right"> <TableCell className="text-right">
<div className="flex items-center justify-end gap-2">
{note.sapResponseAvailable ? (
<Button <Button
variant="outline" variant="outline"
size="sm" size="sm"
onClick={() => navigate(`/form16/credit-notes/${note.id}`)} onClick={async () => {
await openSapPreview(Number(note.id), note.creditNoteNumber);
}}
> >
View Details <Download className="w-4 h-4 mr-2" />
View
</Button> </Button>
) : (
<Button
variant="outline"
size="sm"
onClick={async () => {
toast.loading('Pulling credit note...', { id: `pull-cn-${note.id}` });
try {
await apiClient.post('/form16/sap/pull');
await fetchNotes();
toast.success('Refreshed.', { id: `pull-cn-${note.id}` });
} catch {
toast.error('Failed to pull credit note', { id: `pull-cn-${note.id}` });
}
}}
>
<RefreshCw className="w-4 h-4 mr-2" />
Pull
</Button>
)}
</div>
</TableCell> </TableCell>
</TableRow> </TableRow>
)) ))

View File

@ -0,0 +1,384 @@
import { useState, useEffect, useCallback, useMemo } from 'react';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Input } from '@/components/ui/input';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Search, Loader2, Receipt, RefreshCw, Eye, FileText, IndianRupee, CalendarClock } from 'lucide-react';
import { toast } from 'sonner';
import {
listDebitNotes,
getDebitNoteSapResponseUrl,
type Form16DebitNoteListItem,
type ListDebitNotesParams,
type ListDebitNotesSummary,
} from '@/services/form16Api';
import apiClient from '@/services/authApi';
function formatDate(value: string | null | undefined): string {
if (!value) return '';
try {
const d = new Date(value);
return Number.isNaN(d.getTime()) ? value : d.toLocaleDateString('en-IN', { day: '2-digit', month: 'short', year: 'numeric' });
} catch {
return value;
}
}
function formatAmount(value: number | null | undefined): string {
if (value == null) return '';
return new Intl.NumberFormat('en-IN', { style: 'currency', currency: 'INR', maximumFractionDigits: 0 }).format(value);
}
function formatIssuedAt(value: string | null | undefined): string {
if (!value) return '';
try {
const d = new Date(value);
return Number.isNaN(d.getTime())
? value
: d.toLocaleString('en-IN', { day: '2-digit', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit' });
} catch {
return value;
}
}
function buildAbsoluteBackendUrl(url: string): string {
if (!url) return url;
if (/^https?:\/\//i.test(url)) return url;
const apiBase = ((import.meta as any).env?.VITE_API_BASE_URL as string | undefined) || 'http://localhost:5000/api/v1';
const origin = apiBase.replace(/\/api\/v1\/?$/i, '');
return `${origin}${url.startsWith('/') ? '' : '/'}${url}`;
}
function parseSapResponseCsv(rawCsv: string): Record<string, string> | null {
const lines = rawCsv
.split(/\r?\n/)
.map((l) => l.trim())
.filter(Boolean);
if (lines.length < 2) return null;
const header = lines[0]!.split('|').map((h) => h.trim());
// Debit response should contain: TRNS_UNIQ_NO, CLAIM_NUMBER, DOC_NO, MSG_TYP, MESSAGE
for (let i = lines.length - 1; i >= 1; i--) {
const values = lines[i]!.split('|');
const obj: Record<string, string> = {};
header.forEach((h, idx) => (obj[h] = (values[idx] || '').trim()));
const trns = (obj.TRNS_UNIQ_NO || '').trim();
const claim = (obj.CLAIM_NUMBER || '').trim();
const doc = (obj.DOC_NO || '').trim();
const typ = (obj.MSG_TYP || '').trim();
if (trns || (claim && (doc || typ))) return obj;
}
return null;
}
const DEFAULT_SUMMARY: ListDebitNotesSummary = {
totalDebitNotes: 0,
totalAmount: 0,
impactedDealersCount: 0,
};
export function Form16DebitNotes() {
const [debitNotes, setDebitNotes] = useState<Form16DebitNoteListItem[]>([]);
const [summary, setSummary] = useState<ListDebitNotesSummary>(DEFAULT_SUMMARY);
const [loading, setLoading] = useState(true);
const [searchQuery, setSearchQuery] = useState('');
const [previewOpen, setPreviewOpen] = useState(false);
const [previewLoading, setPreviewLoading] = useState(false);
const [previewRow, setPreviewRow] = useState<Record<string, string> | null>(null);
const [previewMeta, setPreviewMeta] = useState<{ amountText: string; issuedAtText: string } | null>(null);
const [pulling, setPulling] = useState(false);
const fetchNotes = useCallback(async (params?: ListDebitNotesParams) => {
try {
setLoading(true);
const result = await listDebitNotes(params);
setDebitNotes(result.debitNotes);
setSummary(result.summary ?? DEFAULT_SUMMARY);
} catch (error: unknown) {
console.error('[Form16DebitNotes] Failed to fetch:', error);
toast.error(error instanceof Error ? error.message : 'Failed to load debit notes');
setDebitNotes([]);
setSummary(DEFAULT_SUMMARY);
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
fetchNotes();
}, [fetchNotes]);
const filteredNotes = useMemo(() => {
if (!searchQuery.trim()) return debitNotes;
const q = searchQuery.trim().toLowerCase();
return debitNotes.filter(
(n) =>
(n.debitNoteNumber && n.debitNoteNumber.toLowerCase().includes(q)) ||
(n.creditNoteNumber && n.creditNoteNumber.toLowerCase().includes(q)) ||
(n.dealerName && n.dealerName.toLowerCase().includes(q)) ||
(n.dealerCode && n.dealerCode.toLowerCase().includes(q)) ||
(n.form16aNumber && n.form16aNumber.toLowerCase().includes(q))
);
}, [debitNotes, searchQuery]);
const openSapPreview = useCallback(async (note: Form16DebitNoteListItem) => {
setPreviewOpen(true);
setPreviewLoading(true);
setPreviewRow(null);
setPreviewMeta({ amountText: formatAmount(note.amount), issuedAtText: formatIssuedAt(note.issueDate) });
try {
const url = await getDebitNoteSapResponseUrl(Number(note.id));
const absUrl = buildAbsoluteBackendUrl(url);
const res = await apiClient.get<Blob>(absUrl, { responseType: 'blob' });
const rawCsv = await res.data.text();
const row = parseSapResponseCsv(rawCsv);
if (!row) throw new Error('Could not parse SAP response CSV');
setPreviewRow(row);
} catch (e: any) {
const msg =
e?.response?.status === 409
? 'The debit note is being generated, wait.'
: (e instanceof Error ? e.message : 'Failed to load SAP response');
toast.error(String(msg));
setPreviewOpen(false);
} finally {
setPreviewLoading(false);
}
}, []);
const pullNow = useCallback(async () => {
setPulling(true);
toast.loading('Pulling SAP responses...', { id: 'pull-debit' });
try {
const res = await apiClient.post<{ data?: { processed?: number; debitProcessed?: number }; message?: string }>('/form16/sap/pull');
await fetchNotes();
const data = res.data?.data;
const debitCount = typeof data?.debitProcessed === 'number' ? data.debitProcessed : data?.processed;
if (typeof debitCount === 'number' && debitCount > 0) {
toast.success(`Pulled. ${debitCount} debit response(s) processed. List refreshed.`, { id: 'pull-debit' });
} else {
toast.success('Pulled. List refreshed. (No new debit responses in folder.)', { id: 'pull-debit' });
}
} catch {
toast.error('Failed to pull SAP responses', { id: 'pull-debit' });
} finally {
setPulling(false);
}
}, [fetchNotes]);
return (
<div className="space-y-6 min-h-screen bg-gray-50 p-4 md:p-6 w-full">
<Dialog
open={previewOpen}
onOpenChange={(open) => {
setPreviewOpen(open);
if (!open) {
setPreviewRow(null);
setPreviewMeta(null);
}
}}
>
<DialogContent className="sm:max-w-2xl">
<DialogHeader>
<DialogTitle>SAP Response</DialogTitle>
<DialogDescription>
{previewLoading ? 'Loading SAP response CSV…' : 'Review SAP response details.'}
</DialogDescription>
</DialogHeader>
{previewLoading ? (
<div className="py-8 flex items-center justify-center gap-2 text-gray-600">
<Loader2 className="w-5 h-5 animate-spin" />
Loading SAP response
</div>
) : previewRow ? (
<div className="space-y-4">
{/* Block 1 (green): TRNS_UNIQ_NO + CLAIM_NUMBER */}
<div className="rounded-xl border border-emerald-200 bg-emerald-50/70 p-4">
<div className="flex items-center gap-2">
<FileText className="w-4 h-4 text-emerald-700" />
<p className="text-xs font-semibold text-emerald-800 tracking-wide uppercase">SAP Response Identifiers</p>
</div>
<div className="mt-3 grid grid-cols-1 sm:grid-cols-2 gap-3">
<div className="rounded-lg border border-emerald-200 bg-white/70 p-3">
<p className="text-xs text-emerald-700 uppercase tracking-wide">TRNS_UNIQ_NO</p>
<p className="text-sm font-semibold text-emerald-900 break-all mt-1">{previewRow['TRNS_UNIQ_NO'] || ''}</p>
</div>
<div className="rounded-lg border border-emerald-200 bg-white/70 p-3">
<p className="text-xs text-emerald-700 uppercase tracking-wide">CLAIM_NUMBER</p>
<p className="text-sm font-semibold text-emerald-900 break-all mt-1">{previewRow['CLAIM_NUMBER'] || ''}</p>
</div>
</div>
</div>
{/* Block 2 (yellow): AMOUNT, DOC_NO, MSG_TYP, MESSAGE, ISSUED DATE */}
<div className="rounded-xl border border-amber-200 bg-amber-50/70 p-4">
<div className="flex items-center gap-2 mb-3">
<IndianRupee className="w-4 h-4 text-amber-700" />
<p className="text-xs font-semibold text-amber-800 tracking-wide uppercase">Debit Note Details</p>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
<div className="rounded-lg border border-amber-200 bg-white/70 p-3">
<p className="text-xs text-amber-700 uppercase tracking-wide flex items-center gap-2">
<IndianRupee className="w-4 h-4" /> Amount
</p>
<p className="text-base font-semibold text-amber-900 mt-1">{previewMeta?.amountText ?? ''}</p>
</div>
<div className="rounded-lg border border-amber-200 bg-white/70 p-3">
<p className="text-xs text-amber-700 uppercase tracking-wide flex items-center gap-2">
<CalendarClock className="w-4 h-4" /> Issued Date
</p>
<p className="text-base font-semibold text-amber-900 mt-1">{previewMeta?.issuedAtText ?? ''}</p>
</div>
<div className="rounded-lg border border-amber-200 bg-white/70 p-3">
<p className="text-xs text-amber-700 uppercase tracking-wide">DOC_NO</p>
<p className="text-sm font-semibold text-amber-900 break-all mt-1">{previewRow['DOC_NO'] || ''}</p>
</div>
<div className="rounded-lg border border-amber-200 bg-white/70 p-3">
<p className="text-xs text-amber-700 uppercase tracking-wide">MSG_TYP</p>
<p className="text-sm font-semibold text-amber-900 break-all mt-1">{previewRow['MSG_TYP'] || ''}</p>
</div>
</div>
<div className="rounded-lg border border-amber-200 bg-white/70 p-3 mt-3">
<p className="text-xs text-amber-700 uppercase tracking-wide">MESSAGE</p>
<p className="text-sm font-medium text-amber-900 break-words mt-1">{previewRow['MESSAGE'] || ''}</p>
</div>
</div>
</div>
) : (
<div className="py-8 text-sm text-gray-600">No preview available.</div>
)}
<DialogFooter className="gap-2 sm:gap-0">
<Button variant="outline" onClick={() => setPreviewOpen(false)}>
Close
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
<div className="w-full min-w-0">
<div className="mb-6">
<h1 className="text-2xl sm:text-3xl font-bold text-gray-900 mb-2">Debit Notes</h1>
<p className="text-sm text-gray-600">View all issued debit notes</p>
</div>
<div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
<Card>
<CardHeader className="pb-3">
<CardDescription>Total Debit Notes Issued</CardDescription>
<CardTitle className="text-3xl">{loading ? '...' : summary.totalDebitNotes}</CardTitle>
</CardHeader>
</Card>
<Card>
<CardHeader className="pb-3">
<CardDescription>Total Debit Amount</CardDescription>
<CardTitle className="text-3xl text-red-600">{loading ? '...' : formatAmount(summary.totalAmount)}</CardTitle>
</CardHeader>
</Card>
<Card>
<CardHeader className="pb-3">
<CardDescription>Impacted Dealers</CardDescription>
<CardTitle className="text-3xl">{loading ? '...' : summary.impactedDealersCount}</CardTitle>
</CardHeader>
</Card>
</div>
<Card>
<CardHeader>
<CardTitle>All Debit Notes</CardTitle>
<CardDescription>Search by debit note number, credit note number, dealer, or Form 16A number</CardDescription>
<div className="relative max-w-md">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
<Input
type="search"
placeholder="Search debit notes..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="pl-9"
/>
</div>
</CardHeader>
<CardContent>
<div className="rounded-lg border overflow-hidden">
<Table>
<TableHeader>
<TableRow>
<TableHead>Debit Note No.</TableHead>
<TableHead>Credit Note No.</TableHead>
<TableHead>Dealer</TableHead>
<TableHead>Form 16A No.</TableHead>
<TableHead>Amount</TableHead>
<TableHead>Issue Date</TableHead>
<TableHead>Status</TableHead>
<TableHead className="text-right">Actions</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{loading ? (
<TableRow>
<TableCell colSpan={8} className="text-center py-12">
<Loader2 className="w-6 h-6 animate-spin mx-auto mb-2 text-teal-600" />
<p className="text-gray-500">Loading debit notes...</p>
</TableCell>
</TableRow>
) : filteredNotes.length === 0 ? (
<TableRow>
<TableCell colSpan={8} className="text-center py-12 text-gray-500">
<Receipt className="w-12 h-12 mx-auto mb-3 text-gray-400" />
<p>No debit notes found</p>
<p className="text-sm mt-1">{searchQuery.trim() ? 'Try a different search.' : 'Debit notes will appear here once issued.'}</p>
</TableCell>
</TableRow>
) : (
filteredNotes.map((note) => (
<TableRow key={note.id} className="hover:bg-gray-50 transition-colors">
<TableCell className="font-medium">{note.debitNoteNumber ?? ''}</TableCell>
<TableCell className="font-medium">{note.creditNoteNumber ?? ''}</TableCell>
<TableCell>{note.dealerName ?? note.dealerCode ?? ''}</TableCell>
<TableCell>{note.form16aNumber ?? ''}</TableCell>
<TableCell>{formatAmount(note.amount)}</TableCell>
<TableCell>{formatDate(note.issueDate)}</TableCell>
<TableCell>
<Badge
className={
note.status?.toLowerCase() === 'issued' || note.status?.toLowerCase() === 'completed'
? 'bg-green-100 text-green-800 border-green-200'
: 'bg-gray-100 text-gray-700 border-gray-200'
}
>
{note.status ?? ''}
</Badge>
</TableCell>
<TableCell className="text-right">
<div className="flex items-center justify-end gap-2">
{note.sapResponseAvailable ? (
<Button variant="outline" size="sm" onClick={() => openSapPreview(note)}>
<Eye className="w-4 h-4 mr-2" />
View
</Button>
) : (
<Button variant="outline" size="sm" onClick={pullNow} disabled={pulling}>
{pulling ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : <RefreshCw className="w-4 h-4 mr-2" />}
Pull
</Button>
)}
</div>
</TableCell>
</TableRow>
))
)}
</TableBody>
</Table>
</div>
</CardContent>
</Card>
</div>
</div>
);
}

View File

@ -180,6 +180,10 @@ export function Form16Submit() {
status === 'duplicate' status === 'duplicate'
? 'A credit note has already been issued for this financial year and quarter. This submission is recorded as a new version.' ? 'A credit note has already been issued for this financial year and quarter. This submission is recorded as a new version.'
: undefined; : undefined;
const mismatchMessage =
status === 'mismatch'
? (result.validationNotes || 'Form 16A details did not match with 26AS data.')
: undefined;
toast.success(status === 'success' ? 'Form 16A matched with 26AS. Credit note generated.' : 'Form 16A submitted successfully'); toast.success(status === 'success' ? 'Form 16A matched with 26AS. Credit note generated.' : 'Form 16A submitted successfully');
navigate('/form16/submit/result', { navigate('/form16/submit/result', {
state: { state: {
@ -187,7 +191,7 @@ export function Form16Submit() {
requestId: result.requestId, requestId: result.requestId,
requestNumber: result.requestNumber, requestNumber: result.requestNumber,
creditNoteNumber: result.creditNoteNumber ?? undefined, creditNoteNumber: result.creditNoteNumber ?? undefined,
message: duplicateMessage, message: duplicateMessage ?? mismatchMessage,
}, },
}); });
} catch (err: unknown) { } catch (err: unknown) {

View File

@ -5,6 +5,8 @@ import { Card, CardContent } from '@/components/ui/card';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { StatusChip } from './StatusChip'; import { StatusChip } from './StatusChip';
import { TimelineStep } from './TimelineStep'; import { TimelineStep } from './TimelineStep';
import { contactAdminForForm16Mismatch } from '@/services/form16Api';
import { toast } from 'sonner';
export type SubmissionResultStatus = 'success' | 'mismatch' | 'duplicate' | 'error'; export type SubmissionResultStatus = 'success' | 'mismatch' | 'duplicate' | 'error';
@ -32,6 +34,18 @@ export function RequestSubmissionSuccess({
}: RequestSubmissionSuccessProps) { }: RequestSubmissionSuccessProps) {
const isSuccess = status === 'success'; const isSuccess = status === 'success';
const isMismatch = status === 'mismatch'; const isMismatch = status === 'mismatch';
const isMissing26AsMismatch = isMismatch && (message || '').toLowerCase().includes('26as') && (message || '').toLowerCase().includes('no 26as');
const onContactAdmin = async () => {
try {
await contactAdminForForm16Mismatch(requestId);
toast.success('Administrator notified');
} catch (e: any) {
const msg = e?.response?.data?.message || e?.message || 'Failed to notify administrator';
toast.error(String(msg));
}
};
const isDuplicate = status === 'duplicate'; const isDuplicate = status === 'duplicate';
const isError = status === 'error'; const isError = status === 'error';
@ -160,6 +174,16 @@ export function RequestSubmissionSuccess({
<p className="text-sm text-amber-800 whitespace-pre-wrap">{message}</p> <p className="text-sm text-amber-800 whitespace-pre-wrap">{message}</p>
</div> </div>
)} )}
{isMissing26AsMismatch && (
<div className="mt-3 p-3 bg-white border border-amber-200 rounded-md">
<p className="text-sm font-semibold text-gray-900 mb-1">
Contact administrator: FORM 26AS does not match FORM 16A.
</p>
<p className="text-sm text-gray-700">
If you have submitted the updated Form 16A but the latest 26AS is not uploaded for this quarter yet, please notify RE so they can upload/update 26AS.
</p>
</div>
)}
</> </>
) : ( ) : (
<> <>
@ -253,6 +277,11 @@ export function RequestSubmissionSuccess({
{isDuplicate ? 'Back to New Submission' : isMismatch ? 'Resubmit Form 16A' : 'Try Again'} {isDuplicate ? 'Back to New Submission' : isMismatch ? 'Resubmit Form 16A' : 'Try Again'}
</Button> </Button>
)} )}
{isMissing26AsMismatch && (
<Button onClick={onContactAdmin} variant="outline" className="border-amber-300 text-amber-800">
Contact admin
</Button>
)}
<Button onClick={onComplete} variant="outline"> <Button onClick={onComplete} variant="outline">
Back to My Requests Back to My Requests
</Button> </Button>

View File

@ -102,9 +102,15 @@ export interface Form16AdminConfig {
reminderEnabled: boolean; reminderEnabled: boolean;
reminderDays: number; reminderDays: number;
notification26AsDataAdded?: Form16NotificationItem | Form16Notification26AsItem; notification26AsDataAdded?: Form16NotificationItem | Form16Notification26AsItem;
/** RE reminder to upload 26AS (quarter end + N days) */
reminder26AsUploadEnabled?: boolean;
reminder26AsUploadAfterQuarterEndDays?: number;
notificationForm16SuccessCreditNote?: Form16NotificationItem; notificationForm16SuccessCreditNote?: Form16NotificationItem;
notificationForm16Unsuccessful?: Form16NotificationItem; notificationForm16Unsuccessful?: Form16NotificationItem;
alertSubmitForm16Enabled?: boolean; alertSubmitForm16Enabled?: boolean;
/** Dealer reminder to submit Form 16A (quarter end + N days, repeat every X days) */
alertSubmitForm16AfterQuarterEndDays?: number;
alertSubmitForm16EveryDays?: number;
alertSubmitForm16FrequencyDays?: number; alertSubmitForm16FrequencyDays?: number;
alertSubmitForm16FrequencyHours?: number; alertSubmitForm16FrequencyHours?: number;
/** When to run the alert job daily (HH:mm, 24h, server timezone). */ /** When to run the alert job daily (HH:mm, 24h, server timezone). */

View File

@ -50,6 +50,8 @@ export interface Form16CreditNoteItem {
id: string; id: string;
creditNoteNumber: string | null; creditNoteNumber: string | null;
sapDocumentNumber: string | null; sapDocumentNumber: string | null;
/** True when SAP response CSV is ingested and downloadable */
sapResponseAvailable?: boolean;
amount: number | null; amount: number | null;
issueDate: string | null; issueDate: string | null;
financialYear: string | null; financialYear: string | null;
@ -62,6 +64,14 @@ export interface Form16CreditNoteItem {
dealerName?: string | null; dealerName?: string | null;
} }
export async function getCreditNoteDownloadUrl(id: number): Promise<string> {
const { data } = await apiClient.get<{ data?: { url?: string }; url?: string }>(`/form16/credit-notes/${id}/download`);
const payload = data?.data ?? data;
const url = payload?.url;
if (!url) throw new Error('Download link not available');
return url;
}
export interface ListCreditNotesSummary { export interface ListCreditNotesSummary {
totalCreditNotes: number; totalCreditNotes: number;
totalAmount: number; totalAmount: number;
@ -79,6 +89,41 @@ export interface ListCreditNotesParams {
quarter?: string; quarter?: string;
} }
// ---------- Debit notes (RE only) ----------
export interface Form16DebitNoteListItem {
id: number;
debitNoteNumber: string | null;
sapDocumentNumber?: string | null;
sapResponseAvailable?: boolean;
amount: number | null;
issueDate: string | null;
status: string | null;
financialYear?: string | null;
quarter?: string | null;
creditNoteNumber?: string | null;
dealerCode?: string | null;
dealerName?: string | null;
form16aNumber?: string | null;
}
export interface ListDebitNotesSummary {
totalDebitNotes: number;
totalAmount: number;
impactedDealersCount?: number;
}
export interface ListDebitNotesResponse {
debitNotes: Form16DebitNoteListItem[];
total: number;
summary?: ListDebitNotesSummary;
}
export interface ListDebitNotesParams {
financialYear?: string;
quarter?: string;
}
export interface Form16Permissions { export interface Form16Permissions {
canViewForm16Submission: boolean; canViewForm16Submission: boolean;
canView26AS: boolean; canView26AS: boolean;
@ -115,6 +160,32 @@ export async function listCreditNotes(params?: ListCreditNotesParams): Promise<L
}; };
} }
/**
* RE only. List debit notes.
*/
export async function listDebitNotes(params?: ListDebitNotesParams): Promise<ListDebitNotesResponse> {
const searchParams = new URLSearchParams();
if (params?.financialYear) searchParams.set('financialYear', params.financialYear);
if (params?.quarter) searchParams.set('quarter', params.quarter);
const query = searchParams.toString();
const url = query ? `/form16/debit-notes?${query}` : '/form16/debit-notes';
const { data } = await apiClient.get<{ data?: ListDebitNotesResponse; debitNotes?: Form16DebitNoteListItem[]; total?: number; summary?: ListDebitNotesSummary }>(url);
const payload = data?.data ?? data;
return {
debitNotes: payload?.debitNotes ?? [],
total: payload?.total ?? 0,
summary: payload?.summary,
};
}
export async function getDebitNoteSapResponseUrl(id: number): Promise<string> {
const { data } = await apiClient.get<{ data?: { url?: string }; url?: string }>(`/form16/debit-notes/${id}/sap-response`);
const payload = data?.data ?? data;
const url = payload?.url;
if (!url) throw new Error('SAP response link not available');
return url;
}
/** Get credit note linked to a Form 16 request (for workflow tab). */ /** Get credit note linked to a Form 16 request (for workflow tab). */
export async function getCreditNoteByRequestId(requestId: string): Promise<Form16CreditNoteItem | null> { export async function getCreditNoteByRequestId(requestId: string): Promise<Form16CreditNoteItem | null> {
const { data } = await apiClient.get<{ data?: { creditNote?: Form16CreditNoteItem | null }; creditNote?: Form16CreditNoteItem | null }>(`/form16/requests/${encodeURIComponent(requestId)}/credit-note`); const { data } = await apiClient.get<{ data?: { creditNote?: Form16CreditNoteItem | null }; creditNote?: Form16CreditNoteItem | null }>(`/form16/requests/${encodeURIComponent(requestId)}/credit-note`);
@ -329,6 +400,8 @@ export interface CreateForm16SubmissionResponse {
submissionId: number; submissionId: number;
/** Set when 26AS matching runs: 'success' | 'failed' | 'resubmission_needed' */ /** Set when 26AS matching runs: 'success' | 'failed' | 'resubmission_needed' */
validationStatus?: string; validationStatus?: string;
/** Reason/details returned by backend (e.g. no 26AS, amount mismatch) */
validationNotes?: string;
/** Credit note number when validationStatus === 'success' */ /** Credit note number when validationStatus === 'success' */
creditNoteNumber?: string | null; creditNoteNumber?: string | null;
} }
@ -361,6 +434,11 @@ export async function createForm16Submission(payload: CreateForm16SubmissionPayl
return req; return req;
} }
/** Dealer: notify RE admins when 26AS is missing/outdated for the quarter (contact admin CTA). */
export async function contactAdminForForm16Mismatch(requestId: string): Promise<void> {
await apiClient.post(`/form16/requests/${encodeURIComponent(requestId)}/contact-admin`);
}
// ---------- RE: 26AS ---------- // ---------- RE: 26AS ----------
export interface Tds26asEntryItem { export interface Tds26asEntryItem {
id: number; id: number;