First commit

This commit is contained in:
Mathieu 2025-11-04 15:18:19 +01:00
commit 279292a984
21 changed files with 7888 additions and 0 deletions

14
.dockerignore Normal file
View file

@ -0,0 +1,14 @@
Dockerfile*
docker-compose*
.dockerignore
.git
.gitignore
README.md
.next
.swc
node_modules
npm-debug.log
yarn-error.log
.env*.local
.vscode
.idea

34
.gitignore vendored Normal file
View file

@ -0,0 +1,34 @@
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# local env files
.env*.local
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts
/.yarn/

8
.idea/.gitignore vendored Normal file
View file

@ -0,0 +1,8 @@
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

45
Dockerfile Normal file
View file

@ -0,0 +1,45 @@
FROM node:20-alpine AS base
# Install dependencies only when needed
FROM base AS deps
RUN apk add --no-cache libc6-compat
WORKDIR /app
# Install dependencies
COPY package.json package-lock.json* ./
RUN npm ci
# Rebuild the source code only when needed
FROM base AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
# Next.js collects anonymous telemetry data about general usage
ENV NEXT_TELEMETRY_DISABLED=1
RUN npm run build
# Production image, copy all the files and run next
FROM base AS runner
WORKDIR /app
ENV NODE_ENV=production
ENV NEXT_TELEMETRY_DISABLED=1
RUN addgroup --system --gid 1001 nodejs
RUN adduser --system --uid 1001 nextjs
# Copy necessary files
COPY --from=builder /app/public ./public
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static
USER nextjs
EXPOSE 3000
ENV PORT=3000
ENV HOSTNAME="0.0.0.0"
CMD ["node", "server.js"]

19
Dockerfile.jsonserver Normal file
View file

@ -0,0 +1,19 @@
FROM node:20-alpine
WORKDIR /app
# Install json-server globally
RUN npm install -g json-server@0.17.4
# Create data directory
RUN mkdir -p /data
# Copy initial db.json
COPY db.json /data/db.json
EXPOSE 3001
# Use volume mount for persistence
VOLUME ["/data"]
CMD ["json-server", "--watch", "/data/db.json", "--host", "0.0.0.0", "--port", "3001"]

74
README.md Normal file
View file

@ -0,0 +1,74 @@
# Worker Presence Tracker
A Next.js application for tracking worker presence with a point system.
## Point System
- Each worker has **13 points** for a 2-week sprint (10 working days)
- Each presence day = 1.3 points
- Points are calculated based on the number of presential days worked
## Getting Started
### Development Mode
1. Install dependencies:
```bash
npm install
```
2. Start the JSON server (in one terminal):
```bash
npm run json-server
```
3. Run the development server (in another terminal):
```bash
npm run dev
```
4. Open [http://localhost:3000](http://localhost:3000) in your browser
### Docker Deployment
#### Local Testing with Docker Compose
```bash
docker-compose up -d
```
#### Docker Swarm Deployment
1. Build the images:
```bash
./deploy.sh
```
2. Deploy to swarm:
```bash
docker stack deploy -c docker-compose.swarm.yml presence-tracker
```
3. Check the deployment:
```bash
docker stack services presence-tracker
```
4. Remove the stack:
```bash
docker stack rm presence-tracker
```
The application will be available at:
- Web UI: http://localhost:3000
- JSON API: http://localhost:3001
## Features
- Add workers with their presence days
- Edit worker presence days inline
- Automatic point calculation
- View points earned, points used, and remaining points
- Summary statistics (total workers, average presence, etc.)
- Reset all presences button (for new sprint)
- Persistent storage with json-server
- Responsive design with Tailwind CSS

3
app/globals.css Normal file
View file

@ -0,0 +1,3 @@
@tailwind base;
@tailwind components;
@tailwind utilities;

19
app/layout.tsx Normal file
View file

@ -0,0 +1,19 @@
import type { Metadata } from "next";
import "./globals.css";
export const metadata: Metadata = {
title: "Worker Presence Tracker",
description: "Track worker presence with point system",
};
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en">
<body>{children}</body>
</html>
);
}

337
app/page.tsx Normal file
View file

