Compare commits

...

5 Commits

Author SHA1 Message Date
fe76deb2d9 Merge pull request 'dodanie logowania' (#2) from login into master
Reviewed-on: #2
2024-10-28 23:26:52 +01:00
Wiktor Szynaka
a383f2594f dodanie logowania 2024-10-28 23:23:38 +01:00
Wiktor Szynaka
d646ce2b74 lekkie poprawki 2024-06-17 22:25:19 +01:00
Wiktor Szynaka
3d2fa3edf8 lekkie poprawki 2024-06-17 16:18:56 +01:00
d29f34348e Merge pull request '2_przyrost' (#1) from 2_przyrost into master
Reviewed-on: #1
2024-06-15 23:41:24 +02:00
12 changed files with 891 additions and 280 deletions

83
firm/package-lock.json generated
View File

@ -11,14 +11,16 @@
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"axios": "^1.6.8",
"axios": "^1.7.2",
"jwt-decode": "^4.0.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.23.0",
"react-router-dom": "^6.23.1",
"react-scripts": "^5.0.1",
"react-select": "^5.8.0",
"tailwindcss": "^3.4.3",
"web-vitals": "^2.1.4"
"web-vitals": "^2.1.4",
"yup": "^1.4.0"
}
},
"node_modules/@adobe/css-tools": {
@ -3464,9 +3466,9 @@
}
},
"node_modules/@remix-run/router": {
"version": "1.16.0",
"resolved": "https://registry.npmjs.org/@remix-run/router/-/router-1.16.0.tgz",
"integrity": "sha512-Quz1KOffeEf/zwkCBM3kBtH4ZoZ+pT3xIXBG4PPW/XFtDP7EGhtTiC2+gpL9GnR7+Qdet5Oa6cYSvwKYg6kN9Q==",
"version": "1.16.1",
"resolved": "https://registry.npmjs.org/@remix-run/router/-/router-1.16.1.tgz",
"integrity": "sha512-es2g3dq6Nb07iFxGk5GuHN20RwBZOsuDQN7izWIisUcv9r+d2C5jQxqmgkdebXgReWfiyUabcki6Fg77mSNrig==",
"engines": {
"node": ">=14.0.0"
}
@ -5559,9 +5561,9 @@
}
},
"node_modules/axios": {
"version": "1.6.8",
"resolved": "https://registry.npmjs.org/axios/-/axios-1.6.8.tgz",
"integrity": "sha512-v/ZHtJDU39mDpyBoFVkETcd/uNdxrWRrg3bKpOKzXFA6Bvqopts6ALSMU3y6ijYxbw2B+wPrIv46egTzJXCLGQ==",
"version": "1.7.2",
"resolved": "https://registry.npmjs.org/axios/-/axios-1.7.2.tgz",
"integrity": "sha512-2A8QhOMrbomlDuiLeK9XibIBzuHeRcqqNOHp0Cyp5EoJ1IFDh+XZH3A6BkXtv0K4gFGCI0Y4BM7B1wOEi0Rmgw==",
"dependencies": {
"follow-redirects": "^1.15.6",
"form-data": "^4.0.0",
@ -12538,6 +12540,14 @@
"node": ">=4.0"
}
},
"node_modules/jwt-decode": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/jwt-decode/-/jwt-decode-4.0.0.tgz",
"integrity": "sha512-+KJGIyHgkGuIq3IEBNftfhW/LfWhXUIY6OmyVWjliu5KH1y0fw7VQ8YndE2O4qZdMSd9SqbnC8GOcZEy0Om7sA==",
"engines": {
"node": ">=18"
}
},
"node_modules/keyv": {
"version": "4.5.4",
"resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz",
@ -14941,6 +14951,11 @@
"resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz",
"integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ=="
},
"node_modules/property-expr": {
"version": "2.0.6",
"resolved": "https://registry.npmjs.org/property-expr/-/property-expr-2.0.6.tgz",
"integrity": "sha512-SVtmxhRE/CGkn3eZY1T6pC8Nln6Fr/lu1mKSgRud0eC73whjGfoAogbn78LkD8aFL0zz3bAFerKSnOl7NlErBA=="
},
"node_modules/proxy-addr": {
"version": "2.0.7",
"resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz",
@ -15320,11 +15335,11 @@
}
},
"node_modules/react-router": {
"version": "6.23.0",
"resolved": "https://registry.npmjs.org/react-router/-/react-router-6.23.0.tgz",
"integrity": "sha512-wPMZ8S2TuPadH0sF5irFGjkNLIcRvOSaEe7v+JER8508dyJumm6XZB1u5kztlX0RVq6AzRVndzqcUh6sFIauzA==",
"version": "6.23.1",
"resolved": "https://registry.npmjs.org/react-router/-/react-router-6.23.1.tgz",
"integrity": "sha512-fzcOaRF69uvqbbM7OhvQyBTFDVrrGlsFdS3AL+1KfIBtGETibHzi3FkoTRyiDJnWNc2VxrfvR+657ROHjaNjqQ==",
"dependencies": {
"@remix-run/router": "1.16.0"
"@remix-run/router": "1.16.1"
},
"engines": {
"node": ">=14.0.0"
@ -15334,12 +15349,12 @@
}
},
"node_modules/react-router-dom": {
"version": "6.23.0",
"resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-6.23.0.tgz",
"integrity": "sha512-Q9YaSYvubwgbal2c9DJKfx6hTNoBp3iJDsl+Duva/DwxoJH+OTXkxGpql4iUK2sla/8z4RpjAm6EWx1qUDuopQ==",
"version": "6.23.1",
"resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-6.23.1.tgz",
"integrity": "sha512-utP+K+aSTtEdbWpC+4gxhdlPFwuEfDKq8ZrPFU65bbRJY+l706qjR7yaidBpo3MSeA/fzwbXWbKBI6ftOnP3OQ==",
"dependencies": {
"@remix-run/router": "1.16.0",
"react-router": "6.23.0"
"@remix-run/router": "1.16.1",
"react-router": "6.23.1"
},
"engines": {
"node": ">=14.0.0"
@ -17212,6 +17227,11 @@
"resolved": "https://registry.npmjs.org/thunky/-/thunky-1.1.0.tgz",
"integrity": "sha512-eHY7nBftgThBqOyHGVN+l8gF0BucP09fMo0oO/Lb0w1OF80dJv+lDVpXG60WMQvkcxAkNybKsrEIE3ZtKGmPrA=="
},
"node_modules/tiny-case": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/tiny-case/-/tiny-case-1.0.3.tgz",
"integrity": "sha512-Eet/eeMhkO6TX8mnUteS9zgPbUMQa4I6Kkp5ORiBD5476/m+PIRiumP5tmh5ioJpH7k51Kehawy2UDfsnxxY8Q=="
},
"node_modules/tmpl": {
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/tmpl/-/tmpl-1.0.5.tgz",
@ -17244,6 +17264,11 @@
"node": ">=0.6"
}
},
"node_modules/toposort": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/toposort/-/toposort-2.0.2.tgz",
"integrity": "sha512-0a5EOkAUp8D4moMi2W8ZF8jcga7BgZd91O/yabJCFY8az+XSzeGyTKs0Aoo897iV1Nj6guFq8orWDS96z91oGg=="
},
"node_modules/tough-cookie": {
"version": "4.1.4",
"resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-4.1.4.tgz",
@ -18718,6 +18743,28 @@
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/yup": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/yup/-/yup-1.4.0.tgz",
"integrity": "sha512-wPbgkJRCqIf+OHyiTBQoJiP5PFuAXaWiJK6AmYkzQAh5/c2K9hzSApBZG5wV9KoKSePF7sAxmNSvh/13YHkFDg==",
"dependencies": {
"property-expr": "^2.0.5",
"tiny-case": "^1.0.3",
"toposort": "^2.0.2",
"type-fest": "^2.19.0"
}
},
"node_modules/yup/node_modules/type-fest": {
"version": "2.19.0",
"resolved": "https://registry.npmjs.org/type-fest/-/type-fest-2.19.0.tgz",
"integrity": "sha512-RAH822pAdBgcNMAfWnCBU3CFZcfZ/i1eZjwFU/dsLKumyuuP3niueg2UAukXYF0E2AAoc82ZSSf9J0WQBinzHA==",
"engines": {
"node": ">=12.20"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
}
}
}

