Compare commits

...

25 Commits

Author SHA1 Message Date
5d066c96c9 Set orderDate to orderDateInput 2026-01-04 23:31:13 +03:00
91f18a6a9a Move item to another order 2026-01-04 22:14:28 +03:00
74e7dc8fd5 Russian describtion of errors 2026-01-04 21:53:47 +03:00
1f542c65ab Update README.md 2026-01-03 22:58:14 +03:00
18999515b2 Merge pull request 'Docker' (#3) from Docker into master
Reviewed-on: #3
2026-01-03 18:46:21 +01:00
23c67c9e6e Fix button logic 2026-01-03 20:41:15 +03:00
75df8970fd Move client and server dockerfile to special path 2026-01-03 19:54:48 +03:00
8b0fa219aa Update README.md 2026-01-03 19:50:42 +03:00
22b592e3ef Remove slnx from project 2026-01-03 19:50:34 +03:00
151c98e994 Server 2026-01-03 19:47:01 +03:00
8c9ea53964 Nginx 2026-01-03 19:46:45 +03:00
c6c3cf2227 env file for Docker 2026-01-03 19:44:35 +03:00
ec2531cacb Initial sql for MariaDB 2026-01-03 19:44:22 +03:00
fab2dd6ac9 Merge pull request 'Client' (#2) from Client into master
Reviewed-on: #2
2026-01-03 16:50:30 +01:00
7b0a6c9f37 Merge branch 'master' into Client 2026-01-03 16:50:19 +01:00
94b0216568 Merge branch 'master' of ssh://git.tjoyspotifylastfm.ru:10022/ParkSuMin/DELIVER_MAN 2026-01-03 18:36:43 +03:00
62ecf92ce7 Update package-lock.json 2026-01-03 18:36:37 +03:00
f3d834574b Beautify HTML 2026-01-03 18:34:47 +03:00
08ddf65ec1 Switch-construction in click 2026-01-03 18:33:53 +03:00
cd1f3a1e87 Beautify 2026-01-03 18:22:36 +03:00
25a92e4b98 Switch ID 2026-01-03 18:21:09 +03:00
78ddbb4601 Merge pull request 'API' (#1) from API into master
Reviewed-on: #1
2026-01-03 16:18:52 +01:00
13fe841e54 Database 2026-01-03 18:17:29 +03:00
58b88c05a7 CORS problem resolve 2026-01-03 18:16:18 +03:00
85d1a9f046 API check 2026-01-03 18:15:52 +03:00
14 changed files with 2739 additions and 1377 deletions

5
.dockerignore Normal file
View File

@@ -0,0 +1,5 @@
node_modules
.git
.gitignore
.gitattributes
README.md

View File

@@ -1,6 +0,0 @@
<Solution>
<Project Path="DELIVER_MAN.esproj">
<Build />
<Deploy />
</Project>
</Solution>

View File

@@ -1 +1,24 @@
# DELIVER_MAN # DELIVER_MAN
## Core Functionality
- View product inventory with current stock levels.
- Create orders with customer name and order date.
- Edit order details (customer name, date) and delete orders.
- Add items to orders, update item quantities or products, and remove items.
- Move items between orders.
- Prevent overselling by validating stock on add/update.
## Run via Docker
Run client + server + database:
```bash
docker compose up --build
```
Open the client at `http://localhost:8080`.
Notes:
- The API is proxied through the client container to the server at `/api`.
- The MariaDB schema/data is auto-initialized from `docker/init.sql` on first run.

60
docker-compose.yml Normal file
View File

@@ -0,0 +1,60 @@
services:
db:
image: mariadb:11.4
environment:
MARIADB_DATABASE: delivery
MARIADB_USER: app
MARIADB_PASSWORD: app
MARIADB_ROOT_PASSWORD: root
volumes:
- db_data:/var/lib/mysql
- ./docker/init.sql:/docker-entrypoint-initdb.d/init.sql:ro
networks:
- backend
healthcheck:
test: ["CMD", "mariadb-admin", "ping", "-h", "localhost", "-u", "root", "-proot"]
interval: 10s
timeout: 5s
retries: 5
server:
build:
context: .
dockerfile: docker/Dockerfile.server
environment:
HOST: db
PORT: 3306
DATABASE: delivery
USER: app
PASSWORD: app
depends_on:
db:
condition: service_healthy
networks:
- backend
- frontend
healthcheck:
test: ["CMD", "node", "-e", "fetch('http://localhost:3000/api/current-date').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"]
interval: 10s
timeout: 5s
retries: 5
client:
build:
context: .
dockerfile: docker/Dockerfile.client
depends_on:
server:
condition: service_healthy
ports:
- "8080:80"
networks:
- frontend
volumes:
db_data:
networks:
backend:
internal: true
frontend:

4
docker/Dockerfile.client Normal file
View File

@@ -0,0 +1,4 @@
FROM nginx:1.27-alpine
COPY docker/nginx.conf /etc/nginx/conf.d/default.conf
COPY public /usr/share/nginx/html

13
docker/Dockerfile.server Normal file
View File

@@ -0,0 +1,13 @@
FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY server ./server
ENV NODE_ENV=production
EXPOSE 3000
CMD ["npm", "start"]

105
docker/init.sql Normal file
View File

@@ -0,0 +1,105 @@
/*M!999999\- enable the sandbox mode */
-- MariaDB dump 10.19-11.7.2-MariaDB, for Win64 (AMD64)
--
-- Host: localhost Database: delivery
-- ------------------------------------------------------
-- Server version 12.1.2-MariaDB
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*M!100616 SET @OLD_NOTE_VERBOSITY=@@NOTE_VERBOSITY, NOTE_VERBOSITY=0 */;
--
-- Table structure for table `order_items`
--
DROP TABLE IF EXISTS `order_items`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8mb4 */;
CREATE TABLE `order_items` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`order_id` varchar(256) DEFAULT NULL,
`product_id` varchar(256) DEFAULT NULL,
`quantity` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `order_items_orders_FK` (`order_id`),
KEY `order_items_products_FK` (`product_id`),
CONSTRAINT `order_items_orders_FK` FOREIGN KEY (`order_id`) REFERENCES `orders` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `order_items_products_FK` FOREIGN KEY (`product_id`) REFERENCES `products` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_uca1400_ai_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `order_items`
--
LOCK TABLES `order_items` WRITE;
/*!40000 ALTER TABLE `order_items` DISABLE KEYS */;
/*!40000 ALTER TABLE `order_items` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `orders`
--
DROP TABLE IF EXISTS `orders`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8mb4 */;
CREATE TABLE `orders` (
`id` varchar(256) NOT NULL,
`customer_name` varchar(256) DEFAULT NULL,
`order_date` date DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_uca1400_ai_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `products`
--
DROP TABLE IF EXISTS `products`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8mb4 */;
CREATE TABLE `products` (
`id` varchar(256) NOT NULL,
`name` varchar(256) NOT NULL,
`quantity` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_uca1400_ai_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `products`
--
LOCK TABLES `products` WRITE;
/*!40000 ALTER TABLE `products` DISABLE KEYS */;
INSERT INTO `products` VALUES
('QH-1','Отвёртки',30),
('QH-3','Гайки',13),
('QW-1','Молоток',32),
('QW-2','Гвозди',65);
/*!40000 ALTER TABLE `products` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Dumping routines for database 'delivery'
--
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*M!100616 SET NOTE_VERBOSITY=@OLD_NOTE_VERBOSITY */;
-- Dump completed on 2026-01-03 18:57:33

19
docker/nginx.conf Normal file
View File

@@ -0,0 +1,19 @@
server {
listen 80;
server_name _;
root /usr/share/nginx/html;
index index.html;
location /api/ {
proxy_pass http://server:3000;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
location / {
try_files $uri $uri/ /index.html;
}
}

2489
package-lock.json generated

File diff suppressed because it is too large Load Diff

625
public/app.js Normal file
View File

@@ -0,0 +1,625 @@
const notification = document.getElementById('notification');
const currentDateEl = document.getElementById('current-date');
const orderDateInput = document.getElementById('order-date');
const customerNameInput = document.getElementById('customer-name');
const orderForm = document.getElementById('order-form');
const ordersContainer = document.getElementById('orders');
const inventoryList = document.getElementById('inventory');
const advanceButton = document.getElementById('advance-date');
const API_BASE =
window.location.protocol === 'file:' ? 'http://localhost:3000' : window.location.origin;
let products = [];
let orders = [];
let currentDate = '';
function getLocalISODate() {
const now = new Date();
const offsetMs = now.getTimezoneOffset() * 60 * 1000;
return new Date(now.getTime() - offsetMs).toISOString().slice(0, 10);
}
class OrderCard {
constructor(order, allOrders, allProducts) {
this.order = order;
this.orders = allOrders;
this.products = allProducts;
}
build() {
const card = document.createElement('div');
card.className = 'card shadow-sm order-card';
const body = document.createElement('div');
body.className = 'card-body';
body.appendChild(this.buildHeader());
body.appendChild(this.buildItemsSection());
card.appendChild(body);
return card;
}
buildHeader() {
const header = document.createElement('div');
header.className = 'd-flex justify-content-between flex-wrap gap-2';
const info = document.createElement('div');
const name = document.createElement('h3');
name.className = 'h5 mb-1';
name.textContent = this.order.customer_name;
const idMeta = document.createElement('div');
idMeta.className = 'text-muted order-meta';
idMeta.textContent = `ID: ${this.order.id}`;
const dateMeta = document.createElement('div');
dateMeta.className = 'text-muted order-meta';
dateMeta.textContent = `Дата: ${this.order.order_date}`;
info.appendChild(name);
info.appendChild(idMeta);
info.appendChild(dateMeta);
const actions = document.createElement('div');
actions.className = 'd-flex gap-2 align-items-start';
actions.appendChild(this.buildButton('Изменить', 'btn-outline-secondary', {
action: 'edit-order',
id: this.order.id
}));
actions.appendChild(this.buildButton('Удалить', 'btn-outline-danger', {
action: 'delete-order',
id: this.order.id
}));
header.appendChild(info);
header.appendChild(actions);
return header;
}
buildItemsSection() {
const wrapper = document.createElement('div');
wrapper.className = 'mt-3';
wrapper.appendChild(this.buildItemsTable());
wrapper.appendChild(this.buildAddItemForm());
return wrapper;
}
buildItemsTable() {
const table = document.createElement('table');
table.className = 'table table-sm align-middle';
table.innerHTML = `
<thead>
<tr>
<th>ID</th>
<th>Товар</th>
<th>Количество</th>
<th class="text-end">Действия</th>
</tr>
</thead>
`;
const body = document.createElement('tbody');
this.order.items.forEach((item) => {
body.appendChild(this.buildItemRow(item));
});
table.appendChild(body);
return table;
}
buildItemRow(item) {
const row = document.createElement('tr');
const idCell = document.createElement('td');
idCell.className = 'text-muted small';
idCell.textContent = item.product_id ?? item.id;
const productCell = document.createElement('td');
const productSelect = this.buildProductSelect(item.product_id);
productSelect.classList.add('form-select-sm');
productSelect.dataset.action = 'item-product';
productSelect.dataset.itemId = item.id;
productSelect.setAttribute('aria-label', 'Товар');
productCell.appendChild(productSelect);
const quantityCell = document.createElement('td');
const quantityInput = document.createElement('input');
quantityInput.type = 'number';
quantityInput.min = '1';
quantityInput.className = 'form-control form-control-sm';
quantityInput.value = item.quantity;
quantityInput.dataset.action = 'item-quantity';
quantityInput.dataset.itemId = item.id;
quantityInput.setAttribute('aria-label', 'Количество');
quantityCell.appendChild(quantityInput);
const actionsCell = document.createElement('td');
actionsCell.className = 'text-end item-actions';
actionsCell.appendChild(this.buildItemActionButtons(item));
actionsCell.appendChild(this.buildMoveControls(item));
row.appendChild(idCell);
row.appendChild(productCell);
row.appendChild(quantityCell);
row.appendChild(actionsCell);
return row;
}
buildItemActionButtons(item) {
const wrapper = document.createElement('div');
wrapper.className = 'd-flex gap-2 justify-content-end';
wrapper.appendChild(
this.buildButton('Сохранить', 'btn-outline-primary', {
action: 'save-item',
orderId: this.order.id,
itemId: item.id
})
);
wrapper.appendChild(
this.buildButton('Удалить', 'btn-outline-danger', {
action: 'delete-item',
orderId: this.order.id,
itemId: item.id
})
);
return wrapper;
}
buildMoveControls(item) {
const wrapper = document.createElement('div');
wrapper.className = 'd-flex gap-2 justify-content-end mt-2';
const select = document.createElement('select');
select.className = 'form-select form-select-sm';
select.dataset.action = 'move-target';
select.dataset.itemId = item.id;
select.setAttribute('aria-label', 'Выбор заказа для перемещения');
const placeholder = document.createElement('option');
placeholder.value = '';
placeholder.textContent = 'Переместить в...';
select.appendChild(placeholder);
this.orders
.filter((otherOrder) => otherOrder.id !== this.order.id)
.forEach((otherOrder) => {
const option = document.createElement('option');
option.value = otherOrder.id;
option.textContent = otherOrder.customer_name;
select.appendChild(option);
});
wrapper.appendChild(select);
wrapper.appendChild(
this.buildButton('Перенести', 'btn-outline-secondary', {
action: 'move-item',
itemId: item.id
})
);
return wrapper;
}
buildAddItemForm() {
const form = document.createElement('form');
form.className = 'row g-2 align-items-end';
form.dataset.action = 'add-item';
form.dataset.orderId = this.order.id;
const productCol = document.createElement('div');
productCol.className = 'col-md-6';
const productLabel = document.createElement('label');
productLabel.className = 'form-label';
productLabel.textContent = 'Товар';
const usedProductIds = new Set(
(this.order.items || [])
.map((item) => item.product_id)
.filter((value) => value !== null && value !== undefined)
);
const productSelect = this.buildProductSelect(undefined, usedProductIds);
const productSelectId = `add-item-product-${this.order.id}`;
productSelect.name = 'productId';
productSelect.id = productSelectId;
productLabel.htmlFor = productSelectId;
productCol.appendChild(productLabel);
productCol.appendChild(productSelect);
const quantityCol = document.createElement('div');
quantityCol.className = 'col-md-3';
const quantityLabel = document.createElement('label');
quantityLabel.className = 'form-label';
quantityLabel.textContent = 'Кол-во';
const quantityInput = document.createElement('input');
const quantityInputId = `add-item-quantity-${this.order.id}`;
quantityInput.type = 'number';
quantityInput.min = '1';
quantityInput.className = 'form-control';
quantityInput.name = 'quantity';
quantityInput.id = quantityInputId;
quantityLabel.htmlFor = quantityInputId;
quantityInput.required = true;
quantityCol.appendChild(quantityLabel);
quantityCol.appendChild(quantityInput);
const actionCol = document.createElement('div');
actionCol.className = 'col-md-3';
const addButton = document.createElement('button');
addButton.type = 'submit';
addButton.className = 'btn btn-success w-100';
addButton.textContent = 'Добавить позицию';
actionCol.appendChild(addButton);
if (productSelect.options.length === 0) {
const placeholder = document.createElement('option');
placeholder.value = '';
placeholder.textContent = 'Нет доступных позиций';
productSelect.appendChild(placeholder);
productSelect.disabled = true;
quantityInput.disabled = true;
addButton.disabled = true;
}
form.appendChild(productCol);
form.appendChild(quantityCol);
form.appendChild(actionCol);
return form;
}
buildProductSelect(selectedId, excludedIds) {
const select = document.createElement('select');
select.className = 'form-select';
this.products.forEach((product) => {
if (excludedIds && excludedIds.has(product.id)) {
return;
}
const option = document.createElement('option');
option.value = product.id;
option.textContent = product.name;
if (selectedId && product.id === selectedId) {
option.selected = true;
}
select.appendChild(option);
});
return select;
}
buildButton(label, style, data = {}) {
const button = document.createElement('button');
button.type = 'button';
button.className = `btn ${style} btn-sm`;
button.textContent = label;
Object.entries(data).forEach(([key, value]) => {
button.dataset[key] = value;
});
return button;
}
}
function showNotification(message, type = 'warning') {
notification.textContent = message;
notification.className = `alert alert-${type}`;
notification.classList.remove('d-none');
setTimeout(() => {
notification.classList.add('d-none');
}, 4000);
}
function resolveApiUrl(url) {
if (url.startsWith('http://') || url.startsWith('https://')) {
return url;
}
if (url.startsWith('/')) {
return `${API_BASE}${url}`;
}
return `${API_BASE}/${url}`;
}
async function fetchJson(url, options) {
const response = await fetch(resolveApiUrl(url), options);
if (!response.ok) {
const payload = await response.json().catch(() => ({
message: 'Ошибка запроса.'
}));
throw new Error(payload.error || payload.message || 'Error');
}
if (response.status === 204) {
return null;
}
return response.json();
}
function renderInventory() {
inventoryList.innerHTML = '';
products.forEach((product) => {
const item = document.createElement('li');
item.className = 'list-group-item d-flex justify-content-between align-items-center';
item.innerHTML = `
<span>${product.name}</span>
<span class="badge bg-secondary rounded-pill">${product.quantity}</span>
`;
inventoryList.appendChild(item);
});
}
function renderOrders() {
ordersContainer.innerHTML = '';
if (orders.length === 0) {
ordersContainer.innerHTML = '<p class="text-muted">Заказы отсутствуют.</p>';
return;
}
orders.forEach((order) => {
const card = new OrderCard(order, orders, products).build();
ordersContainer.appendChild(card);
});
}
function normalizeProducts(data) {
if (!Array.isArray(data)) {
return [];
}
return data.map((product) => ({
id: product.id ?? product.ID,
name: product.name ?? product.pr_name,
quantity: product.quantity ?? product.count
}));
}
function normalizeOrderItems(items) {
if (!Array.isArray(items)) {
return [];
}
return items.map((item, index) => ({
id: item.id ?? item.item_id ?? `${item.product_id ?? item.productId ?? 'item'}-${index}`,
product_id: item.product_id ?? item.productId ?? item.product,
product_name: item.product_name ?? item.name,
quantity: item.quantity,
price: item.price
}));
}
function normalizeOrders(data) {
if (!Array.isArray(data)) {
return [];
}
return data.map((order) => ({
id: order.id ?? order.ID,
customer_name: order.customer_name ?? order.customer,
order_date: order.order_date ?? order.date,
status: order.status,
total_amount: order.total_amount ?? order.total,
items: normalizeOrderItems(order.items)
}));
}
async function refreshData() {
const [currentDateData, productsData, ordersData] = await Promise.all([
fetchJson('/api/current-date'),
fetchJson('/api/products'),
fetchJson('/api/orders')
]);
currentDate = currentDateData.currentDate;
products = normalizeProducts(productsData);
orders = normalizeOrders(ordersData);
currentDateEl.textContent = currentDate;
orderDateInput.min = currentDate;
orderDateInput.value = currentDate
renderInventory();
renderOrders();
}
function initializeApp() {
const requiredElements = [
notification,
currentDateEl,
orderDateInput,
customerNameInput,
orderForm,
ordersContainer,
inventoryList,
advanceButton
];
if (requiredElements.some((element) => !element)) {
console.error('Missing required elements.');
return;
}
const initialDate = getLocalISODate();
currentDate = initialDate;
currentDateEl.textContent = initialDate;
orderDateInput.min = initialDate;
orderDateInput.value = initialDate;
orderForm.addEventListener('submit', async (event) => {
event.preventDefault();
try {
await fetchJson('/api/orders', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
customerName: customerNameInput.value.trim(),
orderDate: orderDateInput.value
})
});
customerNameInput.value = '';
orderDateInput.value = currentDate;
await refreshData();
} catch (error) {
showNotification(error.message, 'warning');
}
});
advanceButton.addEventListener('click', async () => {
try {
await fetchJson('/api/current-date/advance', {
method: 'POST'
});
await refreshData();
showNotification('Дата переведена. Заказы за сегодня отправлены.', 'success');
} catch (error) {
showNotification(error.message, 'warning');
}
});
ordersContainer.addEventListener('submit', async (event) => {
if (event.target.matches('form[data-action="add-item"]')) {
event.preventDefault();
const orderId = event.target.dataset.orderId;
const productId = event.target.productId.value;
const quantity = Number.parseInt(event.target.quantity.value, 10);
try {
const response = await fetchJson(`/api/orders/${orderId}/items`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
productId,
quantity
})
});
const order = orders.find((entry) => entry.id === orderId);
const product = products.find((entry) => entry.id === productId);
if (order) {
const newItem = normalizeOrderItems([{
id: response?.itemId,
product_id: productId,
product_name: product?.name,
quantity
}])[0];
order.items = [...order.items, newItem];
renderOrders();
}
event.target.reset();
await refreshData();
} catch (error) {
showNotification(error.message, 'warning');
}
}
});
ordersContainer.addEventListener('click', async (event) => {
const {
action,
id,
itemId,
orderId
} = event.target.dataset;
try {
switch (action) {
case 'delete-order': {
await fetchJson(`/api/orders/${id}`, {
method: 'DELETE'
});
await refreshData();
return;
}
case 'edit-order': {
const newName = prompt('Введите новое ФИО заказчика', '');
if (newName === null) {
return;
}
const newDate = prompt('Введите дату заказа (YYYY-MM-DD)', currentDate);
if (!newDate) {
return;
}
Date
await fetchJson(`/api/orders/${id}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
customerName: newName,
orderDate: newDate
})
});
await refreshData();
return;
}
case 'save-item': {
const quantityInput = ordersContainer.querySelector(
`[data-action="item-quantity"][data-item-id="${itemId}"]`
);
const productSelect = ordersContainer.querySelector(
`[data-action="item-product"][data-item-id="${itemId}"]`
);
try {
await fetchJson(`/api/orders/${orderId}/items/${itemId}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
productId: productSelect.value,
quantity: Number.parseInt(quantityInput.value, 10)
})
});
await refreshData();
return;
} catch (error) {
showNotification(error.message, 'warning');
await refreshData();
return;
}
}
case 'delete-item': {
await fetchJson(`/api/orders/${orderId}/items/${itemId}`, {
method: 'DELETE'
});
await refreshData();
return;
}
case 'move-item': {
const targetSelect = ordersContainer.querySelector(
`[data-action="move-target"][data-item-id="${itemId}"]`
);
if (!targetSelect.value) {
showNotification('Выберите заказ для перемещения.', 'warning');
return;
}
await fetchJson(`/api/order-items/${itemId}/move`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
targetOrderId: targetSelect.value
})
});
await refreshData();
return;
}
default:
return;
}
} catch (error) {
showNotification(error.message, 'warning');
}
});
refreshData().catch((error) => {
showNotification(error.message, 'warning');
});
}
initializeApp();

