This commit is contained in:
2026-05-10 18:25:58 +01:00
parent 165af509ef
commit e4f4992a1b
31 changed files with 2708 additions and 495 deletions

View File

@@ -19,7 +19,12 @@ import { prisma } from "@/lib/db/prisma";
import { BlockchainService } from "@/lib/services/blockchain.service";
import { NotificationService } from "@/lib/services/notification.service";
import { ContractService } from "@/lib/services/contract.service";
import type { BlockchainTransactionView, BlockchainStats } from "@/lib/services/blockchain.types";
import { CertificateService } from "@/lib/services/certificate.service";
import type {
BlockchainTransactionView,
BlockchainStats,
CryptographicCertificate,
} from "@/lib/services/blockchain.types";
/**
* Register a contract's document on the blockchain.
@@ -44,7 +49,8 @@ export async function registerContractOnBlockchain(contractId: string) {
if (!BlockchainService.isConfigured()) {
return {
success: false,
error: "Blockchain not configured. Start a Hardhat node and check your .env.",
error:
"Blockchain not configured. Start a Hardhat node and check your .env.",
};
}
@@ -74,7 +80,7 @@ export async function registerContractOnBlockchain(contractId: string) {
// Hash the document and register on-chain
const proof = await BlockchainService.hashAndRegister(
contract.fileUrl,
contract.fileName
contract.fileName,
);
// Save proof data to the Contract record
@@ -137,7 +143,8 @@ export async function registerContractOnBlockchain(contractId: string) {
console.error("❌ Blockchain registration error:", error);
return {
success: false,
error: error instanceof Error ? error.message : "Unknown blockchain error",
error:
error instanceof Error ? error.message : "Unknown blockchain error",
};
}
}
@@ -151,14 +158,18 @@ export async function verifyContractOnBlockchain(contractId: string) {
if (!clerkId) return { success: false, error: "Unauthorized" };
if (!BlockchainService.isReadConfigured()) {
return { success: false, error: "Blockchain not configured for verification" };
return {
success: false,
error: "Blockchain not configured for verification",
};
}
const user = await ContractService.getUserByClerkId(clerkId);
if (!user) return { success: false, error: "User not found" };
const contract = await ContractService.getById(contractId);
if (contract.userId !== user.id) return { success: false, error: "Unauthorized" };
if (contract.userId !== user.id)
return { success: false, error: "Unauthorized" };
if (!contract.documentHash) {
return {
@@ -167,7 +178,9 @@ export async function verifyContractOnBlockchain(contractId: string) {
};
}
const verification = await BlockchainService.verifyOnChain(contract.documentHash);
const verification = await BlockchainService.verifyOnChain(
contract.documentHash,
);
return {
success: true,
@@ -199,7 +212,10 @@ export async function verifyDocumentHashOnBlockchain(documentHash: string) {
if (!clerkId) return { success: false, error: "Unauthorized" };
if (!BlockchainService.isReadConfigured()) {
return { success: false, error: "Blockchain not configured for verification" };
return {
success: false,
error: "Blockchain not configured for verification",
};
}
// Ensure proper format
@@ -313,3 +329,97 @@ export async function getBlockchainStats(): Promise<{
};
}
}
/**
* Generate a cryptographic certificate for a blockchain-registered contract.
*
* The certificate contains:
* - Contract metadata
* - Blockchain proof (txHash, block, timestamp)
* - A digital signature created by the server wallet
*
* @param contractId - The contract ID
* @returns Certificate data (JSON) or error
*/
export async function generateContractCertificate(contractId: string): Promise<{
success: boolean;
certificate?: CryptographicCertificate;
certificateJson?: string;
certificatePdfBase64?: string;
certificateFileName?: string;
error?: string;
}> {
try {
const { userId: clerkId } = await auth();
if (!clerkId) return { success: false, error: "Unauthorized" };
if (!BlockchainService.isReadConfigured()) {
return {
success: false,
error: "Blockchain not configured for certificate generation",
};
}
const user = await ContractService.getUserByClerkId(clerkId);
if (!user) return { success: false, error: "User not found" };
const contract = await ContractService.getById(contractId);
if (contract.userId !== user.id) {
return {
success: false,
error: "Unauthorized: Contract does not belong to you",
};
}
// Check if contract is registered on blockchain
if (!contract.documentHash || !contract.txHash) {
return {
success: false,
error:
"Contract is not registered on blockchain. Register it first to generate a certificate.",
};
}
// Generate the certificate
const certificate = await CertificateService.generateCertificate(
contract.id,
contract.title,
contract.fileName,
contract.documentHash,
contract.txHash,
contract.blockNumber || 0,
contract.blockTimestamp?.toISOString() || new Date().toISOString(),
contract.blockchainNetwork || "hardhat",
contract.contractAddress || "",
);
// Generate a professional PDF for download
const pdfBuffer =
await CertificateService.generateCertificatePdf(certificate);
const certificatePdfBase64 = pdfBuffer.toString("base64");
const baseName = (contract.title || contract.fileName || contract.id)
.replace(/[^a-zA-Z0-9-_]+/g, "-")
.replace(/^-+|-+$/g, "")
.slice(0, 64);
const dateStamp = new Date().toISOString().slice(0, 10);
const certificateFileName = `certificate-${baseName || contract.id}-${dateStamp}.pdf`;
// Keep JSON available for internal use or auditing if needed
const certificateJson = JSON.stringify(certificate, null, 2);
return {
success: true,
certificate,
certificateJson,
certificatePdfBase64,
certificateFileName,
};
} catch (error: unknown) {
console.error("❌ Certificate generation error:", error);
return {
success: false,
error: error instanceof Error ? error.message : "Unknown error",
};
}
}

