v1.0.0
This commit is contained in:
commit
f2a1d072ee
137
.gitignore
vendored
Normal file
137
.gitignore
vendored
Normal file
@ -0,0 +1,137 @@
|
||||
# Dependencies
|
||||
node_modules/
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
|
||||
# Environment variables
|
||||
.env
|
||||
.env.local
|
||||
.env.development.local
|
||||
.env.test.local
|
||||
.env.production.local
|
||||
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
lerna-debug.log*
|
||||
|
||||
# Runtime data
|
||||
pids
|
||||
*.pid
|
||||
*.seed
|
||||
*.pid.lock
|
||||
|
||||
# Coverage directory used by tools like istanbul
|
||||
coverage/
|
||||
*.lcov
|
||||
|
||||
# nyc test coverage
|
||||
.nyc_output
|
||||
|
||||
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
|
||||
.grunt
|
||||
|
||||
# Bower dependency directory (https://bower.io/)
|
||||
bower_components
|
||||
|
||||
# node-waf configuration
|
||||
.lock-wscript
|
||||
|
||||
# Compiled binary addons (https://nodejs.org/api/addons.html)
|
||||
build/Release
|
||||
|
||||
# Dependency directories
|
||||
node_modules/
|
||||
jspm_packages/
|
||||
|
||||
# TypeScript cache
|
||||
*.tsbuildinfo
|
||||
|
||||
# Optional npm cache directory
|
||||
.npm
|
||||
|
||||
# Optional eslint cache
|
||||
.eslintcache
|
||||
|
||||
# Microbundle cache
|
||||
.rpt2_cache/
|
||||
.rts2_cache_cjs/
|
||||
.rts2_cache_es/
|
||||
.rts2_cache_umd/
|
||||
|
||||
# Optional REPL history
|
||||
.node_repl_history
|
||||
|
||||
# Output of 'npm pack'
|
||||
*.tgz
|
||||
|
||||
# Yarn Integrity file
|
||||
.yarn-integrity
|
||||
|
||||
# dotenv environment variables file
|
||||
.env.test
|
||||
|
||||
# parcel-bundler cache (https://parceljs.org/)
|
||||
.cache
|
||||
.parcel-cache
|
||||
|
||||
# Next.js build output
|
||||
.next
|
||||
|
||||
# Nuxt.js build / generate output
|
||||
.nuxt
|
||||
dist
|
||||
|
||||
# Gatsby files
|
||||
.cache/
|
||||
public
|
||||
|
||||
# vuepress build output
|
||||
.vuepress/dist
|
||||
|
||||
# Serverless directories
|
||||
.serverless/
|
||||
|
||||
# FuseBox cache
|
||||
.fusebox/
|
||||
|
||||
# DynamoDB Local files
|
||||
.dynamodb/
|
||||
|
||||
# TernJS port file
|
||||
.tern-port
|
||||
|
||||
# Stores VSCode versions used for testing VSCode extensions
|
||||
.vscode-test
|
||||
|
||||
# OS generated files
|
||||
.DS_Store
|
||||
.DS_Store?
|
||||
._*
|
||||
.Spotlight-V100
|
||||
.Trashes
|
||||
ehthumbs.db
|
||||
Thumbs.db
|
||||
|
||||
# IDE
|
||||
.vscode/
|
||||
.idea/
|
||||
*.swp
|
||||
*.swo
|
||||
*~
|
||||
|
||||
# Database
|
||||
*.sqlite
|
||||
*.db
|
||||
|
||||
# Temporary files
|
||||
*.tmp
|
||||
*.temp
|
||||
|
||||
# Build artifacts
|
||||
build/
|
||||
dist/
|
||||
69
README.md
Normal file
69
README.md
Normal file
@ -0,0 +1,69 @@
|
||||
# Неучтенное время
|
||||
|
||||
Приложение для отслеживания рабочего времени с ролевой системой (администратор, менеджер, пользователь).
|
||||
|
||||
## Структура проекта
|
||||
|
||||
- `backend/` - Серверная часть (Node.js, Express, Sequelize)
|
||||
- `frontend/` - Клиентская часть (React, Vite)
|
||||
|
||||
## Установка
|
||||
|
||||
1. Клонируйте репозиторий:
|
||||
|
||||
```
|
||||
git clone <repository-url>
|
||||
cd time-tracking
|
||||
```
|
||||
|
||||
2. Установите зависимости для backend:
|
||||
|
||||
```
|
||||
cd backend
|
||||
npm install
|
||||
```
|
||||
|
||||
3. Установите зависимости для frontend:
|
||||
```
|
||||
cd ../frontend
|
||||
npm install
|
||||
```
|
||||
|
||||
## Настройка
|
||||
|
||||
1. В папке `backend` создайте файл `.env` на основе `.env.example` и настройте переменные окружения (например, подключение к базе данных).
|
||||
|
||||
2. Настройте базу данных:
|
||||
```
|
||||
cd backend
|
||||
npx sequelize-cli db:migrate
|
||||
```
|
||||
|
||||
## Запуск
|
||||
|
||||
1. Запустите backend:
|
||||
|
||||
```
|
||||
cd backend
|
||||
npm start
|
||||
```
|
||||
|
||||
2. В новом терминале запустите frontend:
|
||||
```
|
||||
cd frontend
|
||||
npm run dev
|
||||
```
|
||||
|
||||
Приложение будет доступно по адресу http://localhost:3000 (или порт, указанный в настройках).
|
||||
|
||||
## Роли пользователей
|
||||
|
||||
- **Администратор**: Полный доступ, управление пользователями, просмотр всех записей времени.
|
||||
- **Менеджер**: Управление своими подчиненными, просмотр их записей.
|
||||
- **Пользователь**: Добавление и просмотр своих записей времени.
|
||||
|
||||
## Технологии
|
||||
|
||||
- Backend: Node.js, Express, Sequelize, JWT
|
||||
- Frontend: React, Vite, Axios
|
||||
- Database: SQLite (или другая, в зависимости от конфигурации)
|
||||
8
backend/.sequelizerc
Normal file
8
backend/.sequelizerc
Normal file
@ -0,0 +1,8 @@
|
||||
const path = require("path");
|
||||
|
||||
module.exports = {
|
||||
config: path.resolve("config", "config.js"),
|
||||
"models-path": path.resolve("models"),
|
||||
"seeders-path": path.resolve("seeders"),
|
||||
"migrations-path": path.resolve("migrations"),
|
||||
};
|
||||
28
backend/config/config.js
Normal file
28
backend/config/config.js
Normal file
@ -0,0 +1,28 @@
|
||||
require("dotenv").config();
|
||||
|
||||
module.exports = {
|
||||
development: {
|
||||
username: process.env.DB_USER || "postgres",
|
||||
password: process.env.DB_PASSWORD || "password",
|
||||
database: process.env.DB_NAME || "time_tracking_dev",
|
||||
host: process.env.DB_HOST || "localhost",
|
||||
port: process.env.DB_PORT || 5432,
|
||||
dialect: "postgres",
|
||||
},
|
||||
test: {
|
||||
username: process.env.DB_USER || "postgres",
|
||||
password: process.env.DB_PASSWORD || "password",
|
||||
database: process.env.DB_NAME || "time_tracking_test",
|
||||
host: process.env.DB_HOST || "localhost",
|
||||
port: process.env.DB_PORT || 5432,
|
||||
dialect: "postgres",
|
||||
},
|
||||
production: {
|
||||
username: process.env.DB_USER,
|
||||
password: process.env.DB_PASSWORD,
|
||||
database: process.env.DB_NAME,
|
||||
host: process.env.DB_HOST,
|
||||
port: process.env.DB_PORT || 5432,
|
||||
dialect: "postgres",
|
||||
},
|
||||
};
|
||||
26
backend/config/config.json
Normal file
26
backend/config/config.json
Normal file
@ -0,0 +1,26 @@
|
||||
{
|
||||
"development": {
|
||||
"username": process.env.DB_USER || "postgres",
|
||||
"password": process.env.DB_PASSWORD || "password",
|
||||
"database": process.env.DB_NAME || "time_tracking_dev",
|
||||
"host": process.env.DB_HOST || "localhost",
|
||||
"port": process.env.DB_PORT || 5432,
|
||||
"dialect": "postgres"
|
||||
},
|
||||
"test": {
|
||||
"username": process.env.DB_USER || "postgres",
|
||||
"password": process.env.DB_PASSWORD || "password",
|
||||
"database": process.env.DB_NAME || "time_tracking_test",
|
||||
"host": process.env.DB_HOST || "localhost",
|
||||
"port": process.env.DB_PORT || 5432,
|
||||
"dialect": "postgres"
|
||||
},
|
||||
"production": {
|
||||
"username": process.env.DB_USER,
|
||||
"password": process.env.DB_PASSWORD,
|
||||
"database": process.env.DB_NAME,
|
||||
"host": process.env.DB_HOST,
|
||||
"port": process.env.DB_PORT || 5432,
|
||||
"dialect": "postgres"
|
||||
}
|
||||
}
|
||||
38
backend/middleware/auth.js
Normal file
38
backend/middleware/auth.js
Normal file
@ -0,0 +1,38 @@
|
||||
const jwt = require("jsonwebtoken");
|
||||
const { User } = require("../models");
|
||||
|
||||
const authenticate = async (req, res, next) => {
|
||||
try {
|
||||
const token = req.header("Authorization")?.replace("Bearer ", "");
|
||||
if (!token) {
|
||||
return res.status(401).json({ message: "Access denied" });
|
||||
}
|
||||
|
||||
const decoded = jwt.verify(token, process.env.JWT_SECRET);
|
||||
const user = await User.findByPk(decoded.id);
|
||||
if (!user) {
|
||||
return res.status(401).json({ message: "Invalid token" });
|
||||
}
|
||||
|
||||
req.user = user;
|
||||
next();
|
||||
} catch (error) {
|
||||
res.status(401).json({ message: "Invalid token" });
|
||||
}
|
||||
};
|
||||
|
||||
const authorizeAdmin = (req, res, next) => {
|
||||
if (req.user.role !== "admin") {
|
||||
return res.status(403).json({ message: "Admin access required" });
|
||||
}
|
||||
next();
|
||||
};
|
||||
|
||||
const authorizeManager = (req, res, next) => {
|
||||
if (req.user.role !== "admin" && req.user.role !== "manager") {
|
||||
return res.status(403).json({ message: "Manager access required" });
|
||||
}
|
||||
next();
|
||||
};
|
||||
|
||||
module.exports = { authenticate, authorizeAdmin, authorizeManager };
|
||||
34
backend/migrations/20251011144754-create-user.js
Normal file
34
backend/migrations/20251011144754-create-user.js
Normal file
@ -0,0 +1,34 @@
|
||||
'use strict';
|
||||
/** @type {import('sequelize-cli').Migration} */
|
||||
module.exports = {
|
||||
async up(queryInterface, Sequelize) {
|
||||
await queryInterface.createTable('Users', {
|
||||
id: {
|
||||
allowNull: false,
|
||||
autoIncrement: true,
|
||||
primaryKey: true,
|
||||
type: Sequelize.INTEGER
|
||||
},
|
||||
username: {
|
||||
type: Sequelize.STRING
|
||||
},
|
||||
password: {
|
||||
type: Sequelize.STRING
|
||||
},
|
||||
role: {
|
||||
type: Sequelize.STRING
|
||||
},
|
||||
createdAt: {
|
||||
allowNull: false,
|
||||
type: Sequelize.DATE
|
||||
},
|
||||
updatedAt: {
|
||||
allowNull: false,
|
||||
type: Sequelize.DATE
|
||||
}
|
||||
});
|
||||
},
|
||||
async down(queryInterface, Sequelize) {
|
||||
await queryInterface.dropTable('Users');
|
||||
}
|
||||
};
|
||||
37
backend/migrations/20251011144803-create-time-entry.js
Normal file
37
backend/migrations/20251011144803-create-time-entry.js
Normal file
@ -0,0 +1,37 @@
|
||||
'use strict';
|
||||
/** @type {import('sequelize-cli').Migration} */
|
||||
module.exports = {
|
||||
async up(queryInterface, Sequelize) {
|
||||
await queryInterface.createTable('TimeEntries', {
|
||||
id: {
|
||||
allowNull: false,
|
||||
autoIncrement: true,
|
||||
primaryKey: true,
|
||||
type: Sequelize.INTEGER
|
||||
},
|
||||
userId: {
|
||||
type: Sequelize.INTEGER
|
||||
},
|
||||
date: {
|
||||
type: Sequelize.DATE
|
||||
},
|
||||
reason: {
|
||||
type: Sequelize.STRING
|
||||
},
|
||||
hours: {
|
||||
type: Sequelize.DECIMAL
|
||||
},
|
||||
createdAt: {
|
||||
allowNull: false,
|
||||
type: Sequelize.DATE
|
||||
},
|
||||
updatedAt: {
|
||||
allowNull: false,
|
||||
type: Sequelize.DATE
|
||||
}
|
||||
});
|
||||
},
|
||||
async down(queryInterface, Sequelize) {
|
||||
await queryInterface.dropTable('TimeEntries');
|
||||
}
|
||||
};
|
||||
51
backend/models/index.js
Normal file
51
backend/models/index.js
Normal file
@ -0,0 +1,51 @@
|
||||
"use strict";
|
||||
|
||||
require("dotenv").config();
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const Sequelize = require("sequelize");
|
||||
const process = require("process");
|
||||
const basename = path.basename(__filename);
|
||||
const env = process.env.NODE_ENV || "development";
|
||||
const config = require(__dirname + "/../config/config.js")[env];
|
||||
const db = {};
|
||||
|
||||
let sequelize;
|
||||
if (config.use_env_variable) {
|
||||
sequelize = new Sequelize(process.env[config.use_env_variable], config);
|
||||
} else {
|
||||
sequelize = new Sequelize(
|
||||
config.database,
|
||||
config.username,
|
||||
config.password,
|
||||
config
|
||||
);
|
||||
}
|
||||
|
||||
fs.readdirSync(__dirname)
|
||||
.filter((file) => {
|
||||
return (
|
||||
file.indexOf(".") !== 0 &&
|
||||
file !== basename &&
|
||||
file.slice(-3) === ".js" &&
|
||||
file.indexOf(".test.js") === -1
|
||||
);
|
||||
})
|
||||
.forEach((file) => {
|
||||
const model = require(path.join(__dirname, file))(
|
||||
sequelize,
|
||||
Sequelize.DataTypes
|
||||
);
|
||||
db[model.name] = model;
|
||||
});
|
||||
|
||||
Object.keys(db).forEach((modelName) => {
|
||||
if (db[modelName].associate) {
|
||||
db[modelName].associate(db);
|
||||
}
|
||||
});
|
||||
|
||||
db.sequelize = sequelize;
|
||||
db.Sequelize = Sequelize;
|
||||
|
||||
module.exports = db;
|
||||
39
backend/models/timeentry.js
Normal file
39
backend/models/timeentry.js
Normal file
@ -0,0 +1,39 @@
|
||||
"use strict";
|
||||
const { Model } = require("sequelize");
|
||||
module.exports = (sequelize, DataTypes) => {
|
||||
class TimeEntry extends Model {
|
||||
/**
|
||||
* Helper method for defining associations.
|
||||
* This method is not a part of Sequelize lifecycle.
|
||||
* The `models/index` file will call this method automatically.
|
||||
*/
|
||||
static associate(models) {
|
||||
this.belongsTo(models.User, { foreignKey: "userId" });
|
||||
}
|
||||
}
|
||||
TimeEntry.init(
|
||||
{
|
||||
userId: {
|
||||
type: DataTypes.INTEGER,
|
||||
allowNull: false,
|
||||
},
|
||||
date: {
|
||||
type: DataTypes.DATE,
|
||||
allowNull: false,
|
||||
},
|
||||
reason: {
|
||||
type: DataTypes.STRING,
|
||||
allowNull: false,
|
||||
},
|
||||
hours: {
|
||||
type: DataTypes.DECIMAL,
|
||||
allowNull: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
sequelize,
|
||||
modelName: "TimeEntry",
|
||||
}
|
||||
);
|
||||
return TimeEntry;
|
||||
};
|
||||
62
backend/models/user.js
Normal file
62
backend/models/user.js
Normal file
@ -0,0 +1,62 @@
|
||||
"use strict";
|
||||
const { Model } = require("sequelize");
|
||||
const bcrypt = require("bcryptjs");
|
||||
module.exports = (sequelize, DataTypes) => {
|
||||
class User extends Model {
|
||||
/**
|
||||
* Helper method for defining associations.
|
||||
* This method is not a part of Sequelize lifecycle.
|
||||
* The `models/index` file will call this method automatically.
|
||||
*/
|
||||
static associate(models) {
|
||||
this.hasMany(models.TimeEntry, { foreignKey: "userId" });
|
||||
}
|
||||
|
||||
// Instance method to check password
|
||||
async checkPassword(password) {
|
||||
return bcrypt.compare(password, this.password);
|
||||
}
|
||||
}
|
||||
|
||||
User.init(
|
||||
{
|
||||
username: {
|
||||
type: DataTypes.STRING,
|
||||
allowNull: false,
|
||||
unique: true,
|
||||
},
|
||||
password: {
|
||||
type: DataTypes.STRING,
|
||||
allowNull: false,
|
||||
},
|
||||
role: {
|
||||
type: DataTypes.STRING,
|
||||
allowNull: false,
|
||||
defaultValue: "user",
|
||||
},
|
||||
},
|
||||
{
|
||||
sequelize,
|
||||
modelName: "User",
|
||||
hooks: {
|
||||
beforeCreate: async (user) => {
|
||||
if (user.password) {
|
||||
const bcrypt = require("bcryptjs");
|
||||
const salt = await bcrypt.genSalt(10);
|
||||
user.password = await bcrypt.hash(user.password, salt);
|
||||
}
|
||||
},
|
||||
beforeUpdate: async (user) => {
|
||||
if (user.password && user.changed("password")) {
|
||||
console.log("Хэшируем пароль при обновлении");
|
||||
const bcrypt = require("bcryptjs");
|
||||
const salt = await bcrypt.genSalt(10);
|
||||
user.password = await bcrypt.hash(user.password, salt);
|
||||
console.log("Пароль хэширован");
|
||||
}
|
||||
},
|
||||
},
|
||||
}
|
||||
);
|
||||
return User;
|
||||
};
|
||||
2356
backend/package-lock.json
generated
Normal file
2356
backend/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
26
backend/package.json
Normal file
26
backend/package.json
Normal file
@ -0,0 +1,26 @@
|
||||
{
|
||||
"name": "backend",
|
||||
"version": "1.0.0",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"start": "node server.js",
|
||||
"dev": "node server.js",
|
||||
"test": "echo \"Error: no test specified\" && exit 1"
|
||||
},
|
||||
"keywords": [],
|
||||
"author": "",
|
||||
"license": "ISC",
|
||||
"description": "",
|
||||
"dependencies": {
|
||||
"bcryptjs": "^3.0.2",
|
||||
"cors": "^2.8.5",
|
||||
"dotenv": "^17.2.3",
|
||||
"express": "^5.1.0",
|
||||
"jsonwebtoken": "^9.0.2",
|
||||
"pg": "^8.16.3",
|
||||
"sequelize": "^6.37.7"
|
||||
},
|
||||
"devDependencies": {
|
||||
"sequelize-cli": "^6.6.3"
|
||||
}
|
||||
}
|
||||
38
backend/routes/auth.js
Normal file
38
backend/routes/auth.js
Normal file
@ -0,0 +1,38 @@
|
||||
const express = require("express");
|
||||
const jwt = require("jsonwebtoken");
|
||||
const { User } = require("../models");
|
||||
const { authenticate } = require("../middleware/auth");
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
// Login
|
||||
router.post("/login", async (req, res) => {
|
||||
try {
|
||||
const { username, password } = req.body;
|
||||
const user = await User.findOne({ where: { username } });
|
||||
if (!user || !(await user.checkPassword(password))) {
|
||||
return res.status(400).json({ message: "Invalid credentials" });
|
||||
}
|
||||
|
||||
const token = jwt.sign(
|
||||
{ id: user.id, role: user.role },
|
||||
process.env.JWT_SECRET,
|
||||
{ expiresIn: "1h" }
|
||||
);
|
||||
res.json({
|
||||
token,
|
||||
user: { id: user.id, username: user.username, role: user.role },
|
||||
});
|
||||
} catch (error) {
|
||||
res.status(500).json({ message: "Server error" });
|
||||
}
|
||||
});
|
||||
|
||||
// Get current user
|
||||
router.get("/me", authenticate, async (req, res) => {
|
||||
res.json({
|
||||
user: { id: req.user.id, username: req.user.username, role: req.user.role },
|
||||
});
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
126
backend/routes/timeEntries.js
Normal file
126
backend/routes/timeEntries.js
Normal file
@ -0,0 +1,126 @@
|
||||
const express = require("express");
|
||||
const { TimeEntry, User } = require("../models");
|
||||
const {
|
||||
authenticate,
|
||||
authorizeAdmin,
|
||||
authorizeManager,
|
||||
} = require("../middleware/auth");
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
// Get time entries for current user
|
||||
router.get("/", authenticate, async (req, res) => {
|
||||
try {
|
||||
const entries = await TimeEntry.findAll({
|
||||
where: { userId: req.user.id },
|
||||
order: [["date", "DESC"]],
|
||||
});
|
||||
res.json(entries);
|
||||
} catch (error) {
|
||||
res.status(500).json({ message: "Server error" });
|
||||
}
|
||||
});
|
||||
|
||||
// Get all time entries (admin and manager)
|
||||
router.get("/all", authenticate, authorizeManager, async (req, res) => {
|
||||
try {
|
||||
const entries = await TimeEntry.findAll({
|
||||
include: [{ model: User, attributes: ["username"] }],
|
||||
order: [["date", "DESC"]],
|
||||
});
|
||||
res.json(entries);
|
||||
} catch (error) {
|
||||
res.status(500).json({ message: "Server error" });
|
||||
}
|
||||
});
|
||||
|
||||
// Get time entries for specific user (admin and manager)
|
||||
router.get(
|
||||
"/user/:userId",
|
||||
authenticate,
|
||||
authorizeManager,
|
||||
async (req, res) => {
|
||||
try {
|
||||
const { userId } = req.params;
|
||||
console.log("Fetching entries for userId:", userId);
|
||||
const entries = await TimeEntry.findAll({
|
||||
where: { userId },
|
||||
order: [["date", "DESC"]],
|
||||
});
|
||||
console.log("Found entries:", entries);
|
||||
res.json(entries);
|
||||
} catch (error) {
|
||||
console.error("Error fetching user entries:", error);
|
||||
res.status(500).json({ message: "Server error" });
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// Create time entry
|
||||
router.post("/", authenticate, async (req, res) => {
|
||||
try {
|
||||
const { date, reason, hours } = req.body;
|
||||
const entry = await TimeEntry.create({
|
||||
userId: req.user.id,
|
||||
date,
|
||||
reason,
|
||||
hours: parseFloat(hours),
|
||||
});
|
||||
res.status(201).json(entry);
|
||||
} catch (error) {
|
||||
res.status(500).json({ message: "Server error" });
|
||||
}
|
||||
});
|
||||
|
||||
// Update time entry (own or admin)
|
||||
router.put("/:id", authenticate, async (req, res) => {
|
||||
try {
|
||||
const { date, reason, hours } = req.body;
|
||||
const entry = await TimeEntry.findByPk(req.params.id);
|
||||
if (!entry) {
|
||||
return res.status(404).json({ message: "Entry not found" });
|
||||
}
|
||||
if (entry.userId !== req.user.id && req.user.role !== "admin") {
|
||||
return res.status(403).json({ message: "Access denied" });
|
||||
}
|
||||
await entry.update({
|
||||
date,
|
||||
reason,
|
||||
hours: parseFloat(hours),
|
||||
});
|
||||
res.json(entry);
|
||||
} catch (error) {
|
||||
res.status(500).json({ message: "Server error" });
|
||||
}
|
||||
});
|
||||
|
||||
// Delete all time entries for current user
|
||||
router.delete("/delete-all", authenticate, async (req, res) => {
|
||||
try {
|
||||
const deletedCount = await TimeEntry.destroy({
|
||||
where: { userId: req.user.id },
|
||||
});
|
||||
res.json({ message: "All entries deleted", deletedCount });
|
||||
} catch (error) {
|
||||
res.status(500).json({ message: "Server error" });
|
||||
}
|
||||
});
|
||||
|
||||
// Delete time entry (own or admin)
|
||||
router.delete("/:id", authenticate, async (req, res) => {
|
||||
try {
|
||||
const entry = await TimeEntry.findByPk(req.params.id);
|
||||
if (!entry) {
|
||||
return res.status(404).json({ message: "Entry not found" });
|
||||
}
|
||||
if (entry.userId !== req.user.id && req.user.role !== "admin") {
|
||||
return res.status(403).json({ message: "Access denied" });
|
||||
}
|
||||
await entry.destroy();
|
||||
res.json({ message: "Entry deleted" });
|
||||
} catch (error) {
|
||||
res.status(500).json({ message: "Server error" });
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
97
backend/routes/users.js
Normal file
97
backend/routes/users.js
Normal file
@ -0,0 +1,97 @@
|
||||
const express = require("express");
|
||||
const { User } = require("../models");
|
||||
const {
|
||||
authenticate,
|
||||
authorizeAdmin,
|
||||
authorizeManager,
|
||||
} = require("../middleware/auth");
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
// Get all users (admin and manager)
|
||||
router.get("/", authenticate, authorizeManager, async (req, res) => {
|
||||
try {
|
||||
const users = await User.findAll({
|
||||
attributes: ["id", "username", "role"],
|
||||
});
|
||||
res.json(users);
|
||||
} catch (error) {
|
||||
res.status(500).json({ message: "Server error" });
|
||||
}
|
||||
});
|
||||
|
||||
// Create user (admin and manager)
|
||||
router.post("/", authenticate, authorizeManager, async (req, res) => {
|
||||
try {
|
||||
const { username, password, role } = req.body;
|
||||
let userRole = role || "user";
|
||||
|
||||
// Managers cannot create admins
|
||||
if (userRole === "admin" && req.user.role !== "admin") {
|
||||
return res
|
||||
.status(403)
|
||||
.json({ message: "Managers cannot create admin users" });
|
||||
}
|
||||
|
||||
// Managers can only create users or managers
|
||||
if (
|
||||
req.user.role === "manager" &&
|
||||
!["user", "manager"].includes(userRole)
|
||||
) {
|
||||
return res
|
||||
.status(403)
|
||||
.json({ message: "Managers can only create users or managers" });
|
||||
}
|
||||
|
||||
const user = await User.create({
|
||||
username,
|
||||
password,
|
||||
role: userRole,
|
||||
});
|
||||
res
|
||||
.status(201)
|
||||
.json({ id: user.id, username: user.username, role: user.role });
|
||||
} catch (error) {
|
||||
if (error.name === "SequelizeUniqueConstraintError") {
|
||||
return res.status(400).json({ message: "Username already exists" });
|
||||
}
|
||||
res.status(500).json({ message: "Server error" });
|
||||
}
|
||||
});
|
||||
|
||||
// Update user password (admin and manager)
|
||||
router.put(
|
||||
"/:id/password",
|
||||
authenticate,
|
||||
authorizeManager,
|
||||
async (req, res) => {
|
||||
try {
|
||||
const { password } = req.body;
|
||||
const user = await User.findByPk(req.params.id);
|
||||
if (!user) {
|
||||
return res.status(404).json({ message: "User not found" });
|
||||
}
|
||||
user.password = password;
|
||||
await user.save();
|
||||
res.json({ message: "Password updated" });
|
||||
} catch (error) {
|
||||
res.status(500).json({ message: "Server error" });
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// Delete user (admin and manager)
|
||||
router.delete("/:id", authenticate, authorizeManager, async (req, res) => {
|
||||
try {
|
||||
const user = await User.findByPk(req.params.id);
|
||||
if (!user) {
|
||||
return res.status(404).json({ message: "User not found" });
|
||||
}
|
||||
await user.destroy();
|
||||
res.json({ message: "User deleted" });
|
||||
} catch (error) {
|
||||
res.status(500).json({ message: "Server error" });
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
93
backend/server.js
Normal file
93
backend/server.js
Normal file
@ -0,0 +1,93 @@
|
||||
require("dotenv").config();
|
||||
const express = require("express");
|
||||
const cors = require("cors");
|
||||
const { Sequelize } = require("sequelize");
|
||||
|
||||
const app = express();
|
||||
const PORT = process.env.PORT || 5000;
|
||||
|
||||
// Middleware
|
||||
app.use(cors());
|
||||
app.use(express.json());
|
||||
|
||||
// Database connection
|
||||
const sequelize = new Sequelize(
|
||||
process.env.DB_NAME,
|
||||
process.env.DB_USER,
|
||||
process.env.DB_PASSWORD,
|
||||
{
|
||||
host: process.env.DB_HOST,
|
||||
port: process.env.DB_PORT,
|
||||
dialect: "postgres",
|
||||
}
|
||||
);
|
||||
|
||||
// Test DB connection
|
||||
sequelize
|
||||
.authenticate()
|
||||
.then(() => console.log("Database connected"))
|
||||
.catch((err) => console.error("Database connection failed:", err));
|
||||
|
||||
// Import models
|
||||
const db = require("./models");
|
||||
const User = db.User;
|
||||
const TimeEntry = db.TimeEntry;
|
||||
|
||||
// Sync database
|
||||
sequelize
|
||||
.sync({ force: false }) // Set to true for development to recreate tables
|
||||
.then(() => {
|
||||
console.log("Database synced");
|
||||
// Create admin user if not exists
|
||||
return User.findOrCreate({
|
||||
where: { username: "admin" },
|
||||
defaults: {
|
||||
username: "admin",
|
||||
password: "admin123", // In production, hash this
|
||||
role: "admin",
|
||||
},
|
||||
});
|
||||
})
|
||||
.then(([user, created]) => {
|
||||
if (created) {
|
||||
console.log("Admin user created");
|
||||
} else {
|
||||
console.log("Admin user already exists");
|
||||
}
|
||||
|
||||
// Create test time entry for admin
|
||||
return TimeEntry.findOrCreate({
|
||||
where: {
|
||||
userId: user.id,
|
||||
date: new Date("2025-10-10"),
|
||||
reason: "Test entry",
|
||||
},
|
||||
defaults: {
|
||||
userId: user.id,
|
||||
date: new Date("2025-10-10"),
|
||||
reason: "Test entry",
|
||||
hours: 8.5,
|
||||
},
|
||||
});
|
||||
})
|
||||
.then(([entry, created]) => {
|
||||
if (created) {
|
||||
console.log("Test time entry created");
|
||||
} else {
|
||||
console.log("Test time entry already exists");
|
||||
}
|
||||
});
|
||||
|
||||
// Routes
|
||||
app.use("/api/auth", require("./routes/auth"));
|
||||
app.use("/api/users", require("./routes/users"));
|
||||
app.use("/api/time-entries", require("./routes/timeEntries"));
|
||||
|
||||
// Health check
|
||||
app.get("/health", (req, res) => res.status(200).json({ status: "OK" }));
|
||||
|
||||
app.get("/", (req, res) => res.send("Time Tracking API"));
|
||||
|
||||
app.listen(PORT, () => {
|
||||
console.log(`Server running on port ${PORT}`);
|
||||
});
|
||||
24
frontend/.gitignore
vendored
Normal file
24
frontend/.gitignore
vendored
Normal file
@ -0,0 +1,24 @@
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
node_modules
|
||||
dist
|
||||
dist-ssr
|
||||
*.local
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
.idea
|
||||
.DS_Store
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
16
frontend/README.md
Normal file
16
frontend/README.md
Normal file
@ -0,0 +1,16 @@
|
||||
# React + Vite
|
||||
|
||||
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
|
||||
|
||||
Currently, two official plugins are available:
|
||||
|
||||
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Babel](https://babeljs.io/) (or [oxc](https://oxc.rs) when used in [rolldown-vite](https://vite.dev/guide/rolldown)) for Fast Refresh
|
||||
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
|
||||
|
||||
## React Compiler
|
||||
|
||||
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
|
||||
|
||||
## Expanding the ESLint configuration
|
||||
|
||||
If you are developing a production application, we recommend using TypeScript with type-aware lint rules enabled. Check out the [TS template](https://github.com/vitejs/vite/tree/main/packages/create-vite/template-react-ts) for information on how to integrate TypeScript and [`typescript-eslint`](https://typescript-eslint.io) in your project.
|
||||
29
frontend/eslint.config.js
Normal file
29
frontend/eslint.config.js
Normal file
@ -0,0 +1,29 @@
|
||||
import js from '@eslint/js'
|
||||
import globals from 'globals'
|
||||
import reactHooks from 'eslint-plugin-react-hooks'
|
||||
import reactRefresh from 'eslint-plugin-react-refresh'
|
||||
import { defineConfig, globalIgnores } from 'eslint/config'
|
||||
|
||||
export default defineConfig([
|
||||
globalIgnores(['dist']),
|
||||
{
|
||||
files: ['**/*.{js,jsx}'],
|
||||
extends: [
|
||||
js.configs.recommended,
|
||||
reactHooks.configs['recommended-latest'],
|
||||
reactRefresh.configs.vite,
|
||||
],
|
||||
languageOptions: {
|
||||
ecmaVersion: 2020,
|
||||
globals: globals.browser,
|
||||
parserOptions: {
|
||||
ecmaVersion: 'latest',
|
||||
ecmaFeatures: { jsx: true },
|
||||
sourceType: 'module',
|
||||
},
|
||||
},
|
||||
rules: {
|
||||
'no-unused-vars': ['error', { varsIgnorePattern: '^[A-Z_]' }],
|
||||
},
|
||||
},
|
||||
])
|
||||
13
frontend/index.html
Normal file
13
frontend/index.html
Normal file
@ -0,0 +1,13 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/icon.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Неучтенное время</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.jsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
3295
frontend/package-lock.json
generated
Normal file
3295
frontend/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
31
frontend/package.json
Normal file
31
frontend/package.json
Normal file
@ -0,0 +1,31 @@
|
||||
{
|
||||
"name": "frontend",
|
||||
"private": true,
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vite build",
|
||||
"lint": "eslint .",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"axios": "^1.12.2",
|
||||
"bootstrap": "^5.3.8",
|
||||
"react": "^19.1.1",
|
||||
"react-dom": "^19.1.1",
|
||||
"react-router-dom": "^7.9.4",
|
||||
"xlsx": "^0.18.5"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.36.0",
|
||||
"@types/react": "^19.1.16",
|
||||
"@types/react-dom": "^19.1.9",
|
||||
"@vitejs/plugin-react": "^5.0.4",
|
||||
"eslint": "^9.36.0",
|
||||
"eslint-plugin-react-hooks": "^5.2.0",
|
||||
"eslint-plugin-react-refresh": "^0.4.22",
|
||||
"globals": "^16.4.0",
|
||||
"vite": "^7.1.7"
|
||||
}
|
||||
}
|
||||
44
frontend/src/App.css
Normal file
44
frontend/src/App.css
Normal file
@ -0,0 +1,44 @@
|
||||
#root {
|
||||
/* Убрано ограничение ширины для полного использования экрана */
|
||||
width: 100%;
|
||||
min-height: 100vh;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.logo {
|
||||
height: 6em;
|
||||
padding: 1.5em;
|
||||
will-change: filter;
|
||||
transition: filter 300ms;
|
||||
}
|
||||
.logo:hover {
|
||||
filter: drop-shadow(0 0 2em #646cffaa);
|
||||
}
|
||||
.logo.react:hover {
|
||||
filter: drop-shadow(0 0 2em #61dafbaa);
|
||||
}
|
||||
|
||||
@keyframes logo-spin {
|
||||
from {
|
||||
transform: rotate(0deg);
|
||||
}
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: no-preference) {
|
||||
a:nth-of-type(2) .logo {
|
||||
animation: logo-spin infinite 20s linear;
|
||||
}
|
||||
}
|
||||
|
||||
.card {
|
||||
padding: 2em;
|
||||
}
|
||||
|
||||
.read-the-docs {
|
||||
color: #888;
|
||||
}
|
||||
85
frontend/src/App.jsx
Normal file
85
frontend/src/App.jsx
Normal file
@ -0,0 +1,85 @@
|
||||
import { useEffect } from "react";
|
||||
import { useAuth } from "./contexts/AuthContext";
|
||||
import { BrowserRouter, Routes, Route, Navigate } from "react-router-dom";
|
||||
import Login from "./components/Login";
|
||||
import Dashboard from "./components/Dashboard";
|
||||
import AdminPage from "./components/AdminPage";
|
||||
import ManagerPage from "./components/ManagerPage";
|
||||
import HealthCheck from "./components/HealthCheck";
|
||||
|
||||
function App() {
|
||||
const { user, loading } = useAuth();
|
||||
|
||||
const ProtectedAdminRoute = ({ children }) => {
|
||||
return user && user.role === "admin" ? children : <Navigate to="/" />;
|
||||
};
|
||||
|
||||
const ProtectedManagerRoute = ({ children }) => {
|
||||
return user && (user.role === "admin" || user.role === "manager") ? (
|
||||
children
|
||||
) : (
|
||||
<Navigate to="/" />
|
||||
);
|
||||
};
|
||||
|
||||
// Диагностические логи для отладки размера интерфейса
|
||||
useEffect(() => {
|
||||
console.log("App Debug - Container dimensions:", {
|
||||
windowWidth: window.innerWidth,
|
||||
windowHeight: window.innerHeight,
|
||||
rootElement: document.getElementById("root")?.getBoundingClientRect(),
|
||||
bodyElement: document.body.getBoundingClientRect(),
|
||||
});
|
||||
|
||||
const handleResize = () => {
|
||||
console.log("App Debug - Resize event:", {
|
||||
windowWidth: window.innerWidth,
|
||||
windowHeight: window.innerHeight,
|
||||
});
|
||||
};
|
||||
|
||||
window.addEventListener("resize", handleResize);
|
||||
return () => window.removeEventListener("resize", handleResize);
|
||||
}, []);
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="d-flex justify-content-center mt-5">
|
||||
<div className="spinner-border" role="status"></div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<BrowserRouter>
|
||||
<div className="container-fluid px-3" style={{ marginTop: "2rem" }}>
|
||||
<HealthCheck />
|
||||
{user ? (
|
||||
<Routes>
|
||||
<Route path="/" element={<Dashboard />} />
|
||||
<Route
|
||||
path="/admin"
|
||||
element={
|
||||
<ProtectedAdminRoute>
|
||||
<AdminPage />
|
||||
</ProtectedAdminRoute>
|
||||
}
|
||||
/>
|
||||
<Route
|
||||
path="/manager"
|
||||
element={
|
||||
<ProtectedManagerRoute>
|
||||
<ManagerPage />
|
||||
</ProtectedManagerRoute>
|
||||
}
|
||||
/>
|
||||
</Routes>
|
||||
) : (
|
||||
<Login />
|
||||
)}
|
||||
</div>
|
||||
</BrowserRouter>
|
||||
);
|
||||
}
|
||||
|
||||
export default App;
|
||||
1
frontend/src/assets/react.svg
Normal file
1
frontend/src/assets/react.svg
Normal file
@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>
|
||||
|
After Width: | Height: | Size: 4.0 KiB |
142
frontend/src/components/AddTimeEntryModal.jsx
Normal file
142
frontend/src/components/AddTimeEntryModal.jsx
Normal file
@ -0,0 +1,142 @@
|
||||
import { useState, useEffect } from "react";
|
||||
|
||||
const AddTimeEntryModal = ({
|
||||
show,
|
||||
onHide,
|
||||
onAdd,
|
||||
isEdit = false,
|
||||
existingEntry = null,
|
||||
onUpdate,
|
||||
}) => {
|
||||
const [entry, setEntry] = useState({ date: "", reason: "", hours: "" });
|
||||
|
||||
useEffect(() => {
|
||||
if (isEdit && existingEntry) {
|
||||
setEntry({
|
||||
date: existingEntry.date
|
||||
? new Date(existingEntry.date).toISOString().split("T")[0]
|
||||
: "",
|
||||
reason: existingEntry.reason || "",
|
||||
hours: existingEntry.hours || "",
|
||||
});
|
||||
} else if (!isEdit) {
|
||||
setEntry({ date: "", reason: "", hours: "" });
|
||||
}
|
||||
}, [isEdit, existingEntry, show]);
|
||||
|
||||
const handleSubmit = (e) => {
|
||||
e.preventDefault();
|
||||
if (isEdit && onUpdate) {
|
||||
onUpdate(existingEntry.id, entry);
|
||||
} else {
|
||||
onAdd(entry);
|
||||
}
|
||||
if (!isEdit) {
|
||||
setEntry({ date: "", reason: "", hours: "" });
|
||||
}
|
||||
};
|
||||
|
||||
const handleChange = (e) => {
|
||||
setEntry({ ...entry, [e.target.name]: e.target.value });
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`modal ${show ? "show d-block" : ""}`}
|
||||
tabIndex="-1"
|
||||
role="dialog"
|
||||
style={{
|
||||
display: show ? "block" : "none",
|
||||
zIndex: show ? "1055" : "auto",
|
||||
}}
|
||||
>
|
||||
<div className="modal-dialog modal-dialog-centered" role="document">
|
||||
<div
|
||||
className="modal-content"
|
||||
style={{ zIndex: show ? "1056" : "auto" }}
|
||||
>
|
||||
<div className="modal-header">
|
||||
<h5 className="modal-title">
|
||||
{isEdit
|
||||
? "Редактировать запись"
|
||||
: "Добавить запись о неучтенном времени"}
|
||||
</h5>
|
||||
<button
|
||||
type="button"
|
||||
className="btn-close"
|
||||
onClick={onHide}
|
||||
aria-label="Close"
|
||||
></button>
|
||||
</div>
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div className="modal-body">
|
||||
<div className="mb-3">
|
||||
<label htmlFor="date" className="form-label">
|
||||
Дата
|
||||
</label>
|
||||
<input
|
||||
type="date"
|
||||
className="form-control"
|
||||
id="date"
|
||||
name="date"
|
||||
value={entry.date}
|
||||
onChange={handleChange}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="mb-3">
|
||||
<label htmlFor="reason" className="form-label">
|
||||
Причина
|
||||
</label>
|
||||
<textarea
|
||||
className="form-control"
|
||||
id="reason"
|
||||
name="reason"
|
||||
value={entry.reason}
|
||||
onChange={handleChange}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="mb-3">
|
||||
<label htmlFor="hours" className="form-label">
|
||||
Количество часов
|
||||
</label>
|
||||
<input
|
||||
type="number"
|
||||
step="0.1"
|
||||
className="form-control"
|
||||
id="hours"
|
||||
name="hours"
|
||||
value={entry.hours}
|
||||
onChange={handleChange}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="modal-footer">
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary"
|
||||
onClick={onHide}
|
||||
>
|
||||
Отмена
|
||||
</button>
|
||||
<button type="submit" className="btn btn-primary">
|
||||
{isEdit ? "Обновить" : "Добавить"}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
{show && (
|
||||
<div
|
||||
className="modal-backdrop fade show"
|
||||
style={{ zIndex: "1054" }}
|
||||
onClick={onHide}
|
||||
></div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default AddTimeEntryModal;
|
||||
11
frontend/src/components/AdminPage.jsx
Normal file
11
frontend/src/components/AdminPage.jsx
Normal file
@ -0,0 +1,11 @@
|
||||
import AdminPanel from "./AdminPanel";
|
||||
|
||||
const AdminPage = () => {
|
||||
return (
|
||||
<div className="container-fluid px-3" style={{ marginTop: "2rem" }}>
|
||||
<AdminPanel />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default AdminPage;
|
||||
406
frontend/src/components/AdminPanel.jsx
Normal file
406
frontend/src/components/AdminPanel.jsx
Normal file
@ -0,0 +1,406 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { Link } from "react-router-dom";
|
||||
import { usersAPI, timeEntriesAPI } from "../services/api";
|
||||
import UserTimeEntriesModal from "./UserTimeEntriesModal";
|
||||
import * as XLSX from "xlsx";
|
||||
|
||||
const AdminPanel = () => {
|
||||
const [users, setUsers] = useState([]);
|
||||
const [showCreateForm, setShowCreateForm] = useState(false);
|
||||
const [newUser, setNewUser] = useState({
|
||||
username: "",
|
||||
password: "",
|
||||
role: "user",
|
||||
});
|
||||
const [resetPasswordId, setResetPasswordId] = useState(null);
|
||||
const [newPassword, setNewPassword] = useState("");
|
||||
const [deleteUserId, setDeleteUserId] = useState(null);
|
||||
const [selectedUser, setSelectedUser] = useState(null);
|
||||
|
||||
useEffect(() => {
|
||||
fetchUsers();
|
||||
}, []);
|
||||
|
||||
const fetchUsers = async () => {
|
||||
try {
|
||||
const response = await usersAPI.getUsers();
|
||||
setUsers(response.data);
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch users:", error);
|
||||
}
|
||||
};
|
||||
|
||||
const handleExportAll = async () => {
|
||||
try {
|
||||
const response = await timeEntriesAPI.getAllEntries();
|
||||
const entries = response.data;
|
||||
const grouped = entries.reduce((acc, entry) => {
|
||||
const username = entry.User?.username || "Unknown";
|
||||
if (!acc[username]) acc[username] = [];
|
||||
acc[username].push(entry);
|
||||
return acc;
|
||||
}, {});
|
||||
const wb = XLSX.utils.book_new();
|
||||
Object.keys(grouped).forEach((username) => {
|
||||
const wsData = [
|
||||
["Дата", "Причина", "Часы"],
|
||||
...grouped[username].map((entry) => [
|
||||
entry.date.split("T")[0],
|
||||
entry.reason,
|
||||
entry.hours,
|
||||
]),
|
||||
];
|
||||
const ws = XLSX.utils.aoa_to_sheet(wsData);
|
||||
// Ширина колонок
|
||||
ws["!cols"] = [{ wch: 15 }, { wch: 40 }, { wch: 10 }];
|
||||
// Стили для заголовков
|
||||
if (ws["A1"])
|
||||
ws["A1"].s = {
|
||||
font: { bold: true },
|
||||
fill: { fgColor: { rgb: "FFD3D3D3" } },
|
||||
};
|
||||
if (ws["B1"])
|
||||
ws["B1"].s = {
|
||||
font: { bold: true },
|
||||
fill: { fgColor: { rgb: "FFD3D3D3" } },
|
||||
};
|
||||
if (ws["C1"])
|
||||
ws["C1"].s = {
|
||||
font: { bold: true },
|
||||
fill: { fgColor: { rgb: "FFD3D3D3" } },
|
||||
};
|
||||
XLSX.utils.book_append_sheet(wb, ws, username);
|
||||
});
|
||||
XLSX.writeFile(wb, "Общая_таблица.xlsx");
|
||||
} catch (error) {
|
||||
console.error("Failed to export all:", error);
|
||||
alert("Ошибка при экспорте общей таблицы");
|
||||
}
|
||||
};
|
||||
|
||||
const handleExportUser = async (userId, username) => {
|
||||
try {
|
||||
const response = await timeEntriesAPI.getUserEntries(userId);
|
||||
const entries = response.data;
|
||||
const wsData = [
|
||||
["Дата", "Причина", "Часы"],
|
||||
...entries.map((entry) => [
|
||||
entry.date.split("T")[0],
|
||||
entry.reason,
|
||||
entry.hours,
|
||||
]),
|
||||
];
|
||||
const ws = XLSX.utils.aoa_to_sheet(wsData);
|
||||
// Ширина колонок
|
||||
ws["!cols"] = [{ wch: 15 }, { wch: 40 }, { wch: 10 }];
|
||||
// Стили для заголовков
|
||||
if (ws["A1"])
|
||||
ws["A1"].s = {
|
||||
font: { bold: true },
|
||||
fill: { fgColor: { rgb: "FFD3D3D3" } },
|
||||
};
|
||||
if (ws["B1"])
|
||||
ws["B1"].s = {
|
||||
font: { bold: true },
|
||||
fill: { fgColor: { rgb: "FFD3D3D3" } },
|
||||
};
|
||||
if (ws["C1"])
|
||||
ws["C1"].s = {
|
||||
font: { bold: true },
|
||||
fill: { fgColor: { rgb: "FFD3D3D3" } },
|
||||
};
|
||||
const wb = XLSX.utils.book_new();
|
||||
XLSX.utils.book_append_sheet(wb, ws, username);
|
||||
XLSX.writeFile(wb, `${username}_таблица.xlsx`);
|
||||
} catch (error) {
|
||||
console.error("Failed to export user:", error);
|
||||
alert("Ошибка при экспорте таблицы пользователя");
|
||||
}
|
||||
};
|
||||
|
||||
const handleCreateUser = async (e) => {
|
||||
e.preventDefault();
|
||||
try {
|
||||
await usersAPI.createUser(newUser);
|
||||
setNewUser({ username: "", password: "", role: "user" });
|
||||
setShowCreateForm(false);
|
||||
fetchUsers();
|
||||
} catch (error) {
|
||||
alert("Ошибка при создании пользователя");
|
||||
}
|
||||
};
|
||||
|
||||
const handleResetPassword = async () => {
|
||||
try {
|
||||
await usersAPI.updatePassword(resetPasswordId, newPassword);
|
||||
setResetPasswordId(null);
|
||||
setNewPassword("");
|
||||
alert("Пароль сброшен");
|
||||
} catch (error) {
|
||||
alert("Ошибка при сбросе пароля");
|
||||
}
|
||||
};
|
||||
|
||||
const handleDeleteUser = async () => {
|
||||
if (deleteUserId) {
|
||||
try {
|
||||
await usersAPI.deleteUser(deleteUserId);
|
||||
setDeleteUserId(null);
|
||||
fetchUsers();
|
||||
} catch (error) {
|
||||
alert("Ошибка при удалении пользователя");
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="w-100 mt-5">
|
||||
<h3>Админ панель</h3>
|
||||
<div className="mb-3">
|
||||
<Link to="/" className="btn btn-primary me-2">
|
||||
Перейти в дешборд
|
||||
</Link>
|
||||
<button
|
||||
className="btn btn-success me-2"
|
||||
onClick={() => setShowCreateForm(true)}
|
||||
>
|
||||
Создать пользователя
|
||||
</button>
|
||||
<button className="btn btn-info" onClick={handleExportAll}>
|
||||
Экспорт общей таблицы
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{showCreateForm && (
|
||||
<form onSubmit={handleCreateUser} className="mb-3">
|
||||
<div className="row">
|
||||
<div className="col-md-3">
|
||||
<input
|
||||
type="text"
|
||||
className="form-control"
|
||||
placeholder="Имя пользователя"
|
||||
value={newUser.username}
|
||||
onChange={(e) =>
|
||||
setNewUser({ ...newUser, username: e.target.value })
|
||||
}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="col-md-3">
|
||||
<input
|
||||
type="password"
|
||||
className="form-control"
|
||||
placeholder="Пароль"
|
||||
value={newUser.password}
|
||||
onChange={(e) =>
|
||||
setNewUser({ ...newUser, password: e.target.value })
|
||||
}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="col-md-3">
|
||||
<select
|
||||
className="form-control"
|
||||
value={newUser.role}
|
||||
onChange={(e) =>
|
||||
setNewUser({ ...newUser, role: e.target.value })
|
||||
}
|
||||
>
|
||||
<option value="user">Пользователь</option>
|
||||
<option value="manager">Руководство</option>
|
||||
<option value="admin">Админ</option>
|
||||
</select>
|
||||
</div>
|
||||
<div className="col-md-3">
|
||||
<button type="submit" className="btn btn-primary me-2">
|
||||
Создать
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary"
|
||||
onClick={() => setShowCreateForm(false)}
|
||||
>
|
||||
Отмена
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
|
||||
<div className="table-responsive w-100">
|
||||
<table className="table table-striped table-hover">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>ID</th>
|
||||
<th>Имя пользователя</th>
|
||||
<th>Роль</th>
|
||||
<th>Действия</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{users.map((user) => (
|
||||
<tr key={user.id}>
|
||||
<td>{user.id}</td>
|
||||
<td>
|
||||
<button
|
||||
className="btn btn-link p-0 text-decoration-none"
|
||||
onClick={() => setSelectedUser(user)}
|
||||
>
|
||||
{user.username}
|
||||
</button>
|
||||
</td>
|
||||
<td>
|
||||
{user.role === "manager"
|
||||
? "Руководство"
|
||||
: user.role === "admin"
|
||||
? "Админ"
|
||||
: "Пользователь"}
|
||||
</td>
|
||||
<td>
|
||||
<button
|
||||
className="btn btn-sm btn-warning me-2"
|
||||
onClick={() => setResetPasswordId(user.id)}
|
||||
>
|
||||
Сбросить пароль
|
||||
</button>
|
||||
<button
|
||||
className="btn btn-sm btn-success me-2"
|
||||
onClick={() => handleExportUser(user.id, user.username)}
|
||||
>
|
||||
Экспорт
|
||||
</button>
|
||||
<button
|
||||
className="btn btn-sm btn-danger"
|
||||
onClick={() => setDeleteUserId(user.id)}
|
||||
>
|
||||
Удалить
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
{resetPasswordId && (
|
||||
<div
|
||||
className="modal show d-block"
|
||||
tabIndex="-1"
|
||||
role="dialog"
|
||||
style={{
|
||||
display: "block",
|
||||
zIndex: "1055",
|
||||
}}
|
||||
>
|
||||
<div className="modal-dialog" role="document">
|
||||
<div className="modal-content" style={{ zIndex: "1056" }}>
|
||||
<div className="modal-header">
|
||||
<h5 className="modal-title">Сброс пароля</h5>
|
||||
<button
|
||||
type="button"
|
||||
className="btn-close"
|
||||
onClick={() => setResetPasswordId(null)}
|
||||
aria-label="Close"
|
||||
></button>
|
||||
</div>
|
||||
<div className="modal-body">
|
||||
<input
|
||||
type="password"
|
||||
className="form-control"
|
||||
placeholder="Новый пароль"
|
||||
value={newPassword}
|
||||
onChange={(e) => setNewPassword(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="modal-footer">
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary"
|
||||
onClick={() => setResetPasswordId(null)}
|
||||
>
|
||||
Отмена
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-primary"
|
||||
onClick={handleResetPassword}
|
||||
>
|
||||
Сбросить
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
className="modal-backdrop fade show"
|
||||
style={{ zIndex: "1054" }}
|
||||
onClick={() => setResetPasswordId(null)}
|
||||
></div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{deleteUserId && (
|
||||
<div
|
||||
className="modal show d-block"
|
||||
tabIndex="-1"
|
||||
role="dialog"
|
||||
style={{
|
||||
display: "block",
|
||||
zIndex: "1055",
|
||||
}}
|
||||
>
|
||||
<div className="modal-dialog" role="document">
|
||||
<div className="modal-content" style={{ zIndex: "1056" }}>
|
||||
<div className="modal-header">
|
||||
<h5 className="modal-title">Подтверждение удаления</h5>
|
||||
<button
|
||||
type="button"
|
||||
className="btn-close"
|
||||
onClick={() => setDeleteUserId(null)}
|
||||
aria-label="Close"
|
||||
></button>
|
||||
</div>
|
||||
<div className="modal-body">
|
||||
<p>
|
||||
Вы уверены, что хотите удалить этого пользователя? Это
|
||||
действие нельзя отменить.
|
||||
</p>
|
||||
</div>
|
||||
<div className="modal-footer">
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary"
|
||||
onClick={() => setDeleteUserId(null)}
|
||||
>
|
||||
Отмена
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-danger"
|
||||
onClick={handleDeleteUser}
|
||||
>
|
||||
Удалить
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
className="modal-backdrop fade show"
|
||||
style={{ zIndex: "1054" }}
|
||||
onClick={() => setDeleteUserId(null)}
|
||||
></div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{selectedUser && (
|
||||
<UserTimeEntriesModal
|
||||
show={!!selectedUser}
|
||||
onHide={() => setSelectedUser(null)}
|
||||
userId={selectedUser.id}
|
||||
userName={selectedUser.username}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default AdminPanel;
|
||||
171
frontend/src/components/Dashboard.jsx
Normal file
171
frontend/src/components/Dashboard.jsx
Normal file
@ -0,0 +1,171 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { useAuth } from "../contexts/AuthContext";
|
||||
import { timeEntriesAPI } from "../services/api";
|
||||
import { Link } from "react-router-dom";
|
||||
import TimeEntriesTable from "./TimeEntriesTable";
|
||||
import AddTimeEntryModal from "./AddTimeEntryModal";
|
||||
import DeleteAllModal from "./DeleteAllModal";
|
||||
|
||||
const Dashboard = () => {
|
||||
const { user, logout } = useAuth();
|
||||
const [entries, setEntries] = useState([]);
|
||||
const [showModal, setShowModal] = useState(false);
|
||||
const [showEditModal, setShowEditModal] = useState(false);
|
||||
const [showDeleteAllModal, setShowDeleteAllModal] = useState(false);
|
||||
const [editingEntry, setEditingEntry] = useState(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
fetchEntries();
|
||||
|
||||
// Диагностические логи для отладки размера интерфейса
|
||||
const logDimensions = () => {
|
||||
console.log("Dashboard Debug - Component dimensions:", {
|
||||
dashboardElement: document
|
||||
.querySelector(".dashboard-container")
|
||||
?.getBoundingClientRect(),
|
||||
windowWidth: window.innerWidth,
|
||||
windowHeight: window.innerHeight,
|
||||
});
|
||||
};
|
||||
|
||||
logDimensions();
|
||||
window.addEventListener("resize", logDimensions);
|
||||
|
||||
return () => window.removeEventListener("resize", logDimensions);
|
||||
}, []);
|
||||
|
||||
const fetchEntries = async () => {
|
||||
try {
|
||||
const response = await timeEntriesAPI.getEntries();
|
||||
setEntries(response.data);
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch entries:", error);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleAddEntry = async (entry) => {
|
||||
try {
|
||||
await timeEntriesAPI.createEntry(entry);
|
||||
setShowModal(false);
|
||||
fetchEntries();
|
||||
} catch (error) {
|
||||
console.error("Failed to add entry:", error);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDeleteEntry = async (id) => {
|
||||
try {
|
||||
await timeEntriesAPI.deleteEntry(id);
|
||||
fetchEntries();
|
||||
} catch (error) {
|
||||
console.error("Failed to delete entry:", error);
|
||||
}
|
||||
};
|
||||
|
||||
const handleEdit = (entry) => {
|
||||
setEditingEntry(entry);
|
||||
setShowEditModal(true);
|
||||
};
|
||||
|
||||
const handleUpdateEntry = async (id, updatedEntry) => {
|
||||
try {
|
||||
await timeEntriesAPI.updateEntry(id, updatedEntry);
|
||||
setShowEditModal(false);
|
||||
setEditingEntry(null);
|
||||
fetchEntries();
|
||||
} catch (error) {
|
||||
console.error("Failed to update entry:", error);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDeleteAll = async () => {
|
||||
try {
|
||||
await timeEntriesAPI.deleteAllEntries();
|
||||
setShowDeleteAllModal(false);
|
||||
fetchEntries();
|
||||
} catch (error) {
|
||||
console.error("Failed to delete all entries:", error);
|
||||
}
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="d-flex justify-content-center mt-5">
|
||||
<div className="spinner-border" role="status"></div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="w-100 dashboard-container">
|
||||
<div className="d-flex justify-content-between align-items-center mb-4">
|
||||
<h2>Добро пожаловать, {user.username}!</h2>
|
||||
<div>
|
||||
{user.role === "admin" && (
|
||||
<Link to="/admin" className="btn btn-secondary me-2">
|
||||
Админ панель
|
||||
</Link>
|
||||
)}
|
||||
{user.role === "manager" && (
|
||||
<Link to="/manager" className="btn btn-secondary me-2">
|
||||
Менеджер панель
|
||||
</Link>
|
||||
)}
|
||||
<button className="btn btn-outline-danger" onClick={logout}>
|
||||
Выйти
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mb-4 d-flex gap-2">
|
||||
<button className="btn btn-primary" onClick={() => setShowModal(true)}>
|
||||
Добавить запись о неучтенном времени
|
||||
</button>
|
||||
<button
|
||||
className="btn btn-danger"
|
||||
onClick={() => setShowDeleteAllModal(true)}
|
||||
>
|
||||
Удалить все записи
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<TimeEntriesTable
|
||||
entries={entries}
|
||||
onDelete={handleDeleteEntry}
|
||||
onEdit={handleEdit}
|
||||
/>
|
||||
|
||||
<div className="mt-3">
|
||||
<strong>
|
||||
Общее количество часов:{" "}
|
||||
{entries
|
||||
.reduce((sum, entry) => sum + parseFloat(entry.hours), 0)
|
||||
.toFixed(1)}
|
||||
</strong>
|
||||
</div>
|
||||
|
||||
<AddTimeEntryModal
|
||||
show={showModal}
|
||||
onHide={() => setShowModal(false)}
|
||||
onAdd={handleAddEntry}
|
||||
/>
|
||||
<AddTimeEntryModal
|
||||
show={showEditModal}
|
||||
onHide={() => setShowEditModal(false)}
|
||||
isEdit={true}
|
||||
existingEntry={editingEntry}
|
||||
onUpdate={handleUpdateEntry}
|
||||
/>
|
||||
<DeleteAllModal
|
||||
show={showDeleteAllModal}
|
||||
onHide={() => setShowDeleteAllModal(false)}
|
||||
onConfirm={handleDeleteAll}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Dashboard;
|
||||
62
frontend/src/components/DeleteAllModal.jsx
Normal file
62
frontend/src/components/DeleteAllModal.jsx
Normal file
@ -0,0 +1,62 @@
|
||||
const DeleteAllModal = ({ show, onHide, onConfirm }) => {
|
||||
return (
|
||||
<div
|
||||
className={`modal ${show ? "show d-block" : ""}`}
|
||||
tabIndex="-1"
|
||||
role="dialog"
|
||||
style={{
|
||||
display: show ? "block" : "none",
|
||||
zIndex: show ? "1055" : "auto",
|
||||
}}
|
||||
>
|
||||
<div className="modal-dialog modal-dialog-centered" role="document">
|
||||
<div
|
||||
className="modal-content"
|
||||
style={{ zIndex: show ? "1056" : "auto" }}
|
||||
>
|
||||
<div className="modal-header">
|
||||
<h5 className="modal-title">Подтверждение удаления</h5>
|
||||
<button
|
||||
type="button"
|
||||
className="btn-close"
|
||||
onClick={onHide}
|
||||
aria-label="Close"
|
||||
></button>
|
||||
</div>
|
||||
<div className="modal-body">
|
||||
<p>
|
||||
Вы уверены, что хотите удалить все свои записи о неучтенном
|
||||
времени?
|
||||
</p>
|
||||
<p className="text-danger">Это действие нельзя отменить.</p>
|
||||
</div>
|
||||
<div className="modal-footer">
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary"
|
||||
onClick={onHide}
|
||||
>
|
||||
Отмена
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-danger"
|
||||
onClick={onConfirm}
|
||||
>
|
||||
Удалить все
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{show && (
|
||||
<div
|
||||
className="modal-backdrop fade show"
|
||||
style={{ zIndex: "1054" }}
|
||||
onClick={onHide}
|
||||
></div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default DeleteAllModal;
|
||||
31
frontend/src/components/HealthCheck.jsx
Normal file
31
frontend/src/components/HealthCheck.jsx
Normal file
@ -0,0 +1,31 @@
|
||||
import { useState, useEffect } from "react";
|
||||
|
||||
const HealthCheck = () => {
|
||||
const [serverDown, setServerDown] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
const checkHealth = async () => {
|
||||
try {
|
||||
const response = await fetch("http://localhost:5000/health");
|
||||
if (!response.ok) throw new Error("Server not responding");
|
||||
setServerDown(false);
|
||||
} catch (error) {
|
||||
setServerDown(true);
|
||||
}
|
||||
};
|
||||
|
||||
checkHealth();
|
||||
const interval = setInterval(checkHealth, 30000); // Check every 30 seconds
|
||||
return () => clearInterval(interval);
|
||||
}, []);
|
||||
|
||||
if (!serverDown) return null;
|
||||
|
||||
return (
|
||||
<div className="alert alert-danger text-center" role="alert">
|
||||
<strong>Внимание!</strong> Сервер недоступен. Идут технические работы.
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default HealthCheck;
|
||||
69
frontend/src/components/Login.jsx
Normal file
69
frontend/src/components/Login.jsx
Normal file
@ -0,0 +1,69 @@
|
||||
import { useState } from "react";
|
||||
import { useAuth } from "../contexts/AuthContext";
|
||||
|
||||
const Login = () => {
|
||||
const [credentials, setCredentials] = useState({
|
||||
username: "",
|
||||
password: "",
|
||||
});
|
||||
const [error, setError] = useState("");
|
||||
const { login } = useAuth();
|
||||
|
||||
const handleSubmit = async (e) => {
|
||||
e.preventDefault();
|
||||
try {
|
||||
await login(credentials);
|
||||
setError("");
|
||||
} catch (err) {
|
||||
setError("Неверные учетные данные");
|
||||
}
|
||||
};
|
||||
|
||||
const handleChange = (e) => {
|
||||
setCredentials({ ...credentials, [e.target.name]: e.target.value });
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="row justify-content-center">
|
||||
<div className="col-lg-6 col-md-8 col-sm-10">
|
||||
<h2 className="text-center mb-4">Вход</h2>
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div className="mb-3">
|
||||
<label htmlFor="username" className="form-label">
|
||||
Имя пользователя
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
className="form-control"
|
||||
id="username"
|
||||
name="username"
|
||||
value={credentials.username}
|
||||
onChange={handleChange}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="mb-3">
|
||||
<label htmlFor="password" className="form-label">
|
||||
Пароль
|
||||
</label>
|
||||
<input
|
||||
type="password"
|
||||
className="form-control"
|
||||
id="password"
|
||||
name="password"
|
||||
value={credentials.password}
|
||||
onChange={handleChange}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
{error && <div className="alert alert-danger">{error}</div>}
|
||||
<button type="submit" className="btn btn-primary w-100">
|
||||
Войти
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Login;
|
||||
11
frontend/src/components/ManagerPage.jsx
Normal file
11
frontend/src/components/ManagerPage.jsx
Normal file
@ -0,0 +1,11 @@
|
||||
import ManagerPanel from "./ManagerPanel";
|
||||
|
||||
const ManagerPage = () => {
|
||||
return (
|
||||
<div className="container-fluid px-3" style={{ marginTop: "2rem" }}>
|
||||
<ManagerPanel />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default ManagerPage;
|
||||
406
frontend/src/components/ManagerPanel.jsx
Normal file
406
frontend/src/components/ManagerPanel.jsx
Normal file
@ -0,0 +1,406 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { Link } from "react-router-dom";
|
||||
import { usersAPI, timeEntriesAPI } from "../services/api";
|
||||
import UserTimeEntriesModal from "./UserTimeEntriesModal";
|
||||
import * as XLSX from "xlsx";
|
||||
|
||||
const ManagerPanel = () => {
|
||||
const [users, setUsers] = useState([]);
|
||||
const [showCreateForm, setShowCreateForm] = useState(false);
|
||||
const [newUser, setNewUser] = useState({
|
||||
username: "",
|
||||
password: "",
|
||||
role: "user",
|
||||
});
|
||||
const [resetPasswordId, setResetPasswordId] = useState(null);
|
||||
const [newPassword, setNewPassword] = useState("");
|
||||
const [deleteUserId, setDeleteUserId] = useState(null);
|
||||
const [selectedUser, setSelectedUser] = useState(null);
|
||||
|
||||
useEffect(() => {
|
||||
fetchUsers();
|
||||
}, []);
|
||||
|
||||
const fetchUsers = async () => {
|
||||
try {
|
||||
const response = await usersAPI.getUsers();
|
||||
setUsers(response.data);
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch users:", error);
|
||||
}
|
||||
};
|
||||
|
||||
const handleExportAll = async () => {
|
||||
try {
|
||||
const response = await timeEntriesAPI.getAllEntries();
|
||||
const entries = response.data;
|
||||
const grouped = entries.reduce((acc, entry) => {
|
||||
const username = entry.User?.username || "Unknown";
|
||||
if (!acc[username]) acc[username] = [];
|
||||
acc[username].push(entry);
|
||||
return acc;
|
||||
}, {});
|
||||
const wb = XLSX.utils.book_new();
|
||||
Object.keys(grouped).forEach((username) => {
|
||||
const wsData = [
|
||||
["Дата", "Причина", "Часы"],
|
||||
...grouped[username].map((entry) => [
|
||||
entry.date.split("T")[0],
|
||||
entry.reason,
|
||||
entry.hours,
|
||||
]),
|
||||
];
|
||||
const ws = XLSX.utils.aoa_to_sheet(wsData);
|
||||
// Ширина колонок
|
||||
ws["!cols"] = [{ wch: 15 }, { wch: 40 }, { wch: 10 }];
|
||||
// Стили для заголовков
|
||||
if (ws["A1"])
|
||||
ws["A1"].s = {
|
||||
font: { bold: true },
|
||||
fill: { fgColor: { rgb: "FFD3D3D3" } },
|
||||
};
|
||||
if (ws["B1"])
|
||||
ws["B1"].s = {
|
||||
font: { bold: true },
|
||||
fill: { fgColor: { rgb: "FFD3D3D3" } },
|
||||
};
|
||||
if (ws["C1"])
|
||||
ws["C1"].s = {
|
||||
font: { bold: true },
|
||||
fill: { fgColor: { rgb: "FFD3D3D3" } },
|
||||
};
|
||||
XLSX.utils.book_append_sheet(wb, ws, username);
|
||||
});
|
||||
XLSX.writeFile(wb, "Общая_таблица.xlsx");
|
||||
} catch (error) {
|
||||
console.error("Failed to export all:", error);
|
||||
alert("Ошибка при экспорте общей таблицы");
|
||||
}
|
||||
};
|
||||
|
||||
const handleExportUser = async (userId, username) => {
|
||||
try {
|
||||
const response = await timeEntriesAPI.getUserEntries(userId);
|
||||
const entries = response.data;
|
||||
const wsData = [
|
||||
["Дата", "Причина", "Часы"],
|
||||
...entries.map((entry) => [
|
||||
entry.date.split("T")[0],
|
||||
entry.reason,
|
||||
entry.hours,
|
||||
]),
|
||||
];
|
||||
const ws = XLSX.utils.aoa_to_sheet(wsData);
|
||||
// Ширина колонок
|
||||
ws["!cols"] = [{ wch: 15 }, { wch: 40 }, { wch: 10 }];
|
||||
// Стили для заголовков
|
||||
if (ws["A1"])
|
||||
ws["A1"].s = {
|
||||
font: { bold: true },
|
||||
fill: { fgColor: { rgb: "FFD3D3D3" } },
|
||||
};
|
||||
if (ws["B1"])
|
||||
ws["B1"].s = {
|
||||
font: { bold: true },
|
||||
fill: { fgColor: { rgb: "FFD3D3D3" } },
|
||||
};
|
||||
if (ws["C1"])
|
||||
ws["C1"].s = {
|
||||
font: { bold: true },
|
||||
fill: { fgColor: { rgb: "FFD3D3D3" } },
|
||||
};
|
||||
const wb = XLSX.utils.book_new();
|
||||
XLSX.utils.book_append_sheet(wb, ws, username);
|
||||
XLSX.writeFile(wb, `${username}_таблица.xlsx`);
|
||||
} catch (error) {
|
||||
console.error("Failed to export user:", error);
|
||||
alert("Ошибка при экспорте таблицы пользователя");
|
||||
}
|
||||
};
|
||||
|
||||
const handleCreateUser = async (e) => {
|
||||
e.preventDefault();
|
||||
try {
|
||||
await usersAPI.createUser(newUser);
|
||||
setNewUser({ username: "", password: "", role: "user" });
|
||||
setShowCreateForm(false);
|
||||
fetchUsers();
|
||||
} catch (error) {
|
||||
alert("Ошибка при создании пользователя");
|
||||
}
|
||||
};
|
||||
|
||||
const handleResetPassword = async () => {
|
||||
try {
|
||||
await usersAPI.updatePassword(resetPasswordId, newPassword);
|
||||
setResetPasswordId(null);
|
||||
setNewPassword("");
|
||||
alert("Пароль сброшен");
|
||||
} catch (error) {
|
||||
alert("Ошибка при сбросе пароля");
|
||||
}
|
||||
};
|
||||
|
||||
const handleDeleteUser = async () => {
|
||||
if (deleteUserId) {
|
||||
try {
|
||||
await usersAPI.deleteUser(deleteUserId);
|
||||
setDeleteUserId(null);
|
||||
fetchUsers();
|
||||
} catch (error) {
|
||||
alert("Ошибка при удалении пользователя");
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="w-100 mt-5">
|
||||
<h3>Менеджер панель</h3>
|
||||
<div className="mb-3">
|
||||
<Link to="/" className="btn btn-primary me-2">
|
||||
Перейти в дешборд
|
||||
</Link>
|
||||
<button
|
||||
className="btn btn-success me-2"
|
||||
onClick={() => setShowCreateForm(true)}
|
||||
>
|
||||
Создать пользователя
|
||||
</button>
|
||||
<button className="btn btn-info" onClick={handleExportAll}>
|
||||
Экспорт общей таблицы
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{showCreateForm && (
|
||||
<form onSubmit={handleCreateUser} className="mb-3">
|
||||
<div className="row">
|
||||
<div className="col-md-3">
|
||||
<input
|
||||
type="text"
|
||||
className="form-control"
|
||||
placeholder="Имя пользователя"
|
||||
value={newUser.username}
|
||||
onChange={(e) =>
|
||||
setNewUser({ ...newUser, username: e.target.value })
|
||||
}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="col-md-3">
|
||||
<input
|
||||
type="password"
|
||||
className="form-control"
|
||||
placeholder="Пароль"
|
||||
value={newUser.password}
|
||||
onChange={(e) =>
|
||||
setNewUser({ ...newUser, password: e.target.value })
|
||||
}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="col-md-3">
|
||||
<select
|
||||
className="form-control"
|
||||
value={newUser.role}
|
||||
onChange={(e) =>
|
||||
setNewUser({ ...newUser, role: e.target.value })
|
||||
}
|
||||
>
|
||||
<option value="user">Пользователь</option>
|
||||
<option value="manager">Руководство</option>
|
||||
</select>
|
||||
</div>
|
||||
<div className="col-md-3">
|
||||
<button type="submit" className="btn btn-primary me-2">
|
||||
Создать
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary"
|
||||
onClick={() => setShowCreateForm(false)}
|
||||
>
|
||||
Отмена
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
|
||||
<div className="table-responsive w-100">
|
||||
<table className="table table-striped table-hover">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>ID</th>
|
||||
<th>Имя пользователя</th>
|
||||
<th>Роль</th>
|
||||
<th>Действия</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{users.map((user) => (
|
||||
<tr key={user.id}>
|
||||
<td>{user.id}</td>
|
||||
<td>
|
||||
<button
|
||||
className="btn btn-link p-0 text-decoration-none"
|
||||
onClick={() => setSelectedUser(user)}
|
||||
>
|
||||
{user.username}
|
||||
</button>
|
||||
</td>
|
||||
<td>
|
||||
{user.role === "manager"
|
||||
? "Руководство"
|
||||
: user.role === "admin"
|
||||
? "Админ"
|
||||
: "Пользователь"}
|
||||
</td>
|
||||
<td>
|
||||
<button
|
||||
className="btn btn-sm btn-warning me-2"
|
||||
onClick={() => setResetPasswordId(user.id)}
|
||||
>
|
||||
Сбросить пароль
|
||||
</button>
|
||||
<button
|
||||
className="btn btn-sm btn-success me-2"
|
||||
onClick={() => handleExportUser(user.id, user.username)}
|
||||
>
|
||||
Экспорт
|
||||
</button>
|
||||
<button
|
||||
className="btn btn-sm btn-danger"
|
||||
onClick={() => setDeleteUserId(user.id)}
|
||||
>
|
||||
Удалить
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
{resetPasswordId && (
|
||||
<div
|
||||
className="modal show d-block"
|
||||
tabIndex="-1"
|
||||
role="dialog"
|
||||
style={{
|
||||
display: "block",
|
||||
zIndex: "1055",
|
||||
}}
|
||||
>
|
||||
<div className="modal-dialog" role="document">
|
||||
<div className="modal-content" style={{ zIndex: "1056" }}>
|
||||
<div className="modal-header">
|
||||
<h5 className="modal-title">Сброс пароля</h5>
|
||||
<button
|
||||
type="button"
|
||||
className="btn-close"
|
||||
onClick={() => setResetPasswordId(null)}
|
||||
aria-label="Close"
|
||||
></button>
|
||||
</div>
|
||||
<div className="modal-body">
|
||||
<input
|
||||
type="password"
|
||||
className="form-control"
|
||||
placeholder="Новый пароль"
|
||||
value={newPassword}
|
||||
onChange={(e) => setNewPassword(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="modal-footer">
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary"
|
||||
onClick={() => setResetPasswordId(null)}
|
||||
>
|
||||
Отмена
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-primary"
|
||||
onClick={handleResetPassword}
|
||||
>
|
||||
Сбросить
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
className="modal-backdrop fade show"
|
||||
style={{ zIndex: "1054" }}
|
||||
onClick={() => setResetPasswordId(null)}
|
||||
></div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{deleteUserId && (
|
||||
<div
|
||||
className="modal show d-block"
|
||||
tabIndex="-1"
|
||||
role="dialog"
|
||||
style={{
|
||||
display: "block",
|
||||
zIndex: "1055",
|
||||
}}
|
||||
>
|
||||
<div className="modal-dialog" role="document">
|
||||
<div className="modal-content" style={{ zIndex: "1056" }}>
|
||||
<div className="modal-header">
|
||||
<h5 className="modal-title">Подтверждение удаления</h5>
|
||||
<button
|
||||
type="button"
|
||||
className="btn-close"
|
||||
onClick={() => setDeleteUserId(null)}
|
||||
aria-label="Close"
|
||||
></button>
|
||||
</div>
|
||||
<div className="modal-body">
|
||||
<p>
|
||||
Вы уверены, что хотите удалить этого пользователя? Это
|
||||
действие нельзя отменить.
|
||||
</p>
|
||||
</div>
|
||||
<div className="modal-footer">
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary"
|
||||
onClick={() => setDeleteUserId(null)}
|
||||
>
|
||||
Отмена
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-danger"
|
||||
onClick={handleDeleteUser}
|
||||
>
|
||||
Удалить
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
className="modal-backdrop fade show"
|
||||
style={{ zIndex: "1054" }}
|
||||
onClick={() => setDeleteUserId(null)}
|
||||
></div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{selectedUser && (
|
||||
<UserTimeEntriesModal
|
||||
show={!!selectedUser}
|
||||
onHide={() => setSelectedUser(null)}
|
||||
userId={selectedUser.id}
|
||||
userName={selectedUser.username}
|
||||
isManager={true}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default ManagerPanel;
|
||||
50
frontend/src/components/TimeEntriesTable.jsx
Normal file
50
frontend/src/components/TimeEntriesTable.jsx
Normal file
@ -0,0 +1,50 @@
|
||||
const TimeEntriesTable = ({ entries, onDelete, onEdit, isManager = false }) => {
|
||||
return (
|
||||
<div className="table-responsive w-100">
|
||||
<table className="table table-striped table-hover">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Дата</th>
|
||||
<th>Причина</th>
|
||||
<th>Часы</th>
|
||||
{!isManager && <th>Действия</th>}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{entries.map((entry) => (
|
||||
<tr key={entry.id}>
|
||||
<td>{new Date(entry.date).toLocaleDateString("ru-RU")}</td>
|
||||
<td>{entry.reason}</td>
|
||||
<td>{entry.hours}</td>
|
||||
{!isManager && (
|
||||
<td>
|
||||
{onEdit && (
|
||||
<button
|
||||
className="btn btn-sm btn-primary me-2"
|
||||
onClick={() => onEdit(entry)}
|
||||
>
|
||||
Редактировать
|
||||
</button>
|
||||
)}
|
||||
{onDelete && (
|
||||
<button
|
||||
className="btn btn-sm btn-danger"
|
||||
onClick={() => onDelete(entry.id)}
|
||||
>
|
||||
Удалить
|
||||
</button>
|
||||
)}
|
||||
</td>
|
||||
)}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
{entries.length === 0 && (
|
||||
<div className="text-center text-muted">Нет записей</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default TimeEntriesTable;
|
||||
133
frontend/src/components/UserTimeEntriesModal.jsx
Normal file
133
frontend/src/components/UserTimeEntriesModal.jsx
Normal file
@ -0,0 +1,133 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { timeEntriesAPI } from "../services/api";
|
||||
import TimeEntriesTable from "./TimeEntriesTable";
|
||||
import AddTimeEntryModal from "./AddTimeEntryModal";
|
||||
|
||||
const UserTimeEntriesModal = ({
|
||||
show,
|
||||
onHide,
|
||||
userId,
|
||||
userName,
|
||||
isManager = false,
|
||||
}) => {
|
||||
const [entries, setEntries] = useState([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [showEditModal, setShowEditModal] = useState(false);
|
||||
const [editingEntry, setEditingEntry] = useState(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (show && userId) {
|
||||
fetchUserEntries();
|
||||
}
|
||||
}, [show, userId]);
|
||||
|
||||
const fetchUserEntries = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const response = await timeEntriesAPI.getUserEntries(userId);
|
||||
console.log("User entries for user", userId, ":", response.data);
|
||||
setEntries(response.data);
|
||||
console.log("Entries set to state:", response.data);
|
||||
} catch (error) {
|
||||
console.error("Failed to fetch user entries:", error);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleEdit = (entry) => {
|
||||
setEditingEntry(entry);
|
||||
setShowEditModal(true);
|
||||
};
|
||||
|
||||
const handleUpdateEntry = async (id, updatedEntry) => {
|
||||
try {
|
||||
await timeEntriesAPI.updateEntry(id, updatedEntry);
|
||||
await fetchUserEntries(); // Refresh the list
|
||||
setShowEditModal(false);
|
||||
setEditingEntry(null);
|
||||
} catch (error) {
|
||||
console.error("Failed to update entry:", error);
|
||||
}
|
||||
};
|
||||
|
||||
const totalHours = entries.reduce(
|
||||
(sum, entry) => sum + parseFloat(entry.hours),
|
||||
0
|
||||
);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`modal ${show ? "show d-block" : ""}`}
|
||||
tabIndex="-1"
|
||||
role="dialog"
|
||||
style={{
|
||||
display: show ? "block" : "none",
|
||||
zIndex: show ? "1055" : "auto",
|
||||
}}
|
||||
>
|
||||
<div className="modal-dialog modal-lg" role="document">
|
||||
<div
|
||||
className="modal-content"
|
||||
style={{ zIndex: show ? "1056" : "auto" }}
|
||||
>
|
||||
<div className="modal-header">
|
||||
<h5 className="modal-title">Записи пользователя: {userName}</h5>
|
||||
<button
|
||||
type="button"
|
||||
className="btn-close"
|
||||
onClick={onHide}
|
||||
aria-label="Close"
|
||||
></button>
|
||||
</div>
|
||||
<div className="modal-body">
|
||||
{loading ? (
|
||||
<div className="d-flex justify-content-center">
|
||||
<div className="spinner-border" role="status"></div>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="mb-3">
|
||||
<strong>
|
||||
Общее количество часов: {totalHours.toFixed(1)}
|
||||
</strong>
|
||||
</div>
|
||||
<TimeEntriesTable
|
||||
entries={entries}
|
||||
onDelete={isManager ? undefined : () => {}}
|
||||
onEdit={isManager ? undefined : handleEdit}
|
||||
isManager={isManager}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<div className="modal-footer">
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-secondary"
|
||||
onClick={onHide}
|
||||
>
|
||||
Закрыть
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{show && (
|
||||
<div
|
||||
className="modal-backdrop fade show"
|
||||
style={{ zIndex: "1054" }}
|
||||
onClick={onHide}
|
||||
></div>
|
||||
)}
|
||||
<AddTimeEntryModal
|
||||
show={showEditModal}
|
||||
onHide={() => setShowEditModal(false)}
|
||||
isEdit={true}
|
||||
existingEntry={editingEntry}
|
||||
onUpdate={handleUpdateEntry}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default UserTimeEntriesModal;
|
||||
43
frontend/src/contexts/AuthContext.jsx
Normal file
43
frontend/src/contexts/AuthContext.jsx
Normal file
@ -0,0 +1,43 @@
|
||||
import { createContext, useState, useEffect, useContext } from "react";
|
||||
import { authAPI } from "../services/api";
|
||||
|
||||
const AuthContext = createContext();
|
||||
|
||||
export const useAuth = () => useContext(AuthContext);
|
||||
|
||||
export const AuthProvider = ({ children }) => {
|
||||
const [user, setUser] = useState(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
const token = localStorage.getItem("token");
|
||||
if (token) {
|
||||
authAPI
|
||||
.getMe()
|
||||
.then((response) => setUser(response.data.user))
|
||||
.catch(() => localStorage.removeItem("token"))
|
||||
.finally(() => setLoading(false));
|
||||
} else {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const login = async (credentials) => {
|
||||
const response = await authAPI.login(credentials);
|
||||
const { token, user } = response.data;
|
||||
localStorage.setItem("token", token);
|
||||
setUser(user);
|
||||
return user;
|
||||
};
|
||||
|
||||
const logout = () => {
|
||||
localStorage.removeItem("token");
|
||||
setUser(null);
|
||||
};
|
||||
|
||||
return (
|
||||
<AuthContext.Provider value={{ user, login, logout, loading }}>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
);
|
||||
};
|
||||
66
frontend/src/index.css
Normal file
66
frontend/src/index.css
Normal file
@ -0,0 +1,66 @@
|
||||
:root {
|
||||
font-family: system-ui, Avenir, Helvetica, Arial, sans-serif;
|
||||
line-height: 1.5;
|
||||
font-weight: 400;
|
||||
|
||||
color-scheme: light dark;
|
||||
color: rgba(255, 255, 255, 0.87);
|
||||
background-color: #242424;
|
||||
|
||||
font-synthesis: none;
|
||||
text-rendering: optimizeLegibility;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
}
|
||||
|
||||
a {
|
||||
font-weight: 500;
|
||||
color: #646cff;
|
||||
text-decoration: inherit;
|
||||
}
|
||||
a:hover {
|
||||
color: #535bf2;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
min-width: 320px;
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
h1 {
|
||||
font-size: 3.2em;
|
||||
line-height: 1.1;
|
||||
}
|
||||
|
||||
button {
|
||||
border-radius: 8px;
|
||||
border: 1px solid transparent;
|
||||
padding: 0.6em 1.2em;
|
||||
font-size: 1em;
|
||||
font-weight: 500;
|
||||
font-family: inherit;
|
||||
background-color: #1a1a1a;
|
||||
cursor: pointer;
|
||||
transition: border-color 0.25s;
|
||||
}
|
||||
button:hover {
|
||||
border-color: #646cff;
|
||||
}
|
||||
button:focus,
|
||||
button:focus-visible {
|
||||
outline: 4px auto -webkit-focus-ring-color;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: light) {
|
||||
:root {
|
||||
color: #213547;
|
||||
background-color: #ffffff;
|
||||
}
|
||||
a:hover {
|
||||
color: #747bff;
|
||||
}
|
||||
button {
|
||||
background-color: #f9f9f9;
|
||||
}
|
||||
}
|
||||
14
frontend/src/main.jsx
Normal file
14
frontend/src/main.jsx
Normal file
@ -0,0 +1,14 @@
|
||||
import { StrictMode } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import "./index.css";
|
||||
import "bootstrap/dist/css/bootstrap.min.css";
|
||||
import { AuthProvider } from "./contexts/AuthContext.jsx";
|
||||
import App from "./App.jsx";
|
||||
|
||||
createRoot(document.getElementById("root")).render(
|
||||
<StrictMode>
|
||||
<AuthProvider>
|
||||
<App />
|
||||
</AuthProvider>
|
||||
</StrictMode>
|
||||
);
|
||||
41
frontend/src/services/api.js
Normal file
41
frontend/src/services/api.js
Normal file
@ -0,0 +1,41 @@
|
||||
import axios from "axios";
|
||||
|
||||
const API_BASE_URL = "http://localhost:5000/api";
|
||||
|
||||
const api = axios.create({
|
||||
baseURL: API_BASE_URL,
|
||||
});
|
||||
|
||||
// Add token to requests
|
||||
api.interceptors.request.use((config) => {
|
||||
const token = localStorage.getItem("token");
|
||||
if (token) {
|
||||
config.headers.Authorization = `Bearer ${token}`;
|
||||
}
|
||||
return config;
|
||||
});
|
||||
|
||||
export const authAPI = {
|
||||
login: (credentials) => api.post("/auth/login", credentials),
|
||||
getMe: () => api.get("/auth/me"),
|
||||
};
|
||||
|
||||
export const usersAPI = {
|
||||
getUsers: () => api.get("/users"),
|
||||
createUser: (user) => api.post("/users", user),
|
||||
updatePassword: (id, password) =>
|
||||
api.put(`/users/${id}/password`, { password }),
|
||||
deleteUser: (id) => api.delete(`/users/${id}`),
|
||||
};
|
||||
|
||||
export const timeEntriesAPI = {
|
||||
getEntries: () => api.get("/time-entries"),
|
||||
getAllEntries: () => api.get("/time-entries/all"),
|
||||
getUserEntries: (userId) => api.get(`/time-entries/user/${userId}`),
|
||||
createEntry: (entry) => api.post("/time-entries", entry),
|
||||
updateEntry: (id, entry) => api.put(`/time-entries/${id}`, entry),
|
||||
deleteEntry: (id) => api.delete(`/time-entries/${id}`),
|
||||
deleteAllEntries: () => api.delete("/time-entries/delete-all"),
|
||||
};
|
||||
|
||||
export default api;
|
||||
7
frontend/vite.config.js
Normal file
7
frontend/vite.config.js
Normal file
@ -0,0 +1,7 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import react from '@vitejs/plugin-react'
|
||||
|
||||
// https://vite.dev/config/
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
})
|
||||
95
package-lock.json
generated
Normal file
95
package-lock.json
generated
Normal file
@ -0,0 +1,95 @@
|
||||
{
|
||||
"name": "time-tracking",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"dependencies": {
|
||||
"react-router-dom": "^7.9.4"
|
||||
}
|
||||
},
|
||||
"node_modules/cookie": {
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmjs.org/cookie/-/cookie-1.0.2.tgz",
|
||||
"integrity": "sha512-9Kr/j4O16ISv8zBBhJoi4bXOYNTkFLOqSL3UDB0njXxCXNezjeyVrJyGOWtgfs/q2km1gwBcfH8q1yEGoMYunA==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/react": {
|
||||
"version": "19.2.0",
|
||||
"resolved": "https://registry.npmjs.org/react/-/react-19.2.0.tgz",
|
||||
"integrity": "sha512-tmbWg6W31tQLeB5cdIBOicJDJRR2KzXsV7uSK9iNfLWQ5bIZfxuPEHp7M8wiHyHnn0DD1i7w3Zmin0FtkrwoCQ==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/react-dom": {
|
||||
"version": "19.2.0",
|
||||
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.0.tgz",
|
||||
"integrity": "sha512-UlbRu4cAiGaIewkPyiRGJk0imDN2T3JjieT6spoL2UeSf5od4n5LB/mQ4ejmxhCFT1tYe8IvaFulzynWovsEFQ==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"scheduler": "^0.27.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": "^19.2.0"
|
||||
}
|
||||
},
|
||||
"node_modules/react-router": {
|
||||
"version": "7.9.4",
|
||||
"resolved": "https://registry.npmjs.org/react-router/-/react-router-7.9.4.tgz",
|
||||
"integrity": "sha512-SD3G8HKviFHg9xj7dNODUKDFgpG4xqD5nhyd0mYoB5iISepuZAvzSr8ywxgxKJ52yRzf/HWtVHc9AWwoTbljvA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"cookie": "^1.0.1",
|
||||
"set-cookie-parser": "^2.6.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": ">=18",
|
||||
"react-dom": ">=18"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"react-dom": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/react-router-dom": {
|
||||
"version": "7.9.4",
|
||||
"resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-7.9.4.tgz",
|
||||
"integrity": "sha512-f30P6bIkmYvnHHa5Gcu65deIXoA2+r3Eb6PJIAddvsT9aGlchMatJ51GgpU470aSqRRbFX22T70yQNUGuW3DfA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"react-router": "7.9.4"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": ">=18",
|
||||
"react-dom": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/scheduler": {
|
||||
"version": "0.27.0",
|
||||
"resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.27.0.tgz",
|
||||
"integrity": "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q==",
|
||||
"license": "MIT",
|
||||
"peer": true
|
||||
},
|
||||
"node_modules/set-cookie-parser": {
|
||||
"version": "2.7.1",
|
||||
"resolved": "https://registry.npmjs.org/set-cookie-parser/-/set-cookie-parser-2.7.1.tgz",
|
||||
"integrity": "sha512-IOc8uWeOZgnb3ptbCURJWNjWUPcO3ZnTTdzsurqERrP6nPyv+paC55vJM0LpOlT2ne+Ix+9+CRG1MNLlyZ4GjQ==",
|
||||
"license": "MIT"
|
||||
}
|
||||
}
|
||||
}
|
||||
5
package.json
Normal file
5
package.json
Normal file
@ -0,0 +1,5 @@
|
||||
{
|
||||
"dependencies": {
|
||||
"react-router-dom": "^7.9.4"
|
||||
}
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user