3 Commits
lab4 ... lab6

Author SHA1 Message Date
xom9k
180f749707 обновил информацию в отчет 2025-05-26 15:35:45 +04:00
xom9k
6a0c72354f добавление отчета 2025-05-23 11:36:49 +04:00
xom9k
ba4efe44be 6 лаба 2025-05-23 10:09:03 +04:00
24 changed files with 2093 additions and 415 deletions

View File

@@ -1,20 +1,44 @@
{
"products": [
{
"name": "дрель",
"price": "9000",
"image": "https://www.interskol.ru/storage/products/1641253262/%D0%94%D0%A3-13%20750%D0%AD%D0%A0%20%D0%B4%D1%80%D0%B5%D0%BB%D1%8C%20%D1%83%D0%B4%D0%B0%D1%80%D0%BD%D0%B0%D1%8F%20(546.1.0.00).jpg",
"categoryId": 1,
"brandId": 1,
"id": "09e4"
"name": "Отвертккк",
"price": 450,
"image": "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTCxcN67AQirgFwXQ3RmffA715CIAIsLJlhLw&s",
"brandId": "3",
"categoryId": "2",
"id": "7922"
},
{
"id": "30c3",
"name": "отвертка",
"price": "450",
"image": "https://cdn.vseinstrumenti.ru/images/goods/ruchnoj-instrument/otvertki/923910/560x504/180280523.jpg",
"categoryId": 2,
"brandId": 3
"id": "569e",
"name": "Дрель",
"price": 9000,
"image": "https://cdn.kuvalda.ru/data/file_resize/product/7c/c9/1b/landing-7cc91b79db759ca3e2a14868fcabbaf0.jpg",
"brandId": "1",
"categoryId": "1"
},
{
"name": "Друль",
"price": 5600,
"image": "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTCxcN67AQirgFwXQ3RmffA715CIAIsLJlhLw&s",
"brandId": "1",
"categoryId": "1",
"id": "0f7d"
},
{
"name": "Лопата",
"price": 1100,
"image": "https://cdn.kuvalda.ru/data/file_resize/product/9e/55/8a/landing-9e558a48a9b3efc6b4e2dfa53a82f0713962.jpg",
"brandId": "3",
"categoryId": "3",
"id": "1354"
},
{
"name": "Бетоносмеситель",
"price": 24000,
"image": "https://electrolite.ru/Pc/shop/full/2252_15929192901144.jpg",
"brandId": "2",
"categoryId": "3",
"id": "aa78"
}
],
"categories": [

File diff suppressed because it is too large Load Diff

View File

@@ -2,6 +2,7 @@
"name": "masterok",
"version": "0.3.0",
"devDependencies": {
"@vitejs/plugin-react": "^4.4.1",
"concurrently": "^9.1.2",
"eslint": "8.56.0",
"eslint-config-airbnb-base": "15.0.0",
@@ -26,7 +27,10 @@
"dependencies": {
"bootstrap": "5.3.3",
"bootstrap-icons": "1.11.3",
"express": "^4.21.2"
"express": "^4.21.2",
"react": "^19.1.0",
"react-dom": "^19.1.0",
"react-router-dom": "^7.6.0"
},
"type": "module"
}

139
MasterOK/src/App.jsx Normal file
View File

@@ -0,0 +1,139 @@
import React, { useState, useEffect, useCallback } from 'react';
import { Routes, Route } from 'react-router-dom';
import Header from './components/Header';
import Footer from './components/Footer';
import ProductEditForm from './components/ProductEditForm';
import HomePage from './pages/HomePage';
import CartPage from './pages/CartPage';
import ContactsPage from './pages/ContactsPage';
import DeliveryPage from './pages/DeliveryPage';
import SalesPage from './pages/SalesPage';
import AddProductPage from './pages/AddProductPage';
import NotFoundPage from './pages/NotFoundPage';
const CART_STORAGE_KEY = 'reactMasterokCart';
function App() {
const [products, setProducts] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
const [editingProduct, setEditingProduct] = useState(null);
const [cart, setCart] = useState(() => {
const storedCart = localStorage.getItem(CART_STORAGE_KEY);
return storedCart ? JSON.parse(storedCart) : [];
});
useEffect(() => {
localStorage.setItem(CART_STORAGE_KEY, JSON.stringify(cart));
}, [cart]);
const fetchProducts = useCallback(async () => {
try {
setLoading(true);
const response = await fetch('/api/products');
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
const data = await response.json();
setProducts(data);
setError(null);
} catch (e) {
setError(e.message);
console.error("Failed to fetch products:", e);
setProducts([]);
} finally {
setLoading(false);
}
}, []);
useEffect(() => { fetchProducts(); }, [fetchProducts]);
const handleProductAdded = useCallback(() => { fetchProducts(); }, [fetchProducts]);
const handleEditProduct = useCallback((product) => { setEditingProduct(product); }, []);
const handleCloseEditModal = useCallback(() => { setEditingProduct(null); }, []);
const handleProductUpdated = useCallback(() => { fetchProducts(); setEditingProduct(null); }, [fetchProducts]);
const handleDeleteProduct = useCallback(async (productId) => {
if (!window.confirm("Вы уверены, что хотите удалить этот товар?")) return;
try {
const response = await fetch(`/api/products/${productId}`, { method: 'DELETE' });
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
fetchProducts();
} catch (e) {
setError(e.message);
console.error("Failed to delete product:", e);
}
}, [fetchProducts]);
const handleAddToCart = useCallback((productToAdd) => {
setCart(prevCart => {
const existingItem = prevCart.find(item => item.id === productToAdd.id);
if (existingItem) {
alert(`${productToAdd.name} уже в корзине!`);
return prevCart;
} else {
alert(`${productToAdd.name} добавлен в корзину!`);
return [...prevCart, { ...productToAdd, quantity: 1 }];
}
});
}, []);
const cartItemCount = cart.reduce((count, item) => count + item.quantity, 0);
return (
<div className={`d-flex flex-column min-vh-100 ${editingProduct ? 'modal-open' : ''}`}>
<Header cartItemCount={cartItemCount} />
<main className="flex-grow-1 py-4">
<div className="container">
<Routes>
<Route
path="/"
element={ (
<HomePage
products={products}
loading={loading}
error={error}
onEditProduct={handleEditProduct}
onDeleteProduct={handleDeleteProduct}
onAddToCart={handleAddToCart}
fetchProducts={fetchProducts}
/>
)}
/>
<Route
path="/add-product"
element={<AddProductPage onProductAdded={handleProductAdded} />}
/>
<Route path="/cart" element={<CartPage cart={cart} setCart={setCart} />} />
<Route path="/contacts" element={<ContactsPage />} />
<Route path="/delivery" element={<DeliveryPage />} />
<Route
path="/sales"
element={ (
<SalesPage
products={products}
loading={loading}
error={error}
onEditProduct={handleEditProduct}
onDeleteProduct={handleDeleteProduct}
onAddToCart={handleAddToCart}
fetchProducts={fetchProducts}
/>
)}
/>
<Route path="*" element={<NotFoundPage />} />
</Routes>
</div>
</main>
<Footer />
{editingProduct && (
<ProductEditForm
product={editingProduct}
onProductUpdated={handleProductUpdated}
onClose={handleCloseEditModal}
/>
)}
{editingProduct && <div className="modal-backdrop fade show"></div>}
</div>
);
}
export default App;

View File

@@ -0,0 +1,29 @@
import React from 'react';
function Footer() {
return (
<footer className="bg-dark text-white py-4 mt-auto"> {}
<div className="container">
<div className="row text-center text-md-start">
<div className="col-md-6 mb-4 mb-md-0">
<h3>Контактная информация</h3>
<p>Адрес: г. Ульяновск, ул. Северный венец, д. 32, к. 3</p>
<p>Телефон: +7 (999) 99-99-90</p>
<p>Email: masterok@mail.ru</p>
</div>
<div className="col-md-6 text-md-end">
<h3>Мы в соцсетях</h3>
<a href="https://t.me/" target="_blank" rel="noopener noreferrer" className="me-2">
<img src="/images/tg.png" alt="Telegram" style={{ width: '32px' }} />
</a>
<a href="https://vk.com/" target="_blank" rel="noopener noreferrer">
<img src="/images/vk.png" alt="VK" style={{ width: '32px' }} />
</a>
</div>
</div>
</div>
</footer>
);
}
export default Footer;

View File

@@ -0,0 +1,47 @@
import React from 'react';
import { Link } from 'react-router-dom';
function Header({ cartItemCount }) {
return (
<header className="custom-header py-3 bg-warning text-dark">
<div className="container">
<nav className="navbar navbar-expand-lg navbar-dark">
<div className="container-fluid">
<Link to="/" className="navbar-brand d-flex align-items-center text-decoration-none text-dark fs-4 fw-bold">
<img src="/images/местерок.png" alt="Логотип МастерОК" className="me-2" style={{ height: '50px' }} />
МастерОК
</Link>
<button className="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span className="navbar-toggler-icon"></span>
</button>
<div className="collapse navbar-collapse" id="navbarNav">
<ul className="navbar-nav ms-auto mb-2 mb-lg-0">
<li className="nav-item me-4"><Link to="/add-product" className="nav-link text-dark">Добавить товар</Link></li>
<li className="nav-item dropdown me-4">
<Link to="/sales" className="nav-link text-dark dropdown-toggle" id="salesDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
Акции
</Link>
<ul className="dropdown-menu" aria-labelledby="salesDropdown">
<li><Link className="dropdown-item" to="/sales">Все акции</Link></li>
<li><Link className="dropdown-item" to="/sales">Праздничные акции</Link></li>
<li><Link className="dropdown-item" to="/sales">Акции частым покупателям</Link></li>
</ul>
</li>
<li className="nav-item me-4"><Link to="/contacts" className="nav-link text-dark">Контакты</Link></li>
<li className="nav-item me-4"><Link to="/delivery" className="nav-link text-dark">Доставка</Link></li>
<li className="nav-item">
<Link to="/cart" className="nav-link text-dark">
<i className="bi bi-cart"></i> Корзина
{cartItemCount > 0 && <span className="badge bg-danger ms-1">{cartItemCount}</span>}
</Link>
</li>
</ul>
</div>
</div>
</nav>
</div>
</header>
);
}
export default Header;

View File

@@ -0,0 +1,131 @@
import React, { useState, useEffect } from 'react';
function ProductAddForm({ onProductAdded }) {
const [name, setName] = useState('');
const [price, setPrice] = useState('');
const [imageUrl, setImageUrl] = useState('');
const [brandId, setBrandId] = useState('');
const [categoryId, setCategoryId] = useState('');
const [brands, setBrands] = useState([]);
const [categories, setCategories] = useState([]);
const [error, setError] = useState(null);
const [success, setSuccess] = useState(false);
useEffect(() => {
fetch('/api/brands')
.then(res => res.json())
.then(setBrands)
.catch(console.error);
fetch('/api/categories')
.then(res => res.json())
.then(setCategories)
.catch(console.error);
}, []);
const handleSubmit = async (e) => {
e.preventDefault();
setError(null);
setSuccess(false);
const newProduct = {
name,
price: parseFloat(price),
image: imageUrl,
brandId,
categoryId
};
try {
const response = await fetch('/api/products', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(newProduct),
});
if (!response.ok) {
const errData = await response.json();
throw new Error(errData.message || `HTTP error! status: ${response.status}`);
}
setSuccess(true);
setName('');
setPrice('');
setImageUrl('');
setBrandId('');
setCategoryId('');
if (onProductAdded) {
onProductAdded();
}
} catch (err) {
setError(err.message);
console.error("Failed to add product:", err);
}
};
return (
<div className="container mt-4">
<h2>Добавление нового товара</h2>
{error && <div className="alert alert-danger">{error}</div>}
{success && <div className="alert alert-success">Товар успешно добавлен!</div>}
<form onSubmit={handleSubmit}>
<div className="mb-3">
<label htmlFor="productName" className="form-label">Название товара</label>
<input
type="text"
className="form-control"
id="productName"
value={name}
onChange={(e) => setName(e.target.value)}
required
/>
</div>
<div className="mb-3">
<label htmlFor="productPrice" className="form-label">Стоимость товара (руб.)</label>
<input
type="number"
className="form-control"
id="productPrice"
value={price}
onChange={(e) => setPrice(e.target.value)}
required
/>
</div>
<div className="mb-3">
<label htmlFor="brandSelect" className="form-label">Бренд</label>
<select className="form-select" id="brandSelect" value={brandId} onChange={(e) => setBrandId(e.target.value)} required>
<option value="">Выберите бренд</option>
{brands.map(brand => (
<option key={brand.id} value={brand.id}>{brand.name}</option>
))}
</select>
</div>
<div className="mb-3">
<label htmlFor="categorySelect" className="form-label">Категория</label>
<select className="form-select" id="categorySelect" value={categoryId} onChange={(e) => setCategoryId(e.target.value)} required>
<option value="">Выберите категорию</option>
{categories.map(category => (
<option key={category.id} value={category.id}>{category.name}</option>
))}
</select>
</div>
<div className="mb-3">
<label htmlFor="productImageUrl" className="form-label">URL картинки товара</label>
<input
type="url"
className="form-control"
id="productImageUrl"
value={imageUrl}
onChange={(e) => setImageUrl(e.target.value)}
required
/>
</div>
<button type="submit" className="btn btn-primary">Добавить товар</button>
</form>
</div>
);
}
export default ProductAddForm;

View File

@@ -0,0 +1,88 @@
import React, { useEffect, useState } from 'react';
function ProductCard({ product, onEdit, onDelete, onAddToCart }) {
const imageUrl = product.image ? product.image : 'https://via.placeholder.com/300x200.png?text=No+Image';
const regularPrice = parseFloat(product.price);
const discountPrice = product.discountPrice ? parseFloat(product.discountPrice) : null;
const [brand, setBrand] = useState(null);
const [category, setCategory] = useState(null);
const isOnSale = discountPrice !== null && discountPrice < regularPrice;
useEffect(() => {
fetch(`/api/brands/${product.brandId}`)
.then(res => res.json())
.then(setBrand)
.catch(console.error);
fetch(`/api/categories/${product.categoryId}`)
.then(res => res.json())
.then(setCategory)
.catch(console.error);
}, [product]);
return (
<div className="col">
<div className={`card h-100 ${isOnSale ? 'border-danger' : ''}`}>
{isOnSale && (
<span
className="position-absolute top-0 start-0 bg-danger text-white p-1 px-2"
style={{ fontSize: '0.8em', borderBottomRightRadius: '0.25rem' }}
>
Акция!
</span>
)}
<img
src={imageUrl}
className="card-img-top"
alt={product.name}
style={{ height: '200px', objectFit: 'cover' }}
onError={(e) => { e.target.onerror = null; e.target.src='https://via.placeholder.com/300x200.png?text=Image+Error'; }}
/>
<div className="card-body d-flex flex-column">
<h5 className="card-title">{product.name}</h5>
{brand && <p className="card-text"><strong>Бренд:</strong> {brand.name}</p>}
{category && <p className="card-text"><strong>Категория:</strong> {category.name}</p>}
<div>
{isOnSale ? (
<>
<p className="card-text text-danger fw-bold mb-0" style={{ fontSize: '1.2em' }}>
{discountPrice.toFixed(2)} руб.
</p>
<p className="card-text text-muted text-decoration-line-through" style={{ fontSize: '0.9em' }}>
{regularPrice.toFixed(2)} руб.
</p>
</>
) : (
<p className="card-text text-warning fw-bold">{regularPrice.toFixed(2)} руб.</p>
)}
</div>
<div className="mt-auto pt-2"> {}
<button
className="btn btn-warning w-100 mb-2"
onClick={() => onAddToCart(product)}
>
В корзину
</button>
<div className="d-flex justify-content-between">
<button
className="btn btn-outline-primary btn-sm"
onClick={() => onEdit(product)}
>
<i className="bi bi-pencil-square"></i> Редактировать
</button>
<button
className="btn btn-outline-danger btn-sm"
onClick={() => onDelete(product.id)}
>
<i className="bi bi-trash"></i> Удалить
</button>
</div>
</div>
</div>
</div>
</div>
);
}
export default ProductCard;

View File

@@ -0,0 +1,153 @@
import React, { useState, useEffect } from 'react';
function ProductEditForm({ product, onProductUpdated, onClose }) {
const [name, setName] = useState('');
const [price, setPrice] = useState('');
const [imageUrl, setImageUrl] = useState('');
const [brandId, setBrandId] = useState('');
const [categoryId, setCategoryId] = useState('');
const [brands, setBrands] = useState([]);
const [categories, setCategories] = useState([]);
const [error, setError] = useState(null);
const [success, setSuccess] = useState(false);
useEffect(() => {
if (product) {
setName(product.name || '');
setPrice(product.price || '');
setImageUrl(product.image || '');
setBrandId(product.brandId || '');
setCategoryId(product.categoryId || '');
setError(null);
setSuccess(false);
} else {
setName('');
setPrice('');
setImageUrl('');
setError(null);
setSuccess(false);
}
fetch('/api/brands').then(res => res.json()).then(setBrands).catch(console.error);
fetch('/api/categories').then(res => res.json()).then(setCategories).catch(console.error);
}, [product]);
const handleSubmit = async (e) => {
e.preventDefault();
setError(null);
setSuccess(false);
if (!product || !product.id) {
setError("Товар для редактирования не выбран.");
return;
}
const updatedProductData = {
name,
price: parseFloat(price),
image: imageUrl,
brandId,
categoryId
};
try {
const response = await fetch(`/api/products/${product.id}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(updatedProductData),
});
if (!response.ok) {
const errData = await response.json();
throw new Error(errData.message || `HTTP error! status: ${response.status}`);
}
setSuccess(true);
if (onProductUpdated) {
onProductUpdated();
}
} catch (err) {
setError(err.message);
console.error("Failed to update product:", err);
}
};
if (!product) return null;
return (
<div className="modal fade show d-block" tabIndex="-1" role="dialog" style={{backgroundColor: 'rgba(0,0,0,0.5)'}}>
<div className="modal-dialog modal-dialog-centered" role="document">
<div className="modal-content">
<div className="modal-header">
<h5 className="modal-title">Редактировать товар: {product.name}</h5>
<button type="button" className="btn-close" onClick={onClose} aria-label="Close"></button>
</div>
<div className="modal-body">
{error && <div className="alert alert-danger">{error}</div>}
{success && <div className="alert alert-success">Товар успешно обновлен!</div>}
<form onSubmit={handleSubmit}>
<div className="mb-3">
<label htmlFor="editProductName" className="form-label">Название товара</label>
<input
type="text"
className="form-control"
id="editProductName"
value={name}
onChange={(e) => setName(e.target.value)}
required
/>
</div>
<div className="mb-3">
<label htmlFor="editProductPrice" className="form-label">Стоимость товара (руб.)</label>
<input
type="number"
className="form-control"
id="editProductPrice"
value={price}
onChange={(e) => setPrice(e.target.value)}
required
/>
</div>
<div className="mb-3">
<label htmlFor="editBrand" className="form-label">Бренд</label>
<select className="form-select" id="editBrand" value={brandId} onChange={(e) => setBrandId(e.target.value)} required>
<option value="">Выберите бренд</option>
{brands.map(brand => (
<option key={brand.id} value={brand.id}>{brand.name}</option>
))}
</select>
</div>
<div className="mb-3">
<label htmlFor="editCategory" className="form-label">Категория</label>
<select className="form-select" id="editCategory" value={categoryId} onChange={(e) => setCategoryId(e.target.value)} required>
<option value="">Выберите категорию</option>
{categories.map(category => (
<option key={category.id} value={category.id}>{category.name}</option>
))}
</select>
</div>
<div className="mb-3">
<label htmlFor="editProductImageUrl" className="form-label">URL картинки товара</label>
<input
type="url"
className="form-control"
id="editProductImageUrl"
value={imageUrl}
onChange={(e) => setImageUrl(e.target.value)}
required
/>
</div>
<div className="modal-footer pb-0">
<button type="button" className="btn btn-secondary" onClick={onClose}>Отмена</button>
<button type="submit" className="btn btn-primary">Сохранить изменения</button>
</div>
</form>
</div>
</div>
</div>
</div>
);
}
export default ProductEditForm;

View File

@@ -0,0 +1,24 @@
import React from 'react';
import ProductCard from './ProductCard';
function ProductList({ products, onEdit, onDelete, onAddToCart }) {
if (!products || products.length === 0) {
return <p>Товары не найдены.</p>;
}
return (
<div className="row row-cols-1 row-cols-md-3 row-cols-lg-4 g-4">
{products.map(product => (
<ProductCard
key={product.id}
product={product}
onEdit={onEdit}
onDelete={onDelete}
onAddToCart={onAddToCart}
/>
))}
</div>
);
}
export default ProductList;

30
MasterOK/src/index.css Normal file
View File

@@ -0,0 +1,30 @@
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
monospace;
}
/* Basic App styling placeholder */
.App {
text-align: center;
}
.App-header {
background-color: #c79840;
min-height: 10vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-size: calc(10px + 2vmin);
color: white;
padding: 20px;
}

View File

@@ -1,111 +1,16 @@
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>МастерОК - Магазин инструментов</title>
<meta charset="UTF-8" />
<link rel="icon" type="image/png" href="./public/images/местерок.png" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>МастерОК - Интернет магазин инструментов</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css" rel="stylesheet">
<link rel="stylesheet" href="styles/style.css">
<link href="public/images/местерок.png" rel="shortcut icon">
<link href="https://fonts.googleapis.com/css2?family=Instrument+Sans&display=swap" rel="stylesheet">
<script type="module" src="scripts/controller.js"></script>
<script type="module" src="index.js"></script>
</head>
<body class="d-flex flex-column min-vh-100">
<header class="custom-header py-3">
<div class="container">
<nav class="navbar navbar-expand-lg navbar-dark">
<div class="container-fluid">
<div class="logo d-flex align-items-center">
<img src="public/images/местерок.png" alt="Логотип МастерОК" class="me-2" style="height: 50px;">
<a href="/" class="text-decoration-none text-white fs-4 fw-bold">МастерОК</a>
</div>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav ms-auto mb-2 mb-lg-0">
<li class="nav-item me-4"><a href="add.html" class="nav-link text-white">Добавить</a></li>
<li class="nav-item dropdown me-4">
<div class="d-flex align-items-center">
<a href="sale.html" class="nav-link text-white">Акции</a>
<span class="nav-link text-white dropdown-toggle-arrow" data-bs-toggle="dropdown"></span>
<ul class="dropdown-menu">
<li><a class="dropdown-item" href="#">Подарок папе</a></li>
<li><a class="dropdown-item" href="#">Супер цены</a></li>
<li><a class="dropdown-item" href="#">Постоянным клиентам</a></li>
</ul>
</div>
</li>
<li class="nav-item me-4"><a href="contacts.html" class="nav-link text-white">Контакты</a></li>
<li class="nav-item me-4"><a href="delivery.html" class="nav-link text-white">Доставка</a></li>
<li class="nav-item">
<a href="basket.html" class="nav-link text-white">
<i class="bi bi-cart"></i> Корзина
</a>
</li>
</ul>
</div>
</div>
</nav>
</div>
</header>
<div class="accordion accordion-flush" id="accordionFlushExample">
<div class="accordion-item">
<h2 class="accordion-header" id="flush-headingOne">
<button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#flush-collapseOne" aria-expanded="false" aria-controls="flush-collapseOne">
Форма добавления товара
</button>
</h2>
<div id="flush-collapseOne" class="accordion-collapse collapse" aria-labelledby="flush-headingOne" data-bs-parent="#accordionFlushExample">
<div class="accordion-body">
<form id="addProductForm">
<div class="mb-3">
<label for="productName" class="form-label">Название товара</label>
<input type="text" class="form-control" id="productName" required>
</div>
<div class="mb-3">
<label for="productPrice" class="form-label">Стоимость товара</label>
<input type="number" class="form-control" id="productPrice" required>
</div>
<div class="mb-3">
<label for="productImageUrl" class="form-label">URL картинки товара</label>
<input type="url" class="form-control" id="productImageUrl" required>
</div>
<button type="submit" class="btn btn-primary">Добавить товар</button>
</form>
</div>
</div>
</div>
</div>
<main class="flex-grow-1 py-4">
<section class="container">
<div class="row row-cols-1 row-cols-md-3 row-cols-lg-4 g-4 product-list">
</div>
</section>
</main>
<footer class="bg-dark text-white py-4">
<div class="container">
<div class="row text-center text-md-start">
<div class="col-md-6 mb-4 mb-md-0">
<h3>Контактная информация</h3>
<p>Адрес: г. Ульяновск, ул. Северный венец, д. 32, к. 3</p>
<p>Телефон: +7 (999) 99-99-90</p>
<p>Email: masterok@mail.ru</p>
</div>
<div class="col-md-6 text-md-end">
<h3>Мы в соцсетях</h3>
<a href="https://t.me/" target="_blank" class="me-2">
<img src="public/images/tg.png" alt="Telegram" style="width: 32px;">
</a>
<a href="https://vk.com/" target="_blank">
<img src="public/images/vk.png" alt="VK" style="width: 32px;">
</a>
</div>
</div>
</div>
</footer>
<body>
<div id="root"></div>
<script type="module" src="/main.jsx"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>

View File

@@ -1,101 +0,0 @@
import { addToCart, updateCartDisplay } from './scripts/cart.js';
document.addEventListener('DOMContentLoaded', () => {
const addToCartButtons = document.querySelectorAll('.btn.btn-primary.add-to-cart-btn');
const cart = JSON.parse(localStorage.getItem('cart')) || [];
addToCartButtons.forEach(button => {
button.addEventListener('click', addToCart);
const productId = button.getAttribute('data-id');
const isInCart = cart.some(item => item.id === productId);
if (isInCart) {
button.textContent = 'В корзине';
button.classList.add('added-to-cart');
button.disabled = true;
}
});
if (window.location.pathname.includes('basket.html')) {
updateCartDisplay();
const checkoutButton = document.getElementById('checkout-btn');
if (checkoutButton) {
checkoutButton.addEventListener('click', () => {
const cart = JSON.parse(localStorage.getItem('cart')) || [];
const totalPrice = cart.reduce((sum, item) => sum + item.price * item.quantity, 0);
const modalTotalPrice = document.getElementById('modal-total-price');
if (modalTotalPrice) {
modalTotalPrice.textContent = totalPrice.toFixed(2);
}
const checkoutModal = new bootstrap.Modal(document.getElementById('checkoutModal'));
checkoutModal.show();
});
}
const checkoutForm = document.getElementById('checkoutForm');
if (checkoutForm) {
checkoutForm.addEventListener('submit', (event) => {
event.preventDefault();
const firstName = document.getElementById('firstName').value;
const lastName = document.getElementById('lastName').value;
const phone = document.getElementById('phone').value;
if (!firstName || !lastName || !phone) {
alert('Пожалуйста, заполните все поля!');
return;
}
const order = {
firstName,
lastName,
phone,
cart: JSON.parse(localStorage.getItem('cart')) || [],
totalPrice: document.getElementById('modal-total-price').textContent
};
console.log('Заказ оформлен:', order);
localStorage.removeItem('cart');
const checkoutModal = bootstrap.Modal.getInstance(document.getElementById('checkoutModal'));
checkoutModal.hide();
alert('Заказ успешно оформлен! Спасибо за покупку!');
updateCartDisplay();
});
}
}
document.getElementById('addProductForm').addEventListener('submit', function(event) {
event.preventDefault();
const productName = document.getElementById('productName').value;
const productPrice = document.getElementById('productPrice').value;
const productImageUrl = document.getElementById('productImageUrl').value;
const newProductCard = document.createElement('div');
newProductCard.className = 'col';
newProductCard.innerHTML = `
<div class="card h-100">
<img src="${productImageUrl}" class="card-img-top" alt="${productName}" width="200" height="300">
<div class="card-body">
<h5 class="card-title">${productName}</h5>
<p class="card-text text-warning fw-bold">${productPrice} руб.</p>
<button class="btn btn-warning" data-id="${Date.now()}" data-name="${productName}" data-price="${productPrice}">В корзину</button>
</div>
</div>
`;
document.querySelector('.row.row-cols-1.row-cols-md-3.row-cols-lg-4.g-4').appendChild(newProductCard);
document.getElementById('addProductForm').reset();
});
});

13
MasterOK/src/main.jsx Normal file
View File

@@ -0,0 +1,13 @@
import React from 'react';
import ReactDOM from 'react-dom/client';
import { BrowserRouter } from 'react-router-dom';
import App from './App.jsx';
import './index.css';
ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
</React.StrictMode>,
);

View File

@@ -0,0 +1,24 @@
import React from 'react';
import ProductAddForm from '../components/ProductAddForm';
import { useNavigate } from 'react-router-dom';
function AddProductPage({ onProductAdded }) {
const navigate = useNavigate();
const handleFormSubmitted = () => {
if (onProductAdded) {
onProductAdded();
}
navigate('/');
};
return (
<div>
<ProductAddForm onProductAdded={handleFormSubmitted} />
</div>
);
}
export default AddProductPage;

View File

@@ -0,0 +1,168 @@
import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
function CartPage({ cart, setCart }) {
const [firstName, setFirstName] = useState('');
const [lastName, setLastName] = useState('');
const [phone, setPhone] = useState('');
const handleRemoveFromCart = (productId) => {
setCart(prevCart => prevCart.filter(item => item.id !== productId));
};
const handleUpdateQuantity = (productId, newQuantity) => {
if (newQuantity < 1) {
handleRemoveFromCart(productId);
return;
}
setCart(prevCart =>
prevCart.map(item =>
item.id === productId ? { ...item, quantity: newQuantity } : item
)
);
};
const calculateTotalPrice = () => {
return cart.reduce((total, item) => {
const price = parseFloat(item.discountPrice && parseFloat(item.discountPrice) < parseFloat(item.price) ? item.discountPrice : item.price);
return total + price * item.quantity;
}, 0).toFixed(2);
};
const handleCheckoutSubmit = (event) => {
event.preventDefault();
const orderDetails = {
customer: {
firstName,
lastName,
phone,
},
items: cart,
total: calculateTotalPrice(),
orderDate: new Date().toISOString(),
};
console.log("Новый заказ:", orderDetails);
alert("Спасибо за ваш заказ! Ваш заказ успешно оформлен.");
setFirstName('');
setLastName('');
setPhone('');
setCart([]);
const modalElement = document.getElementById('checkoutModal');
if (modalElement && window.bootstrap) {
const modalInstance = window.bootstrap.Modal.getInstance(modalElement);
if (modalInstance) {
modalInstance.hide();
}
}
};
if (!cart || cart.length === 0) {
return (
<div className="text-center">
<h1>Корзина пуста</h1>
<p>Похоже, вы еще ничего не добавили в корзину.</p>
<Link to="/" className="btn btn-primary">К товарам</Link>
</div>
);
}
return (
<div>
<h1 className="mb-4">Ваша корзина</h1>
<div className="list-group mb-4">
{cart.map(item => {
const itemPrice = parseFloat(item.discountPrice && parseFloat(item.discountPrice) < parseFloat(item.price) ? item.discountPrice : item.price);
return (
<div key={item.id} className="list-group-item list-group-item-action flex-column align-items-start">
<div className="row">
<div className="col-md-2 col-lg-1 mb-2 mb-md-0">
<img src={item.image || 'https://via.placeholder.com/100x100.png?text=No+Image'} alt={item.name} className="img-fluid rounded" style={{maxHeight: '75px', objectFit: 'contain'}}/>
</div>
<div className="col-md-5 col-lg-6">
<h5 className="mb-1">{item.name}</h5>
<p className="mb-1 text-muted" style={{fontSize: '0.9em'}}>Цена: {itemPrice.toFixed(2)} руб.</p>
</div>
<div className="col-md-3 col-lg-3 d-flex align-items-center">
<button
className="btn btn-outline-secondary btn-sm me-2"
onClick={() => handleUpdateQuantity(item.id, item.quantity - 1)}
disabled={item.quantity <= 1} // Disable if quantity is 1 to prevent going below 1 (remove instead)
>
-
</button>
<span>{item.quantity}</span>
<button
className="btn btn-outline-secondary btn-sm ms-2"
onClick={() => handleUpdateQuantity(item.id, item.quantity + 1)}
>
+
</button>
</div>
<div className="col-md-2 col-lg-2 d-flex align-items-center justify-content-end">
<button
className="btn btn-danger btn-sm"
onClick={() => handleRemoveFromCart(item.id)}
>
<i className="bi bi-trash"></i> Удалить
</button>
</div>
</div>
<div className="row mt-2">
<div className="col text-end">
<strong>Сумма по товару: {(itemPrice * item.quantity).toFixed(2)} руб.</strong>
</div>
</div>
</div>
);
})}
</div>
<div className="d-flex justify-content-end align-items-center mb-3">
<h3>Итого: {calculateTotalPrice()} руб.</h3>
</div>
<div className="d-flex justify-content-end">
<Link to="/" className="btn btn-outline-secondary me-2">Продолжить покупки</Link>
<button className="btn btn-primary" data-bs-toggle="modal" data-bs-target="#checkoutModal">
Оформить заказ
</button>
</div>
<div className="modal fade" id="checkoutModal" tabIndex="-1" aria-labelledby="checkoutModalLabel" aria-hidden="true">
<div className="modal-dialog modal-dialog-centered">
<div className="modal-content">
<div className="modal-header">
<h5 className="modal-title" id="checkoutModalLabel">Оформление заказа</h5>
<button type="button" className="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div className="modal-body">
<p>Общая сумма заказа: <strong>{calculateTotalPrice()}</strong> руб.</p>
{/* Attach onSubmit to the form and manage input values with state */}
<form id="checkoutForm" onSubmit={handleCheckoutSubmit}>
<div className="mb-3">
<label htmlFor="firstName" className="form-label">Имя</label>
<input type="text" className="form-control" id="firstName" value={firstName} onChange={e => setFirstName(e.target.value)} required />
</div>
<div className="mb-3">
<label htmlFor="lastName" className="form-label">Фамилия</label>
<input type="text" className="form-control" id="lastName" value={lastName} onChange={e => setLastName(e.target.value)} required />
</div>
<div className="mb-3">
<label htmlFor="phone" className="form-label">Телефон</label>
<input type="tel" className="form-control" id="phone" value={phone} onChange={e => setPhone(e.target.value)} required />
</div>
<div className="modal-footer">
<button type="button" className="btn btn-secondary" data-bs-dismiss="modal">Отмена</button>
<button type="submit" className="btn btn-primary">Подтвердить заказ</button> { /* form attribute is no longer strictly needed but harmless */}
</div>
</form>
</div>
</div>
</div>
</div>
</div>
);
}
export default CartPage;

View File

@@ -0,0 +1,39 @@
import React from 'react';
function ContactsPage() {
return (
<main class="py-4">
<div class="container">
<h1 class="text-center mb-4">Контакты</h1>
<div class="card mb-4">
<div class="card-body">
<h2 class="card-title">Оформить заказ и узнать наличие</h2>
<p class="card-text"><i class="bi bi-telephone"></i> +7 (8422) 99-99-90</p>
<p class="card-text">ПН - ВС: 8:00 - 20:00</p>
<p class="card-text"><i class="bi bi-envelope"></i> <a href="mailto:masterok@mail.ru">masterok@mail.ru</a></p>
</div>
</div>
<div class="card mb-4">
<div class="card-body">
<h2 class="card-title">Обратная связь</h2>
<p class="card-text">Оставьте свои вопросы, пожелания и комментарии</p>
<a href="#" class="btn btn-warning">НАПИСАТЬ</a>
</div>
</div>
<div class="card">
<div class="card-body">
<h2 class="card-title">Реквизиты</h2>
<p class="card-text">Наименование: ООО «МастерОК»</p>
<p class="card-text"><i class="bi bi-house-door"></i> Адрес: г. Ульяновск, ул. Северный венец, д. 32, к. 3</p>
<p class="card-text">ИНН: 6666666666</p>
<p class="card-text">ОГРН: 1111111111111</p>
<p class="card-text">КПП: 666666666</p>
<p class="card-text">Расчетный счет: 40702810154400028559</p>
</div>
</div>
</div>
</main>
);
}
export default ContactsPage;

View File

@@ -0,0 +1,47 @@
import React from 'react';
function DeliveryPage() {
return (
<main class="py-4">
<div class="container">
<h1 class="text-center mb-4">Доставка</h1>
<div class="card mb-4">
<div class="card-body">
<h3 class="card-title">Шаг 1: Выберите товар</h3>
<p class="card-text">Перейдите в каталог нашего магазина и выберите нужный товар. Добавьте его в корзину.</p>
</div>
</div>
<div class="card mb-4">
<div class="card-body">
<h3 class="card-title">Шаг 2: Оформите заказ</h3>
<p class="card-text">Перейдите в корзину и нажмите на кнопку "Оформить заказ". Заполните необходимые данные для доставки.</p>
</div>
</div>
<div class="card mb-4">
<div class="card-body">
<h3 class="card-title">Шаг 3: Оплатите заказ</h3>
<p class="card-text">Выберите удобный способ оплаты и завершите процесс оплаты. После подтверждения оплаты ваш заказ будет обработан.</p>
</div>
</div>
<div class="card mb-4">
<div class="card-body">
<h3 class="card-title">Шаг 4: Получите заказ</h3>
<p class="card-text">После обработки заказа мы отправим его вам. Вы получите уведомление о доставке с номером для отслеживания.</p>
</div>
</div>
<div class="card">
<div class="card-body">
<h2 class="card-title">Способы оплаты</h2>
<ul class="list-unstyled">
<li><i class="bi bi-check2"></i> Банковская карта (Visa, MasterCard, Мир)</li>
<li><i class="bi bi-check2"></i> Электронные кошельки (WebMoney, Яндекс.Деньги)</li>
<li><i class="bi bi-check2"></i> Наложенный платеж (оплата при получении)</li>
</ul>
</div>
</div>
</div>
</main>
);
}
export default DeliveryPage;

View File

@@ -0,0 +1,86 @@
import React, { useEffect, useState } from 'react';
import ProductList from '../components/ProductList';
function HomePage(props) {
const {
products,
loading,
error,
onEditProduct,
onDeleteProduct,
onAddToCart,
fetchProducts
} = props;
const [sortedProducts, setSortedProducts] = useState([]);
const [sortOrder, setSortOrder] = useState('asc');
const [selectedCategoryId, setSelectedCategoryId] = useState('all');
const [categories, setCategories] = useState([]);
useEffect(() => {
fetch('http://localhost:3000/categories')
.then(res => res.json())
.then(data => setCategories([{ id: 'all', name: 'Все категории' }, ...data]))
.catch(err => console.error('Ошибка при загрузке категорий:', err));
}, []);
useEffect(() => {
let filtered = selectedCategoryId === 'all'
? products
: products.filter(p => p.categoryId === selectedCategoryId);
setSortedProducts(filtered);
}, [products, selectedCategoryId]);
const handleSortByPrice = () => {
const sorted = [...sortedProducts].sort((a, b) =>
sortOrder === 'asc' ? a.price - b.price : b.price - a.price
);
setSortedProducts(sorted);
setSortOrder(prev => (prev === 'asc' ? 'desc' : 'asc'));
};
const handleCategoryChange = (e) => {
setSelectedCategoryId(e.target.value);
};
return (
<div>
<h2 className="mb-4">Товары</h2>
<button className="btn btn-outline-secondary mb-4" onClick={handleSortByPrice}>
Сортировать по цене ({sortOrder === 'asc' ? 'возр.' : 'убыв.'})
</button>
<div className="mb-3">
<label htmlFor="categoryFilter" className="form-label">Фильтр по категории:</label>
<select
id="categoryFilter"
className="form-select"
value={selectedCategoryId}
onChange={handleCategoryChange}
>
{categories.map((cat) => (
<option key={cat.id} value={cat.id}>
{cat.name}
</option>
))}
</select>
</div>
{loading && <p>Загрузка товаров...</p>}
{error && (
<div className="alert alert-danger">
Ошибка: {error}
<button onClick={fetchProducts} className='btn btn-sm btn-link'>Попробовать снова</button>
</div>
)}
{!loading && !error && (
<ProductList
products={sortedProducts}
onEdit={onEditProduct}
onDelete={onDeleteProduct}
onAddToCart={onAddToCart}
/>
)}
</div>
);
}
export default HomePage;

View File

@@ -0,0 +1,14 @@
import React from 'react';
import { Link } from 'react-router-dom';
function NotFoundPage() {
return (
<div className="text-center mt-5">
<h1>404 - Страница не найдена</h1>
<p>Извините, запрашиваемая вами страница не существует.</p>
<Link to="/" className="btn btn-primary">На главную</Link>
</div>
);
}
export default NotFoundPage;

View File

@@ -0,0 +1,75 @@
import React, { useState, useEffect, useCallback } from 'react';
import ProductList from '../components/ProductList';
function SalesPage({ products, loading, error, onEditProduct, onDeleteProduct, onAddToCart, fetchProducts }) {
const [saleProducts, setSaleProducts] = useState([]);
useEffect(() => {
if (products && products.length > 0) {
const filtered = products.filter(p => {
const regularPrice = parseFloat(p.price);
const discountPrice = p.discountPrice ? parseFloat(p.discountPrice) : null;
return discountPrice !== null && discountPrice < regularPrice;
});
setSaleProducts(filtered);
}
}, [products]);
return (
<main class="flex-grow-1 py-4">
<div class="container">
<h2 className="mb-4">Текущие</h2>
<div class="row row-cols-1 row-cols-md-2 row-cols-lg-3 g-4">
<div class="col">
<div class="card h-100">
<img src="public/images/акциямасла.jpg" class="card-img-top" alt="GNV Акция"/>
<div class="card-body">
<h5 class="card-title">Подарок при покупке моторного масла GNV</h5>
<p class="card-text">Действует до 20 февраля 2025</p>
</div>
</div>
</div>
<div class="col">
<div class="card h-100">
<img src="public/images/акция23февраля.jpg" class="card-img-top" alt="Подарок папе"/>
<div class="card-body">
<h5 class="card-title">Подарок папе</h5>
<p class="card-text">Действует до 23 февраля 2025</p>
</div>
</div>
</div>
<div class="col">
<div class="card h-100">
<img src="public/images/акциямакита.jpg" class="card-img-top" alt="Makita Акция"/>
<div class="card-body">
<h5 class="card-title">Подарок при покупке инструмента Makita</h5>
<p class="card-text">Действует до 24 февраля 2025</p>
</div>
</div>
</div>
<div class="col">
<div class="card h-100">
<img src="public/images/акциястанки.jpg" class="card-img-top" alt="BELMASH Акция"/>
<div class="card-body">
<h5 class="card-title">Супер цены на станки BELMASH</h5>
<p class="card-text">Действует до 28 февраля 2025</p>
</div>
</div>
</div>
<div class="col">
<div class="card h-100">
<img src="public/images/масло.jpg" class="card-img-top" alt="Масло Акция"/>
<div class="card-body">
<h5 class="card-title">Масло в подарок при покупке компрессора</h5>
<p class="card-text">Действует до 1 марта 2025</p>
</div>
</div>
</div>
</div>
</div>
</main>
);
}
export default SalesPage;

View File

@@ -1,7 +1,9 @@
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import { resolve } from "path";
export default defineConfig({
plugins: [react()],
root: "src",
build: {
rollupOptions: {

Binary file not shown.

BIN
Отчет_6.docx Normal file

Binary file not shown.