Skip to content

Commit

Permalink
file deletion and file info
Browse files Browse the repository at this point in the history
  • Loading branch information
rotembarsela committed Aug 23, 2024
1 parent ec51ed5 commit 86cce78
Show file tree
Hide file tree
Showing 7 changed files with 142 additions and 80 deletions.
12 changes: 6 additions & 6 deletions client/src/components/excels/ExcelTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,22 +10,22 @@ const ExcelTable: React.FC<ExcelTableProps> = ({ excel }) => {
<table className="min-w-full divide-y divide-gray-200">
<thead className="bg-gray-50">
<tr>
{excel.headerRow.map((header, index) => (
{excel.columns.map((col, index) => (
<th
key={index}
className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
>
{header}
{col}
</th>
))}
</tr>
</thead>
<tbody className="bg-white divide-y divide-gray-200">
{excel.bodyRows.map((row, index) => (
{excel.rows.map((row, index) => (
<tr key={index} className="even:bg-gray-50">
{excel.headerRow.map((header) => (
<td key={header} className="px-6 py-4 whitespace-nowrap">
{row[header]}
{excel.columns.map((col) => (
<td key={col} className="px-6 py-4 whitespace-nowrap">
{row[col]}
</td>
))}
</tr>
Expand Down
2 changes: 1 addition & 1 deletion client/src/components/excels/FileInfo.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ function FileInfo({ excel, onExcelInfoClose }: FileInfoProps) {
return (
<Paper className="w-full h-full flex flex-col gap-12">
<div className="flex items-center justify-between">
<h2 className="text-xl font-bold">{excel.name}</h2>
<h2 className="text-xl font-bold">{excel.fileName}</h2>
<Button onClick={onExcelInfoClose}>Close</Button>
</div>
<Divider />
Expand Down
16 changes: 4 additions & 12 deletions client/src/components/excels/UploadedFiles.tsx
Original file line number Diff line number Diff line change
@@ -1,29 +1,21 @@
import { Excel } from "../../types";
import { APIFetcher } from "../../utils/fetcher";
import Paper from "../Paper";
import Button from "../ui/Button";
import UploadedFileList from "./UploadedFileList";

type UploadedFiles = {
files: Excel[];
onExcelInfoClick: (id: string) => void;
onExcelDownloadClick: (fileId: string, fileName: string) => void;
onExcelDownloadClick: (fileId: string, fileName: string) => Promise<void>;
onExcelRemoveClick: (fileId: string) => Promise<void>;
};

function UploadedFiles({
files,
onExcelInfoClick,
onExcelDownloadClick,
onExcelRemoveClick,
}: UploadedFiles) {
const handleDeleteClick = async (id: string) => {
try {
await APIFetcher<void, undefined>(`/excels/${id}`, "DELETE");
alert("File deleted successfully");
} catch (error) {
console.error("Failed to delete file:", error);
}
};

return (
<Paper className="flex-1 h-full overflow-auto">
<h2 className="text-lg font-bold mb-2">Uploaded Files</h2>
Expand All @@ -37,7 +29,7 @@ function UploadedFiles({
>
Download
</Button>
<Button variant="danger" onClick={() => handleDeleteClick(id)}>
<Button variant="danger" onClick={() => onExcelRemoveClick(id)}>
Remove
</Button>
</div>
Expand Down
50 changes: 40 additions & 10 deletions client/src/routes/excels.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import { useAppContext } from "../context/useAppProvider";
import { APIFetcher } from "../utils/fetcher";
import UploadedFiles from "../components/excels/UploadedFiles";
import PendingFiles from "../components/excels/PendingFiles";
import { mocks } from "../mocks";
import {
Excel,
ExcelsListResponse,
Expand Down Expand Up @@ -38,10 +37,16 @@ function Excels() {
}

const formData = new FormData();
Array.from(files).forEach((file) => {
formData.append("files", file);
files.forEach((file) => {
const cleanName = cleanFileName(file.name);
formData.append("files", new File([file], cleanName));
});

// TODO: check if files length > 5, if so, sperate them into array of 5 files on each (cell) object in the array
// if there are 7 files for example, it will be [{file,file,file,file,file}, {file,file}] and get sent in chunks
// change to /excels/pending/${selectedUser.id}
// change to /excels/uploads/${selectedUser.id}
// on the server it will be /excels/:folderName/:userId
try {
const response = await APIFetcher<ExcelsUploadResponse>(
`/excels/upload/${selectedUser.id}`,
Expand All @@ -59,14 +64,17 @@ function Excels() {
}
};

const handleExcelInfoClick = (id: string) => {
// TODO: Api Call
const findExcelFile = mocks.excelSpreadsheets.find((exc) => exc.id === id);
if (!findExcelFile) {
return;
}
const handleExcelInfoClick = async (fileId: string) => {
try {
const response = await APIFetcher<ExcelSpreadsheet>(
`/excels/${selectedUser.id}/uploads/${fileId}`,
"GET"
);

setExcelInfo(findExcelFile);
setExcelInfo(response);
} catch (error) {
console.error("Info error:", (error as Error).message);
}
};

const handleExcelInfoClose = () => {
Expand Down Expand Up @@ -94,6 +102,27 @@ function Excels() {
}
};

const handleExcelRemoveClick = async (fileId: string) => {
try {
await APIFetcher<void>(
`/excels/delete/${selectedUser.id}/${fileId}`,
"DELETE"
);

const filteredIdFromUploadedFiles = uploadedFiles.filter(
(file) => file.id !== fileId
);

setUploadedFiles(filteredIdFromUploadedFiles);
} catch (error) {
console.error("Failed to delete the file:", (error as Error).message);
}
};

const cleanFileName = (fileName: string) => {
return fileName.replace(/[^\x20-\x7E]/g, "");
};

useEffect(() => {
const getPendingUploadedFiles = async () => {
try {
Expand Down Expand Up @@ -129,6 +158,7 @@ function Excels() {
files={uploadedFiles}
onExcelInfoClick={handleExcelInfoClick}
onExcelDownloadClick={handleExcelDownloadClick}
onExcelRemoveClick={handleExcelRemoveClick}
/>
<PendingFiles files={pendingFiles} />
</div>
Expand Down
8 changes: 4 additions & 4 deletions client/src/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,10 @@ export type ExcelRow = {
};

export type ExcelSpreadsheet = {
id: string;
name: string;
headerRow: string[];
bodyRows: ExcelRow[];
fileId: string;
fileName: string;
columns: string[];
rows: ExcelRow[];
};

export type ExcelsUploadResponse = {
Expand Down
37 changes: 21 additions & 16 deletions server/src/excel/excel.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import { Response } from 'express';
export class ExcelController {
constructor(private readonly excelService: ExcelService) {}

// TODO: change to /:userId, GET
@Get('list/:userId')
async listFiles(@Param('userId') userId: number) {
const pendingFiles = await this.excelService.listFiles(userId, 'pending');
Expand All @@ -28,15 +29,15 @@ export class ExcelController {
};
}

@Get('read/:userId/:folder/:filename')
readFile(
@Get(':userId/uploads/:fileId')
async readFile(
@Param('userId') userId: number,
@Param('folder') folder: 'uploads' | 'pending',
@Param('filename') filename: string,
): string {
return this.excelService.readFile(userId, folder, filename);
@Param('fileId') fileId: number,
) {
return await this.excelService.getCustomerData(userId, fileId);
}

// TODO: change to /:folderName/:userId, POST
@Post('upload/:userId')
@UseInterceptors(FilesInterceptor('files', 10))
async uploadFiles(
Expand All @@ -48,20 +49,28 @@ export class ExcelController {
const pendingFiles = await this.excelService.listFiles(userId, 'pending');
const uploadedFiles = await this.excelService.listFiles(userId, 'uploads');

console.log(`Pending file ${pendingFiles}`);
console.log(`Uploaded file ${uploadedFiles}`);

return {
message: 'Files processed successfully',
pendingFiles,
uploadedFiles,
};
}

@Delete('delete/:userId/:folder/:filename')
deleteFile(
@Delete('delete/:userId/:fileId')
async deleteFile(
@Param('userId') userId: number,
@Param('folder') folder: 'uploads' | 'pending',
@Param('filename') filename: string,
): void {
this.excelService.deleteFile(userId, folder, filename);
@Param('fileId') fileId: number,
): Promise<{ fileId: number }> {
try {
await this.excelService.deleteFile(userId, fileId);
return { fileId };
} catch (error) {
console.error('Error deleting file:', error.message);
throw new NotFoundException(error.message);
}
}

@Get('download/:userId/:fileId')
Expand All @@ -76,10 +85,6 @@ export class ExcelController {
fileId,
);

console.log('before download');
console.log(filePath);
console.log(fileName);

res.download(filePath, fileName, (err) => {
if (err) {
console.error('Error downloading the file:', err);
Expand Down
Loading

0 comments on commit 86cce78

Please sign in to comment.