Compare commits

..

3 Commits

Author SHA1 Message Date
Gitea e347c4baf6 first 2026-06-24 16:14:27 +05:30
Gitea f9cd469db9 first commit 2026-06-24 16:10:54 +05:30
Gitea e6628183b0 Initialize project using Create React App 2026-06-22 13:32:16 +05:30
37 changed files with 18977 additions and 3836 deletions
+1
View File
@@ -0,0 +1 @@
REACT_APP_API_URL=http://localhost:8981/api
+22 -2
View File
@@ -1,3 +1,23 @@
./client/node_module
./server/node_module
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*
+70
View File
@@ -0,0 +1,70 @@
# Getting Started with Create React App
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## Available Scripts
In the project directory, you can run:
### `npm start`
Runs the app in the development mode.\
Open [http://localhost:3000](http://localhost:3000) to view it in your browser.
The page will reload when you make changes.\
You may also see any lint errors in the console.
### `npm test`
Launches the test runner in the interactive watch mode.\
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
### `npm run build`
Builds the app for production to the `build` folder.\
It correctly bundles React in production mode and optimizes the build for the best performance.
The build is minified and the filenames include the hashes.\
Your app is ready to be deployed!
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
### `npm run eject`
**Note: this is a one-way operation. Once you `eject`, you can't go back!**
If you aren't satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you're on your own.
You don't have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn't feel obligated to use this feature. However we understand that this tool wouldn't be useful if you couldn't customize it when you are ready for it.
## Learn More
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
To learn React, check out the [React documentation](https://reactjs.org/).
### Code Splitting
This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting)
### Analyzing the Bundle Size
This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size)
### Making a Progressive Web App
This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app)
### Advanced Configuration
This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration)
### Deployment
This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment)
### `npm run build` fails to minify
This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify)
Submodule client deleted from e347c4baf6
+17426
View File
File diff suppressed because it is too large Load Diff
+41
View File
@@ -0,0 +1,41 @@
{
"name": "client",
"version": "0.1.0",
"private": true,
"proxy": "http://localhost:8981",
"dependencies": {
"@testing-library/dom": "^10.4.1",
"@testing-library/jest-dom": "^6.9.1",
"@testing-library/react": "^16.3.2",
"@testing-library/user-event": "^13.5.0",
"react": "^19.2.7",
"react-dom": "^19.2.7",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4",
"axios": "^1.4.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

+43
View File
@@ -0,0 +1,43 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/CPM_LogoPrimary_Black.png" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>CPM HR UTILITY</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>
Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.4 KiB

+25
View File
@@ -0,0 +1,25 @@
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
},
{
"src": "logo192.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "logo512.png",
"type": "image/png",
"sizes": "512x512"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}
+3
View File
@@ -0,0 +1,3 @@
# https://www.robotstxt.org/robotstxt.html
User-agent: *
Disallow:
-8
View File
@@ -1,8 +0,0 @@
PORT=5000
JWT_SECRET=your_super_secret_jwt_key_change_this_in_production
JWT_EXPIRE=7d
NODE_ENV=development
UPLOAD_FOLDER=uploads
OUTPUT_FOLDER=outputs
COMPRESSION_QUALITY=80
MAX_FILE_SIZE=50000000
-8
View File
@@ -1,8 +0,0 @@
node_modules/
.env
uploads/
outputs/
*.log
.DS_Store
dist/
build/
-72
View File
@@ -1,72 +0,0 @@
# Image Manager - Backend Server
Node.js/Express backend for the Image Manager System with JWT authentication and image compression.
## Features
- JWT-based authentication
- Role-based access control (HR, SLIP)
- Image upload and compression
- File management API
- ZIP file creation
- Auto-delete functionality
## Installation
```bash
npm install
```
## Configuration
Create a `.env` file with:
```
PORT=5000
JWT_SECRET=your_secret_key
JWT_EXPIRE=7d
NODE_ENV=development
MAX_FILE_SIZE=50000000
COMPRESSION_QUALITY=80
```
## Running
```bash
# Production
npm start
# Development with auto-reload
npm run dev
```
## API Endpoints
### Auth
- `POST /api/auth/signup` - Register
- `POST /api/auth/login` - Login
### Files
- `GET /api/files/list` - Get source images
- `GET /api/files/outputs` - Get compressed images
- `POST /api/files/upload` - Upload image
- `POST /api/files/upload-multiple` - Bulk upload
- `POST /api/files/compress/:filename` - Compress
- `POST /api/files/compress-multiple` - Batch compress
- `GET /api/files/download/:filename` - Download
- `POST /api/files/download-zip` - Download ZIP
- `DELETE /api/files/delete/:filename` - Delete
## Dependencies
- express
- cors
- jsonwebtoken
- bcryptjs
- sharp
- multer
- archiver
- dotenv
## Port
Default: 5000
-47
View File
@@ -1,47 +0,0 @@
import express from 'express';
import cors from 'cors';
import dotenv from 'dotenv';
import path from 'path';
import { fileURLToPath } from 'url';
import authRoutes from './routes/auth.js';
import fileRoutes from './routes/files.js';
import { authenticate } from './middleware/auth.js';
dotenv.config();
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const app = express();
app.set('trust proxy', true);
// Middleware
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ limit: '50mb', extended: true }));
// Serve static files
app.use('/outputs', express.static(path.join(__dirname, 'outputs')));
app.use('/source', express.static(path.join(__dirname, 'source')));
// Routes
app.use('/api/auth', authRoutes);
app.use('/api/files', authenticate, fileRoutes);
// Health check
app.get('/health', (req, res) => {
res.json({ status: 'Server is running' });
});
// Error handling middleware
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(err.status || 500).json({
error: err.message || 'Internal Server Error'
});
});
const PORT = process.env.PORT;
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
-26
View File
@@ -1,26 +0,0 @@
import jwt from 'jsonwebtoken';
export const authenticate = (req, res, next) => {
const token = req.headers.authorization?.split(' ')[1];
if (!token) {
return res.status(401).json({ error: 'No token provided' });
}
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET);
req.user = decoded;
next();
} catch (err) {
res.status(401).json({ error: 'Invalid token' });
}
};
export const authorize = (roles = []) => {
return (req, res, next) => {
if (!roles.includes(req.user.role)) {
return res.status(403).json({ error: 'Access denied' });
}
next();
};
};
-2890
View File
File diff suppressed because it is too large Load Diff
-40
View File
@@ -1,40 +0,0 @@
{
"name": "image-manager-server",
"version": "1.0.0",
"description": "Backend for Image Management System with JWT Auth and Role-based Access",
"main": "index.js",
"type": "module",
"scripts": {
"start": "nodemon index.js",
"dev": "nodemon index.js"
},
"keywords": [
"express",
"jwt",
"image",
"compression"
],
"author": "",
"license": "ISC",
"dependencies": {
"@napi-rs/canvas": "^1.0.0",
"archiver": "^6.0.0",
"bcryptjs": "^2.4.3",
"compress-pdf": "^0.6.3",
"cors": "^2.8.5",
"dotenv": "^16.0.3",
"express": "^4.18.2",
"fs-extra": "^11.3.5",
"jsonwebtoken": "^9.0.0",
"multer": "^2.2.0",
"pdf-lib": "^1.17.1",
"pdf-poppler": "^0.2.3",
"pdfjs-dist": "^6.0.227",
"pdfkit": "^0.19.1",
"sharp": "^0.32.6",
"uuid": "^9.0.0"
},
"devDependencies": {
"nodemon": "^2.0.20"
}
}
-98
View File
@@ -1,98 +0,0 @@
import express from 'express';
import jwt from 'jsonwebtoken';
import bcrypt from 'bcryptjs';
const router = express.Router();
// Mock database - replace with real DB in production
const users = [
{
id: 1,
username: 'Hr_admin',
email: 'hr@7823cpmindia.com',
password:'Hr@12345',
// password: '$2a$10$u0F8fM.6qz.2D0X0Z7.D6O9K2n0F8fM.6qz.2D0X0Z7.D6O9K2n0F8', // password123
role: 'HR'
},
{
id: 2,
username: 'slip_admin',
email: 'slip@company.com',
// password: '$2a$10$u0F8fM.6qz.2D0X0Z7.D6O9K2n0F8fM.6qz.2D0X0Z7.D6O9K2n0F8', // password123
password:'Hr@12345',
role: 'SLIP'
}
];
// Signup
router.post('/signup', async (req, res) => {
try {
const { username, email, password, role } = req.body;
if (!['HR', 'SLIP'].includes(role)) {
return res.status(400).json({ error: 'Invalid role' });
}
const hashedPassword = await bcrypt.hash(password, 10);
const newUser = {
id: users.length + 1,
username,
email,
password: hashedPassword,
role
};
users.push(newUser);
const token = jwt.sign(
{ id: newUser.id, username, role },
process.env.JWT_SECRET,
{ expiresIn: process.env.JWT_EXPIRE }
);
res.status(201).json({
token,
user: { id: newUser.id, username, email, role }
});
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// Login
router.post('/login', async (req, res) => {
try {
const { email, password } = req.body;
const user = users.find(u => u.email === email);
if (!user) {
return res.status(400).json({ error: 'Invalid credentials' });
}
const password1 = users.find(u => u.password === password);
if (!password1) {
return res.status(400).json({ error: 'Invalid credentials' });
}
// const isPasswordValid = await bcrypt.compare(password, user.password);
// if (!isPasswordValid) {
// return res.status(400).json({ error: 'Invalid credentials' });
// }
const token = jwt.sign(
{ id: user.id, username: user.username, role: user.role },
process.env.JWT_SECRET,
{ expiresIn: process.env.JWT_EXPIRE }
);
res.json({
token,
user: { id: user.id, username: user.username, email: user.email, role: user.role }
});
} catch (err) {
res.status(500).json({ error: err.message });
}
});
export default router;
-644
View File
@@ -1,644 +0,0 @@
import express from 'express';
import path from 'path';
import fs from 'fs/promises';
import { fileURLToPath } from 'url';
import { execFile } from 'child_process';
import { promisify } from 'util';
import multer from 'multer';
import sharp from 'sharp';
import fsSync from 'fs';
import archiver from 'archiver';
import { v4 as uuidv4 } from 'uuid';
import { authorize } from '../middleware/auth.js';
import { createWriteStream } from 'fs';
import dotenv from 'dotenv';
dotenv.config();
import { PDFDocument, PDFName, PDFRawStream } from 'pdf-lib';
import { createCanvas } from '@napi-rs/canvas';
import * as pdfjsLib from 'pdfjs-dist/legacy/build/pdf.mjs';
const router = express.Router();
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// Create directories if they don't exist
const outputDir = path.join(__dirname, '..', 'outputs');
const sourceDir = path.join(__dirname, '..', 'source');
try {
await fs.mkdir(outputDir, { recursive: true });
await fs.mkdir(sourceDir, { recursive: true });
} catch (err) {
console.error('Error creating directories:', err);
}
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, sourceDir);
},
filename: (req, file, cb) => {
cb(null, file.originalname);
}
});
const upload = multer({
storage,
fileFilter: (req, file, cb) => {
const allowedMimes = [
'image/jpeg',
'image/png',
'image/webp',
'image/gif',
'application/pdf'
];
if (allowedMimes.includes(file.mimetype)) {
cb(null, true);
} else {
cb(new Error('Invalid file type'));
}
},
limits: { fileSize: parseInt(process.env.MAX_FILE_SIZE) || 50000000 }
});
async function clearDirectory(dir) {
const items = await fs.readdir(dir);
await Promise.all(items.map(async (item) => {
const itemPath = path.join(dir, item);
await fs.unlink(itemPath);
}));
}
async function clearSourceDirectory(req, res, next) {
try {
await clearDirectory(sourceDir);
next();
} catch (err) {
next(err);
}
}
// Upload files into source folder, clearing it first
router.post('/upload-multiple', clearSourceDirectory, upload.array('images', 100), async (req, res) => {
try {
if (!req.files || req.files.length === 0) {
return res.status(400).json({ error: 'No files uploaded' });
}
const baseUrl = `${req.protocol}://${req.get('host')}`;
const uploadedFiles = req.files.map((file) => ({
name: file.originalname,
size: file.size,
url: `${baseUrl}/source/${encodeURIComponent(file.filename)}`
}));
res.json({
message: `${req.files.length} files uploaded successfully`,
files: uploadedFiles
});
} catch (err) {
res.status(500).json({ error: err.message });
}
});
router.post('/upload', clearSourceDirectory, upload.single('image'), async (req, res) => {
try {
if (!req.file) {
return res.status(400).json({ error: 'No file uploaded' });
}
const baseUrl = `${req.protocol}://${req.get('host')}`;
res.json({
message: 'File uploaded successfully',
file: {
name: req.file.originalname,
size: req.file.size,
url: `${baseUrl}/source/${encodeURIComponent(req.file.filename)}`
}
});
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// Get source files list from root folder
router.get('/list', async (req, res) => {
try {
const baseUrl = process.env.BASE_URL;
const files = await fs.readdir(sourceDir);
const fileDetails = await Promise.all(
files.map(async (file) => {
const filePath = path.join(sourceDir, file);
const stats = await fs.stat(filePath);
return {
name: file,
size: stats.size,
url: `${baseUrl}/source/${encodeURIComponent(file)}`,
uploadedAt: stats.mtime,
extension: path.extname(file).toLowerCase()
};
})
);
res.json({ files: fileDetails });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
async function compressPdf(inputPath, outputPath, quality = 60, targetKb = null) {
console.log('compressPdf called:', { inputPath, outputPath, quality, targetKb });
if (!fsSync.existsSync(inputPath)) {
throw new Error(`Input file not found: ${inputPath}`);
}
const outputDirPath = path.dirname(outputPath);
if (!fsSync.existsSync(outputDirPath)) {
throw new Error(`Output directory does not exist: ${outputDirPath}`);
}
const inputBytes = fsSync.readFileSync(inputPath);
const originalSize = inputBytes.length;
const targetBytes = targetKb ? targetKb * 1024 : null;
// Step 1: try image-recompression first (keeps text selectable where possible)
const firstAttempt = await tryImageRecompression(inputBytes, quality);
console.log(`Image-recompression attempt: ${firstAttempt.length} bytes`);
if (!targetBytes || firstAttempt.length <= targetBytes) {
fsSync.writeFileSync(outputPath, firstAttempt);
logResult(originalSize, firstAttempt.length, outputPath, targetBytes);
return;
}
// Step 2: target not met — rasterize pages to guarantee size control
console.log('Target not met via image recompression — falling back to page rasterization.');
const baseQuality = Math.max(15, Math.min(90, quality));
const attempts = [
{ dpi: 150, q: baseQuality },
{ dpi: 120, q: Math.max(15, baseQuality - 15) },
{ dpi: 96, q: Math.max(15, baseQuality - 30) },
{ dpi: 72, q: Math.max(15, baseQuality - 45) },
{ dpi: 72, q: 20 },
{ dpi: 50, q: 15 }
];
let bestBuffer = null;
for (const { dpi, q } of attempts) {
console.log(`Rasterizing at dpi=${dpi}, jpegQuality=${q}`);
const buffer = await rasterizeAndBuild(inputPath, dpi, q);
console.log(` -> ${buffer.length} bytes`);
if (!bestBuffer || buffer.length < bestBuffer.length) {
bestBuffer = buffer;
}
if (buffer.length <= targetBytes) {
fsSync.writeFileSync(outputPath, buffer);
console.log(`Target reached via rasterization at dpi=${dpi}, quality=${q}`);
logResult(originalSize, buffer.length, outputPath, targetBytes);
return;
}
}
console.warn(`Could not fully reach target of ${targetKb}KB. Writing smallest achieved version.`);
const finalBuffer = bestBuffer.length < firstAttempt.length ? bestBuffer : firstAttempt;
fsSync.writeFileSync(outputPath, finalBuffer);
logResult(originalSize, finalBuffer.length, outputPath, targetBytes);
}
// --- Step 1 helper: recompress existing embedded JPEG/Flate images in place ---
async function tryImageRecompression(inputBytes, quality) {
const pdfDoc = await PDFDocument.load(inputBytes, { ignoreEncryption: true, updateMetadata: false });
const context = pdfDoc.context;
const indirectObjects = context.enumerateIndirectObjects();
const scaleFactor = quality >= 80 ? 1 : quality >= 60 ? 0.85 : quality >= 40 ? 0.65 : 0.5;
for (const [ref, obj] of indirectObjects) {
try {
if (!(obj instanceof PDFRawStream)) continue;
const dict = obj.dict;
const subtype = dict.get(PDFName.of('Subtype'));
if (!subtype || subtype.toString() !== '/Image') continue;
const filter = dict.get(PDFName.of('Filter'));
const filterName = filter ? filter.toString() : '';
const isJpeg = filterName.includes('DCTDecode');
const isFlate = filterName.includes('FlateDecode');
if (!isJpeg && !isFlate) continue;
const rawBytes = obj.contents;
if (!rawBytes || rawBytes.length < 2000) continue;
let sharpInput;
if (isJpeg) {
sharpInput = Buffer.from(rawBytes);
} else {
const width = dict.get(PDFName.of('Width'))?.asNumber?.();
const height = dict.get(PDFName.of('Height'))?.asNumber?.();
const bpc = dict.get(PDFName.of('BitsPerComponent'))?.asNumber?.() || 8;
const csObj = dict.get(PDFName.of('ColorSpace'));
const csName = csObj ? csObj.toString() : '/DeviceRGB';
if (!width || !height || bpc !== 8) continue;
let channels = 3;
if (csName.includes('Gray')) channels = 1;
else if (csName.includes('CMYK')) channels = 4;
const expectedSize = width * height * channels;
if (rawBytes.length < expectedSize) continue;
sharpInput = await sharp(Buffer.from(rawBytes), { raw: { width, height, channels } }).toBuffer();
}
const image = sharp(sharpInput, { failOn: 'none' });
const metadata = await image.metadata();
const newWidth = Math.round((metadata.width || 0) * scaleFactor);
const compressedBuffer = await image
.resize({ width: newWidth > 0 ? newWidth : undefined, withoutEnlargement: true })
.jpeg({ quality: Math.max(10, Math.min(95, quality)), mozjpeg: true })
.toBuffer();
if (compressedBuffer.length >= rawBytes.length) continue;
const newMeta = await sharp(compressedBuffer).metadata();
dict.set(PDFName.of('Filter'), PDFName.of('DCTDecode'));
dict.set(PDFName.of('Width'), context.obj(newMeta.width));
dict.set(PDFName.of('Height'), context.obj(newMeta.height));
dict.set(PDFName.of('ColorSpace'), PDFName.of('DeviceRGB'));
dict.set(PDFName.of('BitsPerComponent'), context.obj(8));
dict.delete(PDFName.of('DecodeParms'));
dict.delete(PDFName.of('SMask'));
context.assign(ref, PDFRawStream.of(dict, compressedBuffer));
} catch (e) {
continue;
}
}
return await pdfDoc.save({ useObjectStreams: true });
}
// --- Step 2 helper: render every page to a JPEG via pdfjs-dist + napi-rs canvas, rebuild PDF ---
async function rasterizeAndBuild(inputPath, dpi, jpegQuality) {
const data = new Uint8Array(fsSync.readFileSync(inputPath));
const loadingTask = pdfjsLib.getDocument({ data });
const pdfDocument = await loadingTask.promise;
const newPdf = await PDFDocument.create();
const scale = dpi / 72; // pdfjs default is 72 DPI baseline
for (let pageNum = 1; pageNum <= pdfDocument.numPages; pageNum++) {
const page = await pdfDocument.getPage(pageNum);
const viewport = page.getViewport({ scale });
const canvas = createCanvas(Math.ceil(viewport.width), Math.ceil(viewport.height));
const ctx = canvas.getContext('2d');
await page.render({
canvasContext: ctx,
viewport
}).promise;
const pngBuffer = canvas.toBuffer('image/png');
const compressed = await sharp(pngBuffer)
.jpeg({ quality: jpegQuality, mozjpeg: true })
.toBuffer();
const metadata = await sharp(compressed).metadata();
const jpgImage = await newPdf.embedJpg(compressed);
const newPage = newPdf.addPage([metadata.width, metadata.height]);
newPage.drawImage(jpgImage, {
x: 0,
y: 0,
width: metadata.width,
height: metadata.height
});
}
return await newPdf.save({ useObjectStreams: true });
}
function logResult(originalSize, newSize, outputPath, targetBytes) {
if (!fsSync.existsSync(outputPath) || fsSync.statSync(outputPath).size === 0) {
throw new Error(`Compression ran but produced no/empty output at ${outputPath}`);
}
const pct = ((1 - newSize / originalSize) * 100).toFixed(1);
console.log(`Done. ${originalSize} -> ${newSize} bytes (${pct}% reduction)`);
if (targetBytes && newSize > targetBytes) {
console.warn(`Note: final size (${newSize} bytes) still exceeds target (${targetBytes} bytes).`);
}
}
// Compress multiple files from source folder
router.post('/compress-multiple', async (req, res) => {
try {
const { filenames, quality, targetKb } = req.body;
if (!filenames || !Array.isArray(filenames) || filenames.length === 0) {
return res.status(400).json({ error: 'No filenames provided' });
}
const desiredKb = targetKb ? parseInt(targetKb, 10) : null;
const compressedFiles = await Promise.all(
filenames.map(async (filename) => {
const inputPath = path.join(sourceDir, filename);
const outputFilename = filename
const outputPath = path.join(outputDir, outputFilename);
const extension = path.extname(filename).toLowerCase();
try {
await fs.access(inputPath);
if (extension === '.pdf') {
await compressPdf(inputPath, outputPath, parseInt(quality, 10),targetKb);
} else {
let currentQuality = parseInt(quality, 10) || 80;
let sizeOk = false;
if (desiredKb) {
while (currentQuality >= 30) {
await sharp(inputPath)
.resize(2048, 2048, {
fit: 'inside',
withoutEnlargement: true
})
.jpeg({ quality: currentQuality, progressive: true })
.toFile(outputPath);
const stats = await fs.stat(outputPath);
if (stats.size <= desiredKb * 1024) {
sizeOk = true;
break;
}
currentQuality -= 5;
}
if (!sizeOk) {
// keep the smallest generated version
}
} else {
await sharp(inputPath)
.resize(2048, 2048, {
fit: 'inside',
withoutEnlargement: true
})
.jpeg({ quality: currentQuality, progressive: true })
.toFile(outputPath);
}
}
const stats = await fs.stat(outputPath);
return {
original: filename,
compressed: outputFilename,
url: `/outputs/${outputFilename}`,
size: stats.size
};
} catch (err) {
return { original: filename, error: err.message };
}
})
);
res.json({
message: 'Files compressed successfully',
files: compressedFiles
});
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// Compress single file from source folder
router.post('/compress/:filename', async (req, res) => {
try {
const { filename } = req.params;
const { quality, targetKb } = req.body;
const inputPath = path.join(sourceDir, filename);
const outputFilename = filename;
const outputPath = path.join(outputDir, outputFilename);
await fs.access(inputPath);
const extension = path.extname(filename).toLowerCase();
if (extension === '.pdf') {
await compressPdf(inputPath, outputPath, parseInt(quality, 10),targetKb);
} else {
const desiredKb = targetKb ? parseInt(targetKb, 10) : null;
let currentQuality = parseInt(quality, 10)
if (desiredKb) {
let sizeOk = false;
while (currentQuality >= 30) {
await sharp(inputPath)
.resize(2048, 2048, {
fit: 'inside',
withoutEnlargement: true
})
.jpeg({ quality: currentQuality, progressive: true })
.toFile(outputPath);
const stats = await fs.stat(outputPath);
if (stats.size <= desiredKb * 1024) {
sizeOk = true;
break;
}
currentQuality -= 5;
}
if (!sizeOk) {
// Keep the smallest version generated
}
} else {
await sharp(inputPath)
.resize(2048, 2048, {
fit: 'inside',
withoutEnlargement: true
})
.jpeg({ quality: currentQuality, progressive: true })
.toFile(outputPath);
}
}
const stats = await fs.stat(outputPath);
res.json({
message: 'File compressed successfully',
file: {
filename: outputFilename,
url: `/outputs/${outputFilename}`,
size: stats.size
}
});
} catch (err) {
if (err.code === 'ENOENT') {
return res.status(404).json({ error: 'Input file not found' });
}
res.status(500).json({ error: err.message });
}
});
// Download single file
router.get('/download/:filename', async (req, res) => {
try {
const { filename } = req.params;
const filePath = path.join(outputDir, filename);
await fs.access(filePath);
res.download(filePath, filename, async (err) => {
if (err && err.code !== 'ERR_HTTP_HEADERS_SENT') {
console.error('Download error:', err);
} else {
// Auto-delete the downloaded output file
try {
await fs.unlink(filePath);
console.log(`File deleted: ${filename}`);
} catch (delErr) {
console.error('Delete error:', delErr);
}
// ALSO clear the source folder so both source + output end up empty
try {
await clearDirectory(sourceDir);
console.log('Source directory cleared after single file download');
} catch (srcErr) {
console.error('Could not clear source directory:', srcErr);
}
}
});
} catch (err) {
res.status(404).json({ error: 'File not found' });
}
});
// router.get('/download/:filename', async (req, res) => {
// try {
// const { filename } = req.params;
// const filePath = path.join(outputDir, filename);
// await fs.access(filePath);
// res.download(filePath, filename, async (err) => {
// if (err && err.code !== 'ERR_HTTP_HEADERS_SENT') {
// console.error('Download error:', err);
// } else {
// // Auto-delete after successful download
// try {
// await fs.unlink(filePath);
// console.log(`File deleted: ${filename}`);
// } catch (delErr) {
// console.error('Delete error:', delErr);
// }
// }
// });
// } catch (err) {
// res.status(404).json({ error: 'File not found' });
// }
// });
// Download all files as ZIP
router.post('/download-zip', async (req, res) => {
try {
const { filenames } = req.body;
if (!filenames || !Array.isArray(filenames) || filenames.length === 0) {
return res.status(400).json({ error: 'No files specified' });
}
const zipFilename = `download-${uuidv4()}.zip`;
const zipPath = path.join(outputDir, zipFilename);
const output = createWriteStream(zipPath);
const archive = archiver('zip', { zlib: { level: 9 } });
output.on('close', async () => {
res.download(zipPath, zipFilename, async (err) => {
if (err && err.code !== 'ERR_HTTP_HEADERS_SENT') {
console.error('Download error:', err);
} else {
// Auto-delete downloaded ZIP and the included output files
try {
for (const filename of filenames) {
const filePath = path.join(outputDir, filename);
try {
await fs.unlink(filePath);
console.log(`Output file deleted: ${filename}`);
} catch (deleteErr) {
console.error(`Could not delete output file ${filename}:`, deleteErr);
}
}
await fs.unlink(zipPath);
console.log(`ZIP file deleted: ${zipFilename}`);
// ALSO clear the source folder so both source + output end up empty
try {
await clearDirectory(sourceDir);
console.log('Source directory cleared after zip download');
} catch (srcErr) {
console.error('Could not clear source directory:', srcErr);
}
} catch (delErr) {
console.error('Delete error:', delErr);
}
}
});
});
archive.on('error', (err) => {
res.status(500).json({ error: err.message });
});
archive.pipe(output);
// Add files to archive
for (const filename of filenames) {
const filePath = path.join(outputDir, filename);
try {
await fs.access(filePath);
archive.file(filePath, { name: filename });
} catch (err) {
console.warn(`File not found: ${filename}`);
}
}
await archive.finalize();
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// Delete file
router.delete('/delete/:filename', async (req, res) => {
try {
const { filename } = req.params;
const filePath = path.join(outputDir, filename);
await fs.unlink(filePath);
res.json({ message: 'File deleted successfully' });
} catch (err) {
res.status(500).json({ error: 'File not found' });
}
});
// List output files
router.get('/outputs', async (req, res) => {
try {
const baseUrl = process.env.BASE_URL;
const files = await fs.readdir(outputDir);
const fileDetails = await Promise.all(
files.map(async (file) => {
const filePath = path.join(outputDir, file);
const stats = await fs.stat(filePath);
return {
name: file,
size: stats.size,
url: `${baseUrl}/outputs/${encodeURIComponent(file)}`,
createdAt: stats.birthtime
};
})
);
res.json({ files: fileDetails });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
export default router;
+21
View File
@@ -0,0 +1,21 @@
.App {
width: 100%;
min-height: 100vh;
}
.loading {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
font-size: 24px;
color: #667eea;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
+44
View File
@@ -0,0 +1,44 @@
import React, { useState, useEffect } from 'react';
import './App.css';
import Login from './components/Login';
import Dashboard from './components/Dashboard';
function App() {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
// Check if user is already logged in
const savedUser = localStorage.getItem('user');
if (savedUser) {
setUser(JSON.parse(savedUser));
}
setLoading(false);
}, []);
const handleLogin = (userData) => {
setUser(userData);
};
const handleLogout = () => {
localStorage.removeItem('token');
localStorage.removeItem('user');
setUser(null);
};
if (loading) {
return <div className="loading">Loading...</div>;
}
return (
<div className="App">
{user ? (
<Dashboard user={user} onLogout={handleLogout} />
) : (
<Login onLogin={handleLogin} />
)}
</div>
);
}
export default App;
+8
View File
@@ -0,0 +1,8 @@
import { render, screen } from '@testing-library/react';
import App from './App';
test('renders learn react link', () => {
render(<App />);
const linkElement = screen.getByText(/learn react/i);
expect(linkElement).toBeInTheDocument();
});
+97
View File
@@ -0,0 +1,97 @@
.dashboard {
min-height: 100vh;
display: flex;
flex-direction: column;
background: #f5f5f5;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
.dashboard-header {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 20px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}
.header-content {
max-width: 1200px;
margin: 0 auto;
display: flex;
justify-content: space-between;
align-items: center;
}
.dashboard-header h1 {
margin: 0;
font-size: 28px;
}
.user-info {
display: flex;
align-items: center;
gap: 20px;
}
.user-badge {
background: rgba(255, 255, 255, 0.2);
padding: 8px 16px;
border-radius: 20px;
font-size: 14px;
font-weight: 500;
}
.logout-btn {
background: rgba(255, 255, 255, 0.2);
border: 1px solid rgba(255, 255, 255, 0.3);
color: white;
padding: 8px 16px;
border-radius: 6px;
cursor: pointer;
font-size: 14px;
transition: all 0.3s ease;
}
.logout-btn:hover {
background: rgba(255, 255, 255, 0.3);
transform: translateY(-2px);
}
.dashboard-main {
flex: 1;
max-width: 1200px;
width: 100%;
margin: 0 auto;
padding: 30px 20px;
}
.dashboard-footer {
background: #333;
color: white;
text-align: center;
padding: 20px;
font-size: 14px;
}
.dashboard-footer p {
margin: 0;
}
@media (max-width: 768px) {
.header-content {
flex-direction: column;
gap: 15px;
}
.dashboard-header h1 {
font-size: 22px;
}
.user-info {
width: 100%;
justify-content: space-between;
}
.dashboard-main {
padding: 15px 10px;
}
}
+46
View File
@@ -0,0 +1,46 @@
import React from 'react';
import FileExplorer from './FileExplorer';
import './Dashboard.css';
function Dashboard({ user, onLogout }) {
const getRoleIcon = (role) => {
return role === 'HR' ? '👔' : '📋';
};
return (
<div className="dashboard">
<header className="dashboard-header">
<div className="header-content">
<div className="logo-section">
<img
src="/CPM_LogoPrimary_Black.png"
alt="CPM Logo"
style={{ height: "40px", marginRight: "10px" }}
/>
{/* <span>Compressor</span> */}
</div>
<div className="user-info">
<span className="user-badge">
{getRoleIcon(user.role)} {user.username} ({user.role})
</span>
<button onClick={onLogout} className="logout-btn">
🚪 Logout
</button>
</div>
</div>
</header>
<main className="dashboard-main">
<FileExplorer userRole={user.role} />
</main>
<footer className="dashboard-footer">
<p>CPM HR UTILITY 2026 | Role: <strong>{user.role}</strong></p>
</footer>
</div>
);
}
export default Dashboard;
+345
View File
@@ -0,0 +1,345 @@
.file-explorer {
background: white;
border-radius: 12px;
padding: 30px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}
.file-explorer h2 {
color: #333;
margin: 0 0 30px 0;
font-size: 24px;
border-bottom: 2px solid #667eea;
padding-bottom: 15px;
}
.section {
margin-bottom: 40px;
}
.section h3 {
color: #333;
font-size: 18px;
margin: 0 0 20px 0;
}
.section-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 20px;
flex-wrap: wrap;
gap: 15px;
}
/* Upload Section */
.upload-section {
margin-bottom: 40px;
padding: 20px;
border: 1px solid #e2e8f0;
border-radius: 12px;
background: #fafbff;
}
.upload-actions {
display: flex;
gap: 16px;
align-items: center;
flex-wrap: wrap;
margin-top: 16px;
}
.upload-button {
position: relative;
display: inline-flex;
align-items: center;
justify-content: center;
padding: 12px 24px;
border-radius: 10px;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
font-size: 14px;
font-weight: 700;
cursor: pointer;
transition: transform 0.2s ease, box-shadow 0.2s ease;
}
.upload-button:hover:not(:disabled) {
transform: translateY(-2px);
box-shadow: 0 12px 24px rgba(102, 126, 234, 0.22);
}
.upload-button input[type="file"] {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
opacity: 0;
cursor: pointer;
}
.upload-button:disabled {
opacity: 0.65;
cursor: not-allowed;
}
.upload-help {
color: #4a5568;
font-size: 13px;
}
/* Controls */
.controls {
display: flex;
gap: 20px;
align-items: center;
margin-bottom: 20px;
flex-wrap: wrap;
}
.quality-control {
display: flex;
align-items: center;
gap: 10px;
}
.quality-control label {
color: #333;
font-size: 14px;
white-space: nowrap;
}
.quality-control input[type="range"] {
width: 150px;
}
/* Buttons */
.select-all-btn,
.compress-btn,
.download-all-btn {
padding: 10px 20px;
border: none;
border-radius: 6px;
font-size: 14px;
font-weight: 600;
cursor: pointer;
transition: all 0.3s ease;
}
.select-all-btn {
background: #f0f0f0;
color: #333;
}
.select-all-btn:hover:not(:disabled) {
background: #e0e0e0;
}
.compress-btn {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
}
.compress-btn:hover:not(:disabled) {
transform: translateY(-2px);
box-shadow: 0 5px 15px rgba(102, 126, 234, 0.3);
}
.compress-btn:disabled {
opacity: 0.6;
cursor: not-allowed;
}
.download-all-btn {
background: #4CAF50;
color: white;
}
.download-all-btn:hover:not(:disabled) {
background: #45a049;
transform: translateY(-2px);
box-shadow: 0 5px 15px rgba(76, 175, 80, 0.3);
}
.download-all-btn:disabled {
opacity: 0.6;
cursor: not-allowed;
}
/* Files Grid */
.files-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
gap: 20px;
margin-top: 20px;
}
.file-card {
background: #f9f9f9;
border: 2px solid #eee;
border-radius: 8px;
padding: 15px;
text-align: center;
transition: all 0.3s ease;
position: relative;
overflow: hidden;
}
.file-card:hover {
border-color: #667eea;
box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}
.file-card.selected {
background: #e8f5e9;
border-color: #4CAF50;
}
.file-card.compressing {
opacity: 0.6;
pointer-events: none;
}
.file-card.downloading {
opacity: 0.6;
}
.file-checkbox {
position: absolute;
top: 10px;
left: 10px;
width: 20px;
height: 20px;
cursor: pointer;
}
.file-thumbnail {
width: 100%;
height: 120px;
object-fit: cover;
border-radius: 6px;
margin: 10px 0;
display: block;
}
.file-info {
margin-top: 10px;
}
.file-name {
color: #333;
font-size: 12px;
margin: 5px 0;
word-break: break-word;
font-weight: 500;
}
.file-size {
color: #999;
font-size: 11px;
margin: 5px 0;
}
.badge {
display: inline-block;
background: #667eea;
color: white;
padding: 3px 8px;
border-radius: 12px;
font-size: 10px;
margin-top: 5px;
}
/* Compressed Files Section */
.output-section {
margin-top: 40px;
border-top: 2px solid #eee;
padding-top: 30px;
}
.file-card.compressed {
padding: 10px;
}
.file-actions {
display: flex;
gap: 8px;
justify-content: center;
margin-bottom: 10px;
}
.action-btn {
width: 36px;
height: 36px;
border: none;
border-radius: 6px;
font-size: 18px;
cursor: pointer;
transition: all 0.3s ease;
background: #f0f0f0;
}
.action-btn:hover:not(:disabled) {
background: #e0e0e0;
transform: scale(1.1);
}
.action-btn.download {
background: #4CAF50;
color: white;
}
.action-btn.download:hover:not(:disabled) {
background: #45a049;
}
.action-btn.delete {
background: #f44336;
color: white;
}
.action-btn.delete:hover:not(:disabled) {
background: #da190b;
}
.action-btn:disabled {
opacity: 0.6;
cursor: not-allowed;
}
/* Responsive */
@media (max-width: 768px) {
.file-explorer {
padding: 20px;
}
.file-explorer h2 {
font-size: 18px;
}
.controls {
flex-direction: column;
align-items: stretch;
}
.quality-control {
flex-direction: column;
}
.compress-btn,
.download-all-btn,
.select-all-btn {
width: 100%;
}
.files-grid {
grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
gap: 15px;
}
.file-thumbnail {
height: 100px;
}
}
+344
View File
@@ -0,0 +1,344 @@
import React, { useState, useEffect } from 'react';
import { filesAPI } from '../utils/api';
import './FileExplorer.css';
function FileExplorer({ userRole }) {
const [files, setFiles] = useState([]);
const [outputFiles, setOutputFiles] = useState([]);
const [selectedFiles, setSelectedFiles] = useState(new Set());
const [compression, setCompression] = useState(false);
const [compressQuality, setCompressQuality] = useState(80);
const [targetKb, setTargetKb] = useState('');
const [loading, setLoading] = useState(false);
const [compressingFiles, setCompressingFiles] = useState(new Set());
const [downloadingFiles, setDownloadingFiles] = useState(new Set());
const [uploading, setUploading] = useState(false);
useEffect(() => {
loadFiles();
loadOutputFiles();
}, []);
const loadFiles = async () => {
try {
const response = await filesAPI.list();
setFiles(response.data.files || []);
} catch (err) {
console.error('Error loading files:', err);
}
};
const loadOutputFiles = async () => {
try {
const response = await filesAPI.getOutputs();
setOutputFiles(response.data.files || []);
} catch (err) {
console.error('Error loading output files:', err);
}
};
const refreshSourceFiles = async () => {
setLoading(true);
try {
await loadFiles();
} finally {
setLoading(false);
}
};
const uploadFiles = async (files) => {
const fileArray = Array.from(files || []);
if (fileArray.length === 0) {
return;
}
setUploading(true);
try {
const formData = new FormData();
if (fileArray.length === 1) {
formData.append('image', fileArray[0]);
await filesAPI.upload(formData);
} else {
fileArray.forEach((file) => formData.append('images', file));
await filesAPI.uploadMultiple(formData);
}
await loadFiles();
} catch (err) {
const message = err.response?.data?.error || err.message;
alert('Upload failed: ' + message);
} finally {
setUploading(false);
}
};
const toggleSelectFile = (filename) => {
const newSelected = new Set(selectedFiles);
if (newSelected.has(filename)) {
newSelected.delete(filename);
} else {
newSelected.add(filename);
}
setSelectedFiles(newSelected);
};
const selectAllFiles = () => {
if (selectedFiles.size === files.length) {
setSelectedFiles(new Set());
} else {
setSelectedFiles(new Set(files.map(f => f.name)));
}
};
const compressSelected = async () => {
if (selectedFiles.size === 0) {
alert('Please select files to compress');
return;
}
setCompression(true);
setCompressingFiles(new Set(selectedFiles));
try {
const response = await filesAPI.compressMultiple(
Array.from(selectedFiles),
compressQuality,
targetKb
);
alert(`${response.data.files.length} files processed successfully!`);
setSelectedFiles(new Set());
setTargetKb('');
await loadOutputFiles();
} catch (err) {
const message = err.response?.data?.error || err.message;
alert('Compression failed: ' + message);
} finally {
setCompression(false);
setCompressingFiles(new Set());
}
};
const downloadFile = async (filename) => {
setDownloadingFiles(prev => new Set([...prev, filename]));
try {
const response = await filesAPI.downloadFile(filename);
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', filename);
document.body.appendChild(link);
link.click();
link.parentNode.removeChild(link);
await loadOutputFiles();
await loadFiles();
} catch (err) {
const message = err.response?.data?.error || err.message;
alert('Download failed: ' + message);
} finally {
setDownloadingFiles(prev => {
const newSet = new Set(prev);
newSet.delete(filename);
return newSet;
});
}
};
const downloadAllSelected = async () => {
if (outputFiles.length === 0) {
alert('No files to download');
return;
}
setDownloadingFiles(new Set(outputFiles.map(f => f.name)));
try {
const response = await filesAPI.downloadZip(outputFiles.map(f => f.name));
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', `compressed-files-${Date.now()}.zip`);
document.body.appendChild(link);
link.click();
link.parentNode.removeChild(link);
await loadOutputFiles();
await loadFiles();
setSelectedFiles(new Set());
} catch (err) {
alert('Download failed: ' + err.message);
} finally {
setDownloadingFiles(new Set());
}
};
const deleteFile = async (filename) => {
if (window.confirm('Delete this file?')) {
try {
await filesAPI.deleteFile(filename);
loadOutputFiles();
} catch (err) {
const message = err.response?.data?.error || err.message;
alert('Delete failed: ' + message);
}
}
};
return (
<div className="file-explorer">
<h2></h2>
<div className="section upload-section">
<div className="section-header">
<div>
<h3>📂 Source Folder Upload</h3>
<p className="folder-note">
Upload single or multiple JPG Images or Pdf. The source folder is cleared before the new images or pdf are saved.
</p>
</div>
<button className="refresh-btn" onClick={refreshSourceFiles} disabled={loading || uploading}>
{loading ? '⏳ Refreshing...' : '🔄 Refresh Source Folder'}
</button>
</div>
<div className="upload-actions">
<label className="upload-button" aria-label="Upload files">
{uploading ? '⏳ Uploading...' : '📤 Upload Files'}
<input
type="file"
multiple
accept="image/jpeg,image/png,image/webp,image/gif,application/pdf"
onChange={(e) => uploadFiles(e.target.files)}
disabled={uploading}
/>
</label>
<span
className="upload-help"
style={{ color: "red" }}
>
Choose up to 100 images or Pdf to replace the current source folder.
</span>
</div>
</div>
<div className="section source-section">
<div className="section-header">
<h3>📸 Source Files (Images & PDFs) ({files.length})</h3>
</div>
{files.length === 0 ? (
<p className="empty-output">No source files yet. Upload images or PDFs to see them here.</p>
) : (
<>
<div className="controls">
<div className="quality-control">
<label>Compression Quality: {compressQuality}%</label>
<input
type="range"
min="20"
max="100"
value={compressQuality}
onChange={(e) => setCompressQuality(e.target.value)}
/>
</div>
<div className="size-control">
<label>Target Size (KB)</label>
<input
type="number"
value={targetKb}
onChange={(e) => setTargetKb(e.target.value)}
placeholder="e.g. 200"
min="20"
/>
</div>
<button className="select-all-btn" onClick={selectAllFiles}>
{selectedFiles.size === files.length ? '✓ Deselect All' : '☐ Select All'}
</button>
<button
className="compress-btn"
onClick={compressSelected}
disabled={selectedFiles.size === 0 || compression}
>
{compression ? '⏳ Compressing...' : `🗜️ Compress Selected (${selectedFiles.size})`}
</button>
</div>
<div className="files-grid">
{files.map(file => (
<div key={file.name} className={`file-card ${selectedFiles.has(file.name) ? 'selected' : ''} ${compressingFiles.has(file.name) ? 'compressing' : ''}`}>
<input
type="checkbox"
checked={selectedFiles.has(file.name)}
onChange={() => toggleSelectFile(file.name)}
className="file-checkbox"
/>
{file.extension === '.pdf' ? (
<div className="pdf-preview">PDF</div>
) : (
<img src={file.url} alt={file.name} className="file-thumbnail" />
)}
<div className="file-info">
<p className="file-name">{file.name}</p>
<p className="file-size">{(file.size / 1024).toFixed(2)} KB</p>
</div>
</div>
))}
</div>
</>
)}
</div>
{/* Compressed Files Section */}
<div className="section output-section">
<div className="section-header">
<h3> Compressed Files (Images & PDFs) ({outputFiles.length})</h3>
<button
className="download-all-btn"
onClick={downloadAllSelected}
disabled={downloadingFiles.size > 0 || outputFiles.length === 0}
>
{downloadingFiles.size > 0 ? '⏳ Downloading...' : '⬇️ Download All as ZIP'}
</button>
</div>
{outputFiles.length === 0 ? (
<p className="empty-output">No compressed Files yet. Compress source files to see them here.</p>
) : (
<div className="files-grid">
{outputFiles.map(file => (
<div key={file.name} className={`file-card compressed ${downloadingFiles.has(file.name) ? 'downloading' : ''}`}>
<div className="file-actions">
<button
className="action-btn download"
onClick={() => downloadFile(file.name)}
disabled={downloadingFiles.has(file.name)}
title="Download"
>
{downloadingFiles.has(file.name) ? '⏳' : '⬇️'}
</button>
<button
className="action-btn delete"
onClick={() => deleteFile(file.name)}
title="Delete"
>
🗑
</button>
</div>
{file.name.toLowerCase().endsWith('.pdf') ? (
<div className="pdf-preview">PDF</div>
) : (
<img src={file.url} alt={file.name} className="file-thumbnail" />
)}
<div className="file-info">
<p className="file-name">{file.name}</p>
<p className="file-size">{(file.size / 1024).toFixed(2)} KB</p>
</div>
</div>
))}
</div>
)}
</div>
</div>
);
}
export default FileExplorer;
+187
View File
@@ -0,0 +1,187 @@
.login-container {
min-height: 100vh;
display: flex;
justify-content: center;
align-items: center;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
.login-card {
background: white;
border-radius: 12px;
padding: 40px;
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
width: 100%;
max-width: 400px;
animation: slideUp 0.5s ease-out;
}
@keyframes slideUp {
from {
opacity: 0;
transform: translateY(30px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.login-card h1 {
text-align: center;
color: #333;
margin-bottom: 30px;
font-size: 28px;
}
.role-selector {
margin-bottom: 30px;
}
.role-selector h3 {
color: #666;
font-size: 14px;
margin-bottom: 10px;
text-transform: uppercase;
}
.role-selector {
display: flex;
flex-direction: column;
gap: 8px;
}
.role-btn {
background: #f0f0f0;
border: 2px solid #ddd;
border-radius: 8px;
padding: 12px;
cursor: pointer;
font-size: 14px;
transition: all 0.3s ease;
}
.role-btn:hover {
border-color: #667eea;
background: #f5f5ff;
}
.role-btn.active {
background: #667eea;
color: white;
border-color: #667eea;
}
.form-group {
margin-bottom: 20px;
}
.form-group label {
display: block;
margin-bottom: 8px;
color: #333;
font-weight: 500;
font-size: 14px;
}
.form-group input,
.form-group select {
width: 100%;
padding: 12px;
border: 1px solid #ddd;
border-radius: 6px;
font-size: 14px;
transition: border-color 0.3s ease;
box-sizing: border-box;
}
.form-group input:focus,
.form-group select:focus {
outline: none;
border-color: #667eea;
box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}
.error-message {
background: #fee;
color: #c33;
padding: 12px;
border-radius: 6px;
margin-bottom: 20px;
font-size: 14px;
}
.submit-btn {
width: 100%;
padding: 12px;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
border: none;
border-radius: 6px;
font-size: 16px;
font-weight: 600;
cursor: pointer;
transition: transform 0.2s ease;
}
.submit-btn:hover:not(:disabled) {
transform: translateY(-2px);
box-shadow: 0 5px 20px rgba(102, 126, 234, 0.3);
}
.submit-btn:disabled {
opacity: 0.6;
cursor: not-allowed;
}
.toggle-auth {
text-align: center;
margin-top: 20px;
}
.toggle-auth p {
color: #666;
font-size: 14px;
margin: 0;
}
.toggle-btn {
background: none;
border: none;
color: #667eea;
cursor: pointer;
font-weight: 600;
text-decoration: underline;
margin-left: 5px;
}
.toggle-btn:hover {
color: #764ba2;
}
.login-logo-section {
text-align: center;
margin-bottom: 25px;
}
.cpm-logo {
width: 220px;
height: auto;
object-fit: contain;
}
.login-title {
margin: 0;
font-size: 28px;
font-weight: 700;
color: #003366;
}
.login-subtitle {
margin-top: 8px;
color: #666;
font-size: 14px;
}
+168
View File
@@ -0,0 +1,168 @@
import React, { useState } from 'react';
import { authAPI } from '../utils/api';
import './Login.css';
function Login({ onLogin }) {
const [isLogin, setIsLogin] = useState(true);
const [email, setEmail] = useState('hr@company.com');
const [password, setPassword] = useState('password123');
const [username, setUsername] = useState('');
const [role, setRole] = useState('HR');
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
const handleSubmit = async (e) => {
e.preventDefault();
setLoading(true);
setError('');
try {
if (isLogin) {
const response = await authAPI.login({ email, password });
localStorage.setItem('token', response.data.token);
localStorage.setItem('user', JSON.stringify(response.data.user));
onLogin(response.data.user);
} else {
const response = await authAPI.signup({
username,
email,
password,
role,
});
localStorage.setItem('token', response.data.token);
localStorage.setItem('user', JSON.stringify(response.data.user));
onLogin(response.data.user);
}
} catch (err) {
setError(err.response?.data?.error || 'Something went wrong');
} finally {
setLoading(false);
}
};
return (
<div className="login-container">
<div className="login-card">
{/* CPM LOGO */}
<div className="login-logo-section">
<img
src="/CPM_LogoPrimary_Black.png"
alt="CPM Logo"
className="cpm-logo"
/>
<p className="login-subtitle">
CPM HR Utility Portal
</p>
</div>
<div className="role-selector">
<h3>Accounts</h3>
<button
type="button"
className={`role-btn ${
email === 'hr@company.com' ? 'active' : ''
}`}
onClick={() => {
setEmail('hr@company.com');
setPassword('password123');
setRole('HR');
}}
>
🗜 Image & PDF Compression Tool
</button>
<button
type="button"
className={`role-btn ${
email === 'slip@company.com' ? 'active' : ''
}`}
onClick={() => {
setEmail('slip@company.com');
setPassword('password123');
setRole('SLIP');
}}
>
📋 Contractor Payment Slip Processing
</button>
</div>
<form onSubmit={handleSubmit}>
{!isLogin && (
<>
<div className="form-group">
<label>Username</label>
<input
type="text"
value={username}
onChange={(e) => setUsername(e.target.value)}
required
/>
</div>
<div className="form-group">
<label>Role</label>
<select
value={role}
onChange={(e) => setRole(e.target.value)}
>
<option value="HR">HR</option>
<option value="SLIP">SLIP</option>
</select>
</div>
</>
)}
<div className="form-group">
<label>Email</label>
<input
type="email"
// value={email}
onChange={(e) => setEmail(e.target.value)}
required
/>
</div>
<div className="form-group">
<label>Password</label>
<input
type="password"
// value={password}
onChange={(e) => setPassword(e.target.value)}
required
/>
</div>
{error && (
<div className="error-message">
{error}
</div>
)}
<button
type="submit"
disabled={loading}
className="submit-btn"
>
{loading
? 'Loading...'
: isLogin
? 'Login'
: 'Sign Up'}
</button>
</form>
</div>
</div>
);
}
export default Login;
+13
View File
@@ -0,0 +1,13 @@
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
monospace;
}
+17
View File
@@ -0,0 +1,17 @@
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 841.9 595.3"><g fill="#61DAFB"><path d="M666.3 296.5c0-32.5-40.7-63.3-103.1-82.4 14.4-63.6 8-114.2-20.2-130.4-6.5-3.8-14.1-5.6-22.4-5.6v22.3c4.6 0 8.3.9 11.4 2.6 13.6 7.8 19.5 37.5 14.9 75.7-1.1 9.4-2.9 19.3-5.1 29.4-19.6-4.8-41-8.5-63.5-10.9-13.5-18.5-27.5-35.3-41.6-50 32.6-30.3 63.2-46.9 84-46.9V78c-27.5 0-63.5 19.6-99.9 53.6-36.4-33.8-72.4-53.2-99.9-53.2v22.3c20.7 0 51.4 16.5 84 46.6-14 14.7-28 31.4-41.3 49.9-22.6 2.4-44 6.1-63.6 11-2.3-10-4-19.7-5.2-29-4.7-38.2 1.1-67.9 14.6-75.8 3-1.8 6.9-2.6 11.5-2.6V78.5c-8.4 0-16 1.8-22.6 5.6-28.1 16.2-34.4 66.7-19.9 130.1-62.2 19.2-102.7 49.9-102.7 82.3 0 32.5 40.7 63.3 103.1 82.4-14.4 63.6-8 114.2 20.2 130.4 6.5 3.8 14.1 5.6 22.5 5.6 27.5 0 63.5-19.6 99.9-53.6 36.4 33.8 72.4 53.2 99.9 53.2 8.4 0 16-1.8 22.6-5.6 28.1-16.2 34.4-66.7 19.9-130.1 62-19.1 102.5-49.9 102.5-82.3zm-130.2-66.7c-3.7 12.9-8.3 26.2-13.5 39.5-4.1-8-8.4-16-13.1-24-4.6-8-9.5-15.8-14.4-23.4 14.2 2.1 27.9 4.7 41 7.9zm-45.8 106.5c-7.8 13.5-15.8 26.3-24.1 38.2-14.9 1.3-30 2-45.2 2-15.1 0-30.2-.7-45-1.9-8.3-11.9-16.4-24.6-24.2-38-7.6-13.1-14.5-26.4-20.8-39.8 6.2-13.4 13.2-26.8 20.7-39.9 7.8-13.5 15.8-26.3 24.1-38.2 14.9-1.3 30-2 45.2-2 15.1 0 30.2.7 45 1.9 8.3 11.9 16.4 24.6 24.2 38 7.6 13.1 14.5 26.4 20.8 39.8-6.3 13.4-13.2 26.8-20.7 39.9zm32.3-13c5.4 13.4 10 26.8 13.8 39.8-13.1 3.2-26.9 5.9-41.2 8 4.9-7.7 9.8-15.6 14.4-23.7 4.6-8 8.9-16.1 13-24.1zM421.2 430c-9.3-9.6-18.6-20.3-27.8-32 9 .4 18.2.7 27.5.7 9.4 0 18.7-.2 27.8-.7-9 11.7-18.3 22.4-27.5 32zm-74.4-58.9c-14.2-2.1-27.9-4.7-41-7.9 3.7-12.9 8.3-26.2 13.5-39.5 4.1 8 8.4 16 13.1 24 4.7 8 9.5 15.8 14.4 23.4zM420.7 163c9.3 9.6 18.6 20.3 27.8 32-9-.4-18.2-.7-27.5-.7-9.4 0-18.7.2-27.8.7 9-11.7 18.3-22.4 27.5-32zm-74 58.9c-4.9 7.7-9.8 15.6-14.4 23.7-4.6 8-8.9 16-13 24-5.4-13.4-10-26.8-13.8-39.8 13.1-3.1 26.9-5.8 41.2-7.9zm-90.5 125.2c-35.4-15.1-58.3-34.9-58.3-50.6 0-15.7 22.9-35.6 58.3-50.6 8.6-3.7 18-7 27.7-10.1 5.7 19.6 13.2 40 22.5 60.9-9.2 20.8-16.6 41.1-22.2 60.6-9.9-3.1-19.3-6.5-28-10.2zM310 490c-13.6-7.8-19.5-37.5-14.9-75.7 1.1-9.4 2.9-19.3 5.1-29.4 19.6 4.8 41 8.5 63.5 10.9 13.5 18.5 27.5 35.3 41.6 50-32.6 30.3-63.2 46.9-84 46.9-4.5-.1-8.3-1-11.3-2.7zm237.2-76.2c4.7 38.2-1.1 67.9-14.6 75.8-3 1.8-6.9 2.6-11.5 2.6-20.7 0-51.4-16.5-84-46.6 14-14.7 28-31.4 41.3-49.9 22.6-2.4 44-6.1 63.6-11 2.3 10.1 4.1 19.8 5.2 29.1zm38.5-66.7c-8.6 3.7-18 7-27.7 10.1-5.7-19.6-13.2-40-22.5-60.9 9.2-20.8 16.6-41.1 22.2-60.6 9.9 3.1 19.3 6.5 28.1 10.2 35.4 15.1 58.3 34.9 58.3 50.6-.1 15.7-23 35.6-58.4 50.6zM320.8 78.4z"/><circle cx="420.9" cy="296.5" r="45.7"/><path d="M520.5 78.1z"/></g></svg>

After

Width:  |  Height:  |  Size: 2.6 KiB

+13
View File
@@ -0,0 +1,13 @@
const reportWebVitals = onPerfEntry => {
if (onPerfEntry && onPerfEntry instanceof Function) {
import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
getCLS(onPerfEntry);
getFID(onPerfEntry);
getFCP(onPerfEntry);
getLCP(onPerfEntry);
getTTFB(onPerfEntry);
});
}
};
export default reportWebVitals;
+5
View File
@@ -0,0 +1,5 @@
// jest-dom adds custom jest matchers for asserting on DOM nodes.
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import '@testing-library/jest-dom';
+37
View File
@@ -0,0 +1,37 @@
import axios from 'axios';
const API_URL = process.env.REACT_APP_API_URL;
const api = axios.create({
baseURL: API_URL
});
// Add token to requests
api.interceptors.request.use((config) => {
const token = localStorage.getItem('token');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
});
// Auth endpoints
export const authAPI = {
signup: (data) => api.post('/auth/signup', data),
login: (data) => api.post('/auth/login', data)
};
// Files endpoints
export const filesAPI = {
list: () => api.get('/files/list'),
upload: (formData) => api.post('/files/upload', formData),
uploadMultiple: (formData) => api.post('/files/upload-multiple', formData),
compress: (filename, quality, targetKb) => api.post(`/files/compress/${filename}`, { quality, targetKb }),
compressMultiple: (filenames, quality, targetKb) => api.post('/files/compress-multiple', { filenames, quality, targetKb }),
downloadFile: (filename) => api.get(`/files/download/${filename}`, { responseType: 'blob' }),
downloadZip: (filenames) => api.post('/files/download-zip', { filenames }, { responseType: 'blob' }),
getOutputs: () => api.get('/files/outputs'),
deleteFile: (filename) => api.delete(`/files/delete/${filename}`)
};
export default api;