View File

@ -7,13 +7,15 @@
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"axios": "^1.7.2",
"jwt-decode": "^4.0.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.23.1",
"react-scripts": "^5.0.1",
"react-select": "^5.8.0",
"tailwindcss": "^3.4.3",
"web-vitals": "^2.1.4"
"web-vitals": "^2.1.4",
"yup": "^1.4.0"
},
"scripts": {
"start": "react-scripts start",

View File

@ -1,36 +1,70 @@
import 'tailwindcss/tailwind.css';
import React from 'react';
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
import React, { useState, useEffect } from 'react';
import { BrowserRouter as Router, Route, Routes, Navigate } from 'react-router-dom';
import PanelAdministratora from './components/PanelAdministratora';
import ZarzadzanieProduktami from './components/ZarzadzanieProduktami';
import Transakcje from './components/Transakcje';
import NavBar from './components/NavBar'
import NavBar from './components/NavBar';
import Sidebar from './components/Sidebar';
import Wydatki from './components/Wydatki';
import Raporty from './components/Raporty';
import Login from './components/Login';
import Harmonogram from './components/Harmonogram';
import { jwtDecode } from 'jwt-decode';
const App = () => {
const [token, setToken] = useState(localStorage.getItem('token'));
const [userRole, setUserRole] = useState(null);
useEffect(() => {
if (token) {
try {
const decodedToken = jwtDecode(token);
console.log(decodedToken);
setUserRole(decodedToken['http://schemas.microsoft.com/ws/2008/06/identity/claims/role']);
} catch (error) {
console.error('Failed to decode token:', error);
setUserRole(null);
}
} else {
setUserRole(null);
}
}, [token]);
return (
<Router>
<div className="">
<NavBar />
<div className="flex w-screen">
{token && <NavBar setToken={setToken} />}
<div className="flex w-screen">
{token && (
<div className="w-17/100 bg-gray-200">
<Sidebar />
<Sidebar userRole={userRole} />
</div>
)}
<div className="w-3/4">
<Routes>
<Route path="/transakcje" element={<Transakcje />} />
<Route path="/panel" element={<PanelAdministratora />} />
<Route path="/produkty" element={<ZarzadzanieProduktami />} />
<Route path="/wydatki" element={<Wydatki />} />
<Route path="/raporty" element={<Raporty />} />
{/* Przekierowanie na stronę logowania, jeśli token jest pusty */}
<Route path="/" element={token ? <Navigate to="/transakcje" /> : <Navigate to="/login" />} />
{/* Strona logowania */}
<Route path="/login" element={token ? <Navigate to="/transakcje" /> : <Login setToken={setToken} />} />
{/* Chronione ścieżki */}
<Route path="/transakcje" element={token ? <Transakcje /> : <Navigate to="/login" />} />
<Route path="/panel" element={token ? <PanelAdministratora /> : <Navigate to="/login" />} />
<Route path="/produkty" element={token ? <ZarzadzanieProduktami /> : <Navigate to="/login" />} />
<Route path="/wydatki" element={token ? <Wydatki /> : <Navigate to="/login" />} />
<Route path="/raporty" element={token ? <Raporty /> : <Navigate to="/login" />} />
<Route path="/harmonogram" element={token ? <Harmonogram /> : <Navigate to="/login" />} />
{/* Przekierowanie dla nieznanych ścieżek */}
<Route path="*" element={<Navigate to="/login" />} />
</Routes>
</div>
</div>
</div>
</Router>
</Router>
);
}
};
export default App;

