Compare commits
34 Commits
f1d1c2737a
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
| 5d066c96c9 | |||
| 91f18a6a9a | |||
| 74e7dc8fd5 | |||
| 1f542c65ab | |||
| 18999515b2 | |||
| 23c67c9e6e | |||
| 75df8970fd | |||
| 8b0fa219aa | |||
| 22b592e3ef | |||
| 151c98e994 | |||
| 8c9ea53964 | |||
| c6c3cf2227 | |||
| ec2531cacb | |||
| fab2dd6ac9 | |||
| 7b0a6c9f37 | |||
| 94b0216568 | |||
| 62ecf92ce7 | |||
| f3d834574b | |||
| 08ddf65ec1 | |||
| cd1f3a1e87 | |||
| 25a92e4b98 | |||
| 78ddbb4601 | |||
| 13fe841e54 | |||
| 58b88c05a7 | |||
| 85d1a9f046 | |||
| 363798ca44 | |||
| 45e07d6413 | |||
|
|
c6604703fe | ||
|
|
d39f5f129e | ||
| a1d326aa40 | |||
| ec65f155b2 | |||
| bfde13afd0 | |||
| 4e0bc9d428 | |||
| a4bbee1c0f |
5
.dockerignore
Normal file
5
.dockerignore
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
node_modules
|
||||||
|
.git
|
||||||
|
.gitignore
|
||||||
|
.gitattributes
|
||||||
|
README.md
|
||||||
3
.gitignore
vendored
3
.gitignore
vendored
@@ -137,9 +137,8 @@ dist
|
|||||||
# Vite logs files
|
# Vite logs files
|
||||||
vite.config.js.timestamp-*
|
vite.config.js.timestamp-*
|
||||||
vite.config.ts.timestamp-*
|
vite.config.ts.timestamp-*
|
||||||
/.vs/DELIVER_MAN.slnx
|
/.vs/*
|
||||||
/.vscode
|
/.vscode
|
||||||
/obj/Debug
|
/obj/Debug
|
||||||
*.slnx
|
|
||||||
*.esproj
|
*.esproj
|
||||||
/CHANGELOG.md
|
/CHANGELOG.md
|
||||||
|
|||||||
25
README.md
25
README.md
@@ -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
60
docker-compose.yml
Normal 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
4
docker/Dockerfile.client
Normal 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
13
docker/Dockerfile.server
Normal 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
105
docker/init.sql
Normal 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
19
docker/nginx.conf
Normal 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
2489
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
35
package.json
35
package.json
@@ -1,20 +1,19 @@
|
|||||||
{
|
{
|
||||||
"name": "deliver_man",
|
"name": "deliver-man-server",
|
||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
"description": "",
|
"description": "",
|
||||||
"main": "server.js",
|
"main": "server.js",
|
||||||
"scripts": {
|
"type": "module",
|
||||||
"test": "echo \"Error: no test specified\" && exit 1",
|
"scripts": {
|
||||||
"start": "node server.js"
|
"start": "node server/server.js",
|
||||||
},
|
"dev": "nodemon server/server.js"
|
||||||
"keywords": [],
|
},
|
||||||
"author": "",
|
"dependencies": {
|
||||||
"license": "ISC",
|
"dotenv": "^17.2.3",
|
||||||
"type": "commonjs",
|
"express": "^4.22.1",
|
||||||
"dependencies": {
|
"mariadb": "^3.4.5"
|
||||||
"express": "^5.2.1"
|
},
|
||||||
},
|
"devDependencies": {
|
||||||
"devDependencies": {
|
"nodemon": "^3.0.1"
|
||||||
"nodemon": "^3.1.11"
|
}
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
625
public/app.js
Normal file
625
public/app.js
Normal 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();
|
||||||
59
public/index.html
Normal file
59
public/index.html
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="ru">
|
||||||
|
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
|
<title>Личный кабинет склада — Заказы</title>
|
||||||
|
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" />
|
||||||
|
<link href="/styles.css" rel="stylesheet" />
|
||||||
|
<script src="./app.js" defer></script>
|
||||||
|
</head>
|
||||||
|
|
||||||
|
<body class="bg-light">
|
||||||
|
<div class="container py-4">
|
||||||
|
<div class="d-flex flex-wrap gap-3 align-items-center justify-content-between mb-4">
|
||||||
|
<div>
|
||||||
|
<h1 class="h3 mb-1">Заказы склада</h1>
|
||||||
|
<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 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 class="col-lg-8">
|
||||||
|
<div id="orders" class="d-grid gap-3"></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</body>
|
||||||
|
|
||||||
|
</html>
|
||||||
15
public/styles.css
Normal file
15
public/styles.css
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
body {
|
||||||
|
font-family: "Inter", "Segoe UI", sans-serif;
|
||||||
|
}
|
||||||
|
|
||||||
|
.order-card {
|
||||||
|
border-left: 4px solid #0d6efd;
|
||||||
|
}
|
||||||
|
|
||||||
|
.order-meta {
|
||||||
|
font-size: 0.9rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.item-actions {
|
||||||
|
min-width: 220px;
|
||||||
|
}
|
||||||
42
server.js
42
server.js
@@ -1,42 +0,0 @@
|
|||||||
const express = require('express');
|
|
||||||
const app = express();
|
|
||||||
const PORT = process.env.PORT || 3000;
|
|
||||||
|
|
||||||
app.use(express.json());
|
|
||||||
|
|
||||||
app.get('/', (req, res) => {
|
|
||||||
res.json({
|
|
||||||
message: 'Hello, World!',
|
|
||||||
status: 'OK'
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
app.get('/health', (req, res) => {
|
|
||||||
res.status(200).json({
|
|
||||||
status: 'healthy',
|
|
||||||
timestamp: new Date().toISOString()
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
app.post('/api/data', (req, res) => {
|
|
||||||
const data = req.body;
|
|
||||||
res.json({
|
|
||||||
message: 'Data received',
|
|
||||||
data: data,
|
|
||||||
timestamp: new Date().toISOString()
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
app.use((req, res) => {
|
|
||||||
res.status(404).json({ error: 'Invalid route' });
|
|
||||||
});
|
|
||||||
|
|
||||||
app.use((err, req, res, next) => {
|
|
||||||
console.error(err.stack);
|
|
||||||
res.status(500).json({ error: 'Something went wrong!' });
|
|
||||||
});
|
|
||||||
|
|
||||||
app.listen(PORT, () => {
|
|
||||||
console.log(`✅ Server running on port ${PORT}`);
|
|
||||||
console.log(`📡 Local: http://localhost:${PORT}`);
|
|
||||||
});
|
|
||||||
660
server/db/database.js
Normal file
660
server/db/database.js
Normal file
@@ -0,0 +1,660 @@
|
|||||||
|
import mdb from "mariadb"
|
||||||
|
|
||||||
|
export const DB_INTERNAL_ERROR = 'INTERNAL';
|
||||||
|
export const DB_USER_ERROR = 'USER';
|
||||||
|
|
||||||
|
let currentDate = (new Date()).toISOString().slice(0, 10);
|
||||||
|
|
||||||
|
export function getCurrentDate() {
|
||||||
|
return currentDate;
|
||||||
|
}
|
||||||
|
|
||||||
|
function Random_Increase() {
|
||||||
|
return Math.floor(Math.random() * 5) + 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function setCurrentDate(newDate) {
|
||||||
|
currentDate = newDate;
|
||||||
|
console.log(`📅 Date changed to: ${currentDate}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default class DBAdapter {
|
||||||
|
#dbhost = 'localhost';
|
||||||
|
#dbPort = 3306;
|
||||||
|
#dbName = 'N';
|
||||||
|
#dbUserLogin = 'u';
|
||||||
|
#dbUserPassword = 'p';
|
||||||
|
#pool = null;
|
||||||
|
|
||||||
|
constructor({
|
||||||
|
dbHost,
|
||||||
|
dbPort,
|
||||||
|
dbName,
|
||||||
|
dbUserLogin,
|
||||||
|
dbUserPassword
|
||||||
|
}) {
|
||||||
|
this.#dbhost = dbHost;
|
||||||
|
this.#dbPort = dbPort;
|
||||||
|
this.#dbName = dbName;
|
||||||
|
this.#dbUserLogin = dbUserLogin;
|
||||||
|
this.#dbUserPassword = dbUserPassword;
|
||||||
|
this.#pool = mdb.createPool({
|
||||||
|
host: this.#dbhost,
|
||||||
|
port: this.#dbPort,
|
||||||
|
database: this.#dbName,
|
||||||
|
user: this.#dbUserLogin,
|
||||||
|
password: this.#dbUserPassword,
|
||||||
|
dateStrings: true,
|
||||||
|
acquireTimeout: 10000,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async #getConnection() {
|
||||||
|
return await this.#pool.getConnection();
|
||||||
|
}
|
||||||
|
|
||||||
|
async connect() {
|
||||||
|
try {
|
||||||
|
const conn = await this.#pool.getConnection();
|
||||||
|
console.log("✅ Database connection test successful");
|
||||||
|
conn.release();
|
||||||
|
} catch (err) {
|
||||||
|
console.error("❌ Database connection failed:", err.message);
|
||||||
|
return Promise.reject();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async disconnect() {
|
||||||
|
await this.#pool.end();
|
||||||
|
console.log("DISCONNECT");
|
||||||
|
}
|
||||||
|
|
||||||
|
async stock(){
|
||||||
|
try {
|
||||||
|
const products = await this.#pool.query('SELECT id FROM products');
|
||||||
|
for (const product of products) {
|
||||||
|
const increment = Random_Increase();
|
||||||
|
await this.#pool.query('UPDATE products SET quantity = quantity + ? WHERE id = ?', [
|
||||||
|
increment,
|
||||||
|
product.id
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
} catch (err){
|
||||||
|
return Promise.reject({
|
||||||
|
type: err
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async getProducts() {
|
||||||
|
try {
|
||||||
|
const products = await this.#pool.query('SELECT * FROM products ORDER BY name');
|
||||||
|
return products;
|
||||||
|
} catch(err){
|
||||||
|
console.log(`WHOOPS`);
|
||||||
|
return Promise.reject();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async getOrders() {
|
||||||
|
try {
|
||||||
|
const raw_orders = await this.#pool.query('SELECT * FROM orders ORDER BY order_date ASC');
|
||||||
|
|
||||||
|
const items = await this.#pool.query(
|
||||||
|
`SELECT order_items.*, products.name AS product_name FROM order_items
|
||||||
|
JOIN products ON order_items.product_id = products.id`
|
||||||
|
);
|
||||||
|
|
||||||
|
const groupedItems = {};
|
||||||
|
if (items && items.length > 0) {
|
||||||
|
items.forEach(item => {
|
||||||
|
const orderId = item.order_id;
|
||||||
|
if (!groupedItems[orderId]) {
|
||||||
|
groupedItems[orderId] = [];
|
||||||
|
}
|
||||||
|
groupedItems[orderId].push(item);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const ordersWithItems = raw_orders.map(order => {
|
||||||
|
return {
|
||||||
|
...order,
|
||||||
|
items: groupedItems[order.id] || []
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
return ordersWithItems;
|
||||||
|
} catch(err) {
|
||||||
|
console.log(`WHOOPS: ${err.message}`);
|
||||||
|
return Promise.reject(err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async addOrder({ id, customer_name, orderDate} ){
|
||||||
|
if (!id || !customer_name || !orderDate){
|
||||||
|
return Promise.reject({
|
||||||
|
type: DB_USER_ERROR,
|
||||||
|
error: new Error("Пустое имя клиента или дата заказа")
|
||||||
|
});
|
||||||
|
}
|
||||||
|
const currentDate = await getCurrentDate();
|
||||||
|
if (orderDate < currentDate){
|
||||||
|
return Promise.reject({
|
||||||
|
type: DB_USER_ERROR,
|
||||||
|
error: new Error("Недопустимая дата заказа")
|
||||||
|
});
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
await this.#pool.query('INSERT INTO orders (id, customer_name, order_date) VALUES (?, ?, ?)',
|
||||||
|
[id, customer_name, orderDate]
|
||||||
|
);
|
||||||
|
} catch(err){
|
||||||
|
return Promise.reject({
|
||||||
|
type: DB_INTERNAL_ERROR,
|
||||||
|
error: new Error("Ошибка сервера")
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async getOrdersByDate(date){
|
||||||
|
try {
|
||||||
|
const order_ids = await this.#pool.query('SELECT id FROM orders WHERE order_date = ?', [date]);
|
||||||
|
return order_ids;
|
||||||
|
} catch(err){
|
||||||
|
return Promise.reject();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async clearOrders(orderIds) {
|
||||||
|
if (!orderIds || orderIds.length === 0) {
|
||||||
|
console.log("No orders to delete");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const placeholders = orderIds.map(() => '?').join(',');
|
||||||
|
|
||||||
|
const result = await this.#pool.query(
|
||||||
|
`DELETE FROM orders WHERE id IN (${placeholders})`,
|
||||||
|
orderIds
|
||||||
|
);
|
||||||
|
|
||||||
|
console.log(`✅ Deleted ${result.affectedRows} orders with IDs:`, orderIds);
|
||||||
|
|
||||||
|
} catch(err) {
|
||||||
|
console.error(`❌ Error deleting orders:`, err.message);
|
||||||
|
return Promise.reject();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async changeOrderInfo({ id, customer_name, orderDate }) {
|
||||||
|
if (!id || !customer_name || !orderDate) {
|
||||||
|
return Promise.reject({
|
||||||
|
type: DB_USER_ERROR,
|
||||||
|
error: new Error("Нужен ID заказа, имя и дата"),
|
||||||
|
message: "Нужен ID заказа, имя и дата" // Добавляем message напрямую
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const currentDate = await getCurrentDate();
|
||||||
|
if (orderDate < currentDate) {
|
||||||
|
return Promise.reject({
|
||||||
|
type: DB_USER_ERROR,
|
||||||
|
error: new Error("Дата заказа не может быть раньше текущей"),
|
||||||
|
message: "Дата заказа не может быть раньше текущей"
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const order = await this.#pool.query('SELECT * FROM orders WHERE id = ?', [id]);
|
||||||
|
|
||||||
|
if (!order || order.length === 0) { // Исправлено: проверяем length
|
||||||
|
return Promise.reject({
|
||||||
|
type: DB_USER_ERROR,
|
||||||
|
error: new Error("Заказ не найден"),
|
||||||
|
message: "Заказ не найден"
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const updatedName = customer_name;
|
||||||
|
const updatedDate = orderDate;
|
||||||
|
|
||||||
|
await this.#pool.query('UPDATE orders SET customer_name = ?, order_date = ? WHERE id = ?',
|
||||||
|
[updatedName, updatedDate, id]
|
||||||
|
);
|
||||||
|
|
||||||
|
} catch(err) {
|
||||||
|
console.error('Database error in changeOrderInfo:', err);
|
||||||
|
return Promise.reject({
|
||||||
|
type: DB_INTERNAL_ERROR,
|
||||||
|
error: new Error("Ошибка сервера"),
|
||||||
|
message: err.message || "Ошибка операции с базой данных",
|
||||||
|
details: err.message
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async deleteOrderById(order_id) {
|
||||||
|
let connection;
|
||||||
|
|
||||||
|
try {
|
||||||
|
connection = await this.#pool.getConnection();
|
||||||
|
await connection.beginTransaction();
|
||||||
|
|
||||||
|
const orderItems = await connection.query(
|
||||||
|
`SELECT product_id, quantity FROM order_items WHERE order_id = ?`,
|
||||||
|
[order_id]
|
||||||
|
);
|
||||||
|
|
||||||
|
for (const item of orderItems) {
|
||||||
|
await connection.query(
|
||||||
|
'UPDATE products SET quantity = quantity + ? WHERE id = ?',
|
||||||
|
[item.quantity, item.product_id]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
await connection.query(
|
||||||
|
`DELETE FROM order_items WHERE order_id = ?`,
|
||||||
|
[order_id]
|
||||||
|
);
|
||||||
|
|
||||||
|
await connection.query(
|
||||||
|
`DELETE FROM orders WHERE id = ?`,
|
||||||
|
[order_id]
|
||||||
|
);
|
||||||
|
|
||||||
|
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
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async addOrderItem({ orderId, productId, quantity }) {
|
||||||
|
let connection;
|
||||||
|
|
||||||
|
try {
|
||||||
|
connection = await this.#pool.getConnection();
|
||||||
|
|
||||||
|
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];
|
||||||
|
|
||||||
|
if (!productRow) {
|
||||||
|
await connection.rollback();
|
||||||
|
connection.release();
|
||||||
|
return Promise.reject({
|
||||||
|
type: DB_USER_ERROR,
|
||||||
|
error: new Error("Товар не найден")
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (productRow.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 = ?',
|
||||||
|
[quantity, productId]
|
||||||
|
);
|
||||||
|
|
||||||
|
const result = await connection.query(
|
||||||
|
'INSERT INTO order_items (order_id, product_id, quantity) VALUES (?, ?, ?)',
|
||||||
|
[orderId, productId, quantity]
|
||||||
|
);
|
||||||
|
|
||||||
|
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, productId }) {
|
||||||
|
let connection;
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (!itemId || !Number.isFinite(quantity) || quantity <= 0) {
|
||||||
|
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];
|
||||||
|
if (!itemRow) {
|
||||||
|
await connection.rollback();
|
||||||
|
connection.release();
|
||||||
|
return Promise.reject({
|
||||||
|
type: DB_USER_ERROR,
|
||||||
|
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;
|
||||||
|
|
||||||
|
if (diff > 0) {
|
||||||
|
const product = await connection.query(
|
||||||
|
'SELECT quantity FROM products WHERE id = ? FOR UPDATE',
|
||||||
|
[itemRow.product_id]
|
||||||
|
);
|
||||||
|
|
||||||
|
const productRow = product?.[0];
|
||||||
|
if (!productRow || productRow.quantity < diff) {
|
||||||
|
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 = ?',
|
||||||
|
[diff, itemRow.product_id]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (diff < 0) {
|
||||||
|
await connection.query(
|
||||||
|
'UPDATE products SET quantity = quantity + ? WHERE id = ?',
|
||||||
|
[-diff, itemRow.product_id]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
await connection.query(
|
||||||
|
'UPDATE order_items SET quantity = ? WHERE id = ?',
|
||||||
|
[quantity, 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
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async deleteOrderItem(itemId) {
|
||||||
|
let connection;
|
||||||
|
|
||||||
|
try {
|
||||||
|
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];
|
||||||
|
if (!itemRow) {
|
||||||
|
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(
|
||||||
|
'DELETE FROM order_items WHERE id = ?',
|
||||||
|
[itemId]
|
||||||
|
);
|
||||||
|
|
||||||
|
await connection.commit();
|
||||||
|
connection.release();
|
||||||
|
|
||||||
|
} 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 }) {
|
||||||
|
let connection;
|
||||||
|
|
||||||
|
try {
|
||||||
|
connection = await this.#pool.getConnection();
|
||||||
|
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];
|
||||||
|
if (!itemRow) {
|
||||||
|
await connection.rollback();
|
||||||
|
connection.release();
|
||||||
|
return Promise.reject({
|
||||||
|
type: DB_USER_ERROR,
|
||||||
|
error: new Error("Позиция заказа не найдена")
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (itemRow.order_id === targetOrderId) {
|
||||||
|
await connection.rollback();
|
||||||
|
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();
|
||||||
|
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
5
server/docker.env
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
HOST="db"
|
||||||
|
PORT=3306
|
||||||
|
DATABASE="delivery"
|
||||||
|
USER="app"
|
||||||
|
PASSWORD="app"
|
||||||
410
server/server.js
Normal file
410
server/server.js
Normal file
@@ -0,0 +1,410 @@
|
|||||||
|
import express from "express";
|
||||||
|
import dotenv from "dotenv"
|
||||||
|
import { randomUUID } from "crypto";
|
||||||
|
import DBAdapter, { getCurrentDate, setCurrentDate } 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({
|
||||||
|
path: './server/docker.env'
|
||||||
|
});
|
||||||
|
|
||||||
|
const {
|
||||||
|
HOST,
|
||||||
|
PORT,
|
||||||
|
DATABASE,
|
||||||
|
USER,
|
||||||
|
PASSWORD
|
||||||
|
} = process.env;
|
||||||
|
|
||||||
|
const appPort = 3000;
|
||||||
|
|
||||||
|
const app = express();
|
||||||
|
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({
|
||||||
|
dbHost: HOST,
|
||||||
|
dbPort: PORT,
|
||||||
|
dbName: DATABASE,
|
||||||
|
dbUserLogin: USER,
|
||||||
|
dbUserPassword: PASSWORD
|
||||||
|
});
|
||||||
|
|
||||||
|
function AddDays(dateString, days) {
|
||||||
|
let date = new Date(dateString);
|
||||||
|
date.setDate(date.getDate() + days);
|
||||||
|
return date.toISOString().slice(0, 10);
|
||||||
|
}
|
||||||
|
|
||||||
|
app.get('/api/current-date', async (req, res) => {
|
||||||
|
let currentDate = getCurrentDate();
|
||||||
|
res.json({ currentDate });
|
||||||
|
});
|
||||||
|
|
||||||
|
app.post('/api/current-date/advance', async (req, res) => {
|
||||||
|
let currentDate = getCurrentDate();
|
||||||
|
try {
|
||||||
|
const raw_ids = await adapter.getOrdersByDate(currentDate);
|
||||||
|
if (raw_ids && raw_ids.length > 0) {
|
||||||
|
const ids = raw_ids.map(item => item.id);
|
||||||
|
await adapter.clearOrders(ids);
|
||||||
|
}
|
||||||
|
let nextDate = AddDays(currentDate, 1);
|
||||||
|
await adapter.stock();
|
||||||
|
await setCurrentDate(nextDate);
|
||||||
|
res.json({ currentDate: nextDate });
|
||||||
|
} catch (err){
|
||||||
|
res.statusCode = 500;
|
||||||
|
res.message = "WHOOPS";
|
||||||
|
res.json({
|
||||||
|
timeStamp: new Date().toISOString(),
|
||||||
|
statusCode: res.statusCode,
|
||||||
|
error : `${err}`
|
||||||
|
})
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
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 {
|
||||||
|
const db_orders = await adapter.getOrders();
|
||||||
|
|
||||||
|
const orders = db_orders.map(
|
||||||
|
( {id, customer_name, order_date, status, total_amount, items} ) => ({
|
||||||
|
ID: id,
|
||||||
|
customer: customer_name,
|
||||||
|
date: order_date,
|
||||||
|
status: status,
|
||||||
|
total: total_amount,
|
||||||
|
items: items ? items.map(item => ({
|
||||||
|
id: item.id,
|
||||||
|
product_id: item.product_id,
|
||||||
|
product_name: item.product_name || item.name,
|
||||||
|
quantity: item.quantity,
|
||||||
|
price: item.price
|
||||||
|
})) : []
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
res.statusCode = 200;
|
||||||
|
res.message = "OK";
|
||||||
|
res.json(orders);
|
||||||
|
|
||||||
|
} catch (err) {
|
||||||
|
res.statusCode = 500;
|
||||||
|
res.message = "WHOOPS";
|
||||||
|
res.json({
|
||||||
|
timeStamp: new Date().toISOString(),
|
||||||
|
statusCode: 500,
|
||||||
|
error: `${err}`
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
app.post('/api/orders', async (req, res) => {
|
||||||
|
let { customerName, orderDate } = req.body;
|
||||||
|
let id = randomUUID();
|
||||||
|
|
||||||
|
try {
|
||||||
|
await adapter.addOrder({
|
||||||
|
id,
|
||||||
|
customer_name: customerName,
|
||||||
|
orderDate
|
||||||
|
});
|
||||||
|
|
||||||
|
res.status(201).json({
|
||||||
|
id,
|
||||||
|
customerName,
|
||||||
|
orderDate
|
||||||
|
});
|
||||||
|
|
||||||
|
} catch (err) {
|
||||||
|
console.log('Error in POST /api/orders:', err);
|
||||||
|
switch(err.type) {
|
||||||
|
case DB_INTERNAL_ERROR:
|
||||||
|
res.status(500).json({
|
||||||
|
timeStamp: new Date().toISOString(),
|
||||||
|
statusCode: 500,
|
||||||
|
error: err.error?.message || err.message
|
||||||
|
});
|
||||||
|
break;
|
||||||
|
|
||||||
|
case DB_USER_ERROR:
|
||||||
|
res.status(400).json({
|
||||||
|
timeStamp: new Date().toISOString(),
|
||||||
|
statusCode: 400,
|
||||||
|
error: err.error?.message || err.message
|
||||||
|
});
|
||||||
|
break;
|
||||||
|
|
||||||
|
default:
|
||||||
|
res.status(500).json({
|
||||||
|
timeStamp: new Date().toISOString(),
|
||||||
|
statusCode: 500,
|
||||||
|
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) => {
|
||||||
|
try {
|
||||||
|
await adapter.deleteOrderById(req.params.id);
|
||||||
|
res.statusCode = 200;
|
||||||
|
res.message = "OK";
|
||||||
|
res.json({message: "success"});
|
||||||
|
} catch (err){
|
||||||
|
res.statusCode = 500;
|
||||||
|
res.message = "WHOOPS";
|
||||||
|
res.json({
|
||||||
|
timeStamp: new Date().toISOString(),
|
||||||
|
statusCode: 500,
|
||||||
|
error: `${err}`
|
||||||
|
});
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
app.post('/api/orders/:orderId/items', async (req, res) => {
|
||||||
|
let orderId = req.params.orderId;
|
||||||
|
let { productId, quantity } = req.body;
|
||||||
|
|
||||||
|
if (!productId || !quantity || quantity <= 0) {
|
||||||
|
return res.status(400).json({
|
||||||
|
timeStamp: new Date().toISOString(),
|
||||||
|
statusCode: 400,
|
||||||
|
error: "Некорректный товар или количество"
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const itemId = await adapter.addOrderItem({
|
||||||
|
orderId,
|
||||||
|
productId,
|
||||||
|
quantity
|
||||||
|
});
|
||||||
|
|
||||||
|
return res.status(201).json({
|
||||||
|
itemId: itemId.toString(),
|
||||||
|
orderId,
|
||||||
|
productId,
|
||||||
|
quantity
|
||||||
|
});
|
||||||
|
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Error adding order item:', err);
|
||||||
|
|
||||||
|
if (err.type === DB_USER_ERROR) {
|
||||||
|
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) => {
|
||||||
|
let itemId = req.params.itemId;
|
||||||
|
let { quantity, productId } = req.body;
|
||||||
|
quantity = Number.parseInt(quantity, 10);
|
||||||
|
|
||||||
|
try {
|
||||||
|
await adapter.updateOrderItem({
|
||||||
|
itemId,
|
||||||
|
productId,
|
||||||
|
quantity
|
||||||
|
});
|
||||||
|
|
||||||
|
res.status(201).json({
|
||||||
|
itemId,
|
||||||
|
productId,
|
||||||
|
quantity
|
||||||
|
});
|
||||||
|
|
||||||
|
} catch (err) {
|
||||||
|
const statusCode = err.type === DB_USER_ERROR ? 400 : 500;
|
||||||
|
res.status(statusCode).json({
|
||||||
|
timeStamp: new Date().toISOString(),
|
||||||
|
statusCode,
|
||||||
|
error: err.error?.message || err.message
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
app.delete('/api/orders/:orderId/items/:itemId', async (req, res) => {
|
||||||
|
try {
|
||||||
|
await adapter.deleteOrderItem(req.params.itemId);
|
||||||
|
return res.status(204).end();
|
||||||
|
} catch (err) {
|
||||||
|
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: "Внутренняя ошибка сервера",
|
||||||
|
details: err.message
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
app.post('/api/order-items/:itemId/move', async (req, res) => {
|
||||||
|
let itemId = req.params.itemId;
|
||||||
|
let targetOrderId = req.body.targetOrderId;
|
||||||
|
|
||||||
|
try {
|
||||||
|
await adapter.moveOrderItem({
|
||||||
|
itemId,
|
||||||
|
targetOrderId,
|
||||||
|
});
|
||||||
|
|
||||||
|
res.status(201).json({
|
||||||
|
itemId,
|
||||||
|
targetOrderId,
|
||||||
|
});
|
||||||
|
|
||||||
|
} catch (err) {
|
||||||
|
// TODO
|
||||||
|
res.status(500).json({
|
||||||
|
timeStamp: new Date().toISOString(),
|
||||||
|
statusCode: 500,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
|
app.use((req, res) => {
|
||||||
|
res.status(404).json({ error: 'Неверный маршрут' });
|
||||||
|
});
|
||||||
|
|
||||||
|
const server = app.listen(appPort, async() => {
|
||||||
|
try {
|
||||||
|
await adapter.connect();
|
||||||
|
console.log(`✅ Server running on port ${appPort}`);
|
||||||
|
console.log(`📡 Local: http://localhost:${appPort}`);
|
||||||
|
} catch(err){
|
||||||
|
console.log("Shutting down application...");
|
||||||
|
process.exit(100);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
process.on('SIGTERM', () => {
|
||||||
|
console.log("CLOSE APP");
|
||||||
|
server.close(async () => {
|
||||||
|
await adapter.disconnect();
|
||||||
|
console.log("DB DISCONNECTED");
|
||||||
|
});
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user