Compare commits

...

18 Commits

Author SHA1 Message Date
18999515b2 Merge pull request 'Docker' (#3) from Docker into master
Reviewed-on: #3
2026-01-03 18:46:21 +01:00
23c67c9e6e Fix button logic 2026-01-03 20:41:15 +03:00
75df8970fd Move client and server dockerfile to special path 2026-01-03 19:54:48 +03:00
8b0fa219aa Update README.md 2026-01-03 19:50:42 +03:00
22b592e3ef Remove slnx from project 2026-01-03 19:50:34 +03:00
151c98e994 Server 2026-01-03 19:47:01 +03:00
8c9ea53964 Nginx 2026-01-03 19:46:45 +03:00
c6c3cf2227 env file for Docker 2026-01-03 19:44:35 +03:00
ec2531cacb Initial sql for MariaDB 2026-01-03 19:44:22 +03:00
fab2dd6ac9 Merge pull request 'Client' (#2) from Client into master
Reviewed-on: #2
2026-01-03 16:50:30 +01:00
7b0a6c9f37 Merge branch 'master' into Client 2026-01-03 16:50:19 +01:00
94b0216568 Merge branch 'master' of ssh://git.tjoyspotifylastfm.ru:10022/ParkSuMin/DELIVER_MAN 2026-01-03 18:36:43 +03:00
62ecf92ce7 Update package-lock.json 2026-01-03 18:36:37 +03:00
f3d834574b Beautify HTML 2026-01-03 18:34:47 +03:00
08ddf65ec1 Switch-construction in click 2026-01-03 18:33:53 +03:00
cd1f3a1e87 Beautify 2026-01-03 18:22:36 +03:00
25a92e4b98 Switch ID 2026-01-03 18:21:09 +03:00
78ddbb4601 Merge pull request 'API' (#1) from API into master
Reviewed-on: #1
2026-01-03 16:18:52 +01:00
14 changed files with 2278 additions and 1232 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,15 @@
# DELIVER_MAN # DELIVER_MAN
## Docker
Run client + server + database:
```bash
docker compose up --build
```
Open the client at `http://localhost:8080`.
Notes:
- The API is proxied through the client container to the server at `/api`.
- The MariaDB schema/data is auto-initialized from `docker/init.sql` on first run.

60
docker-compose.yml Normal file
View File

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

4
docker/Dockerfile.client Normal file
View File

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

13
docker/Dockerfile.server Normal file
View File

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

105
docker/init.sql Normal file
View File

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

19
docker/nginx.conf Normal file
View File

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

2489
package-lock.json generated

File diff suppressed because it is too large Load Diff

629
public/app.js Normal file
View File

@@ -0,0 +1,629 @@
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;
if (!orderDateInput.value) {
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;
if (!orderDateInput.value) {
orderDateInput.value = initialDate;
}
orderForm.addEventListener('submit', async (event) => {
event.preventDefault();
try {
await fetchJson('/api/orders', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
customerName: customerNameInput.value.trim(),
orderDate: orderDateInput.value
})
});
customerNameInput.value = '';
orderDateInput.value = currentDate;
await refreshData();
} catch (error) {
showNotification(error.message, 'warning');
}
});
advanceButton.addEventListener('click', async () => {
try {
await fetchJson('/api/current-date/advance', {
method: 'POST'
});
await refreshData();
showNotification('Дата переведена. Заказы за сегодня отправлены.', 'success');
} catch (error) {
showNotification(error.message, 'warning');
}
});
ordersContainer.addEventListener('submit', async (event) => {
if (event.target.matches('form[data-action="add-item"]')) {
event.preventDefault();
const orderId = event.target.dataset.orderId;
const productId = event.target.productId.value;
const quantity = Number.parseInt(event.target.quantity.value, 10);
try {
const response = await fetchJson(`/api/orders/${orderId}/items`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
productId,
quantity
})
});
const order = orders.find((entry) => entry.id === orderId);
const product = products.find((entry) => entry.id === productId);
if (order) {
const newItem = normalizeOrderItems([{
id: response?.itemId,
product_id: productId,
product_name: product?.name,
quantity
}])[0];
order.items = [...order.items, newItem];
renderOrders();
}
event.target.reset();
await refreshData();
} catch (error) {
showNotification(error.message, 'warning');
}
}
});
ordersContainer.addEventListener('click', async (event) => {
const {
action,
id,
itemId,
orderId
} = event.target.dataset;
try {
switch (action) {
case 'delete-order': {
await fetchJson(`/api/orders/${id}`, {
method: 'DELETE'
});
await refreshData();
return;
}
case 'edit-order': {
const newName = prompt('Введите новое ФИО заказчика', '');
if (newName === null) {
return;
}
const newDate = prompt('Введите дату заказа (YYYY-MM-DD)', currentDate);
if (!newDate) {
return;
}
Date
await fetchJson(`/api/orders/${id}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
customerName: newName,
orderDate: newDate
})
});
await refreshData();
return;
}
case 'save-item': {
const quantityInput = ordersContainer.querySelector(
`[data-action="item-quantity"][data-item-id="${itemId}"]`
);
const productSelect = ordersContainer.querySelector(
`[data-action="item-product"][data-item-id="${itemId}"]`
);
try {
await fetchJson(`/api/orders/${orderId}/items/${itemId}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
productId: productSelect.value,
quantity: Number.parseInt(quantityInput.value, 10)
})
});
await refreshData();
return;
} catch (error) {
showNotification(error.message, 'warning');
await refreshData();
return;
}
}
case 'delete-item': {
await fetchJson(`/api/orders/${orderId}/items/${itemId}`, {
method: 'DELETE'
});
await refreshData();
return;
}
case 'move-item': {
const targetSelect = ordersContainer.querySelector(
`[data-action="move-target"][data-item-id="${itemId}"]`
);
if (!targetSelect.value) {
showNotification('Выберите заказ для перемещения.', 'warning');
return;
}
await fetchJson(`/api/order-items/${itemId}/move`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
targetOrderId: targetSelect.value
})
});
await refreshData();
return;
}
default:
return;
}
} catch (error) {
showNotification(error.message, 'warning');
}
});
refreshData().catch((error) => {
showNotification(error.message, 'warning');
});
}
initializeApp();

View File

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

View File

@@ -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("Invalid item or quantity")
});
}
connection = await this.#pool.getConnection(); connection = await this.#pool.getConnection();
await connection.beginTransaction(); await connection.beginTransaction();
@@ -406,6 +413,51 @@ export default class DBAdapter {
}); });
} }
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("Product not found")
});
}
if (newProductRow.quantity < quantity) {
await connection.rollback();
connection.release();
return Promise.reject({
type: DB_USER_ERROR,
error: new Error("Insufficient product quantity")
});
}
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) {

5
server/docker.env Normal file
View File

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

View File

@@ -4,8 +4,9 @@ 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 {
@@ -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
}); });
} }
}); });