Docker #3
5
.dockerignore
Normal file
5
.dockerignore
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
node_modules
|
||||||
|
.git
|
||||||
|
.gitignore
|
||||||
|
.gitattributes
|
||||||
|
README.md
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
<Solution>
|
|
||||||
<Project Path="DELIVER_MAN.esproj">
|
|
||||||
<Build />
|
|
||||||
<Deploy />
|
|
||||||
</Project>
|
|
||||||
</Solution>
|
|
||||||
14
README.md
14
README.md
@@ -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
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -121,7 +121,7 @@ class OrderCard {
|
|||||||
idCell.textContent = item.product_id ?? item.id;
|
idCell.textContent = item.product_id ?? item.id;
|
||||||
|
|
||||||
const productCell = document.createElement('td');
|
const productCell = document.createElement('td');
|
||||||
const productSelect = this.buildProductSelect(item);
|
const productSelect = this.buildProductSelect(item.product_id);
|
||||||
productSelect.classList.add('form-select-sm');
|
productSelect.classList.add('form-select-sm');
|
||||||
productSelect.dataset.action = 'item-product';
|
productSelect.dataset.action = 'item-product';
|
||||||
productSelect.dataset.itemId = item.id;
|
productSelect.dataset.itemId = item.id;
|
||||||
@@ -220,7 +220,12 @@ class OrderCard {
|
|||||||
const productLabel = document.createElement('label');
|
const productLabel = document.createElement('label');
|
||||||
productLabel.className = 'form-label';
|
productLabel.className = 'form-label';
|
||||||
productLabel.textContent = 'Товар';
|
productLabel.textContent = 'Товар';
|
||||||
const productSelect = this.buildProductSelect();
|
const usedProductIds = new Set(
|
||||||
|
(this.order.items || [])
|
||||||
|
.map((item) => item.product_id)
|
||||||
|
.filter((value) => value !== null && value !== undefined)
|
||||||
|
);
|
||||||
|
const productSelect = this.buildProductSelect(undefined, usedProductIds);
|
||||||
const productSelectId = `add-item-product-${this.order.id}`;
|
const productSelectId = `add-item-product-${this.order.id}`;
|
||||||
productSelect.name = 'productId';
|
productSelect.name = 'productId';
|
||||||
productSelect.id = productSelectId;
|
productSelect.id = productSelectId;
|
||||||
@@ -253,6 +258,16 @@ class OrderCard {
|
|||||||
addButton.textContent = 'Добавить позицию';
|
addButton.textContent = 'Добавить позицию';
|
||||||
actionCol.appendChild(addButton);
|
actionCol.appendChild(addButton);
|
||||||
|
|
||||||
|
if (productSelect.options.length === 0) {
|
||||||
|
const placeholder = document.createElement('option');
|
||||||
|
placeholder.value = '';
|
||||||
|
placeholder.textContent = 'Нет доступных позиций';
|
||||||
|
productSelect.appendChild(placeholder);
|
||||||
|
productSelect.disabled = true;
|
||||||
|
quantityInput.disabled = true;
|
||||||
|
addButton.disabled = true;
|
||||||
|
}
|
||||||
|
|
||||||
form.appendChild(productCol);
|
form.appendChild(productCol);
|
||||||
form.appendChild(quantityCol);
|
form.appendChild(quantityCol);
|
||||||
form.appendChild(actionCol);
|
form.appendChild(actionCol);
|
||||||
@@ -260,10 +275,13 @@ class OrderCard {
|
|||||||
return form;
|
return form;
|
||||||
}
|
}
|
||||||
|
|
||||||
buildProductSelect(selectedId) {
|
buildProductSelect(selectedId, excludedIds) {
|
||||||
const select = document.createElement('select');
|
const select = document.createElement('select');
|
||||||
select.className = 'form-select';
|
select.className = 'form-select';
|
||||||
this.products.forEach((product) => {
|
this.products.forEach((product) => {
|
||||||
|
if (excludedIds && excludedIds.has(product.id)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
const option = document.createElement('option');
|
const option = document.createElement('option');
|
||||||
option.value = product.id;
|
option.value = product.id;
|
||||||
option.textContent = product.name;
|
option.textContent = product.name;
|
||||||
@@ -313,7 +331,7 @@ async function fetchJson(url, options) {
|
|||||||
const payload = await response.json().catch(() => ({
|
const payload = await response.json().catch(() => ({
|
||||||
message: 'Ошибка запроса.'
|
message: 'Ошибка запроса.'
|
||||||
}));
|
}));
|
||||||
throw new Error(payload.message || 'Ошибка запроса.');
|
throw new Error(payload.error || payload.message || 'Error');
|
||||||
}
|
}
|
||||||
if (response.status === 204) {
|
if (response.status === 204) {
|
||||||
return null;
|
return null;
|
||||||
@@ -549,6 +567,7 @@ function initializeApp() {
|
|||||||
`[data-action="item-product"][data-item-id="${itemId}"]`
|
`[data-action="item-product"][data-item-id="${itemId}"]`
|
||||||
);
|
);
|
||||||
|
|
||||||
|
try {
|
||||||
await fetchJson(`/api/orders/${orderId}/items/${itemId}`, {
|
await fetchJson(`/api/orders/${orderId}/items/${itemId}`, {
|
||||||
method: 'PUT',
|
method: 'PUT',
|
||||||
headers: {
|
headers: {
|
||||||
@@ -561,6 +580,11 @@ function initializeApp() {
|
|||||||
});
|
});
|
||||||
await refreshData();
|
await refreshData();
|
||||||
return;
|
return;
|
||||||
|
} catch (error) {
|
||||||
|
showNotification(error.message, 'warning');
|
||||||
|
await refreshData();
|
||||||
|
return;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
case 'delete-item': {
|
case 'delete-item': {
|
||||||
await fetchJson(`/api/orders/${orderId}/items/${itemId}`, {
|
await fetchJson(`/api/orders/${orderId}/items/${itemId}`, {
|
||||||
|
|||||||
@@ -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
5
server/docker.env
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
HOST="db"
|
||||||
|
PORT=3306
|
||||||
|
DATABASE="delivery"
|
||||||
|
USER="app"
|
||||||
|
PASSWORD="app"
|
||||||
@@ -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
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user