Compare commits
12 Commits
f1d1c2737a
...
API
| Author | SHA1 | Date | |
|---|---|---|---|
| 13fe841e54 | |||
| 58b88c05a7 | |||
| 85d1a9f046 | |||
| 363798ca44 | |||
| 45e07d6413 | |||
|
|
c6604703fe | ||
|
|
d39f5f129e | ||
| a1d326aa40 | |||
| ec65f155b2 | |||
| bfde13afd0 | |||
| 4e0bc9d428 | |||
| a4bbee1c0f |
3
.gitignore
vendored
3
.gitignore
vendored
@@ -137,9 +137,8 @@ dist
|
||||
# Vite logs files
|
||||
vite.config.js.timestamp-*
|
||||
vite.config.ts.timestamp-*
|
||||
/.vs/DELIVER_MAN.slnx
|
||||
/.vs/*
|
||||
/.vscode
|
||||
/obj/Debug
|
||||
*.slnx
|
||||
*.esproj
|
||||
/CHANGELOG.md
|
||||
|
||||
6
DELIVER_MAN.slnx
Normal file
6
DELIVER_MAN.slnx
Normal file
@@ -0,0 +1,6 @@
|
||||
<Solution>
|
||||
<Project Path="DELIVER_MAN.esproj">
|
||||
<Build />
|
||||
<Deploy />
|
||||
</Project>
|
||||
</Solution>
|
||||
17
package.json
17
package.json
@@ -1,20 +1,19 @@
|
||||
{
|
||||
"name": "deliver_man",
|
||||
"name": "deliver-man-server",
|
||||
"version": "1.0.0",
|
||||
"description": "",
|
||||
"main": "server.js",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"test": "echo \"Error: no test specified\" && exit 1",
|
||||
"start": "node server.js"
|
||||
"start": "node server/server.js",
|
||||
"dev": "nodemon server/server.js"
|
||||
},
|
||||
"keywords": [],
|
||||
"author": "",
|
||||
"license": "ISC",
|
||||
"type": "commonjs",
|
||||
"dependencies": {
|
||||
"express": "^5.2.1"
|
||||
"dotenv": "^17.2.3",
|
||||
"express": "^4.22.1",
|
||||
"mariadb": "^3.4.5"
|
||||
},
|
||||
"devDependencies": {
|
||||
"nodemon": "^3.1.11"
|
||||
"nodemon": "^3.0.1"
|
||||
}
|
||||
}
|
||||
|
||||
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}`);
|
||||
});
|
||||
584
server/db/database.js
Normal file
584
server/db/database.js
Normal file
@@ -0,0 +1,584 @@
|
||||
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("Empty in customer name or order date")
|
||||
});
|
||||
}
|
||||
const currentDate = await getCurrentDate();
|
||||
if (orderDate < currentDate){
|
||||
return Promise.reject({
|
||||
type: DB_USER_ERROR,
|
||||
error: new Error("Invalid order date")
|
||||
});
|
||||
}
|
||||
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("Server 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("Order ID, name or date is required!"),
|
||||
message: "Order ID, name or date is required!" // Добавляем message напрямую
|
||||
});
|
||||
}
|
||||
|
||||
const currentDate = await getCurrentDate();
|
||||
if (orderDate < currentDate) {
|
||||
return Promise.reject({
|
||||
type: DB_USER_ERROR,
|
||||
error: new Error("Order date cannot be less than current date"),
|
||||
message: "Order date cannot be less than current date"
|
||||
});
|
||||
}
|
||||
|
||||
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("Order not found"),
|
||||
message: "Order not found"
|
||||
});
|
||||
}
|
||||
|
||||
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("Server error"),
|
||||
message: err.message || "Database operation failed",
|
||||
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("Failed to delete order"),
|
||||
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("Order not found")
|
||||
});
|
||||
}
|
||||
|
||||
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("Product not found")
|
||||
});
|
||||
}
|
||||
|
||||
if (productRow.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 = ?',
|
||||
[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 = "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 }) {
|
||||
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("Order item not found")
|
||||
});
|
||||
}
|
||||
|
||||
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("Insufficient product quantity")
|
||||
});
|
||||
}
|
||||
|
||||
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("Failed to update order item"),
|
||||
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("Order item not found")
|
||||
});
|
||||
}
|
||||
|
||||
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("Failed to delete order item"),
|
||||
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("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];
|
||||
if (!itemRow) {
|
||||
await connection.rollback();
|
||||
connection.release();
|
||||
return Promise.reject({
|
||||
type: DB_USER_ERROR,
|
||||
error: new Error("Order item not found")
|
||||
});
|
||||
}
|
||||
|
||||
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("Failed to move order item"),
|
||||
details: err.message
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
405
server/server.js
Normal file
405
server/server.js
Normal file
@@ -0,0 +1,405 @@
|
||||
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";
|
||||
|
||||
dotenv.config({
|
||||
path: './server/.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');
|
||||
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: "Unknown error",
|
||||
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: "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) => {
|
||||
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: "Invalid productId or quantity"
|
||||
});
|
||||
}
|
||||
|
||||
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 || "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"
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
app.put('/api/orders/:orderId/items/:itemId', async (req, res) => {
|
||||
let itemId = req.params.itemId;
|
||||
let quantity = req.body.quantity;
|
||||
|
||||
try {
|
||||
await adapter.updateOrderItem({
|
||||
itemId,
|
||||
quantity
|
||||
});
|
||||
|
||||
res.status(201).json({
|
||||
itemId,
|
||||
quantity
|
||||
});
|
||||
|
||||
} catch (err) {
|
||||
res.json({
|
||||
timeStamp: new Date().toISOString(),
|
||||
statusCode: 500,
|
||||
error: 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: "Server error",
|
||||
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) => {
|
||||
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: 'Invalid route' });
|
||||
});
|
||||
|
||||
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