View File

@ -0,0 +1,11 @@
import React from 'react';
const Harmonogram = () => {
return (
<div>
<h1>Harmonogram</h1>
</div>
);
};
export default Harmonogram;

View File

@ -0,0 +1,58 @@
import React, { useState } from 'react';
import axios from 'axios';
import { useNavigate } from 'react-router-dom';
const Login = ({ setToken }) => {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState('');
const navigate = useNavigate();
const handleLogin = async (e) => {
e.preventDefault();
try {
const response = await axios.post('https://localhost:7039/api/user/login', { email, password });
const token = response.data;
setToken(token);
localStorage.setItem('token', token);
navigate('/');
} catch (error) {
setError('Nieprawidłowy email lub hasło');
}
};
return (
<div className="flex justify-center items-center h-screen">
<form onSubmit={handleLogin} className="p-4 bg-white shadow-md rounded">
<h2 className="text-2xl mb-4 text-center">Logowanie</h2>
{error && <p className="text-red-500">{error}</p>}
<div className="mb-4">
<label className="block mb-2">Email:</label>
<input
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
className="border rounded w-full p-2"
required
/>
</div>
<div className="mb-4">
<label className="block mb-2">Hasło:</label>
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
className="border rounded w-full p-2"
required
/>
</div>
<button type="submit" className="w-full bg-blue-500 text-white p-2 rounded">
Zaloguj się
</button>
</form>
</div>
);
};
export default Login;

View File

