Skip to content

🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.

Add delete import data endpoint

Edward Cuifce9f23842e8
diff --git a/client/src/api/admin/import.ts b/client/src/api/admin/import.ts
index adf5903d7..00e62818c 100644
--- a/client/src/api/admin/import.ts
+++ b/client/src/api/admin/import.ts
@@ -23,6 +23,10 @@ interface ImportSiteDataResponse {
message: string;
}
+interface DeleteImportResponse {
+ message: string;
+}
+
export function useGetSiteImports(site: number) {
return useQuery({
queryKey: ["get-site-imports", site],
@@ -67,3 +71,21 @@ export function useImportSiteData(site: number) {
retry: false,
});
}
+
+export function useDeleteSiteImport(site: number) {
+ const queryClient = useQueryClient();
+
+ return useMutation({
+ mutationFn: async (importId: string) => {
+ return await authedFetch<APIResponse<DeleteImportResponse>>(`/delete-site-import/${site}/${importId}`, undefined, {
+ method: "DELETE",
+ });
+ },
+ onSuccess: async () => {
+ await queryClient.invalidateQueries({
+ queryKey: ["get-site-imports", site]
+ });
+ },
+ retry: false,
+ });
+}
diff --git a/client/src/components/SiteSettings/ImportManager.tsx b/client/src/components/SiteSettings/ImportManager.tsx
index 0ce6ca8d5..854d9fffd 100644
--- a/client/src/components/SiteSettings/ImportManager.tsx
+++ b/client/src/components/SiteSettings/ImportManager.tsx
@@ -41,8 +41,9 @@ import {
Clock,
Loader2,
Database,
+ Trash2,
} from "lucide-react";
-import { useGetSiteImports, useImportSiteData } from "@/api/admin/import";
+import { useGetSiteImports, useImportSiteData, useDeleteSiteImport } from "@/api/admin/import";
import { SplitDateRangePicker, DateRange } from "@/components/SplitDateRangePicker";
interface ImportManagerProps {
@@ -68,11 +69,14 @@ export function ImportManager({ siteId, disabled }: ImportManagerProps) {
const [dateRange, setDateRange] = useState<DateRange>({});
const [fileError, setFileError] = useState<FileValidationError | null>(null);
const [showConfirmDialog, setShowConfirmDialog] = useState<boolean>(false);
+ const [deleteImportId, setDeleteImportId] = useState<string | null>(null);
+ const [showDeleteDialog, setShowDeleteDialog] = useState<boolean>(false);
const fileInputRef = useRef<HTMLInputElement>(null);
const { data, isLoading, error } = useGetSiteImports(siteId);
const mutation = useImportSiteData(siteId);
+ const deleteMutation = useDeleteSiteImport(siteId);
const resetFileInput = () => {
setFile(null);
@@ -159,6 +163,19 @@ export function ImportManager({ siteId, disabled }: ImportManagerProps) {
}
};
+ const handleDeleteClick = (importId: string) => {
+ setDeleteImportId(importId);
+ setShowDeleteDialog(true);
+ };
+
+ const handleDeleteConfirm = () => {
+ if (deleteImportId) {
+ deleteMutation.mutate(deleteImportId);
+ setDeleteImportId(null);
+ setShowDeleteDialog(false);
+ }
+ };
+
const getStatusInfo = (status: string) => {
switch (status.toLowerCase()) {
case "completed":
@@ -328,6 +345,30 @@ export function ImportManager({ siteId, disabled }: ImportManagerProps) {
</div>
</Alert>
)}
+
+ {/* Delete Success Message */}
+ {deleteMutation.isSuccess && (
+ <Alert className="border-green-200 bg-green-50">
+ <div className="flex items-center gap-2">
+ <CheckCircle2 className="h-4 w-4 text-green-600" />
+ <AlertDescription>
+ Import deleted successfully.
+ </AlertDescription>
+ </div>
+ </Alert>
+ )}
+
+ {/* Delete Error Message */}
+ {deleteMutation.isError && (
+ <Alert variant="destructive">
+ <div className="flex items-center gap-2">
+ <AlertCircle className="h-4 w-4" />
+ <AlertDescription>
+ {deleteMutation.error.message || "Failed to delete import. Please try again."}
+ </AlertDescription>
+ </div>
+ </Alert>
+ )}
</CardContent>
</Card>
@@ -367,6 +408,7 @@ export function ImportManager({ siteId, disabled }: ImportManagerProps) {
<TableHead>Source</TableHead>
<TableHead>Status</TableHead>
<TableHead className="text-right">Events</TableHead>
+ <TableHead className="text-right">Actions</TableHead>
</TableRow>
</TableHeader>
<TableBody>
@@ -408,6 +450,23 @@ export function ImportManager({ siteId, disabled }: ImportManagerProps) {
<TableCell className="text-right">
{imp.importedEvents.toLocaleString()}
</TableCell>
+ <TableCell className="text-right">
+ {(imp.status === "completed" || imp.status === "failed") && (
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => handleDeleteClick(imp.importId)}
+ disabled={disabled || deleteMutation.isPending}
+ className="h-8 w-8 p-0"
+ >
+ {deleteMutation.isPending && deleteMutation.variables === imp.importId ? (
+ <Loader2 className="h-4 w-4 animate-spin" />
+ ) : (
+ <Trash2 className="h-4 w-4" />
+ )}
+ </Button>
+ )}
+ </TableCell>
</TableRow>
);
})}
@@ -436,6 +495,25 @@ export function ImportManager({ siteId, disabled }: ImportManagerProps) {
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
+
+ {/* Delete Confirmation Dialog */}
+ <AlertDialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Delete Import</AlertDialogTitle>
+ <AlertDialogDescription>
+ Are you sure you want to delete this import? This action cannot be undone.
+ The import data and associated files will be permanently removed.
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Cancel</AlertDialogCancel>
+ <AlertDialogAction onClick={handleDeleteConfirm} className="bg-red-600 hover:bg-red-700">
+ Delete Import
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
</div>
);
}
diff --git a/server/src/api/sites/deleteSiteImport.ts b/server/src/api/sites/deleteSiteImport.ts
new file mode 100644
index 000000000..0b76160e4
--- /dev/null
+++ b/server/src/api/sites/deleteSiteImport.ts
@@ -0,0 +1,85 @@
+import { FastifyReply, FastifyRequest } from "fastify";
+import { z } from "zod";
+import { getUserHasAdminAccessToSite } from "../../lib/auth-utils.js";
+import { ImportStatusManager } from "../../services/import/importStatusManager.js";
+import { deleteImportFile } from "../../services/import/utils.js";
+import { IS_CLOUD } from "../../lib/const.js";
+import { r2Storage } from "../../services/storage/r2StorageService.js";
+
+const deleteImportRequestSchema = z.object({
+ params: z.object({
+ site: z.string().min(1),
+ importId: z.string().min(1),
+ }),
+}).strict();
+
+type DeleteImportRequest = {
+ Params: z.infer<typeof deleteImportRequestSchema.shape.params>;
+};
+
+export async function deleteSiteImport(
+ request: FastifyRequest<DeleteImportRequest>,
+ reply: FastifyReply,
+) {
+ try {
+ const parsed = deleteImportRequestSchema.safeParse({
+ params: request.params,
+ });
+
+ if (!parsed.success) {
+ return reply.status(400).send({ error: "Validation error" });
+ }
+
+ const { site, importId } = parsed.data.params;
+
+ const userHasAccess = await getUserHasAdminAccessToSite(request, site);
+ if (!userHasAccess) {
+ return reply.status(403).send({ error: "Forbidden" });
+ }
+
+ // Get the import to verify it exists and belongs to this site
+ const importRecord = await ImportStatusManager.getImportById(importId);
+ if (!importRecord) {
+ return reply.status(404).send({ error: "Import not found" });
+ }
+
+ // Verify the import belongs to this site
+ if (importRecord.siteId !== Number(site)) {
+ return reply.status(403).send({ error: "Import does not belong to this site" });
+ }
+
+ // Don't allow deletion of active imports
+ if (importRecord.status === "pending" || importRecord.status === "processing") {
+ return reply.status(400).send({ error: "Cannot delete active import" });
+ }
+
+ // Delete the import file if it exists
+ try {
+ // For completed/failed imports, try to delete the file
+ // We construct the storage location based on whether it's R2 or local
+ let storageLocation: string;
+ if (IS_CLOUD && r2Storage.isEnabled()) {
+ storageLocation = `imports/${importId}/${importRecord.fileName}`;
+ } else {
+ storageLocation = `/tmp/imports/${importId}.csv`;
+ }
+
+ await deleteImportFile(storageLocation, IS_CLOUD && r2Storage.isEnabled());
+ } catch (fileError) {
+ // Log the error but don't fail the deletion - the file might not exist
+ console.warn(`Failed to delete import file for ${importId}:`, fileError);
+ }
+
+ // Delete the import record from the database
+ await ImportStatusManager.deleteImport(importId);
+
+ return reply.send({
+ data: {
+ message: "Import deleted successfully"
+ }
+ });
+ } catch (error) {
+ console.error("Error deleting import:", error);
+ return reply.status(500).send({ error: "Internal server error" });
+ }
+}
diff --git a/server/src/index.ts b/server/src/index.ts
index 6d8635fe1..61898aa60 100644
--- a/server/src/index.ts
+++ b/server/src/index.ts
@@ -72,13 +72,13 @@ import { loadAllowedDomains } from "./lib/allowedDomains.js";
import { getSessionFromReq, mapHeaders } from "./lib/auth-utils.js";
import { auth } from "./lib/auth.js";
import { IS_CLOUD } from "./lib/const.js";
-import { siteConfig } from "./lib/siteConfig.js";
import { trackEvent } from "./services/tracker/trackEvent.js";
// need to import telemetry service here to start it
import { telemetryService } from "./services/telemetryService.js";
import { extractSiteId, isSitePublic } from "./utils.js";
import { getSiteImports } from "./api/sites/getSiteImports.js";
import { importSiteData } from "./api/sites/importSiteData.js";
+import { deleteSiteImport } from "./api/sites/deleteSiteImport.js";
import boss from "./db/postgres/boss.js";
import { registerCsvParseWorker } from "./services/import/workers/csvParseWorker.js";
import { registerDataInsertWorker } from "./services/import/workers/dataInsertWorker.js";
@@ -351,6 +351,7 @@ server.get("/api/session-replay/:sessionId/:site", getSessionReplayEvents);
// Imports
server.post("/api/import-site-data/:site", importSiteData);
server.get("/api/get-site-imports/:site", getSiteImports);
+server.delete("/api/delete-site-import/:site/:importId", deleteSiteImport);
// Administrative
server.get("/api/config", getConfig);
diff --git a/server/src/services/import/importStatusManager.ts b/server/src/services/import/importStatusManager.ts
index 154c4e633..cd4063095 100644
--- a/server/src/services/import/importStatusManager.ts
+++ b/server/src/services/import/importStatusManager.ts
@@ -63,4 +63,24 @@ export class ImportStatusManager {
throw new Error(`Failed to get imports for site: ${error instanceof Error ? error.message : "Unknown error"}`);
}
}
+
+ static async deleteImport(importId: string): Promise<void> {
+ try {
+ await db.delete(importStatus).where(eq(importStatus.importId, importId));
+ } catch (error) {
+ console.error(`Failed to delete import ${importId}:`, error);
+ throw new Error(`Failed to delete import: ${error instanceof Error ? error.message : "Unknown error"}`);
+ }
+ }
+
+ static async getImportById(importId: string): Promise<SelectImportStatus | undefined> {
+ try {
+ return await db.query.importStatus.findFirst({
+ where: eq(importStatus.importId, importId),
+ });
+ } catch (error) {
+ console.error(`Failed to get import ${importId}:`, error);
+ throw new Error(`Failed to get import: ${error instanceof Error ? error.message : "Unknown error"}`);
+ }
+ }
}