@ -0,0 +1,337 @@
'use client';
import { useState, useEffect } from 'react';
import { workersAPI, Worker } from '@/lib/api';
export default function Home() {
const [workers, setWorkers] = useState<Worker[]>([]);
const [newWorkerName, setNewWorkerName] = useState('');
const [newPresenceDays, setNewPresenceDays] = useState('');
const [editingId, setEditingId] = useState<string | null>(null);
const [editingDays, setEditingDays] = useState('');
const [loading, setLoading] = useState(false);
const TOTAL_POINTS = 13;
const TOTAL_DAYS = 10;
const POINTS_PER_DAY = TOTAL_POINTS / TOTAL_DAYS;
useEffect(() => {
loadWorkers();
}, []);
const loadWorkers = async () => {
try {
const data = await workersAPI.getAll();
setWorkers(data);
} catch (error) {
console.error('Failed to load workers:', error);
alert('Failed to load workers. Make sure json-server is running.');
}
};
const addWorker = async () => {
if (!newWorkerName.trim() || !newPresenceDays.trim()) return;
const days = parseInt(newPresenceDays);
if (isNaN(days) || days < 0 || days > TOTAL_DAYS) {
alert(`Please enter a valid number of days between 0 and ${TOTAL_DAYS}`);
return;
}
try {
setLoading(true);
await workersAPI.create({
name: newWorkerName.trim(),
presenceDays: days,
});
await loadWorkers();
setNewWorkerName('');
setNewPresenceDays('');
} catch (error) {
console.error('Failed to add worker:', error);
alert('Failed to add worker');
} finally {
setLoading(false);
}
};
const removeWorker = async (id: string) => {
try {
setLoading(true);
await workersAPI.delete(id);
await loadWorkers();
} catch (error) {
console.error('Failed to remove worker:', error);
alert('Failed to remove worker');
} finally {
setLoading(false);
}
};
const startEditing = (worker: Worker) => {
setEditingId(worker.id);
setEditingDays(worker.presenceDays.toString());
};
const cancelEditing = () => {
setEditingId(null);
setEditingDays('');
};
const saveEditing = async (id: string) => {
const days = parseInt(editingDays);
if (isNaN(days) || days < 0 || days > TOTAL_DAYS) {
alert(`Please enter a valid number of days between 0 and ${TOTAL_DAYS}`);
return;
}
try {
setLoading(true);
await workersAPI.update(id, { presenceDays: days });
await loadWorkers();
setEditingId(null);
setEditingDays('');
} catch (error) {
console.error('Failed to update worker:', error);
alert('Failed to update worker');
} finally {
setLoading(false);
}
};
const resetAllPresences = async () => {
if (!confirm('Are you sure you want to reset all worker presences to 0?')) {
return;
}
try {
setLoading(true);
await workersAPI.resetAllPresences();
await loadWorkers();
} catch (error) {
console.error('Failed to reset presences:', error);
alert('Failed to reset presences');
} finally {
setLoading(false);
}
};
const calculatePoints = (days: number): number => {
return days * POINTS_PER_DAY;
};
const calculateUsedPoints = (days: number): number => {
return TOTAL_POINTS - calculatePoints(days);
};
return (
<main className="min-h-screen bg-gradient-to-br from-blue-50 to-indigo-100 p-8">
<div className="max-w-4xl mx-auto">
<div className="flex justify-between items-start mb-8">
<div>
<h1 className="text-4xl font-bold text-gray-800 mb-2">Worker Presence Tracker</h1>
<p className="text-gray-600">
Sprint duration: 2 weeks (10 working days) | Total points per worker: {TOTAL_POINTS}
</p>
</div>
{workers.length > 0 && (
<button
onClick={resetAllPresences}
disabled={loading}
className="px-4 py-2 bg-orange-600 text-white rounded-lg hover:bg-orange-700 transition-colors font-medium disabled:opacity-50 disabled:cursor-not-allowed"
>
Reset All Presences
</button>
)}
</div>
{/* Add Worker Form */}
<div className="bg-white rounded-lg shadow-md p-6 mb-8">
<h2 className="text-xl font-semibold text-gray-800 mb-4">Add Worker</h2>
<div className="flex flex-col sm:flex-row gap-3">
<input
type="text"
placeholder="Worker name"
value={newWorkerName}
onChange={(e) => setNewWorkerName(e.target.value)}
className="flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
onKeyPress={(e) => e.key === 'Enter' && addWorker()}
/>
<input
type="number"
placeholder="Presence days (0-10)"
value={newPresenceDays}
onChange={(e) => setNewPresenceDays(e.target.value)}
min="0"
max="10"
className="w-full sm:w-48 px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
onKeyPress={(e) => e.key === 'Enter' && addWorker()}
/>
<button
onClick={addWorker}
disabled={loading}
className="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors font-medium disabled:opacity-50 disabled:cursor-not-allowed"
>
Add
</button>
</div>
</div>
{/* Workers List */}
{workers.length > 0 ? (
<div className="bg-white rounded-lg shadow-md overflow-hidden">
<div className="overflow-x-auto">
<table className="w-full">
<thead className="bg-gray-50 border-b border-gray-200">
<tr>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Worker Name
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Presence Days
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Points Earned
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Points Used
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Remaining Points
</th>
<th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
Actions
</th>
</tr>
</thead>
<tbody className="bg-white divide-y divide-gray-200">
{workers.map((worker) => {
const pointsEarned = calculatePoints(worker.presenceDays);
const pointsUsed = calculateUsedPoints(worker.presenceDays);
const remainingPoints = TOTAL_POINTS - pointsUsed;
const isEditing = editingId === worker.id;
return (
<tr key={worker.id} className="hover:bg-gray-50">
<td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
{worker.name}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-700">
{isEditing ? (
<input
type="number"
value={editingDays}
onChange={(e) => setEditingDays(e.target.value)}
min="0"
max="10"
className="w-20 px-2 py-1 border border-blue-300 rounded focus:outline-none focus:ring-2 focus:ring-blue-500"
onKeyPress={(e) => {
if (e.key === 'Enter') saveEditing(worker.id);
if (e.key === 'Escape') cancelEditing();
}}
autoFocus
/>
) : (
`${worker.presenceDays} / ${TOTAL_DAYS}`
)}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-green-600 font-medium">
{pointsEarned.toFixed(2)}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-red-600 font-medium">
{pointsUsed.toFixed(2)}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-700 font-medium">
{remainingPoints.toFixed(2)} / {TOTAL_POINTS}
</td>
<td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
{isEditing ? (
<div className="flex gap-2 justify-end">
<button
onClick={() => saveEditing(worker.id)}
className="text-green-600 hover:text-green-900 transition-colors"
>
Save
</button>
<button
onClick={cancelEditing}
className="text-gray-600 hover:text-gray-900 transition-colors"
>
Cancel
</button>
</div>
) : (
<div className="flex gap-2 justify-end">
<button
onClick={() => startEditing(worker)}
className="text-blue-600 hover:text-blue-900 transition-colors"
>
Edit
</button>
<button
onClick={() => removeWorker(worker.id)}
className="text-red-600 hover:text-red-900 transition-colors"
>
Remove
</button>
</div>
)}
</td>
</tr>
);
})}
</tbody>
</table>
</div>
{/* Summary */}
<div className="bg-gray-50 px-6 py-4 border-t border-gray-200">
<div className="flex flex-wrap gap-6 text-sm">
<div>
<span className="text-gray-600">Total Workers: </span>
<span className="font-semibold text-gray-900">{workers.length}</span>
</div>
<div>
<span className="text-gray-600">Avg Presence Days: </span>
<span className="font-semibold text-gray-900">
{workers.length > 0
? (workers.reduce((sum, w) => sum + w.presenceDays, 0) / workers.length).toFixed(1)
: '0'}
</span>
</div>
<div>
<span className="text-gray-600">Total Presence Days: </span>
<span className="font-semibold text-gray-900">
{workers.reduce((sum, w) => sum + w.presenceDays, 0)}
</span>
</div>
<div>
<span className="text-gray-600">Total Remaining Points: </span>
<span className="font-semibold text-blue-600">
{workers.reduce((sum, w) => sum + calculatePoints(w.presenceDays), 0).toFixed(2)}
</span>
</div>
</div>
</div>
</div>
) : (
<div className="bg-white rounded-lg shadow-md p-12 text-center">
<p className="text-gray-500 text-lg">No workers added yet. Add your first worker above.</p>
</div>
)}
{/* Info Box */}
<div className="mt-8 bg-blue-50 border border-blue-200 rounded-lg p-4">
<h3 className="font-semibold text-blue-900 mb-2">How it works:</h3>
<ul className="text-sm text-blue-800 space-y-1">
<li> Each worker has {TOTAL_POINTS} points for a 2-week sprint ({TOTAL_DAYS} working days)</li>
<li> Each presence day equals {POINTS_PER_DAY.toFixed(2)} points</li>
<li> Points Earned = Presence Days × {POINTS_PER_DAY.toFixed(2)}</li>
<li> Points Used = {TOTAL_POINTS} - Points Earned (days not present)</li>
<li> Remaining Points = Points Earned</li>
</ul>
</div>
</div>
</main>
);
}

