72 lines
2.5 KiB
TypeScript
72 lines
2.5 KiB
TypeScript
import { Request, Response } from "express";
|
|
import { createDocument, findDocumentById, deleteDocument, getDocumentsByClient } from "../models/Document";
|
|
import { successResponse, errorResponse } from "../utils/response";
|
|
import { logAction } from "../services/auditService";
|
|
import fs from "fs";
|
|
import path from "path";
|
|
import { env } from "../config/env";
|
|
|
|
export const uploadDocument = async (req: any, res: Response) => {
|
|
try {
|
|
if (!req.file) return errorResponse(res, "No file uploaded", 400);
|
|
|
|
const { client_id, category = "general" } = req.body;
|
|
const doc = await createDocument({
|
|
client_id,
|
|
name: req.file.originalname,
|
|
file_path: req.file.filename,
|
|
file_type: req.file.mimetype,
|
|
file_size: req.file.size,
|
|
category,
|
|
uploaded_by: req.user.userId
|
|
});
|
|
|
|
await logAction(req, "UPLOAD", "document", doc.id, { name: req.file.originalname, client_id });
|
|
return successResponse(res, doc, "Document uploaded", 201);
|
|
} catch (error: any) {
|
|
return errorResponse(res, error.message, 500);
|
|
}
|
|
};
|
|
|
|
export const getDocuments = async (req: Request, res: Response) => {
|
|
try {
|
|
const { client_id } = req.query;
|
|
if (!client_id) return errorResponse(res, "client_id required", 400);
|
|
|
|
const documents = await getDocumentsByClient(client_id as string);
|
|
return successResponse(res, documents);
|
|
} catch (error: any) {
|
|
return errorResponse(res, error.message, 500);
|
|
}
|
|
};
|
|
|
|
export const deleteDocumentHandler = async (req: any, res: Response) => {
|
|
try {
|
|
const doc = await findDocumentById(req.params.id);
|
|
if (!doc) return errorResponse(res, "Document not found", 404);
|
|
|
|
const filePath = path.join(env.UPLOAD_DIR, doc.file_path);
|
|
if (fs.existsSync(filePath)) fs.unlinkSync(filePath);
|
|
|
|
await deleteDocument(req.params.id);
|
|
await logAction(req, "DELETE", "document", req.params.id);
|
|
return successResponse(res, null, "Document deleted");
|
|
} catch (error: any) {
|
|
return errorResponse(res, error.message, 500);
|
|
}
|
|
};
|
|
|
|
export const downloadDocument = async (req: Request, res: Response) => {
|
|
try {
|
|
const doc = await findDocumentById(req.params.id);
|
|
if (!doc) return errorResponse(res, "Document not found", 404);
|
|
|
|
const filePath = path.join(env.UPLOAD_DIR, doc.file_path);
|
|
if (!fs.existsSync(filePath)) return errorResponse(res, "File not found", 404);
|
|
|
|
res.download(filePath, doc.name);
|
|
} catch (error: any) {
|
|
return errorResponse(res, error.message, 500);
|
|
}
|
|
};
|