"use client" import { useParams } from "next/navigation" import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query" import { type ColumnDef } from "@tanstack/react-table" import { useState } from "react" import { Plus, Trash2 } from "lucide-react" import { toast } from "sonner" import { useAuthApi } from "@/shared/useApi" import { DataTable, ColumnHeader } from "@/shared/data-view/table-view" import { confirm } from "@/shared/components/confirm-dialog" import { Button } from "@/shared/components/ui/button" import { Card, CardContent } from "@/shared/components/ui/card" import { Dialog, DialogContent, DialogHeader, DialogTitle, } from "@/shared/components/ui/dialog" import { CreditNoteDocumentForm } from "@/modules/credit-notes/credit-note-document-form" type CreditNoteAttachment = { id: number name?: string url?: string created_at: string } export default function CreditNoteDocumentsPage() { const { id: creditNoteId } = useParams<{ id: string }>() const api = useAuthApi() const queryClient = useQueryClient() const [dialogOpen, setDialogOpen] = useState(false) const queryKey = ["credit-note-attachments", creditNoteId] const { data, isLoading } = useQuery({ queryKey, queryFn: async () => { const response = await api.creditNotes.show(creditNoteId) return (response as any)?.data ?? response }, }) const deleteMutation = useMutation({ mutationFn: (attachmentId: number) => api.creditNotes.deleteAttachment(creditNoteId, { attachment_id: attachmentId }), onSuccess: () => { toast.success("Attachment deleted successfully.") queryClient.invalidateQueries({ queryKey }) }, onError: () => { toast.error("Failed to delete attachment.") }, }) const handleDelete = async (attachment: CreditNoteAttachment) => { const confirmed = await confirm({ title: "Delete Attachment", description: `Are you sure you want to delete "${attachment.name || "this attachment"}"?`, confirmLabel: "Delete", variant: "destructive", }) if (confirmed) { deleteMutation.mutate(attachment.id) } } const columns: ColumnDef[] = [ { accessorKey: "name", header: ({ column }) => , cell: ({ getValue, row }) => { const name = getValue() const url = row.original.url if (url) { return ( {name || "Attachment"} ) } return name || "—" }, }, { accessorKey: "created_at", header: ({ column }) => , cell: ({ getValue }) => { const val = getValue() return val ? new Date(val).toLocaleDateString() : "—" }, }, { id: "actions", header: () => Actions, cell: ({ row }) => ( ), enableSorting: false, }, ] const attachments: CreditNoteAttachment[] = (data as any)?.attachments ?? [] return (
{}} isLoading={isLoading} /> Upload Attachment { setDialogOpen(false) queryClient.invalidateQueries({ queryKey }) }} />
) }