9
db.json Normal file
View file

@ -0,0 +1,9 @@
{
"workers": [
{
"name": "Mathieu",
"presenceDays": 0,
"id": 1
}
]
}

14
deploy.sh Executable file
View file

@ -0,0 +1,14 @@
#!/bin/bash
# Build images
echo "Building Docker images..."
docker build -t presence-tracker-web:latest -f Dockerfile .
docker build -t presence-tracker-api:latest -f Dockerfile.jsonserver .
echo "Images built successfully!"
echo ""
echo "To deploy to Docker Swarm:"
echo " docker stack deploy -c docker-compose.swarm.yml presence-tracker"
echo ""
echo "To test locally with docker-compose:"
echo " docker-compose up -d"

51
docker-compose.swarm.yml Normal file
View file

@ -0,0 +1,51 @@
version: '3.8'
services:
json-server:
image: presence-tracker-api:latest
ports:
- "3001:3001"
volumes:
- json-data:/data
networks:
- presence-network
deploy:
replicas: 1
restart_policy:
condition: on-failure
delay: 5s
max_attempts: 3
placement:
constraints:
- node.role == worker
nextjs:
image: presence-tracker-web:latest
ports:
- "3000:3000"
environment:
- API_URL=http://json-server:3001
networks:
- presence-network
deploy:
replicas: 2
restart_policy:
condition: on-failure
delay: 5s
max_attempts: 3
update_config:
parallelism: 1
delay: 10s
placement:
constraints:
- node.role == worker
depends_on:
- json-server
volumes:
json-data:
driver: local
networks:
presence-network:
driver: overlay

