Compare commits

..

3 Commits

Author SHA1 Message Date
13fe841e54 Database 2026-01-03 18:17:29 +03:00
58b88c05a7 CORS problem resolve 2026-01-03 18:16:18 +03:00
85d1a9f046 API check 2026-01-03 18:15:52 +03:00
4 changed files with 469 additions and 787 deletions

View File

@@ -1,605 +0,0 @@
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);
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 productSelect = this.buildProductSelect();
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);
form.appendChild(productCol);
form.appendChild(quantityCol);
form.appendChild(actionCol);
return form;
}
buildProductSelect(selectedId) {
const select = document.createElement('select');
select.className = 'form-select';
this.products.forEach((product) => {
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.message || 'Ошибка запроса.');
}
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}"]`
);
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;
}
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 href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" /> <link
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>
<button id="advance-date" class="btn btn-outline-primary">Переключить дату +1</button> </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 id="notification" class="alert d-none" role="alert"></div> <div class="col-lg-8">
<div id="orders" class="d-grid gap-3"></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>
</div>
</div> </div>
</body> </body>
</html>
</html>

View File

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

View File

@@ -20,6 +20,16 @@ const appPort = 3000;
const app = express(); const app = express();
app.use(express.json()); app.use(express.json());
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
res.setHeader('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE');
if (req.method === 'OPTIONS') {
res.sendStatus(204);
return;
}
next();
});
const adapter = new DBAdapter({ const adapter = new DBAdapter({
dbHost: HOST, dbHost: HOST,
@@ -40,31 +50,6 @@ app.get('/api/current-date', async (req, res) => {
res.json({ currentDate }); res.json({ currentDate });
}); });
app.get('/api/products', async(req, res) => {
try {
const db_products = await adapter.getProducts();
const products = db_products.map(
( {id, name, quantity} ) => ({
ID: id,
pr_name: name,
count: quantity
})
);
res.statusCode = 200;
res.message = "OK";
res.json(products);
} catch (err){
res.statusCode = 500;
res.message = "WHOOPS";
res.json({
timeStamp: new Date().toISOString(),
statusCode: 500,
error : `${err}`
})
}
});
app.post('/api/current-date/advance', async (req, res) => { app.post('/api/current-date/advance', async (req, res) => {
let currentDate = getCurrentDate(); let currentDate = getCurrentDate();
try { try {
@@ -88,7 +73,32 @@ app.post('/api/current-date/advance', async (req, res) => {
} }
}); });
app.get('/api/orders', async(req, res) => { app.get('/api/products', async (req, res) => {
try {
const db_products = await adapter.getProducts();
const products = db_products.map(
( {id, name, quantity} ) => ({
ID: id,
pr_name: name,
count: quantity
})
);
res.statusCode = 200;
res.message = "OK";
res.json(products);
} catch (err){
res.statusCode = 500;
res.message = "WHOOPS";
res.json({
timeStamp: new Date().toISOString(),
statusCode: 500,
error : `${err}`
})
}
});
app.get('/api/orders', async (req, res) => {
try { try {
const db_orders = await adapter.getOrders(); const db_orders = await adapter.getOrders();
@@ -100,6 +110,7 @@ app.get('/api/orders', async(req, res) => {
status: status, status: status,
total: total_amount, total: total_amount,
items: items ? items.map(item => ({ items: items ? items.map(item => ({
id: item.id,
product_id: item.product_id, product_id: item.product_id,
product_name: item.product_name || item.name, product_name: item.product_name || item.name,
quantity: item.quantity, quantity: item.quantity,
@@ -170,6 +181,64 @@ app.post('/api/orders', async (req, res) => {
} }
}); });
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: "Customer name and order date are required"
});
}
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 ||
"Unknown error occurred";
switch(err.type) {
case DB_INTERNAL_ERROR:
return res.status(500).json({
timeStamp: new Date().toISOString(),
statusCode: 500,
error: errorMessage,
details: err.details || "Internal server error"
});
case DB_USER_ERROR:
return res.status(400).json({
timeStamp: new Date().toISOString(),
statusCode: 400,
error: errorMessage
});
default:
return res.status(500).json({
timeStamp: new Date().toISOString(),
statusCode: 500,
error: errorMessage
});
}
}
});
app.delete('/api/orders/:id', async (req, res) => { app.delete('/api/orders/:id', async (req, res) => {
try { try {
await adapter.deleteOrderById(req.params.id); await adapter.deleteOrderById(req.params.id);
@@ -191,25 +260,52 @@ app.post('/api/orders/:orderId/items', async (req, res) => {
let orderId = req.params.orderId; let orderId = req.params.orderId;
let { productId, quantity } = req.body; let { productId, quantity } = req.body;
if (!productId || !quantity || quantity <= 0) {
return res.status(400).json({
timeStamp: new Date().toISOString(),
statusCode: 400,
error: "Invalid productId or quantity"
});
}
try { try {
await adapter.addOrderItem({ const itemId = await adapter.addOrderItem({
orderId, orderId,
productId, productId,
quantity quantity
}); });
res.status(201).json({ return res.status(201).json({
itemId: itemId.toString(),
orderId, orderId,
productId, productId,
quantity quantity
}); });
} catch (err) { } catch (err) {
// TODO console.error('Error adding order item:', err);
res.status(500).json({
timeStamp: new Date().toISOString(), if (err.type === DB_USER_ERROR) {
statusCode: 500, return res.status(400).json({
}); timeStamp: new Date().toISOString(),
statusCode: 400,
error: err.error?.message || "Invalid request",
details: err.details
});
} else if (err.type === DB_INTERNAL_ERROR) {
return res.status(500).json({
timeStamp: new Date().toISOString(),
statusCode: 500,
error: "Internal server error",
details: err.error?.message
});
} else {
return res.status(500).json({
timeStamp: new Date().toISOString(),
statusCode: 500,
error: "Internal server error"
});
}
} }
}); });
@@ -229,10 +325,10 @@ app.put('/api/orders/:orderId/items/:itemId', async (req, res) => {
}); });
} catch (err) { } catch (err) {
// TODO res.json({
res.status(500).json({
timeStamp: new Date().toISOString(), timeStamp: new Date().toISOString(),
statusCode: 500, statusCode: 500,
error: err.message
}); });
} }
}); });
@@ -240,17 +336,25 @@ app.put('/api/orders/:orderId/items/:itemId', async (req, res) => {
app.delete('/api/orders/:orderId/items/:itemId', async (req, res) => { app.delete('/api/orders/:orderId/items/:itemId', async (req, res) => {
try { try {
await adapter.deleteOrderItem(req.params.itemId); await adapter.deleteOrderItem(req.params.itemId);
res.status(204).end(); return res.status(204).end();
} catch (err){ } catch (err) {
res.statusCode = 500; if (err.type === DB_INTERNAL_ERROR) {
res.message = "WHOOPS"; return res.status(500).json({
res.json({ timeStamp: new Date().toISOString(),
timeStamp: new Date().toISOString(), statusCode: 500,
statusCode: 500, error: "Server error",
error: `${err}` details: err.error.message
}); });
} else {
return res.status(500).json({
timeStamp: new Date().toISOString(),
statusCode: 500,
error: "Internal server error",
details: err.message
});
}
} }
}) });
app.post('/api/order-items/:itemId/move', async (req, res) => { app.post('/api/order-items/:itemId/move', async (req, res) => {
let itemId = req.params.itemId; let itemId = req.params.itemId;
@@ -298,4 +402,4 @@ process.on('SIGTERM', () => {
await adapter.disconnect(); await adapter.disconnect();
console.log("DB DISCONNECTED"); console.log("DB DISCONNECTED");
}); });
}); });