@ -1,12 +1,20 @@
import React from 'react';
import { Link } from 'react-router-dom';
import { Link, useNavigate } from 'react-router-dom';
import lupaIcon from "../icons/lupa.jpg";
import domIcon from "../icons/dom.png";
import profilIcon from "../icons/profil.png";
import settingsIcon from "../icons/settings.png";
import znakIcon from "../icons/znak.png";
const Navbar = () => {
const Navbar = ({ setToken }) => {
const navigate = useNavigate();
const handleLogout = () => {
setToken(null);
localStorage.removeItem('token');
navigate('/login');
};
return (
<div className="flex items-center justify-between bg-gray-300 p-7 h-16">
<div className="flex items-center flex-shrink-0 text-black mr-6">
@ -22,7 +30,12 @@ const Navbar = () => {
<Link to="/"><img src={domIcon} alt="" className="w-8 h-8 mr-2" /></Link>
<Link to="/"><img src={znakIcon} alt="" className="w-8 h-8 mr-2" /></Link>
<Link to="/"><img src={settingsIcon} alt="" className="w-8 h-8 mr-2" /></Link>
<Link to="/"><img src={profilIcon} alt="" className="w-8 h-8 mr-2" /></Link>
<img
src={profilIcon}
alt="Profil"
className="w-8 h-8 mr-2 cursor-pointer"
onClick={handleLogout}
/>
</div>
</div>
);

View File

@ -1,47 +1,92 @@
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import koszIcon from "../icons/kosz.png";
import ConfirmationModal from './ConfirmationModal';
const Raporty = () => {
const [fromDate, setFromDate] = useState('');
const [toDate, setToDate] = useState('');
const [error, setError] = useState(null);
const [reports, setReports] = useState([]);
const [deleteReportId, setDeleteReportId] = useState(null);
const fetchReports = async () => {
const token = localStorage.getItem('token');
if (!token) {
console.error('Brak tokena. Użytkownik musi być zalogowany.');
return;
}
try {
const response = await axios.get('https://localhost:7039/api/Report');
const response = await axios.get('https://localhost:7039/api/Report', {
headers: {
Authorization: `Bearer ${token}`
}
});
setReports(response.data);
} catch (error) {
console.error('Błąd podczas pobierania raportów:', error);
}
};
const openDeleteConfirmation = (transactionId) => {
setDeleteReportId(transactionId);
};
const closeDeleteConfirmation = () => {
setDeleteReportId(null);
};
useEffect(() => {
fetchReports();
}, []);
const handleGenerateReport = async () => {
if (!fromDate || !toDate) {
setError('Proszę uzupełnić wszystkie pola.');
return;
}
const token = localStorage.getItem('token');
try {
console.log('Wysyłane dane:', fromDate, toDate);
const response = await axios.post('https://localhost:7039/api/Report', {
fromDate,
toDate
}, {
headers: {
Authorization: `Bearer ${token}`
}
});
const newReport = response.data;
setReports([...reports, newReport]);
} catch (error) {
console.error('Błąd podczas generowania raportu:', error);
if (error.response && error.response.data) {
setError(error.response.data);
} else {
setError('Wystąpił nieoczekiwany błąd. Spróbuj ponownie później.');
}
}
};
const handleDeleteReport = async (reportId) => {
const token = localStorage.getItem('token');
try {
await axios.delete(`https://localhost:7039/api/Report?${reportId}`);
setReports(reports.filter(report => report.id !== reportId)); // Update state after deletion
await axios.delete(`https://localhost:7039/api/Report/${reportId}`, {
headers: {
Authorization: `Bearer ${token}`
}
});
fetchReports();
setDeleteReportId(null);
} catch (error) {
console.error('Błąd podczas usuwania raportu:', error);
if (error.response && error.response.data) {
setError(error.response.data);
} else {
setError('Wystąpił nieoczekiwany błąd. Spróbuj ponownie później.');
}
}
};
const formatDate = (dateString) => {
const options = { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' };
@ -58,9 +103,9 @@ const Raporty = () => {
</div>
<div className="mt-5">
<label htmlFor="fromDate" className="mr-3">Od:</label>
<input type="date" id="fromDate" value={fromDate} onChange={(e) => setFromDate(e.target.value)} className="mr-5" />
<input type="datetime-local" id="fromDate" value={fromDate} onChange={(e) => setFromDate(e.target.value)} className="mr-5" />
<label htmlFor="toDate" className="mr-3">Do:</label>
<input type="date" id="toDate" value={toDate} onChange={(e) => setToDate(e.target.value)} className="mr-5" />
<input type="datetime-local" id="toDate" value={toDate} onChange={(e) => setToDate(e.target.value)} className="mr-5" />
<button onClick={handleGenerateReport} className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded">Generuj</button>
</div>
<div className="mt-5">
@ -87,7 +132,7 @@ const Raporty = () => {
<td className="border border-gray-300 p-2">{report.totalExpenses}</td>
<td className="border border-gray-300 p-2">{report.totalBalance}</td>
<td className="border border-gray-300 p-2">
<button onClick={() => handleDeleteReport(report.id)} className="mr-2 bg-red-500 hover:bg-red-700 text-white font-bold py-2 px-4 rounded flex">
<button onClick={() => openDeleteConfirmation(report.id)} className="mr-2 bg-red-500 hover:bg-red-700 text-white font-bold py-2 px-4 rounded flex">
<img src={koszIcon} alt="" className="w-8 h-8 mr-2" />Usuń</button>
</td>
</tr>
@ -95,6 +140,24 @@ const Raporty = () => {
</tbody>
</table>
</div>
{error && (
<div className="absolute top-0 left-0 w-full h-full bg-black bg-opacity-50 flex items-center justify-center">
<div className="bg-white p-8 rounded-lg">
<h2 className="text-2xl font-bold mb-4">Błąd</h2>
<p>{error}</p>
<button onClick={() => window.location.reload()} className="bg-red-500 hover:bg-red-700 text-white font-bold py-2 px-4 rounded">
Zamknij
</button>
</div>
</div>
)}
{deleteReportId && (
<ConfirmationModal
message="Czy na pewno chcesz usunąć ten raport?"
onCancel={closeDeleteConfirmation}
onConfirm={() => handleDeleteReport(deleteReportId)}
/>
)}
</div>
);
};

View File

@ -7,19 +7,23 @@ import harmonogramIcon from "../icons/harmonogram.png";
import wydatkiIcon from "../icons/wydatki.png";
import raportyIcon from "../icons/raport.png";
const Sidebar = () => {
const Sidebar = ({ userRole }) => {
return (
<div className="bg-gray-200 h-screen flex justify-center marign-0 w-max">
<ul className="">
{userRole !== 'User' && (
<>
<Link to="/panel" className="text-black px-10 py-2 block font-customFont text-center w-max">
<li className='flex items-center'>
<img src={adminIcon} alt="Obrazek 1" className="w-7 h-7 mr-2" />
Panel Administratora
</li></Link>
</>
)}
<Link to="/produkty" className="text-black px-10 py-2 block font-customFont text-center w-max">
<li className='flex items-center'>
<img src={produktIcon} alt="Obrazek 1" className="w-7 h-7 mr-2" />
Zarządzanie Produkatami
Produkty
</li></Link>
<Link to="/transakcje" className="text-black px-10 py-2 block font-customFont text-center w-max">
<li className='flex items-center'>
@ -31,19 +35,22 @@ const Sidebar = () => {
<img src={harmonogramIcon} alt="Obrazek 1" className="w-7 h-7 mr-2" />
Harmonogram
</li></Link>
<Link to="/wydatki" className="text-black px-10 py-2 block font-customFont text-center w-max flex-item-center">
<li className='flex items-center'>
<img src={wydatkiIcon} alt="Obrazek 1" className="w-7 h-7 mr-2" />
Wydatki
</li></Link>
<Link to="/raporty" className="text-black px-10 py-2 block font-customFont text-center w-max flex-item-center">
<li className='flex items-center'>
<img src={raportyIcon} alt="Obrazek 1" className="w-7 h-7 mr-2" />
Raporty
</li></Link>
{userRole !== 'User' && (
<>
<Link to="/wydatki" className="text-black px-10 py-2 block font-customFont text-center w-max flex-item-center">
<li className='flex items-center'>
<img src={wydatkiIcon} alt="Obrazek 1" className="w-7 h-7 mr-2" />
Wydatki
</li></Link>
<Link to="/raporty" className="text-black px-10 py-2 block font-customFont text-center w-max flex-item-center">
<li className='flex items-center'>
<img src={raportyIcon} alt="Obrazek 1" className="w-7 h-7 mr-2" />
Raporty
</li></Link>
</>
)}
</ul>
</div>
);
}
export default Sidebar;
export default Sidebar;

View File

@ -34,16 +34,34 @@ const Transakcje = () => {
});
const fetchTransactions = async () => {
const token = localStorage.getItem('token');
if (!token) {
console.error('Brak tokena. Użytkownik musi być zalogowany.');
return;
}
try {
const response = await axios.get('https://localhost:7039/api/Transaction');
const response = await axios.get('https://localhost:7039/api/Transaction', {
headers: {
Authorization: `Bearer ${token}`
}
});
setTransactions(response.data);
} catch (error) {
console.error('Błąd podczas dodawania transakcji:', error);
}
};
const fetchProducts = async () => {
const token = localStorage.getItem('token');
if (!token) {
console.error('Brak tokena. Użytkownik musi być zalogowany.');
return;
}
try {
const response = await axios.get('https://localhost:7039/api/Products');
const response = await axios.get('https://localhost:7039/api/Products', {
headers: {
Authorization: `Bearer ${token}`
}
});
setProducts(response.data.map(product => ({ value: product.id, label: product.name })));
} catch (error) {
console.error('Błąd podczas pobierania produktów:', error);
@ -57,6 +75,10 @@ const Transakcje = () => {
}, []);
const handleAddTransaction = async () => {
if (!newTransaction.date || !newTransaction.employeeId || newTransaction.transactionProducts.some(product => !product.productName || !product.quantity)) {
setError('Proszę uzupełnić wszystkie pola.');
return;
}
try {
console.log('Nowa transakcja:', newTransaction);
await axios.post('https://localhost:7039/api/Transaction', newTransaction);
@ -91,12 +113,14 @@ const Transakcje = () => {
}
};
const formatDate = (dateString) => {
const options = { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' };
const date = new Date(dateString);
return date.toLocaleDateString('pl-PL', options).replace(",", "");
};
const formatPrice = (price) => {
return parseFloat(price).toFixed(2);
};
const handleAddProduct = () => {
setNewTransaction({
@ -130,6 +154,11 @@ const Transakcje = () => {
setDeleteTransactionId(null);
} catch (error) {
console.error('Błąd podczas usuwania transakcji:', error);
if (error.response && error.response.data) {
setError(error.response.data);
} else {
setError('Wystąpił nieoczekiwany błąd. Spróbuj ponownie później.');
}
}
};
const handleEditTransaction = async (transaction) => {
@ -139,6 +168,9 @@ const Transakcje = () => {
setIsEditModalOpen(true);
return;
}
if (!editTransaction.date || !editTransaction.employeeId || editTransaction.transactionProducts.some(product => !product.productName || !product.quantity) || !editTransaction.paymentType){
setError('Proszę uzupełnić wszystkie pola.');
return;}
await axios.put(`https://localhost:7039/api/Transaction/${editTransaction.id}`, editTransaction);
fetchTransactions();
setIsEditModalOpen(false);
@ -203,8 +235,8 @@ const Transakcje = () => {
</div>
)}
{isEditModalOpen && editTransaction && (
<div className="absolute top-0 left-0 w-full h-full bg-black bg-opacity-50 flex items-center justify-center">
<div className="bg-white p-8 rounded-lg">
<div className="absolute top-0 left-0 w-full h-screen bg-black bg-opacity-50 flex items-center justify-center">
<div className="bg-white p-8 rounded-lg">
<h2 className="text-2xl font-bold mb-4">Edytuj transakcję</h2>
<input
type="datetime-local"
@ -214,6 +246,7 @@ const Transakcje = () => {
placeholder="Data"
className="block w-full mb-4 px-4 py-2 border border-gray-300 rounded-lg"
/>
Numer Pracownika
<input
type="number"
name="employeeId"
@ -230,7 +263,9 @@ const Transakcje = () => {
onChange={(selectedOption) => handleEditProductChange(index, selectedOption)}
options={products}
className="block w-full mb-4"
placeholder="Wybierz produkt..."
/>
Ilość
<input
type="number"
name={`quantity-${index}`}
@ -253,6 +288,7 @@ const Transakcje = () => {
placeholder="Sposób płatności"
className="block w-full mb-4 px-4 py-2 border border-gray-300 rounded-lg"
/>
Zniżka
<input
type="number"
name="discount"
@ -316,6 +352,7 @@ const Transakcje = () => {
onChange={(selectedOption) => handleProductChange(index, selectedOption)}
options={products}
className="block w-full mb-4"
placeholder="Wybierz produkt..."
/>
<input
type="number"
@ -328,12 +365,12 @@ const Transakcje = () => {
}}
placeholder="Ilość" className="block w-full mb-4 px-4 py-2 border border-gray-300 rounded-lg"
/>
<button onClick={() => handleRemoveProduct(index)} className="bg-red-500 hover:bg-red-700 text-white font-bold py-2 px-4 rounded">
<button onClick={() => handleRemoveProduct(index)} className="bg-red-500 hover:bg-red-700 text-white font-bold my-2 py-2 px-4 rounded">
Usuń
</button>
</div>
))}
<button onClick={handleAddProduct} className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded">
<button onClick={handleAddProduct} className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 my-3 rounded">
Dodaj
</button>
<input
@ -372,7 +409,7 @@ const Transakcje = () => {
</button>
<button
onClick={() => setIsModalOpen(false)}
className="bg-red-500 hover:bg-red-700 text-white font-bold py-2 px-4 rounded"
className="bg-red-500 hover:bg-red-700 text-white font-bold py-2 px-4 mx-1 rounded"
>
Anuluj
</button>
@ -410,10 +447,13 @@ const Transakcje = () => {
<div key={product.id}>{product.quantity}</div>
))}
</td>
<td className="border border-gray-300 p-2">{transaction.totalPrice}</td>
<td className="border border-gray-300 p-2">{formatPrice(transaction.totalPrice)}</td>
<td className="border border-gray-300 p-2">{transaction.paymentType}</td>
<td className="border border-gray-300 p-2">{transaction.employeeId}</td>
<td className="border border-gray-300 p-2"><button onClick={() => handleEditTransaction(transaction)}
<td className="border border-gray-300 p-2"><button onClick={() =>{handleEditTransaction(transaction);
console.log(transaction);
}
}
className="mr-2 bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded flex">
<img src={editIcon} alt="" className="w-8 h-8 mr-2" />Edytuj
</button></td>
@ -433,7 +473,7 @@ const Transakcje = () => {
<ConfirmationModal
message="Czy na pewno chcesz usunąć tę transakcję?"
onCancel={closeDeleteConfirmation}
onConfirm={() => handleDeleteTransaction(deleteTransactionId)}
onConfirm={() => {handleDeleteTransaction(deleteTransactionId); setDeleteTransactionId(false);}}
/>)}
</div>
);

View File

@ -2,10 +2,13 @@ import React, { useState, useEffect } from 'react';
import axios from 'axios';
import koszIcon from "../icons/kosz.png";
import plusIcon from "../icons/plus.png";
import ConfirmationModal from './ConfirmationModal';
const Wydatki = () => {
const [expenses, setExpenses] = useState([]);
const [showModal, setShowModal] = useState(false);
const [error, setError] = useState(null);
const [deleteExpenseId, setDeleteExpenseId] = useState(null);
const [newExpense, setNewExpense] = useState({
date: '',
value: '',
@ -13,8 +16,17 @@ const Wydatki = () => {
});
const fetchExpenses = async () => {
const token = localStorage.getItem('token');
if (!token) {
console.error('Brak tokena. Użytkownik musi być zalogowany.');
return;
}
try {
const response = await axios.get('https://localhost:7039/api/Expenses');
const response = await axios.get('https://localhost:7039/api/Expenses', {
headers: {
Authorization: `Bearer ${token}`
}
});
setExpenses(response.data);
} catch (error) {
console.error('Błąd podczas pobierania wydatków:', error);
@ -26,8 +38,17 @@ const Wydatki = () => {
}, []);
const handleAddExpense = async () => {
if (!newExpense.date || !newExpense.value || !newExpense.description) {
setError('Proszę uzupełnić wszystkie pola.');
return;
}
const token = localStorage.getItem('token');
try {
const response = await axios.post('https://localhost:7039/api/Expenses', newExpense);
const response = await axios.post('https://localhost:7039/api/Expenses', newExpense, {
headers: {
Authorization: `Bearer ${token}`
}
});
const addedExpense = response.data;
setExpenses([...expenses, addedExpense]);
setNewExpense({
@ -38,18 +59,38 @@ const Wydatki = () => {
setShowModal(false);
} catch (error) {
console.error('Błąd podczas dodawania wydatku:', error);
setError('Wystąpił błąd podczas dodawania wydatku.');
}
};
const handleDeleteExpense = async (expenseId) => {
const token = localStorage.getItem('token');
try {
await axios.delete(`https://localhost:7039/api/Expenses/${expenseId}`);
await axios.delete(`https://localhost:7039/api/Expenses/${expenseId}`, {
headers: {
Authorization: `Bearer ${token}`
}
});
fetchExpenses();
setDeleteExpenseId(null);
} catch (error) {
console.error('Błąd podczas usuwania wydatku:', error);
if (error.response && error.response.data) {
setError(error.response.data);
} else {
setError('Wystąpił nieoczekiwany błąd. Spróbuj ponownie później.');
}
}
};
const openDeleteConfirmation = (expenseId) => {
setDeleteExpenseId(expenseId);
};
const closeDeleteConfirmation = () => {
setDeleteExpenseId(null);
};
const formatDate = (dateString) => {
const options = { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' };
const date = new Date(dateString);
@ -58,18 +99,14 @@ const Wydatki = () => {
return (
<div className="p-10 ml-11">
<div className="flex items-center justify-between">
<div className="h-20 text-5xl ml-1">
Zarządzanie wydatkami
</div>
</div>
<div className="mt-5">
<div className="flex justify-between items-center">
<h2 className="text-2xl font-bold mb-4">Wydatki</h2>
<button onClick={() => setShowModal(true)} className="bg-green-500 hover:bg-green-700 text-white font-bold py-2 px-4 rounded">
<img src={plusIcon} alt="" className="w-8 h-8 mr-2" />Dodaj
</button>
<div className='flex items-center justify-between'>
<div className='h-20 text-5xl ml-1'>
Wydatki
</div>
<button onClick={() => setShowModal(true)} className="bg-green-500 hover:bg-green-700 text-white font-bold py-2 px-4 rounded flex">
<img src={plusIcon} alt="" className="w-8 h-8 mr-2" />Dodaj
</button>
</div>
<table className="w-full border-collapse border border-gray-300">
<thead className="bg-gray-200 top-0 z-10">
@ -89,8 +126,9 @@ const Wydatki = () => {
<td className="border border-gray-300 p-2">{expense.value}</td>
<td className="border border-gray-300 p-2">{expense.description}</td>
<td className="border border-gray-300 p-2">
<button onClick={() => handleDeleteExpense(expense.id)} className="mr-2 bg-red-500 hover:bg-red-700 text-white font-bold py-2 px-4 rounded flex">
<img src={koszIcon} alt="" className="w-8 h-8 mr-2" />Usuń</button>
<button onClick={() => openDeleteConfirmation(expense.id)} className="mr-2 bg-red-500 hover:bg-red-700 text-white font-bold py-2 px-4 rounded flex">
<img src={koszIcon} alt="" className="w-8 h-8 mr-2" />Usuń
</button>
</td>
</tr>
))}
@ -111,7 +149,7 @@ const Wydatki = () => {
<div className="grid grid-cols-6 gap-6">
<div className="col-span-6 sm:col-span-3">
<label htmlFor="expenseDate" className="block text-sm font-medium text-gray-700">Data</label>
<input type="date" id="expenseDate" value={newExpense.date} onChange={(e) => setNewExpense({ ...newExpense, date: e.target.value })} className="mt-1 border py-1 px-3 block w-full shadow-sm sm:text-sm rounded-md" />
<input type="datetime-local" id="expenseDate" value={newExpense.date} onChange={(e) => setNewExpense({ ...newExpense, date: e.target.value })} className="mt-1 border py-1 px-3 block w-full shadow-sm sm:text-sm rounded-md" />
</div>
<div className="col-span-6 sm:col-span-3">
@ -123,24 +161,41 @@ const Wydatki = () => {
<label htmlFor="expenseDescription" className="block text-sm font-medium text-gray-700">Opis</label>
<textarea id="expenseDescription" value={newExpense.description} onChange={(e) => setNewExpense({ ...newExpense, description: e.target.value })}
className="mt-1 border py-2 px-3 block w-full shadow-sm sm:text-sm rounded-md" rows="4"/>
</div>
</div>
</div>
</div>
<div className="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
<button onClick={handleAddExpense} type="button" className="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-green-600 text-base font-medium text-white hover:bg-green-500 focus:outline-none focus:border-green-700 focus:shadow-outline-green transition ease-in-out duration-150 sm:text-sm sm:leading-5">
Dodaj
<button onClick={() => { handleAddExpense(); }} type="button" className="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-green-600 text-base font-medium text-white hover:bg-green-500 focus:outline-none focus:border-green-700 focus:shadow-outline-green transition ease-in-out duration-150 sm:text-sm sm:leading-5">
Dodaj
</button>
<button onClick={() => setShowModal(false)} type="button" className="mt-3 sm:mt-0 mr-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:text-gray-500 focus:outline-none focus:border-blue-300 focus:shadow-outline-blue transition ease-in-out duration-150 sm:text-sm sm:leading-5">
Anuluj
Anuluj
</button>
</div>
</div>
</div>
</div>
</div>
)}
{error && (
<div className="absolute top-0 left-0 w-full h-full bg-black bg-opacity-50 flex items-center justify-center">
<div className="bg-white p-8 rounded-lg">
<h2 className="text-2xl font-bold mb-4">Błąd</h2>
<p>{error}</p>
<button onClick={() => window.location.reload()} className="bg-red-500 hover:bg-red-700 text-white font-bold py-2 px-4 rounded">
Zamknij
</button>
</div>
</div>
)}
{deleteExpenseId && (
<ConfirmationModal
message="Czy na pewno chcesz usunąć ten raport?"
onCancel={closeDeleteConfirmation}
onConfirm={() => { handleDeleteExpense(deleteExpenseId); }}
/>
)}
</div>
);
};
export default Wydatki;

View File

@ -9,6 +9,7 @@ const ZarzadzanieProduktami = () => {
const [products, setProducts] = useState([]);
const [isModalOpen, setIsModalOpen] = useState(false);
const [isEditModalOpen, setIsEditModalOpen] = useState(false);
const [error, setError] = useState(null);
const [deleteProductId, setDeleteProductId] = useState(null);
const [newProduct, setNewProduct] = useState({
name: "",
@ -20,8 +21,18 @@ const ZarzadzanieProduktami = () => {
const [editProduct, setEditProduct] = useState(null);
const fetchProducts = async () => {
const token = localStorage.getItem('token');
if (!token) {
console.error('Brak tokena. Użytkownik musi być zalogowany.');
return;
}
try {
const response = await axios.get('https://localhost:7039/api/Products');
const response = await axios.get('https://localhost:7039/api/products', {
headers: {
Authorization: `Bearer ${token}`
}
});
setProducts(response.data);
} catch (error) {
console.error('Błąd podczas pobierania produktów:', error);
@ -38,6 +49,10 @@ const ZarzadzanieProduktami = () => {
};
const handleAddProduct = async () => {
if (!newProduct.name || !newProduct.description || !newProduct.price || !newProduct.type || !newProduct.availability) {
setError('Proszę uzupełnić wszystkie pola.');
return;
}
try {
const config = {
headers: {
@ -54,8 +69,13 @@ const ZarzadzanieProduktami = () => {
type: "",
description: ""
});
} catch (error) {
console.error('Błąd podczas dodawania produktu:', error);
} catch (error) {
console.error('Błąd podczas dodawania:', error);
if (error.response && error.response.data) {
setError(error.response.data);
} else {
setError('Wystąpił nieoczekiwany błąd. Spróbuj ponownie później.');
}
}
};
@ -65,12 +85,21 @@ const ZarzadzanieProduktami = () => {
};
const handleSaveEditedProduct = async () => {
if (!editProduct.name || !editProduct.description || !editProduct.price || !editProduct.type || !editProduct.availability) {
setError('Proszę uzupełnić wszystkie pola.');
return;
}
try {
await axios.put(`https://localhost:7039/api/Products/${editProduct.id}`, editProduct);
fetchProducts();
setIsEditModalOpen(false);
} catch (error) {
console.error('Błąd podczas edycji produktu:', error);
} catch (error) {
console.error('Błąd podczas edycji:', error);
if (error.response && error.response.data) {
setError(error.response.data);
} else {
setError('Wystąpił nieoczekiwany błąd. Spróbuj ponownie później.');
}
}
};
@ -81,6 +110,11 @@ const ZarzadzanieProduktami = () => {
setDeleteProductId(null);
} catch (error) {
console.error('Błąd podczas usuwania produktu:', error);
if (error.response && error.response.data) {
setError(error.response.data);
} else {
setError('Wystąpił nieoczekiwany błąd. Spróbuj ponownie później.');
}
}
};
@ -91,6 +125,9 @@ const openDeleteConfirmation = (productId) => {
const closeDeleteConfirmation = () => {
setDeleteProductId(null);
};
const formatPrice = (price) => {
return parseFloat(price).toFixed(2);
};
return (
<div className='p-10 ml-11'>
@ -102,6 +139,17 @@ const closeDeleteConfirmation = () => {
<img src={plusIcon} alt="" className="w-8 h-8 mr-2" />Dodaj
</button>
</div>
{error && (
<div className="absolute top-0 left-0 w-full h-full bg-black bg-opacity-50 flex items-center justify-center">
<div className="bg-white p-8 rounded-lg">
<h2 className="text-2xl font-bold mb-4">Błąd</h2>
<p>{error}</p>
<button onClick={() => window.location.reload()} className="bg-red-500 hover:bg-red-700 text-white font-bold py-2 px-4 rounded">
Zamknij
</button>
</div>
</div>
)}
{isEditModalOpen && editProduct && (
<div className="absolute top-0 left-0 w-full h-full bg-black bg-opacity-50 flex items-center justify-center z-50">
<div className="bg-white p-8 rounded-lg shadow-lg">
@ -147,7 +195,10 @@ const closeDeleteConfirmation = () => {
className="block w-full mb-4 px-4 py-2 border border-gray-300 rounded-lg"
/>
<button
onClick={handleSaveEditedProduct}
onClick={() => {
handleSaveEditedProduct();
setIsEditModalOpen(false);
}}
className="bg-green-500 hover:bg-green-700 text-white font-bold py-2 px-4 rounded"
>
Zapisz zmiany
@ -206,7 +257,10 @@ const closeDeleteConfirmation = () => {
className="block w-full mb-4 px-4 py-2 border border-gray-300 rounded-lg"
/>
<button
onClick={handleAddProduct}
onClick={() => {
handleAddProduct();
setIsModalOpen(false)
}}
className="bg-green-500 hover:bg-green-700 text-white font-bold py-2 px-4 rounded"
>
Dodaj produkt
@ -221,8 +275,8 @@ const closeDeleteConfirmation = () => {
</div>
)}
<div className="w-8/10 mx-auto mt-2">
<div className="h-screen overflow-y-auto margin-0">
<table className="w-full border-collapse border border-gray-500">
<div className="h-screen overflow-y-auto">
<table className="w-full border-collapse border border-gray-300">
<thead className="bg-gray-200 top-0 z-10 sticky">
<tr>
<th className="border border-gray-300 p-2">ID</th>
@ -241,7 +295,7 @@ const closeDeleteConfirmation = () => {
<td className="border border-gray-300 p-2">{product.id}</td>
<td className="border border-gray-300 p-2">{product.name}</td>
<td className="border border-gray-300 p-2">{product.description}</td>
<td className="border border-gray-300 p-2">{product.price}</td>
<td className="border border-gray-300 p-2">{formatPrice(product.price)}</td>
<td className="border border-gray-300 p-2">{product.type}</td>
<td className="border border-gray-300 p-2">{product.availability}</td>
<td className="border border-gray-300 p-2"><button onClick={() => handleEditProduct(product)}
@ -263,7 +317,7 @@ const closeDeleteConfirmation = () => {
<ConfirmationModal
message="Czy na pewno chcesz usunąć ten produkt?"
onCancel={closeDeleteConfirmation}
onConfirm={handleDeleteProduct}
onConfirm={ () => {handleDeleteProduct(); setDeleteProductId(false);}}
/>
)}
</div>

File diff suppressed because it is too large Load Diff