View File

@@ -1,59 +1,59 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="ru"> <html lang="ru">
<head>
<head>
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Личный кабинет склада — Заказы</title> <title>Личный кабинет склада — Заказы</title>
<link <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" />
href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css"
rel="stylesheet"
/>
<link href="/styles.css" rel="stylesheet" /> <link href="/styles.css" rel="stylesheet" />
<script src="./app.js" defer></script> <script src="./app.js" defer></script>
</head> </head>
<body class="bg-light">
<body class="bg-light">
<div class="container py-4"> <div class="container py-4">
<div class="d-flex flex-wrap gap-3 align-items-center justify-content-between mb-4"> <div class="d-flex flex-wrap gap-3 align-items-center justify-content-between mb-4">
<div> <div>
<h1 class="h3 mb-1">Заказы склада</h1> <h1 class="h3 mb-1">Заказы склада</h1>
<p class="text-muted mb-0">Текущая дата: <span id="current-date"></span></p> <p class="text-muted mb-0">Текущая дата: <span id="current-date"></span></p>
</div>
<button id="advance-date" class="btn btn-outline-primary">Переключить дату +1</button>
</div>
<div id="notification" class="alert d-none" role="alert"></div>
<div class="row g-4">
<div class="col-lg-4">
<div class="card shadow-sm">
<div class="card-body">
<h2 class="h5">Создать заказ</h2>
<form id="order-form" class="d-grid gap-2">
<div>
<label class="form-label" for="customer-name">ФИО заказчика</label>
<input type="text" class="form-control" id="customer-name" required />
</div>
<div>
<label class="form-label" for="order-date">Дата заказа</label>
<input type="date" class="form-control" id="order-date" required />
</div>
<button type="submit" class="btn btn-primary">Добавить</button>
</form>
</div> </div>
</div> <button id="advance-date" class="btn btn-outline-primary">Переключить дату +1</button>
</div>
<div class="card shadow-sm mt-4"> <div id="notification" class="alert d-none" role="alert"></div>
<div class="card-body">
<h2 class="h5">Остатки склада</h2> <div class="row g-4">
<ul id="inventory" class="list-group list-group-flush"></ul> <div class="col-lg-4">
<div class="card shadow-sm">
<div class="card-body">
<h2 class="h5">Создать заказ</h2>
<form id="order-form" class="d-grid gap-2">
<div>
<label class="form-label" for="customer-name">ФИО заказчика</label>
<input type="text" class="form-control" id="customer-name" required />
</div>
<div>
<label class="form-label" for="order-date">Дата заказа</label>
<input type="date" class="form-control" id="order-date" required />
</div>
<button type="submit" class="btn btn-primary">Добавить</button>
</form>
</div>
</div>
<div class="card shadow-sm mt-4">
<div class="card-body">
<h2 class="h5">Остатки склада</h2>
<ul id="inventory" class="list-group list-group-flush"></ul>
</div>
</div>
</div> </div>
</div>
</div>
<div class="col-lg-8"> <div class="col-lg-8">
<div id="orders" class="d-grid gap-3"></div> <div id="orders" class="d-grid gap-3"></div>
</div>
</div> </div>
</div>
</div> </div>
</body> </body>
</html>
</html>

View File

@@ -24,7 +24,7 @@ export default class DBAdapter {
#dbName = 'N'; #dbName = 'N';
#dbUserLogin = 'u'; #dbUserLogin = 'u';
#dbUserPassword = 'p'; #dbUserPassword = 'p';
#dbClient = null; #pool = null;
constructor({ constructor({
dbHost, dbHost,
@@ -38,40 +38,43 @@ export default class DBAdapter {
this.#dbName = dbName; this.#dbName = dbName;
this.#dbUserLogin = dbUserLogin; this.#dbUserLogin = dbUserLogin;
this.#dbUserPassword = dbUserPassword; this.#dbUserPassword = dbUserPassword;
this.#dbClient = new mdb.createPool({ this.#pool = mdb.createPool({
host: this.#dbhost, host: this.#dbhost,
port: this.#dbPort, port: this.#dbPort,
database: this.#dbName, database: this.#dbName,
user: this.#dbUserLogin, user: this.#dbUserLogin,
password: this.#dbUserPassword, password: this.#dbUserPassword,
dateStrings: true dateStrings: true,
acquireTimeout: 10000,
}); });
} }
async #getConnection() {
return await this.#pool.getConnection();
}
async connect() { async connect() {
try { try {
// Проверяем подключение, выполняя простой запрос const conn = await this.#pool.getConnection();
const conn = await this.#dbClient.getConnection();
console.log("✅ Database connection test successful"); console.log("✅ Database connection test successful");
conn.release(); conn.release();
} catch (err) { } catch (err) {
console.error("❌ Database connection failed:", err.message); console.error("❌ Database connection failed:", err.message);
// Пробрасываем ошибку дальше
return Promise.reject(); return Promise.reject();
} }
} }
async disconnect() { async disconnect() {
await this.#dbClient.end(); await this.#pool.end();
console.log("DISCONNECT"); console.log("DISCONNECT");
} }
async stock(){ async stock(){
try { try {
const products = await this.#dbClient.query('SELECT id FROM products'); const products = await this.#pool.query('SELECT id FROM products');
for (const product of products) { for (const product of products) {
const increment = Random_Increase(); const increment = Random_Increase();
await this.#dbClient.query('UPDATE products SET quantity = quantity + ? WHERE id = ?', [ await this.#pool.query('UPDATE products SET quantity = quantity + ? WHERE id = ?', [
increment, increment,
product.id product.id
]); ]);
@@ -86,8 +89,7 @@ export default class DBAdapter {
async getProducts() { async getProducts() {
try { try {
const products = await this.#dbClient.query('SELECT * FROM products ORDER BY name'); const products = await this.#pool.query('SELECT * FROM products ORDER BY name');
console.log("All products:", products);
return products; return products;
} catch(err){ } catch(err){
console.log(`WHOOPS`); console.log(`WHOOPS`);
@@ -97,14 +99,12 @@ export default class DBAdapter {
async getOrders() { async getOrders() {
try { try {
const raw_orders = await this.#dbClient.query('SELECT * FROM orders ORDER BY order_date ASC'); const raw_orders = await this.#pool.query('SELECT * FROM orders ORDER BY order_date ASC');
console.log("All orders:", raw_orders);
const items = await this.#dbClient.query( const items = await this.#pool.query(
`SELECT order_items.*, products.name AS product_name FROM order_items `SELECT order_items.*, products.name AS product_name FROM order_items
JOIN products ON order_items.product_id = products.id` JOIN products ON order_items.product_id = products.id`
); );
console.log("All order items:", items);
const groupedItems = {}; const groupedItems = {};
if (items && items.length > 0) { if (items && items.length > 0) {
@@ -132,34 +132,34 @@ export default class DBAdapter {
} }
async addOrder({ id, customer_name, orderDate} ){ async addOrder({ id, customer_name, orderDate} ){
if (!customer_name || !orderDate){ if (!id || !customer_name || !orderDate){
return Promise.reject({ return Promise.reject({
type: DB_USER_ERROR, type: DB_USER_ERROR,
error: new Error("Empty in customer name or order date") error: new Error("Пустое имя клиента или дата заказа")
}); });
} }
const currentDate = await getCurrentDate(); const currentDate = await getCurrentDate();
if (orderDate < currentDate){ if (orderDate < currentDate){
return Promise.reject({ return Promise.reject({
type: DB_USER_ERROR, type: DB_USER_ERROR,
error: new Error("Invalid order date") error: new Error("Недопустимая дата заказа")
}); });
} }
try { try {
await this.#dbClient.query('INSERT INTO orders (id, customer_name, order_date) VALUES (?, ?, ?)', await this.#pool.query('INSERT INTO orders (id, customer_name, order_date) VALUES (?, ?, ?)',
[id, customer_name, orderDate] [id, customer_name, orderDate]
); );
} catch(err){ } catch(err){
return Promise.reject({ return Promise.reject({
type: DB_INTERNAL_ERROR, type: DB_INTERNAL_ERROR,
error: new Error("Server error") error: new Error("Ошибка сервера")
}); });
} }
} }
async getOrdersByDate(date){ async getOrdersByDate(date){
try { try {
const order_ids = await this.#dbClient.query('SELECT id FROM orders WHERE order_date = ?', [date]); const order_ids = await this.#pool.query('SELECT id FROM orders WHERE order_date = ?', [date]);
return order_ids; return order_ids;
} catch(err){ } catch(err){
return Promise.reject(); return Promise.reject();
@@ -175,7 +175,7 @@ export default class DBAdapter {
try { try {
const placeholders = orderIds.map(() => '?').join(','); const placeholders = orderIds.map(() => '?').join(',');
const result = await this.#dbClient.query( const result = await this.#pool.query(
`DELETE FROM orders WHERE id IN (${placeholders})`, `DELETE FROM orders WHERE id IN (${placeholders})`,
orderIds orderIds
); );
@@ -188,11 +188,12 @@ export default class DBAdapter {
} }
} }
async changeOrderInfo({ id, customer_name, orderDate }){ async changeOrderInfo({ id, customer_name, orderDate }) {
if (!id) { if (!id || !customer_name || !orderDate) {
return Promise.reject({ return Promise.reject({
type: DB_USER_ERROR, type: DB_USER_ERROR,
error: new Error("Order ID is required") error: new Error("Нужен ID заказа, имя и дата"),
message: "Нужен ID заказа, имя и дата" // Добавляем message напрямую
}); });
} }
@@ -200,202 +201,460 @@ export default class DBAdapter {
if (orderDate < currentDate) { if (orderDate < currentDate) {
return Promise.reject({ return Promise.reject({
type: DB_USER_ERROR, type: DB_USER_ERROR,
error: new Error("Order date cannot be less than current date") error: new Error("Дата заказа не может быть раньше текущей"),
message: "Дата заказа не может быть раньше текущей"
}); });
} }
try { try {
const order = await this.#dbClient.query('SELECT * FROM orders WHERE id = ?', [id]); const order = await this.#pool.query('SELECT * FROM orders WHERE id = ?', [id]);
if (!order){ if (!order || order.length === 0) { // Исправлено: проверяем length
return Promise.reject({ return Promise.reject({
type: DB_USER_ERROR, type: DB_USER_ERROR,
error: new Error("Order not found") error: new Error("Заказ не найден"),
message: "Заказ не найден"
}); });
} }
const updatedName = customer_name; const updatedName = customer_name;
const updatedDate = orderDate; const updatedDate = orderDate;
await this.#dbClient.query('UPDATE orders SET customer_name = ?, order_date = ? WHERE id = ?', await this.#pool.query('UPDATE orders SET customer_name = ?, order_date = ? WHERE id = ?',
[updatedName, updatedDate, id] [updatedName, updatedDate, id]
); );
} catch(err){ } catch(err) {
console.error('Database error in changeOrderInfo:', err);
return Promise.reject({ return Promise.reject({
type: DB_INTERNAL_ERROR, type: DB_INTERNAL_ERROR,
error: new Error("Server error") error: new Error("Ошибка сервера"),
message: err.message || "Ошибка операции с базой данных",
details: err.message
}); });
} }
} }
async deleteOrderById(order_id){ async deleteOrderById(order_id) {
let connection;
try { try {
const orderItems = await this.#dbClient.query( connection = await this.#pool.getConnection();
await connection.beginTransaction();
const orderItems = await connection.query(
`SELECT product_id, quantity FROM order_items WHERE order_id = ?`, `SELECT product_id, quantity FROM order_items WHERE order_id = ?`,
[order_id] [order_id]
); );
for (const item of orderItems){ for (const item of orderItems) {
await this.#dbClient.query('UPDATE products SET quantity = quantity + ? WHERE id = ?', await connection.query(
'UPDATE products SET quantity = quantity + ? WHERE id = ?',
[item.quantity, item.product_id] [item.quantity, item.product_id]
); );
} }
await this.#dbClient.query(
await connection.query(
`DELETE FROM order_items WHERE order_id = ?`,
[order_id]
);
await connection.query(
`DELETE FROM orders WHERE id = ?`, `DELETE FROM orders WHERE id = ?`,
[order_id] [order_id]
); );
} catch(err){
await connection.commit();
connection.release();
} catch (err) {
if (connection) {
try {
await connection.rollback();
} catch (rollbackErr) {
console.error('Rollback error:', rollbackErr.message);
}
connection.release();
}
return Promise.reject({ return Promise.reject({
type: DB_INTERNAL_ERROR, type: DB_INTERNAL_ERROR,
error: new Error("Server error") error: new Error("Не удалось удалить заказ"),
details: err.message
}); });
} }
} }
async addOrderItem({ orderId, productId, quantity }){ async addOrderItem({ orderId, productId, quantity }) {
await this.#dbClient.query('BEGIN'); let connection;
try { try {
const product = await this.#dbClient.query( connection = await this.#pool.getConnection();
'SELECT quantity FROM products WHERE id = ?', [productId]
await connection.beginTransaction();
const orderCheck = await connection.query(
'SELECT id FROM orders WHERE id = ?',
[orderId]
);
if (!orderCheck || orderCheck.length === 0) {
await connection.rollback();
connection.release();
return Promise.reject({
type: DB_USER_ERROR,
error: new Error("Заказ не найден")
});
}
const product = await connection.query(
'SELECT id, quantity FROM products WHERE id = ? FOR UPDATE',
[productId]
); );
const productRow = product?.[0]; const productRow = product?.[0];
if (!productRow || productRow.quantity < quantity){
if (!productRow) {
await connection.rollback();
connection.release();
return Promise.reject({ return Promise.reject({
type: DB_USER_ERROR, type: DB_USER_ERROR,
error: new Error("Insufficient product quantity") error: new Error("Товар не найден")
});
}
if (productRow.quantity < quantity) {
await connection.rollback();
connection.release();
return Promise.reject({
type: DB_USER_ERROR,
error: new Error("Недостаточно товара на складе")
}); });
} }
const result = await this.#dbClient.query( await connection.query(
'INSERT INTO order_items (order_id, product_id, quantity) VALUES (?, ?, ?)',
[orderId, productId, quantity]
);
await this.#dbClient.query(
'UPDATE products SET quantity = quantity - ? WHERE id = ?', 'UPDATE products SET quantity = quantity - ? WHERE id = ?',
[quantity, productId] [quantity, productId]
); );
await this.#dbClient.query('COMMIT'); const result = await connection.query(
} catch (err){ 'INSERT INTO order_items (order_id, product_id, quantity) VALUES (?, ?, ?)',
await this.#dbClient.query('ROLLBACK'); [orderId, productId, quantity]
return Promise.reject(); );
await connection.commit();
connection.release();
return result.insertId;
} catch (err) {
if (connection) {
try {
await connection.rollback();
} catch (rollbackErr) {
console.error('Rollback error:', rollbackErr.message);
}
connection.release();
}
console.error('Transaction error:', err);
let errorType = DB_INTERNAL_ERROR;
let userMessage = "Ошибка операции с базой данных";
let retryable = false;
if (err.code === 'ER_LOCK_WAIT_TIMEOUT' || err.errno === 1205) {
errorType = 'DB_CONFLICT';
userMessage = "Система занята. Попробуйте позже.";
retryable = true;
} else if (err.code === 'ER_DUP_ENTRY') {
errorType = DB_USER_ERROR;
userMessage = "Позиция уже есть в заказе";
}
return Promise.reject({
type: errorType,
error: new Error(userMessage),
details: err.message,
code: err.code,
retryable: retryable,
originalError: err
});
} }
} }
async updateOrderItem({ itemId, quantity }){ async updateOrderItem({ itemId, quantity, productId }) {
await this.#dbClient.query('BEGIN'); let connection;
try { try {
const item = await this.#dbClient.query( if (!itemId || !Number.isFinite(quantity) || quantity <= 0) {
'SELECT product_id, quantity FROM order_items WHERE id = ?', [itemId] return Promise.reject({
type: DB_USER_ERROR,
error: new Error("Неверная позиция или количество")
});
}
connection = await this.#pool.getConnection();
await connection.beginTransaction();
const item = await connection.query(
'SELECT product_id, quantity FROM order_items WHERE id = ? FOR UPDATE',
[itemId]
); );
const itemRow = item?.[0]; const itemRow = item?.[0];
if (!itemRow){ if (!itemRow) {
await connection.rollback();
connection.release();
return Promise.reject({ return Promise.reject({
type: DB_USER_ERROR, type: DB_USER_ERROR,
error: new Error("Order item not found") error: new Error("Позиция заказа не найдена")
}); });
} }
const targetProductId = productId ?? itemRow.product_id;
if (targetProductId !== itemRow.product_id) {
const newProduct = await connection.query(
'SELECT quantity FROM products WHERE id = ? FOR UPDATE',
[targetProductId]
);
const newProductRow = newProduct?.[0];
if (!newProductRow) {
await connection.rollback();
connection.release();
return Promise.reject({
type: DB_USER_ERROR,
error: new Error("Товар не найден")
});
}
if (newProductRow.quantity < quantity) {
await connection.rollback();
connection.release();
return Promise.reject({
type: DB_USER_ERROR,
error: new Error("Недостаточно товара на складе")
});
}
await connection.query(
'UPDATE products SET quantity = quantity + ? WHERE id = ?',
[itemRow.quantity, itemRow.product_id]
);
await connection.query(
'UPDATE products SET quantity = quantity - ? WHERE id = ?',
[quantity, targetProductId]
);
await connection.query(
'UPDATE order_items SET product_id = ?, quantity = ? WHERE id = ?',
[targetProductId, quantity, itemId]
);
await connection.commit();
connection.release();
return;
}
const diff = quantity - itemRow.quantity; const diff = quantity - itemRow.quantity;
if (diff > 0){ if (diff > 0) {
const product = await this.#dbClient.query( const product = await connection.query(
'SELECT quantity FROM products WHERE id = ?', [itemRow.product_id] 'SELECT quantity FROM products WHERE id = ? FOR UPDATE',
[itemRow.product_id]
); );
const productRow = product?.[0]; const productRow = product?.[0];
if (!productRow || productRow.quantity < diff){ if (!productRow || productRow.quantity < diff) {
await connection.rollback();
connection.release();
return Promise.reject({ return Promise.reject({
type: DB_USER_ERROR, type: DB_USER_ERROR,
error: new Error("Insufficient product quantity") error: new Error("Недостаточно товара на складе")
}); });
} }
await this.#dbClient.query( await connection.query(
'UPDATE products SET quantity = quantity - ? WHERE id = ?', 'UPDATE products SET quantity = quantity - ? WHERE id = ?',
[diff, itemRow.product_id] [diff, itemRow.product_id]
); );
} }
if (diff < 0) { if (diff < 0) {
await this.#dbClient.query( await connection.query(
'UPDATE products SET quantity = quantity + ? WHERE id = ?', 'UPDATE products SET quantity = quantity + ? WHERE id = ?',
[-diff, itemRow.product_id] [-diff, itemRow.product_id]
); );
} }
await this.#dbClient.query( await connection.query(
'UPDATE order_items SET quantity = ? WHERE id = ?', 'UPDATE order_items SET quantity = ? WHERE id = ?',
[quantity, itemId] [quantity, itemId]
); );
await this.#dbClient.query('COMMIT'); await connection.commit();
} catch (err){ connection.release();
await this.#dbClient.query('ROLLBACK');
return Promise.reject(); } catch (err) {
if (connection) {
try {
await connection.rollback();
} catch (rollbackErr) {
console.error('Rollback error:', rollbackErr.message);
}
connection.release();
}
return Promise.reject({
type: DB_INTERNAL_ERROR,
error: new Error("Не удалось обновить позицию заказа"),
details: err.message
});
} }
} }
async deleteOrderItem(itemId){ async deleteOrderItem(itemId) {
await this.#dbClient.query('BEGIN'); let connection;
try { try {
const item = await this.#dbClient.query( connection = await this.#pool.getConnection();
'SELECT product_id, quantity FROM order_items WHERE id = ?', [itemId] await connection.beginTransaction();
const item = await connection.query(
'SELECT product_id, quantity FROM order_items WHERE id = ? FOR UPDATE',
[itemId]
); );
const itemRow = item?.[0]; const itemRow = item?.[0];
if (!itemRow){ if (!itemRow) {
await connection.rollback();
connection.release();
return Promise.reject({ return Promise.reject({
type: DB_USER_ERROR, type: DB_USER_ERROR,
error: new Error("Order item not found") error: new Error("Позиция заказа не найдена")
}); });
} }
await this.#dbClient.query( await connection.query(
'UPDATE products SET quantity = quantity + ? WHERE id = ?', 'UPDATE products SET quantity = quantity + ? WHERE id = ?',
[itemRow.quantity, itemRow.product_id] [itemRow.quantity, itemRow.product_id]
); );
await this.#dbClient.query( await connection.query(
'DELETE FROM order_items WHERE id = ?', 'DELETE FROM order_items WHERE id = ?',
[itemId] [itemId]
); );
await this.#dbClient.query('COMMIT'); await connection.commit();
} catch (err){ connection.release();
await this.#dbClient.query('ROLLBACK');
return Promise.reject(); } catch (err) {
if (connection) {
try {
await connection.rollback();
} catch (rollbackErr) {
console.error('Rollback error:', rollbackErr.message);
}
connection.release();
}
console.error('Delete order item error:', err);
return Promise.reject({
type: DB_INTERNAL_ERROR,
error: new Error("Не удалось удалить позицию заказа"),
details: err.message,
itemId: itemId
});
} }
} }
async moveOrderItem( {itemId, targetOrderId }){ async moveOrderItem({ itemId, targetOrderId }) {
await this.#dbClient.query('BEGIN'); let connection;
try { try {
const item = await this.#dbClient.query( connection = await this.#pool.getConnection();
'SELECT id, order_id FROM order_items WHERE id = ?', [itemId] await connection.beginTransaction();
// Проверяем существование целевого заказа
const targetOrderCheck = await connection.query(
'SELECT id FROM orders WHERE id = ?',
[targetOrderId]
);
if (!targetOrderCheck || targetOrderCheck.length === 0) {
await connection.rollback();
connection.release();
return Promise.reject({
type: DB_USER_ERROR,
error: new Error("Целевой заказ не найден")
});
}
const item = await connection.query(
'SELECT id, order_id, product_id, quantity FROM order_items WHERE id = ? FOR UPDATE',
[itemId]
); );
const itemRow = item?.[0]; const itemRow = item?.[0];
if (!itemRow){ if (!itemRow) {
await connection.rollback();
connection.release();
return Promise.reject({ return Promise.reject({
type: DB_USER_ERROR, type: DB_USER_ERROR,
error: new Error("Order item not found") error: new Error("Позиция заказа не найдена")
}); });
} }
await this.#dbClient.query( if (itemRow.order_id === targetOrderId) {
'UPDATE order_items SET order_id = ? WHERE id = ?', await connection.rollback();
[targetOrderId, itemId] connection.release();
return;
}
const targetItem = await connection.query(
'SELECT id, quantity FROM order_items WHERE order_id = ? AND product_id = ? FOR UPDATE',
[targetOrderId, itemRow.product_id]
); );
await this.#dbClient.query('COMMIT'); const targetItemRow = targetItem?.[0];
} catch (err){
await this.#dbClient.query('ROLLBACK'); if (targetItemRow) {
return Promise.reject(); await connection.query(
'UPDATE order_items SET quantity = ? WHERE id = ?',
[targetItemRow.quantity + itemRow.quantity, targetItemRow.id]
);
await connection.query(
'DELETE FROM order_items WHERE id = ?',
[itemId]
);
} else {
await connection.query(
'UPDATE order_items SET order_id = ? WHERE id = ?',
[targetOrderId, itemId]
);
}
await connection.commit();
connection.release();
} catch (err) {
if (connection) {
try {
await connection.rollback();
} catch (rollbackErr) {
console.error('Rollback error:', rollbackErr.message);
}
connection.release();
}
return Promise.reject({
type: DB_INTERNAL_ERROR,
error: new Error("Не удалось перенести позицию заказа"),
details: err.message
});
} }
} }
} }

5
server/docker.env Normal file
View File

@@ -0,0 +1,5 @@
HOST="db"
PORT=3306
DATABASE="delivery"
USER="app"
PASSWORD="app"

View File

@@ -1,11 +1,12 @@
import express from "express"; import express from "express";
import dotenv from "dotenv" import dotenv from "dotenv"
import { randomUUID } from "crypto"; import { randomUUID } from "crypto";
import DBAdapter, { getCurrentDate, setCurrentDate } from "./db/database.js"; import DBAdapter, { getCurrentDate, setCurrentDate } from "./db/database.js";
import { DB_INTERNAL_ERROR, DB_USER_ERROR } from "./db/database.js"; import { DB_INTERNAL_ERROR, DB_USER_ERROR } from "./db/database.js";
// Switch to .env for test in local machine
dotenv.config({ dotenv.config({
path: './server/.env' path: './server/docker.env'
}); });
const { const {
@@ -20,6 +21,16 @@ const appPort = 3000;
const app = express(); const app = express();
app.use(express.json()); app.use(express.json());
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
res.setHeader('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE,OPTIONS');
if (req.method === 'OPTIONS') {
res.sendStatus(204);
return;
}
next();
});
const adapter = new DBAdapter({ const adapter = new DBAdapter({
dbHost: HOST, dbHost: HOST,
@@ -40,31 +51,6 @@ app.get('/api/current-date', async (req, res) => {
res.json({ currentDate }); res.json({ currentDate });
}); });
app.get('/api/products', async(req, res) => {
try {
const db_products = await adapter.getProducts();
const products = db_products.map(
( {id, name, quantity} ) => ({
ID: id,
pr_name: name,
count: quantity
})
);
res.statusCode = 200;
res.message = "OK";
res.json(products);
} catch (err){
res.statusCode = 500;
res.message = "WHOOPS";
res.json({
timeStamp: new Date().toISOString(),
statusCode: 500,
error : `${err}`
})
}
});
app.post('/api/current-date/advance', async (req, res) => { app.post('/api/current-date/advance', async (req, res) => {
let currentDate = getCurrentDate(); let currentDate = getCurrentDate();
try { try {
@@ -88,7 +74,32 @@ app.post('/api/current-date/advance', async (req, res) => {
} }
}); });
app.get('/api/orders', async(req, res) => { app.get('/api/products', async (req, res) => {
try {
const db_products = await adapter.getProducts();
const products = db_products.map(
( {id, name, quantity} ) => ({
ID: id,
pr_name: name,
count: quantity
})
);
res.statusCode = 200;
res.message = "OK";
res.json(products);
} catch (err){
res.statusCode = 500;
res.message = "WHOOPS";
res.json({
timeStamp: new Date().toISOString(),
statusCode: 500,
error : `${err}`
})
}
});
app.get('/api/orders', async (req, res) => {
try { try {
const db_orders = await adapter.getOrders(); const db_orders = await adapter.getOrders();
@@ -100,6 +111,7 @@ app.get('/api/orders', async(req, res) => {
status: status, status: status,
total: total_amount, total: total_amount,
items: items ? items.map(item => ({ items: items ? items.map(item => ({
id: item.id,
product_id: item.product_id, product_id: item.product_id,
product_name: item.product_name || item.name, product_name: item.product_name || item.name,
quantity: item.quantity, quantity: item.quantity,
@@ -163,13 +175,71 @@ app.post('/api/orders', async (req, res) => {
res.status(500).json({ res.status(500).json({
timeStamp: new Date().toISOString(), timeStamp: new Date().toISOString(),
statusCode: 500, statusCode: 500,
message: "Unknown error", message: "Неизвестная ошибка",
error: err.message error: err.message
}); });
} }
} }
}); });
app.put('/api/orders/:id', async (req, res) => {
const { customerName, orderDate } = req.body;
const orderId = req.params.id;
if (!customerName || !orderDate) {
return res.status(400).json({
timeStamp: new Date().toISOString(),
statusCode: 400,
error: "Имя клиента и дата заказа обязательны"
});
}
try {
await adapter.changeOrderInfo({
id: orderId,
customer_name: customerName,
orderDate
});
return res.json({
id: orderId,
customer_name: customerName,
order_date: orderDate
});
} catch(err) {
console.error('Error updating order:', err);
const errorMessage = err.message ||
err.error?.message ||
"Произошла неизвестная ошибка";
switch(err.type) {
case DB_INTERNAL_ERROR:
return res.status(500).json({
timeStamp: new Date().toISOString(),
statusCode: 500,
error: errorMessage,
details: err.details || "Внутренняя ошибка сервера"
});
case DB_USER_ERROR:
return res.status(400).json({
timeStamp: new Date().toISOString(),
statusCode: 400,
error: errorMessage
});
default:
return res.status(500).json({
timeStamp: new Date().toISOString(),
statusCode: 500,
error: errorMessage
});
}
}
});
app.delete('/api/orders/:id', async (req, res) => { app.delete('/api/orders/:id', async (req, res) => {
try { try {
await adapter.deleteOrderById(req.params.id); await adapter.deleteOrderById(req.params.id);
@@ -191,48 +261,79 @@ app.post('/api/orders/:orderId/items', async (req, res) => {
let orderId = req.params.orderId; let orderId = req.params.orderId;
let { productId, quantity } = req.body; let { productId, quantity } = req.body;
if (!productId || !quantity || quantity <= 0) {
return res.status(400).json({
timeStamp: new Date().toISOString(),
statusCode: 400,
error: "Некорректный товар или количество"
});
}
try { try {
await adapter.addOrderItem({ const itemId = await adapter.addOrderItem({
orderId, orderId,
productId, productId,
quantity quantity
}); });
res.status(201).json({ return res.status(201).json({
itemId: itemId.toString(),
orderId, orderId,
productId, productId,
quantity quantity
}); });
} catch (err) { } catch (err) {
// TODO console.error('Error adding order item:', err);
res.status(500).json({
timeStamp: new Date().toISOString(), if (err.type === DB_USER_ERROR) {
statusCode: 500, return res.status(400).json({
}); timeStamp: new Date().toISOString(),
statusCode: 400,
error: err.error?.message || "Некорректный запрос",
details: err.details
});
} else if (err.type === DB_INTERNAL_ERROR) {
return res.status(500).json({
timeStamp: new Date().toISOString(),
statusCode: 500,
error: "Внутренняя ошибка сервера",
details: err.error?.message
});
} else {
return res.status(500).json({
timeStamp: new Date().toISOString(),
statusCode: 500,
error: "Внутренняя ошибка сервера"
});
}
} }
}); });
app.put('/api/orders/:orderId/items/:itemId', async (req, res) => { app.put('/api/orders/:orderId/items/:itemId', async (req, res) => {
let itemId = req.params.itemId; let itemId = req.params.itemId;
let quantity = req.body.quantity; let { quantity, productId } = req.body;
quantity = Number.parseInt(quantity, 10);
try { try {
await adapter.updateOrderItem({ await adapter.updateOrderItem({
itemId, itemId,
productId,
quantity quantity
}); });
res.status(201).json({ res.status(201).json({
itemId, itemId,
productId,
quantity quantity
}); });
} catch (err) { } catch (err) {
// TODO const statusCode = err.type === DB_USER_ERROR ? 400 : 500;
res.status(500).json({ res.status(statusCode).json({
timeStamp: new Date().toISOString(), timeStamp: new Date().toISOString(),
statusCode: 500, statusCode,
error: err.error?.message || err.message
}); });
} }
}); });
@@ -240,17 +341,25 @@ app.put('/api/orders/:orderId/items/:itemId', async (req, res) => {
app.delete('/api/orders/:orderId/items/:itemId', async (req, res) => { app.delete('/api/orders/:orderId/items/:itemId', async (req, res) => {
try { try {
await adapter.deleteOrderItem(req.params.itemId); await adapter.deleteOrderItem(req.params.itemId);
res.status(204).end(); return res.status(204).end();
} catch (err){ } catch (err) {
res.statusCode = 500; if (err.type === DB_INTERNAL_ERROR) {
res.message = "WHOOPS"; return res.status(500).json({
res.json({ timeStamp: new Date().toISOString(),
timeStamp: new Date().toISOString(), statusCode: 500,
statusCode: 500, error: "Ошибка сервера",
error: `${err}` details: err.error.message
}); });
} else {
return res.status(500).json({
timeStamp: new Date().toISOString(),
statusCode: 500,
error: "Внутренняя ошибка сервера",
details: err.message
});
}
} }
}) });
app.post('/api/order-items/:itemId/move', async (req, res) => { app.post('/api/order-items/:itemId/move', async (req, res) => {
let itemId = req.params.itemId; let itemId = req.params.itemId;
@@ -278,7 +387,7 @@ app.post('/api/order-items/:itemId/move', async (req, res) => {
app.use((req, res) => { app.use((req, res) => {
res.status(404).json({ error: 'Invalid route' }); res.status(404).json({ error: 'Неверный маршрут' });
}); });
const server = app.listen(appPort, async() => { const server = app.listen(appPort, async() => {
@@ -298,4 +407,4 @@ process.on('SIGTERM', () => {
await adapter.disconnect(); await adapter.disconnect();
console.log("DB DISCONNECTED"); console.log("DB DISCONNECTED");
}); });
}); });