View File

@@ -0,0 +1,116 @@
"use client";
import { useEffect, useState } from "react";
import { Clock, AlertCircle } from "lucide-react";
interface ContractCountdownProps {
endDate?: string | null;
className?: string;
}
export function ContractCountdown({
endDate,
className = "",
}: ContractCountdownProps) {
const [daysLeft, setDaysLeft] = useState<number | null>(null);
const [isExpired, setIsExpired] = useState(false);
useEffect(() => {
if (!endDate) {
setDaysLeft(null);
return;
}
const calculateDaysLeft = () => {
const end = new Date(endDate);
const today = new Date();
// Reset time for comparison
end.setHours(0, 0, 0, 0);
today.setHours(0, 0, 0, 0);
const timeDiff = end.getTime() - today.getTime();
const days = Math.ceil(timeDiff / (1000 * 3600 * 24));
setIsExpired(days < 0);
setDaysLeft(days);
};
calculateDaysLeft();
// Update every minute to keep countdown fresh
const interval = setInterval(calculateDaysLeft, 60000);
return () => clearInterval(interval);
}, [endDate]);
if (daysLeft === null) {
return null;
}
// Determine colors based on urgency
const getUrgencyStyle = () => {
if (isExpired) {
return {
bg: "bg-red-500/15",
border: "border-red-500/40",
text: "text-red-700 dark:text-red-300",
icon: "text-red-500",
label: "Expired",
};
}
if (daysLeft < 7) {
return {
bg: "bg-red-500/15",
border: "border-red-500/40",
text: "text-red-700 dark:text-red-300",
icon: "text-red-500",
label: `${daysLeft} day${daysLeft !== 1 ? "s" : ""} left`,
};
}
if (daysLeft < 14) {
return {
bg: "bg-orange-500/15",
border: "border-orange-500/40",
text: "text-orange-700 dark:text-orange-300",
icon: "text-orange-500",
label: `${daysLeft} days left`,
};
}
if (daysLeft < 30) {
return {
bg: "bg-amber-500/15",
border: "border-amber-500/40",
text: "text-amber-700 dark:text-amber-300",
icon: "text-amber-500",
label: `${daysLeft} days left`,
};
}
return {
bg: "bg-green-500/15",
border: "border-green-500/40",
text: "text-green-700 dark:text-green-300",
icon: "text-green-500",
label: `${daysLeft} days left`,
};
};
const urgency = getUrgencyStyle();
return (
<div
className={`inline-flex items-center gap-2 rounded-full border ${urgency.bg} ${urgency.border} px-3 py-1.5 text-[11px] font-bold uppercase tracking-wider ${urgency.text} ${className}`}
>
{isExpired ? (
<AlertCircle className={`h-3.5 w-3.5 ${urgency.icon}`} />
) : (
<Clock className={`h-3.5 w-3.5 ${urgency.icon} animate-pulse`} />
)}
{urgency.label}
</div>
);
}

View File

@@ -60,6 +60,7 @@ import {
import { toast } from "sonner";
import { ContractChatModal } from "@/features/contracts/components/modals/contract-chat-modal";
import { ContractProofModal } from "@/features/contracts/components/modals/contract-proof-modal";
import { ContractCountdown } from "@/features/contracts/components/contract-countdown";
import {
stripMarkdown,
exportToCSV,
@@ -1122,6 +1123,10 @@ export function ContractsList({ refreshTrigger }: { refreshTrigger?: number }) {
/>
{status.label}
</span>
{contract.endDate &&
contract.status === "COMPLETED" && (
<ContractCountdown endDate={contract.endDate} />
)}
{contract.isRagged && (
<span className="inline-flex items-center gap-1 rounded-full border border-cyan-500/30 bg-cyan-500/10 px-2 py-0.5 text-[10px] font-bold uppercase tracking-wider text-cyan-700 dark:text-cyan-300">
<Network className="h-3 w-3" />