document page done

This commit is contained in:
2025-06-20 19:19:37 +05:30
parent bbabb3b035
commit 01806a11cd
5 changed files with 699 additions and 138 deletions

View File

@@ -1,8 +1,6 @@
import { Router } from "express";
import { Request, Response } from "express";
import { storage } from "../storage";
import { z } from "zod";
import { ClaimUncheckedCreateInputObjectSchema } from "@repo/db/usedSchemas";
import multer from "multer";
const upload = multer({ storage: multer.memoryStorage() });
@@ -57,9 +55,17 @@ router.get("/claim-pdf/:id", async (req: Request, res: Response): Promise<any> =
const id = parseInt(idParam);
const pdf = await storage.getClaimPdfById(id);
if (!pdf) return res.status(404).json({ error: "PDF not found" });
if (!pdf || !pdf.pdfData) return res.status(404).json({ error: "PDF not found" });
// Fix bad objectified Buffer
if (!Buffer.isBuffer(pdf.pdfData)) {
pdf.pdfData = Buffer.from(Object.values(pdf.pdfData));
}
res.setHeader("Content-Type", "application/pdf");
res.setHeader(
"Content-Disposition",
`attachment; filename="${pdf.filename}"; filename*=UTF-8''${encodeURIComponent(pdf.filename)}`
);
res.send(pdf.pdfData);
} catch (err) {
console.error("Error fetching PDF by ID:", err);

View File

@@ -6,7 +6,7 @@ import {
StaffUncheckedCreateInputObjectSchema,
ClaimUncheckedCreateInputObjectSchema,
InsuranceCredentialUncheckedCreateInputObjectSchema,
ClaimPdfUncheckedCreateInputObjectSchema
ClaimPdfUncheckedCreateInputObjectSchema,
} from "@repo/db/usedSchemas";
import { z } from "zod";
@@ -146,7 +146,7 @@ type ClaimWithServiceLines = Claim & {
}[];
};
// claim types:
// claim types:
type ClaimPdf = z.infer<typeof ClaimPdfUncheckedCreateInputObjectSchema>;
export interface ClaimPdfMetadata {
@@ -166,6 +166,7 @@ export interface IStorage {
// Patient methods
getPatient(id: number): Promise<Patient | undefined>;
getPatientsByUserId(userId: number): Promise<Patient[]>;
getRecentPatients(limit: number, offset: number): Promise<Patient[]>;
createPatient(patient: InsertPatient): Promise<Patient>;
updatePatient(id: number, patient: UpdatePatient): Promise<Patient>;
deletePatient(id: number): Promise<void>;
@@ -175,6 +176,8 @@ export interface IStorage {
getAllAppointments(): Promise<Appointment[]>;
getAppointmentsByUserId(userId: number): Promise<Appointment[]>;
getAppointmentsByPatientId(patientId: number): Promise<Appointment[]>;
getRecentAppointments(limit: number, offset: number): Promise<Appointment[]>;
getAppointmentsOn(date: Date): Promise<Appointment[]>;
createAppointment(appointment: InsertAppointment): Promise<Appointment>;
updateAppointment(
id: number,
@@ -234,7 +237,10 @@ export interface IStorage {
getAllClaimPdfs(): Promise<ClaimPdfMetadata[]>;
getRecentClaimPdfs(limit: number, offset: number): Promise<ClaimPdfMetadata[]>;
getRecentClaimPdfs(
limit: number,
offset: number
): Promise<ClaimPdfMetadata[]>;
deleteClaimPdf(id: number): Promise<boolean>;
@@ -290,6 +296,14 @@ export const storage: IStorage = {
return await db.patient.findMany({ where: { userId } });
},
async getRecentPatients(limit: number, offset: number): Promise<Patient[]> {
return db.patient.findMany({
skip: offset,
take: limit,
orderBy: { createdAt: "desc" },
});
},
async createPatient(patient: InsertPatient): Promise<Patient> {
return await db.patient.create({ data: patient as Patient });
},
@@ -332,6 +346,35 @@ export const storage: IStorage = {
return await db.appointment.findMany({ where: { patientId } });
},
async getAppointmentsOn(date: Date): Promise<Appointment[]> {
const start = new Date(date);
start.setHours(0, 0, 0, 0);
const end = new Date(date);
end.setHours(23, 59, 59, 999);
return db.appointment.findMany({
where: {
date: {
gte: start,
lte: end,
},
},
orderBy: { date: "asc" },
});
},
async getRecentAppointments(
limit: number,
offset: number
): Promise<Appointment[]> {
return db.appointment.findMany({
skip: offset,
take: limit,
orderBy: { date: "desc" }
});
},
async createAppointment(
appointment: InsertAppointment
): Promise<Appointment> {
@@ -534,7 +577,10 @@ export const storage: IStorage = {
});
},
async getRecentClaimPdfs(limit: number, offset: number): Promise<ClaimPdfMetadata[]> {
async getRecentClaimPdfs(
limit: number,
offset: number
): Promise<ClaimPdfMetadata[]> {
return db.claimPdf.findMany({
skip: offset,
take: limit,
@@ -543,6 +589,7 @@ export const storage: IStorage = {
id: true,
filename: true,
uploadedAt: true,
patient:true,
},
});
},
@@ -561,7 +608,10 @@ export const storage: IStorage = {
updates: Partial<Pick<ClaimPdf, "filename" | "pdfData">>
): Promise<ClaimPdf | undefined> {
try {
const updated = await db.claimPdf.update({ where: { id }, data: updates });
const updated = await db.claimPdf.update({
where: { id },
data: updates,
});
return updated;
} catch {
return undefined;

View File

@@ -1,19 +1,19 @@
import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { useEffect, useState } from "react";
import { useMutation, useQuery } from "@tanstack/react-query";
import { TopAppBar } from "@/components/layout/top-app-bar";
import { Sidebar } from "@/components/layout/sidebar";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
Search,
Edit,
Eye,
ChevronLeft,
import { Card, CardContent } from "@/components/ui/card";
import {
Search,
Eye,
ChevronLeft,
ChevronRight,
Settings
Settings,
Trash,
Download,
} from "lucide-react";
import { PatientUncheckedCreateInputObjectSchema } from "@repo/db/usedSchemas";
import { useAuth } from "@/hooks/use-auth";
import { cn } from "@/lib/utils";
import {
@@ -23,37 +23,19 @@ import {
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import {z} from "zod";
const PatientSchema = (
PatientUncheckedCreateInputObjectSchema as unknown as z.ZodObject<any>
).omit({
appointments: true,
});
type Patient = z.infer<typeof PatientSchema>;
const insertPatientSchema = (
PatientUncheckedCreateInputObjectSchema as unknown as z.ZodObject<any>
).omit({
id: true,
createdAt: true,
userId: true,
});
type InsertPatient = z.infer<typeof insertPatientSchema>;
const updatePatientSchema = (
PatientUncheckedCreateInputObjectSchema as unknown as z.ZodObject<any>
)
.omit({
id: true,
createdAt: true,
userId: true,
})
.partial();
type UpdatePatient = z.infer<typeof updatePatientSchema>;
import { ClaimPdfUncheckedCreateInputObjectSchema } from "@repo/db/usedSchemas";
import { z } from "zod";
import "@react-pdf-viewer/core/lib/styles/index.css";
import "@react-pdf-viewer/default-layout/lib/styles/index.css";
import { Viewer, Worker } from "@react-pdf-viewer/core";
import { defaultLayoutPlugin } from "@react-pdf-viewer/default-layout";
import { apiRequest, queryClient } from "@/lib/queryClient";
import { toast } from "@/hooks/use-toast";
import { DeleteConfirmationDialog } from "@/components/ui/deleteDialog";
const ClaimPdfSchema =
ClaimPdfUncheckedCreateInputObjectSchema as unknown as z.ZodObject<any>;
type ClaimPdf = z.infer<typeof ClaimPdfSchema>;
export default function DocumentsPage() {
const { user } = useAuth();
@@ -62,24 +44,139 @@ export default function DocumentsPage() {
const [searchField, setSearchField] = useState("all");
const [currentPage, setCurrentPage] = useState(1);
const itemsPerPage = 5;
const [selectedPdfId, setSelectedPdfId] = useState<number | null>(null);
const defaultLayoutPluginInstance = defaultLayoutPlugin();
const [isDeletePdfOpen, setIsDeletePdfOpen] = useState(false);
const [currentPdf, setCurrentPdf] = useState<ClaimPdf | null>(null);
// Fetch patients
const {
data: patients = [],
isLoading: isLoadingPatients,
} = useQuery<Patient[]>({
queryKey: ["/api/patients"],
const { data: pdfs = [], isLoading } = useQuery<ClaimPdf[]>({
queryKey: ["/api/documents/claim-pdf/recent"],
enabled: !!user,
queryFn: async () => {
const res = await apiRequest("GET", "/api/documents/claim-pdf/recent");
return res.json();
},
});
// Filter patients based on search
const filteredPatients = patients.filter(patient => {
if (!searchTerm) return true;
const deletePdfMutation = useMutation({
mutationFn: async (id: number) => {
await apiRequest("DELETE", `/api/documents/claim-pdf/${id}`);
},
onSuccess: () => {
setIsDeletePdfOpen(false);
setCurrentPdf(null);
queryClient.invalidateQueries({
queryKey: ["/api/documents/claim-pdf/recent"],
});
toast({
title: "Success",
description: "PDF deleted successfully!",
variant: "default",
});
},
onError: (error: any) => {
console.error("Error deleting PDF:", error);
toast({
title: "Error",
description: `Failed to delete PDF: ${error.message || error}`,
variant: "destructive",
});
},
});
const formatDate = (dateString: string) => {
const date = new Date(dateString);
return date.toLocaleDateString("en-US", {
month: "short",
day: "numeric",
year: "numeric",
});
};
const getPatientInitials = (first: string, last: string) =>
`${first[0]}${last[0]}`.toUpperCase();
const [fileBlobUrl, setFileBlobUrl] = useState<string | null>(null);
useEffect(() => {
if (!selectedPdfId) return;
let url: string | null = null;
const fetchPdf = async () => {
try {
const res = await apiRequest(
"GET",
`/api/documents/claim-pdf/${selectedPdfId}`
);
const arrayBuffer = await res.arrayBuffer();
const blob = new Blob([arrayBuffer], { type: "application/pdf" });
const objectUrl = URL.createObjectURL(blob);
setFileBlobUrl(objectUrl);
url = objectUrl;
} catch (err) {
console.error("Failed to load PDF", err);
}
};
fetchPdf();
return () => {
if (url) {
URL.revokeObjectURL(url);
}
};
}, [selectedPdfId]);
const toggleMobileMenu = () => setIsMobileMenuOpen((prev) => !prev);
const viewPdf = (pdfId: number) => {
setSelectedPdfId(pdfId);
};
const downloadPdf = async (pdfId: number, filename: string) => {
try {
const res = await apiRequest("GET", `/api/documents/claim-pdf/${pdfId}`);
const arrayBuffer = await res.arrayBuffer();
const blob = new Blob([arrayBuffer], { type: "application/pdf" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
} catch (err) {
console.error("Failed to download PDF:", err);
}
};
const handleDeletePdf = (pdf: ClaimPdf) => {
setCurrentPdf(pdf);
setIsDeletePdfOpen(true);
};
const handleConfirmDeletePdf = () => {
if (currentPdf) {
deletePdfMutation.mutate(currentPdf.id);
} else {
toast({
title: "Error",
description: "No PDF selected for deletion.",
variant: "destructive",
});
}
};
const filteredPdfs = pdfs.filter((pdf) => {
const patient = pdf.patient;
const searchLower = searchTerm.toLowerCase();
const fullName = `${patient.firstName} ${patient.lastName}`.toLowerCase();
const patientId = `PID-${patient.id.toString().padStart(4, '0')}`;
const patientId = `PID-${patient.id.toString().padStart(4, "0")}`;
switch (searchField) {
case "name":
return fullName.includes(searchLower);
@@ -91,7 +188,7 @@ export default function DocumentsPage() {
default:
return (
fullName.includes(searchLower) ||
patientId.toLowerCase().includes(searchLower) ||
patientId.includes(searchLower) ||
patient.phone?.toLowerCase().includes(searchLower) ||
patient.email?.toLowerCase().includes(searchLower) ||
false
@@ -99,45 +196,31 @@ export default function DocumentsPage() {
}
});
// Pagination
const totalPages = Math.ceil(filteredPatients.length / itemsPerPage);
const totalPages = Math.ceil(filteredPdfs.length / itemsPerPage);
const startIndex = (currentPage - 1) * itemsPerPage;
const endIndex = startIndex + itemsPerPage;
const currentPatients = filteredPatients.slice(startIndex, endIndex);
const toggleMobileMenu = () => {
setIsMobileMenuOpen(!isMobileMenuOpen);
};
const formatDate = (dateString: string) => {
const date = new Date(dateString);
return date.toLocaleDateString('en-US', {
month: 'short',
day: 'numeric',
year: 'numeric'
});
};
const getPatientInitials = (firstName: string, lastName: string) => {
return `${firstName.charAt(0)}${lastName.charAt(0)}`.toUpperCase();
};
const currentPdfs = filteredPdfs.slice(startIndex, startIndex + itemsPerPage);
return (
<div className="flex h-screen bg-gray-50">
<Sidebar isMobileOpen={isMobileMenuOpen} setIsMobileOpen={setIsMobileMenuOpen} />
<Sidebar
isMobileOpen={isMobileMenuOpen}
setIsMobileOpen={setIsMobileMenuOpen}
/>
<div className="flex-1 flex flex-col overflow-hidden">
<TopAppBar toggleMobileMenu={toggleMobileMenu} />
<main className="flex-1 overflow-auto p-6">
<div className="max-w-7xl mx-auto">
{/* Header */}
<div className="mb-6">
<h1 className="text-2xl font-semibold text-gray-900 mb-2">Documents</h1>
<p className="text-gray-600">View and manage all patient information</p>
<h1 className="text-2xl font-semibold text-gray-900 mb-2">
Documents
</h1>
<p className="text-gray-600">
View and manage recent uploaded claim PDFs
</p>
</div>
{/* Search and Filters */}
<Card className="mb-6">
<CardContent className="p-4">
<div className="flex flex-col md:flex-row gap-4">
@@ -171,14 +254,18 @@ export default function DocumentsPage() {
</CardContent>
</Card>
{/* Patient List */}
<Card>
<CardContent className="p-0">
{isLoadingPatients ? (
<div className="text-center py-8">Loading patients...</div>
{isLoading ? (
<div className="text-center py-8">Loading data...</div>
) : currentPdfs.length === 0 ? (
<div className="text-center py-8 text-gray-500">
{searchTerm
? "No results matching your search."
: "No recent claim PDFs available."}
</div>
) : (
<>
{/* Table Header */}
<div className="grid grid-cols-12 gap-4 p-4 bg-gray-50 border-b text-sm font-medium text-gray-600">
<div className="col-span-3">Patient</div>
<div className="col-span-2">DOB / Gender</div>
@@ -188,33 +275,30 @@ export default function DocumentsPage() {
<div className="col-span-1">Actions</div>
</div>
{/* Table Rows */}
{currentPatients.length === 0 ? (
<div className="text-center py-8 text-gray-500">
{searchTerm ? "No patients found matching your search." : "No patients available."}
</div>
) : (
currentPatients.map((patient) => (
<div
key={patient.id}
className="grid grid-cols-12 gap-4 p-4 border-b hover:bg-gray-50 transition-colors"
{currentPdfs.map((pdf) => {
const patient = pdf.patient;
return (
<div
key={pdf.id}
className="grid grid-cols-12 gap-4 p-4 border-b hover:bg-gray-50"
>
{/* Patient Info */}
<div className="col-span-3 flex items-center space-x-3">
<div className="w-10 h-10 bg-gray-200 rounded-full flex items-center justify-center text-sm font-medium text-gray-600">
{getPatientInitials(patient.firstName, patient.lastName)}
{getPatientInitials(
patient.firstName,
patient.lastName
)}
</div>
<div>
<div className="font-medium text-gray-900">
{patient.firstName} {patient.lastName}
</div>
<div className="text-sm text-gray-500">
PID-{patient.id.toString().padStart(4, '0')}
PID-{patient.id.toString().padStart(4, "0")}
</div>
</div>
</div>
{/* DOB / Gender */}
<div className="col-span-2">
<div className="text-sm text-gray-900">
{formatDate(patient.dateOfBirth)}
@@ -224,78 +308,141 @@ export default function DocumentsPage() {
</div>
</div>
{/* Contact */}
<div className="col-span-2">
<div className="text-sm text-gray-900">
{patient.phone || 'Not provided'}
{patient.phone || "Not provided"}
</div>
<div className="text-sm text-gray-500">
{patient.email || 'No email'}
{patient.email || "No email"}
</div>
</div>
{/* Insurance */}
<div className="col-span-2">
<div className="text-sm text-gray-900">
{patient.insuranceProvider ?
`${patient.insuranceProvider.charAt(0).toUpperCase()}${patient.insuranceProvider.slice(1)}` :
'Not specified'
}
{patient.insuranceProvider
? `${patient.insuranceProvider.charAt(0).toUpperCase()}${patient.insuranceProvider.slice(1)}`
: "Not specified"}
</div>
<div className="text-sm text-gray-500">
ID: {patient.insuranceId || 'N/A'}
ID: {patient.insuranceId || "N/A"}
</div>
</div>
{/* Status */}
<div className="col-span-2">
<span className={cn(
"inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium",
patient.status === 'active'
? "bg-green-100 text-green-800"
: "bg-gray-100 text-gray-800"
)}>
{patient.status === 'active' ? 'Active' : 'Inactive'}
<span
className={cn(
"inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium",
patient.status === "active"
? "bg-green-100 text-green-800"
: "bg-gray-100 text-gray-800"
)}
>
{patient.status === "active"
? "Active"
: "Inactive"}
</span>
</div>
{/* Actions */}
<div className="col-span-1">
<div className="flex space-x-1">
<Button variant="ghost" size="sm" className="h-8 w-8 p-0">
<Edit className="h-4 w-4 text-blue-600" />
<Button
variant="ghost"
size="sm"
className="h-8 w-8 p-0"
onClick={() => handleDeletePdf(pdf)}
>
<Trash className="h-4 w-4 text-red-600" />
</Button>
<Button variant="ghost" size="sm" className="h-8 w-8 p-0">
<Button
variant="ghost"
size="sm"
className="h-8 w-8 p-0"
onClick={() =>
downloadPdf(pdf.id, pdf.filename)
}
>
<Download className="h-4 w-4 text-blue-600" />
</Button>
<Button
variant="ghost"
size="sm"
className="h-8 w-8 p-0"
onClick={() => viewPdf(pdf.id)}
>
<Eye className="h-4 w-4 text-gray-600" />
</Button>
</div>
</div>
</div>
))
);
})}
<DeleteConfirmationDialog
isOpen={isDeletePdfOpen}
onConfirm={handleConfirmDeletePdf}
onCancel={() => setIsDeletePdfOpen(false)}
entityName={`PDF #${currentPdf?.id}`}
/>
{/* PDF Viewer */}
{selectedPdfId && fileBlobUrl && (
<div className="mt-6 border rounded-lg shadow-sm p-4 bg-white">
<div className="flex justify-between items-center mb-4">
<h2 className="text-lg font-semibold text-gray-700">
Viewing PDF #{selectedPdfId}
</h2>
<Button
variant="ghost"
onClick={() => {
setSelectedPdfId(null);
setFileBlobUrl(null);
}}
>
Close
</Button>
</div>
<div className="h-[80vh] border">
<Worker workerUrl="https://unpkg.com/pdfjs-dist@3.11.174/build/pdf.worker.min.js">
<Viewer
fileUrl={fileBlobUrl}
plugins={[defaultLayoutPluginInstance]}
/>
</Worker>
</div>
</div>
)}
{/* Pagination */}
{totalPages > 1 && (
<div className="flex items-center justify-between p-4 border-t bg-gray-50">
<div className="text-sm text-gray-700">
Showing {startIndex + 1} to {Math.min(endIndex, filteredPatients.length)} of {filteredPatients.length} results
Showing {startIndex + 1} to{" "}
{Math.min(
startIndex + itemsPerPage,
filteredPdfs.length
)}{" "}
of {filteredPdfs.length} results
</div>
<div className="flex items-center space-x-2">
<Button
variant="outline"
size="sm"
onClick={() => setCurrentPage(Math.max(1, currentPage - 1))}
onClick={() => setCurrentPage(currentPage - 1)}
disabled={currentPage === 1}
>
<ChevronLeft className="h-4 w-4 mr-1" />
Previous
</Button>
{/* Page Numbers */}
{Array.from({ length: totalPages }, (_, i) => i + 1).map((page) => (
{Array.from(
{ length: totalPages },
(_, i) => i + 1
).map((page) => (
<Button
key={page}
variant={currentPage === page ? "default" : "outline"}
variant={
currentPage === page ? "default" : "outline"
}
size="sm"
onClick={() => setCurrentPage(page)}
className="w-8 h-8 p-0"
@@ -303,11 +450,10 @@ export default function DocumentsPage() {
{page}
</Button>
))}
<Button
variant="outline"
size="sm"
onClick={() => setCurrentPage(Math.min(totalPages, currentPage + 1))}
onClick={() => setCurrentPage(currentPage + 1)}
disabled={currentPage === totalPages}
>
Next
@@ -325,4 +471,4 @@ export default function DocumentsPage() {
</div>
</div>
);
}
}