38
docker-compose.yml Normal file
View file

@ -0,0 +1,38 @@
version: '3.8'
services:
json-server:
build:
context: .
dockerfile: Dockerfile.jsonserver
container_name: presence-tracker-api
ports:
- "3001:3001"
volumes:
- json-data:/data
networks:
- presence-network
restart: unless-stopped
nextjs:
build:
context: .
dockerfile: Dockerfile
container_name: presence-tracker-web
ports:
- "3000:3000"
environment:
- API_URL=http://json-server:3001
depends_on:
- json-server
networks:
- presence-network
restart: unless-stopped
volumes:
json-data:
driver: local
networks:
presence-network:
driver: bridge

53
lib/api.ts Normal file
View file

@ -0,0 +1,53 @@
const API_URL = typeof window !== 'undefined'
? (process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3001')
: (process.env.API_URL || 'http://localhost:3001');
export interface Worker {
id: string;
name: string;
presenceDays: number;
}
export const workersAPI = {
async getAll(): Promise<Worker[]> {
const response = await fetch(`${API_URL}/workers`);
if (!response.ok) throw new Error('Failed to fetch workers');
return response.json();
},
async create(worker: Omit<Worker, 'id'>): Promise<Worker> {
const response = await fetch(`${API_URL}/workers`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(worker),
});
if (!response.ok) throw new Error('Failed to create worker');
return response.json();
},
async update(id: string, worker: Partial<Worker>): Promise<Worker> {
const response = await fetch(`${API_URL}/workers/${id}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(worker),
});
if (!response.ok) throw new Error('Failed to update worker');
return response.json();
},
async delete(id: string): Promise<void> {
const response = await fetch(`${API_URL}/workers/${id}`, {
method: 'DELETE',
});
if (!response.ok) throw new Error('Failed to delete worker');
},
async resetAllPresences(): Promise<void> {
const workers = await this.getAll();
await Promise.all(
workers.map(worker =>
this.update(worker.id, { presenceDays: 0 })
)
);
},
};

16
next.config.ts Normal file
View file

@ -0,0 +1,16 @@
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
output: 'standalone',
async rewrites() {
const apiUrl = process.env.API_URL || 'http://localhost:3001';
return [
{
source: '/api/:path*',
destination: `${apiUrl}/:path*`,
},
];
},
};
export default nextConfig;

3961
package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

28
package.json Normal file
View file

@ -0,0 +1,28 @@
{
"name": "presence-tracker",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint",
"json-server": "json-server --watch db.json --port 3001"
},
"dependencies": {
"next": "^15.0.0",
"react": "^19.0.0",
"react-dom": "^19.0.0"
},
"devDependencies": {
"@types/node": "^20.0.0",
"@types/react": "^19.0.0",
"@types/react-dom": "^19.0.0",
"autoprefixer": "^10.4.0",
"json-server": "^0.17.4",
"postcss": "^8.4.0",
"tailwindcss": "^3.4.0",
"typescript": "^5.0.0"
},
"packageManager": "yarn@4.9.4+sha512.7b1cb0b62abba6a537b3a2ce00811a843bea02bcf53138581a6ae5b1bf563f734872bd47de49ce32a9ca9dcaff995aa789577ffb16811da7c603dcf69e73750b"
}

9
postcss.config.mjs Normal file
View file

@ -0,0 +1,9 @@
/** @type {import('postcss-load-config').Config} */
const config = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
};
export default config;

14
tailwind.config.ts Normal file
View file

@ -0,0 +1,14 @@
import type { Config } from "tailwindcss";
const config: Config = {
content: [
"./pages/**/*.{js,ts,jsx,tsx,mdx}",
"./components/**/*.{js,ts,jsx,tsx,mdx}",
"./app/**/*.{js,ts,jsx,tsx,mdx}",
],
theme: {
extend: {},
},
plugins: [],
};
export default config;

27
tsconfig.json Normal file
View file

@ -0,0 +1,27 @@
{
"compilerOptions": {
"target": "ES2017",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": ["./*"]
}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"]
}

3115
yarn.lock Normal file

File diff suppressed because it is too large Load diff