Skip to content
Snippets Groups Projects
Commit 78e1d3f9 authored by Kisvári Benedek's avatar Kisvári Benedek
Browse files

Changing backend

parent 009f30d4
No related branches found
No related tags found
No related merge requests found
......@@ -152,3 +152,48 @@ packages/template-compiler/browser.js
dist
temp
types/v3-generated.d.ts
*#
*.iml
*.ipr
*.iws
*.jar
*.sw?
*~
.#*
.*.md.html
.DS_Store
.attach_pid*
.classpath
.factorypath
.gradle
.metadata
.project
.recommenders
.settings
.springBeans
.vscode
/code
MANIFEST.MF
_site/
activemq-data
bin
build
!/**/src/**/bin
!/**/src/**/build
build.log
dependency-reduced-pom.xml
dump.rdb
interpolated*.xml
lib/
manifest.yml
out
overridedb.*
target
.flattened-pom.xml
secrets.yml
.gradletasknamecache
.sts4-cache
.git-hooks/
node_modules
const express = require('express');
const cors = require('cors');
const { Sequelize, DataTypes } = require('sequelize');
const bcrypt = require('bcrypt');
const app = express();
app.use(cors());
app.use(express.json());
// SQLite adatbázis létrehozása
const sequelize = new Sequelize({
dialect: 'sqlite',
storage: 'shop.db'
});
// === MODELS ===
// Felhasználók (Users)
const User = sequelize.define('User', {
username: {
type: DataTypes.STRING,
unique: true,
allowNull: false
},
password_hash: {
type: DataTypes.STRING,
allowNull: false
},
role: {
type: DataTypes.ENUM('admin', 'customer'),
defaultValue: 'customer'
}
});
// Termékek (Products)
const Product = sequelize.define('Product', {
name: {
type: DataTypes.STRING,
allowNull: false
},
category: DataTypes.STRING,
price: {
type: DataTypes.INTEGER,
allowNull: false
},
stock: {
type: DataTypes.INTEGER,
defaultValue: 0
},
image_url: DataTypes.STRING
});
// Rendelések (Orders)
const Order = sequelize.define('Order', {
user_id: {
type: DataTypes.INTEGER,
allowNull: false
},
total_amount: {
type: DataTypes.FLOAT,
allowNull: false
},
status: {
type: DataTypes.STRING,
allowNull: false
},
order_date: {
type: DataTypes.DATE,
allowNull: false
}
}, {
underscored: true
});
// OrderItem model
const OrderItem = sequelize.define('OrderItem', {
orderId: {
type: DataTypes.INTEGER,
allowNull: false
},
productId: {
type: DataTypes.INTEGER,
allowNull: false
},
quantity: {
type: DataTypes.INTEGER,
allowNull: false
},
price: {
type: DataTypes.FLOAT,
allowNull: false
}
});
// Associations
Order.hasMany(OrderItem, { foreignKey: 'orderId' });
OrderItem.belongsTo(Order, { foreignKey: 'orderId' });
// === KAPCSOLATOK ===
User.hasMany(Order, { foreignKey: 'user_id' });
Order.belongsTo(User, { foreignKey: 'user_id' });
// === SYNC DATABASE ===
//{ force: true } // Ezt csak egyszer futtassuk le, hogy újra létrehozza a táblákat
sequelize.sync( ).then(() => {
console.log("Adatbázis szinkronizálva!");
});
// === API VÉGPONTOK (példák) ===
// Termékek lekérése
app.get('/products', async (req, res) => {
const products = await Product.findAll();
res.json(products);
});
// Új termék létrehozása
app.post('/products', async (req, res) => {
const product = await Product.create(req.body);
res.json(product);
});
// Felhasználók lekérése
app.get('/users', async (req, res) => {
const users = await User.findAll();
res.json(users);
});
// Rendelések lekérése
app.get('/orders', async (req, res) => {
const orders = await Order.findAll({ include: User });
res.json(orders);
});
app.post('/login', async (req, res) => {
try {
const { username, password } = req.body;
// Find user
const user = await User.findOne({
where: { username }
});
if (!user) {
return res.status(401).json({
success: false,
message: 'Hibás felhasználónév vagy jelszó'
});
}
// Compare password with stored hash
const passwordMatch = await bcrypt.compare(password, user.password_hash);
if (!passwordMatch) {
return res.status(401).json({
success: false,
message: 'Hibás felhasználónév vagy jelszó'
});
}
// Success - return user info
res.json({
success: true,
user: {
id: user.id,
username: user.username,
role: user.role
},
token: `dummy-token-${user.id}` // In production, use JWT
});
} catch (error) {
console.error('Login error:', error);
res.status(500).json({
success: false,
message: 'Szerver hiba történt'
});
}
});
app.post('/register', async (req, res) => {
try {
const { username, password } = req.body;
// Check if user already exists
const existingUser = await User.findOne({ where: { username } });
if (existingUser) {
return res.status(400).json({
success: false,
message: 'Ez a felhasználónév már foglalt'
});
}
// Hash password (10 rounds of salt)
const password_hash = await bcrypt.hash(password, 10);
// Create the new user
const newUser = await User.create({
username,
password_hash,
role: 'customer' // Default role
});
// Return success with user info (except password)
res.status(201).json({
success: true,
user: {
id: newUser.id,
username: newUser.username,
role: newUser.role
},
token: `dummy-token-${newUser.id}` // In production, use JWT
});
} catch (error) {
console.error('Registration error:', error);
res.status(500).json({
success: false,
message: 'Hiba történt a regisztráció során'
});
}
});
app.post('/orders', async (req, res) => {
try {
const { items } = req.body;
const token = req.headers.authorization?.split(' ')[1];
// Validate token and get user
if (!token) {
return res.status(401).json({
success: false,
message: 'Bejelentkezés szükséges'
});
}
// In production, use real JWT verification
const userId = token.split('-').pop();
if (!userId) {
return res.status(401).json({
success: false,
message: 'Érvénytelen hitelesítés'
});
}
// Calculate total amount and validate items
let totalAmount = 0;
// Check all products and their stock before processing
for (const item of items) {
const product = await Product.findByPk(item.productId);
if (!product) {
return res.status(404).json({
success: false,
message: `A ${item.productId} azonosítójú termék nem található`
});
}
// Check if enough stock
if (product.stock < item.quantity) {
return res.status(400).json({
success: false,
message: `Sajnos a "${product.name}" termékből csak ${product.stock} db áll rendelkezésre`
});
}
totalAmount += product.price * item.quantity;
}
// Create the order in the database
const order = await Order.create({
user_id: userId,
total_amount: totalAmount,
status: 'confirmed',
order_date: new Date()
});
// Process order items and update stock
for (const item of items) {
// Create order item
await OrderItem.create({
orderId: order.id,
productId: item.productId,
quantity: item.quantity,
price: (await Product.findByPk(item.productId)).price
});
// Update product stock
const product = await Product.findByPk(item.productId);
product.stock -= item.quantity;
await product.save();
}
res.status(201).json({
success: true,
orderId: order.id,
message: 'Rendelés sikeresen feldolgozva'
});
} catch (error) {
console.error('Order processing error:', error);
res.status(500).json({
success: false,
message: 'Hiba történt a vásárlás során'
});
}
});
OrderItem.belongsTo(Product, { foreignKey: 'productId', as: 'product' });
// Get user's orders
app.get('/user/orders', async (req, res) => {
try {
const token = req.headers.authorization?.split(' ')[1];
if (!token) {
return res.status(401).json({
success: false,
message: 'Bejelentkezés szükséges'
});
}
// In a real app, use JWT verification
const userId = token.split('-').pop();
if (!userId) {
return res.status(401).json({
success: false,
message: 'Érvénytelen hitelesítés'
});
}
// Fetch user's orders with order items and product details
const orders = await Order.findAll({
where: { user_id: userId },
include: [{
model: OrderItem,
attributes: ['id', 'productId', 'quantity', 'price'],
include: [{
model: Product,
as: 'product',
attributes: ['id', 'name']
}]
}],
order: [['order_date', 'DESC']] // Most recent first
});
res.json({
success: true,
orders
});
} catch (error) {
console.error('Error fetching user orders:', error);
res.status(500).json({
success: false,
message: 'Hiba történt a rendelések lekérése során'
});
}
});
// Szerver indítása
app.listen(3000, () => {
console.log("Backend fut a http://localhost:3000 címen");
});
This diff is collapsed.
{
"name": "backend",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"description": "",
"dependencies": {
"bcrypt": "^5.1.1",
"cors": "^2.8.5",
"express": "^5.1.0",
"sequelize": "^6.37.7",
"sqlite3": "^5.1.7"
}
}
File deleted
package kisbe32.backend;
import jakarta.persistence.*;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
@Entity
@Table(name = "orders")
public class Order {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
@Column(name = "id", nullable = false)
private Integer id;
@ManyToOne
@JoinColumn(name = "user_id", nullable = false)
private User user;
@Column(name = "order_date", nullable = false)
private LocalDateTime orderDate;
@Column(name = "status", nullable = false, length = 20)
private String status;
@Column(name = "total_price", nullable = false)
private BigDecimal totalPrice;
@OneToMany(mappedBy = "order", cascade = CascadeType.ALL)
private List<OrderItem> items;
protected Order() {}
public Order(User user, String status, BigDecimal totalPrice) {
this.user = user;
this.orderDate = LocalDateTime.now();
this.status = status;
this.totalPrice = totalPrice;
}
// Getters
public Integer getId() { return id; }
public User getUser() { return user; }
public LocalDateTime getOrderDate() { return orderDate; }
public String getStatus() { return status; }
public BigDecimal getTotalPrice() { return totalPrice; }
public List<OrderItem> getItems() { return items; }
}
\ No newline at end of file
package kisbe32.backend;
import jakarta.persistence.*;
import java.math.BigDecimal;
import java.time.LocalDateTime;
@Entity
@Table(name = "orderitems")
public class OrderItem {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
@Column(name = "id", nullable = false)
private Integer id;
@ManyToOne
@JoinColumn(name = "order_id", nullable = false)
private Order order;
@ManyToOne
@JoinColumn(name = "product_id", nullable = false)
private Product product;
@Column(name = "quantity", nullable = false)
private Integer quantity;
@Column(name = "price", nullable = false)
private BigDecimal price;
@Column(name = "created_at", nullable = false)
private LocalDateTime createdAt;
@Column(name = "updated_at", nullable = false)
private LocalDateTime updatedAt;
protected OrderItem() {}
public OrderItem(Order order, Product product, Integer quantity, BigDecimal price) {
this.order = order;
this.product = product;
this.quantity = quantity;
this.price = price;
}
// Getters
public Integer getId() { return id; }
public Order getOrder() { return order; }
public Product getProduct() { return product; }
public Integer getQuantity() { return quantity; }
public BigDecimal getPrice() { return price; }
}
\ No newline at end of file
package kisbe32.backend;
import jakarta.persistence.*;
import java.math.BigDecimal;
@Entity
@Table(name = "products")
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
@Column(name = "id", nullable = false)
private Integer id;
@Column(name = "name", nullable = false, length = 100)
private String name;
@Column(name = "category", length = 50)
private String category;
@Column(name = "price", nullable = false)
private BigDecimal price;
@Column(name = "stock", nullable = false)
private Integer stock;
@Column(name = "image_url", length = Integer.MAX_VALUE)
private String imageUrl;
protected Product() {}
public Product(String name, String category, BigDecimal price, Integer stock, String imageUrl) {
this.name = name;
this.category = category;
this.price = price;
this.stock = stock;
this.imageUrl = imageUrl;
}
public String getImageUrl() {
return imageUrl;
}
public Integer getStock() {
return stock;
}
public BigDecimal getPrice() {
return price;
}
public String getCategory() {
return category;
}
public String getName() {
return name;
}
public Integer getId() {
return id;
}
}
package kisbe32.backend;
import jakarta.persistence.*;
import java.time.LocalDateTime;
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
@Column(name = "id", nullable = false)
private Integer id;
@Column(name = "username", nullable = false, length = 50, unique = true)
private String username;
@Column(name = "email", nullable = false, length = 100, unique = true)
private String email;
@Column(name = "password", nullable = false, length = 255)
private String password;
@Column(name = "created_at")
private LocalDateTime createdAt;
protected User() {}
public User(String username, String email, String password) {
this.username = username;
this.email = email;
this.password = password;
this.createdAt = LocalDateTime.now();
}
// Getters
public Integer getId() { return id; }
public String getUsername() { return username; }
public String getEmail() { return email; }
public String getPassword() { return password; }
public LocalDateTime getCreatedAt() { return createdAt; }
}
\ No newline at end of file
SELECT *
FROM Products;
Select *
from Orders;
select *
from Users;
INSERT INTO Products (name, category, price, stock, image_url, createdAt, updatedAt)
VALUES ('AMD Ryzen 7 5800X 3.8GHz Socket AM4 dobozos (100-100000063WOF)', 'Processor', 66490, 10,
'https://cdn.aqua.hu/864/100-100000063WOF-975612.jpg', date (), date ());
INSERT INTO Products (name, category, price, stock, image_url, createdAt, updatedAt)
VALUES ('AMD Ryzen 7 7800X3D 4.2GHz Socket AM5 dobozos (100-100000910WOF)', 'Processor', 202890, 1,
'https://cdn.aqua.hu/2026/100-100000910WOF-1779523.jpg', date (), date ());
INSERT INTO Products (name, category, price, stock, image_url, createdAt, updatedAt)
VALUES ('ASUS GeForce RTX 5070 12GB PRIME OC Edition videokártya', 'Videocard', 324990, 5,
'https://cdn.aqua.hu/1965/1-1750620.jpg', date (), date ());
INSERT INTO Products (name, category, price, stock, image_url, createdAt, updatedAt)
VALUES ('PowerColor Radeon RX 9070 16GB Reaper videokártya (RX9070 16G-A)', 'Videocard', 309990, 15,
'https://cdn.aqua.hu/2006/1-1769834.jpg', date (), date ());
INSERT INTO Products (name, category, price, stock, image_url, createdAt, updatedAt)
VALUES ('32GB 3600MHz DDR4 RAM G.Skill Trident Z Neo CL16 (2X16GB) (F4-3600C16D-32GTZNC)', 'Memory', 36990, 5,
'https://cdn.aqua.hu/725/F4-3600C16D-32GTZNC-851923.jpg', date (), date ());
INSERT INTO Products (name, category, price, stock, image_url, createdAt, updatedAt)
VALUES ('960GB Kingston SSD SATA3 2,5" A400 meghajtó (SA400S37/960G)', 'storage', 21690, 60,
'https://cdn.aqua.hu/424/SA400S37_960G-576811.jpg', date (), date ());
INSERT INTO Products (name, category, price, stock, image_url, createdAt, updatedAt)
VALUES ('ASUS ROG STRIX B550-F GAMING alaplap', 'motherboard', 57190, 5,
'https://cdn.aqua.hu/828/ROG%20STRIX%20B550-F%20GAMING-944693.jpg', date (), date ());
INSERT INTO Products (name, category, price, stock, image_url, createdAt, updatedAt)
VALUES ('ASUS TUF GAMING X670E-PLUS alaplap', 'motherboard', 109660, 0,
'https://cdn.aqua.hu/2024/TUF%20GAMING%20X670E-PLUS-1778696.jpg', date (), date ());
UPDATE Products
SET stock = stock + 10
WHERE name = 'ASUS TUF GAMING X670E-PLUS alaplap';
UPDATE Products
SET stock = stock + 5;
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment