Compare commits

..

13 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
12 changed files with 408 additions and 79 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;
}
}

View File

@@ -121,7 +121,7 @@ class OrderCard {
idCell.textContent = item.product_id ?? item.id; idCell.textContent = item.product_id ?? item.id;
const productCell = document.createElement('td'); const productCell = document.createElement('td');
const productSelect = this.buildProductSelect(item); const productSelect = this.buildProductSelect(item.product_id);
productSelect.classList.add('form-select-sm'); productSelect.classList.add('form-select-sm');
productSelect.dataset.action = 'item-product'; productSelect.dataset.action = 'item-product';
productSelect.dataset.itemId = item.id; productSelect.dataset.itemId = item.id;
@@ -220,7 +220,12 @@ class OrderCard {
const productLabel = document.createElement('label'); const productLabel = document.createElement('label');
productLabel.className = 'form-label'; productLabel.className = 'form-label';
productLabel.textContent = 'Товар'; productLabel.textContent = 'Товар';
const productSelect = this.buildProductSelect(); 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}`; const productSelectId = `add-item-product-${this.order.id}`;
productSelect.name = 'productId'; productSelect.name = 'productId';
productSelect.id = productSelectId; productSelect.id = productSelectId;
@@ -253,6 +258,16 @@ class OrderCard {
addButton.textContent = 'Добавить позицию'; addButton.textContent = 'Добавить позицию';
actionCol.appendChild(addButton); 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(productCol);
form.appendChild(quantityCol); form.appendChild(quantityCol);
form.appendChild(actionCol); form.appendChild(actionCol);
@@ -260,10 +275,13 @@ class OrderCard {
return form; return form;
} }
buildProductSelect(selectedId) { buildProductSelect(selectedId, excludedIds) {
const select = document.createElement('select'); const select = document.createElement('select');
select.className = 'form-select'; select.className = 'form-select';
this.products.forEach((product) => { this.products.forEach((product) => {
if (excludedIds && excludedIds.has(product.id)) {
return;
}
const option = document.createElement('option'); const option = document.createElement('option');
option.value = product.id; option.value = product.id;
option.textContent = product.name; option.textContent = product.name;
@@ -313,7 +331,7 @@ async function fetchJson(url, options) {
const payload = await response.json().catch(() => ({ const payload = await response.json().catch(() => ({
message: 'Ошибка запроса.' message: 'Ошибка запроса.'
})); }));
throw new Error(payload.message || 'Ошибка запроса.'); throw new Error(payload.error || payload.message || 'Error');
} }
if (response.status === 204) { if (response.status === 204) {
return null; return null;
@@ -397,9 +415,7 @@ async function refreshData() {
currentDateEl.textContent = currentDate; currentDateEl.textContent = currentDate;
orderDateInput.min = currentDate; orderDateInput.min = currentDate;
if (!orderDateInput.value) { orderDateInput.value = currentDate
orderDateInput.value = currentDate;
}
renderInventory(); renderInventory();
renderOrders(); renderOrders();
@@ -426,9 +442,7 @@ function initializeApp() {
currentDate = initialDate; currentDate = initialDate;
currentDateEl.textContent = initialDate; currentDateEl.textContent = initialDate;
orderDateInput.min = initialDate; orderDateInput.min = initialDate;
if (!orderDateInput.value) { orderDateInput.value = initialDate;
orderDateInput.value = initialDate;
}
orderForm.addEventListener('submit', async (event) => { orderForm.addEventListener('submit', async (event) => {
event.preventDefault(); event.preventDefault();
@@ -549,18 +563,24 @@ function initializeApp() {
`[data-action="item-product"][data-item-id="${itemId}"]` `[data-action="item-product"][data-item-id="${itemId}"]`
); );
await fetchJson(`/api/orders/${orderId}/items/${itemId}`, { try {
method: 'PUT', await fetchJson(`/api/orders/${orderId}/items/${itemId}`, {
headers: { method: 'PUT',
'Content-Type': 'application/json' headers: {
}, 'Content-Type': 'application/json'
body: JSON.stringify({ },
productId: productSelect.value, body: JSON.stringify({
quantity: Number.parseInt(quantityInput.value, 10) productId: productSelect.value,
}) quantity: Number.parseInt(quantityInput.value, 10)
}); })
await refreshData(); });
return; await refreshData();
return;
} catch (error) {
showNotification(error.message, 'warning');
await refreshData();
return;
}
} }
case 'delete-item': { case 'delete-item': {
await fetchJson(`/api/orders/${orderId}/items/${itemId}`, { await fetchJson(`/api/orders/${orderId}/items/${itemId}`, {

View File

@@ -135,14 +135,14 @@ export default class DBAdapter {
if (!id || !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 {
@@ -152,7 +152,7 @@ export default class DBAdapter {
} 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("Ошибка сервера")
}); });
} }
} }
@@ -192,8 +192,8 @@ export default class DBAdapter {
if (!id || !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("Order ID, name or date is required!"), error: new Error("Нужен ID заказа, имя и дата"),
message: "Order ID, name or date is required!" // Добавляем message напрямую message: "Нужен ID заказа, имя и дата" // Добавляем message напрямую
}); });
} }
@@ -201,8 +201,8 @@ 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: "Order date cannot be less than current date" message: "Дата заказа не может быть раньше текущей"
}); });
} }
@@ -212,8 +212,8 @@ export default class DBAdapter {
if (!order || order.length === 0) { // Исправлено: проверяем length 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: "Order not found" message: "Заказ не найден"
}); });
} }
@@ -228,8 +228,8 @@ export default class DBAdapter {
console.error('Database error in changeOrderInfo:', 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 || "Database operation failed", message: err.message || "Ошибка операции с базой данных",
details: err.message details: err.message
}); });
} }
@@ -279,7 +279,7 @@ export default class DBAdapter {
return Promise.reject({ return Promise.reject({
type: DB_INTERNAL_ERROR, type: DB_INTERNAL_ERROR,
error: new Error("Failed to delete order"), error: new Error("Не удалось удалить заказ"),
details: err.message details: err.message
}); });
} }
@@ -303,7 +303,7 @@ export default class DBAdapter {
connection.release(); connection.release();
return Promise.reject({ return Promise.reject({
type: DB_USER_ERROR, type: DB_USER_ERROR,
error: new Error("Order not found") error: new Error("Заказ не найден")
}); });
} }
@@ -319,7 +319,7 @@ export default class DBAdapter {
connection.release(); connection.release();
return Promise.reject({ return Promise.reject({
type: DB_USER_ERROR, type: DB_USER_ERROR,
error: new Error("Product not found") error: new Error("Товар не найден")
}); });
} }
@@ -328,7 +328,7 @@ export default class DBAdapter {
connection.release(); 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("Недостаточно товара на складе")
}); });
} }
@@ -361,16 +361,16 @@ export default class DBAdapter {
console.error('Transaction error:', err); console.error('Transaction error:', err);
let errorType = DB_INTERNAL_ERROR; let errorType = DB_INTERNAL_ERROR;
let userMessage = "Database operation failed"; let userMessage = "Ошибка операции с базой данных";
let retryable = false; let retryable = false;
if (err.code === 'ER_LOCK_WAIT_TIMEOUT' || err.errno === 1205) { if (err.code === 'ER_LOCK_WAIT_TIMEOUT' || err.errno === 1205) {
errorType = 'DB_CONFLICT'; errorType = 'DB_CONFLICT';
userMessage = "System is busy. Please try again in a moment."; userMessage = "Система занята. Попробуйте позже.";
retryable = true; retryable = true;
} else if (err.code === 'ER_DUP_ENTRY') { } else if (err.code === 'ER_DUP_ENTRY') {
errorType = DB_USER_ERROR; errorType = DB_USER_ERROR;
userMessage = "Item already exists in the order"; userMessage = "Позиция уже есть в заказе";
} }
return Promise.reject({ return Promise.reject({
@@ -384,10 +384,17 @@ export default class DBAdapter {
} }
} }
async updateOrderItem({ itemId, quantity }) { async updateOrderItem({ itemId, quantity, productId }) {
let connection; let connection;
try { try {
if (!itemId || !Number.isFinite(quantity) || quantity <= 0) {
return Promise.reject({
type: DB_USER_ERROR,
error: new Error("Неверная позиция или количество")
});
}
connection = await this.#pool.getConnection(); connection = await this.#pool.getConnection();
await connection.beginTransaction(); await connection.beginTransaction();
@@ -402,10 +409,55 @@ export default class DBAdapter {
connection.release(); 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) {
@@ -420,7 +472,7 @@ export default class DBAdapter {
connection.release(); 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("Недостаточно товара на складе")
}); });
} }
@@ -457,7 +509,7 @@ export default class DBAdapter {
return Promise.reject({ return Promise.reject({
type: DB_INTERNAL_ERROR, type: DB_INTERNAL_ERROR,
error: new Error("Failed to update order item"), error: new Error("Не удалось обновить позицию заказа"),
details: err.message details: err.message
}); });
} }
@@ -481,7 +533,7 @@ export default class DBAdapter {
connection.release(); 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("Позиция заказа не найдена")
}); });
} }
@@ -512,7 +564,7 @@ export default class DBAdapter {
return Promise.reject({ return Promise.reject({
type: DB_INTERNAL_ERROR, type: DB_INTERNAL_ERROR,
error: new Error("Failed to delete order item"), error: new Error("Не удалось удалить позицию заказа"),
details: err.message, details: err.message,
itemId: itemId itemId: itemId
}); });
@@ -537,12 +589,12 @@ export default class DBAdapter {
connection.release(); connection.release();
return Promise.reject({ return Promise.reject({
type: DB_USER_ERROR, type: DB_USER_ERROR,
error: new Error("Target order not found") error: new Error("Целевой заказ не найден")
}); });
} }
const item = await connection.query( const item = await connection.query(
'SELECT id, order_id FROM order_items WHERE id = ? FOR UPDATE', 'SELECT id, order_id, product_id, quantity FROM order_items WHERE id = ? FOR UPDATE',
[itemId] [itemId]
); );
@@ -552,15 +604,39 @@ export default class DBAdapter {
connection.release(); 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 connection.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]
); );
const targetItemRow = targetItem?.[0];
if (targetItemRow) {
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(); await connection.commit();
connection.release(); connection.release();
@@ -576,9 +652,9 @@ export default class DBAdapter {
return Promise.reject({ return Promise.reject({
type: DB_INTERNAL_ERROR, type: DB_INTERNAL_ERROR,
error: new Error("Failed to move order item"), error: new Error("Не удалось перенести позицию заказа"),
details: err.message 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 {
@@ -23,7 +24,7 @@ app.use(express.json());
app.use((req, res, next) => { app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type'); res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
res.setHeader('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE'); res.setHeader('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE,OPTIONS');
if (req.method === 'OPTIONS') { if (req.method === 'OPTIONS') {
res.sendStatus(204); res.sendStatus(204);
return; return;
@@ -174,7 +175,7 @@ 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
}); });
} }
@@ -189,7 +190,7 @@ app.put('/api/orders/:id', async (req, res) => {
return res.status(400).json({ return res.status(400).json({
timeStamp: new Date().toISOString(), timeStamp: new Date().toISOString(),
statusCode: 400, statusCode: 400,
error: "Customer name and order date are required" error: "Имя клиента и дата заказа обязательны"
}); });
} }
@@ -211,7 +212,7 @@ app.put('/api/orders/:id', async (req, res) => {
const errorMessage = err.message || const errorMessage = err.message ||
err.error?.message || err.error?.message ||
"Unknown error occurred"; "Произошла неизвестная ошибка";
switch(err.type) { switch(err.type) {
case DB_INTERNAL_ERROR: case DB_INTERNAL_ERROR:
@@ -219,7 +220,7 @@ app.put('/api/orders/:id', async (req, res) => {
timeStamp: new Date().toISOString(), timeStamp: new Date().toISOString(),
statusCode: 500, statusCode: 500,
error: errorMessage, error: errorMessage,
details: err.details || "Internal server error" details: err.details || "Внутренняя ошибка сервера"
}); });
case DB_USER_ERROR: case DB_USER_ERROR:
@@ -264,7 +265,7 @@ app.post('/api/orders/:orderId/items', async (req, res) => {
return res.status(400).json({ return res.status(400).json({
timeStamp: new Date().toISOString(), timeStamp: new Date().toISOString(),
statusCode: 400, statusCode: 400,
error: "Invalid productId or quantity" error: "Некорректный товар или количество"
}); });
} }
@@ -289,21 +290,21 @@ app.post('/api/orders/:orderId/items', async (req, res) => {
return res.status(400).json({ return res.status(400).json({
timeStamp: new Date().toISOString(), timeStamp: new Date().toISOString(),
statusCode: 400, statusCode: 400,
error: err.error?.message || "Invalid request", error: err.error?.message || "Некорректный запрос",
details: err.details details: err.details
}); });
} else if (err.type === DB_INTERNAL_ERROR) { } else if (err.type === DB_INTERNAL_ERROR) {
return res.status(500).json({ return res.status(500).json({
timeStamp: new Date().toISOString(), timeStamp: new Date().toISOString(),
statusCode: 500, statusCode: 500,
error: "Internal server error", error: "Внутренняя ошибка сервера",
details: err.error?.message details: err.error?.message
}); });
} else { } else {
return res.status(500).json({ return res.status(500).json({
timeStamp: new Date().toISOString(), timeStamp: new Date().toISOString(),
statusCode: 500, statusCode: 500,
error: "Internal server error" error: "Внутренняя ошибка сервера"
}); });
} }
} }
@@ -311,24 +312,28 @@ app.post('/api/orders/:orderId/items', async (req, res) => {
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) {
res.json({ const statusCode = err.type === DB_USER_ERROR ? 400 : 500;
res.status(statusCode).json({
timeStamp: new Date().toISOString(), timeStamp: new Date().toISOString(),
statusCode: 500, statusCode,
error: err.message error: err.error?.message || err.message
}); });
} }
}); });
@@ -342,14 +347,14 @@ app.delete('/api/orders/:orderId/items/:itemId', async (req, res) => {
return res.status(500).json({ return res.status(500).json({
timeStamp: new Date().toISOString(), timeStamp: new Date().toISOString(),
statusCode: 500, statusCode: 500,
error: "Server error", error: "Ошибка сервера",
details: err.error.message details: err.error.message
}); });
} else { } else {
return res.status(500).json({ return res.status(500).json({
timeStamp: new Date().toISOString(), timeStamp: new Date().toISOString(),
statusCode: 500, statusCode: 500,
error: "Internal server error", error: "Внутренняя ошибка сервера",
details: err.message details: err.message
}); });
} }
@@ -382,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() => {