Skip to content

Commit

Permalink
first commit
Browse files Browse the repository at this point in the history
  • Loading branch information
amin-ni88 committed Dec 24, 2024
0 parents commit 7fb8258
Show file tree
Hide file tree
Showing 3,276 changed files with 724,377 additions and 0 deletions.
The diff you're trying to view is too large. We only load the first 3000 changed files.
172 changes: 172 additions & 0 deletions app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
from flask import Flask, request, jsonify, render_template
from flask_cors import CORS
from flask_sqlalchemy import SQLAlchemy
from werkzeug.security import generate_password_hash, check_password_hash
import stripe

app = Flask(__name__)
CORS(app)

# Database configuration
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///store.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)

# Stripe configuration
stripe.api_key = 'your_stripe_secret_key'

# User model
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
password = db.Column(db.String(200), nullable=False)

# Product model
class Product(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80), nullable=False)
price = db.Column(db.Float, nullable=False)
description = db.Column(db.String(200), nullable=True)

# Order model
class Order(db.Model):
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
product_id = db.Column(db.Integer, db.ForeignKey('product.id'), nullable=False)
quantity = db.Column(db.Integer, nullable=False)

# Create the database
with app.app_context():
db.create_all()

# Sample data for products (optional)
def add_sample_products():
sample_products = [
Product(name="Kids T-Shirt", price=15.99, description="Comfortable cotton t-shirt for kids."),
Product(name="Kids Shorts", price=19.99, description="Stylish shorts for summer."),
Product(name="Kids Jacket", price=29.99, description="Warm jacket for winter."),
Product(name="Kids Shoes", price=39.99, description="Durable shoes for active kids."),
]
db.session.bulk_save_objects(sample_products)
db.session.commit()

# Uncomment to add sample products to the database
# add_sample_products()

# Routes
@app.route('/')
def home():
return render_template('index.html')

@app.route('/auth')
def auth():
return render_template('auth.html')

@app.route('/shop')
def shop():
return render_template('shop.html')

@app.route('/about')
def about():
return render_template('about.html')

@app.route('/contact')
def contact():
return render_template('contact.html')

@app.route('/profile')
def profile():
return render_template('profile.html')

@app.route('/orders')
def orders():
return render_template('orders.html')

@app.route('/success')
def success():
return render_template('success.html')

@app.route('/api/register', methods=['POST'])
def register():
data = request.json
hashed_password = generate_password_hash(data['password'], method='sha256')
new_user = User(username=data['username'], email=data['email'], password=hashed_password)
db.session.add(new_user)
db.session.commit()
return jsonify({"message": "User registered successfully"}), 201

@app.route('/api/login', methods=['POST'])
def login():
data = request.json
user = User.query.filter_by(email=data['email']).first()
if user and check_password_hash(user.password, data['password']):
return jsonify({"message": "User logged in successfully"}), 200
return jsonify({"message": "Invalid credentials"}), 401

@app.route('/api/products', methods=['GET'])
def get_products():
products = Product.query.all()
return jsonify([{"id": p.id, "name": p.name, "price": p.price, "description": p.description} for p in products]), 200

@app.route('/api/user-profile', methods=['GET', 'PUT'])
def user_profile():
if request.method == 'GET':
# Assuming user is logged in and we have their email
email = request.args.get('email') # You would typically get this from a session
user = User.query.filter_by(email=email).first()
if user:
return jsonify({"username": user.username, "email": user.email}), 200
return jsonify({"message": "User not found"}), 404

if request.method == 'PUT':
data = request.json
email = data['email'] # Get email from request
user = User.query.filter_by(email=email).first()
if user:
user.username = data['username']
db.session.commit()
return jsonify({"message": "Profile updated successfully"}), 200
return jsonify({"message": "User not found"}), 404

@app.route('/api/orders', methods=['POST'])
def create_order():
data = request.json
user = User.query.filter_by(email=data['email']).first()
if user:
new_order = Order(user_id=user.id, product_id=data['product_id'], quantity=data['quantity'])
db.session.add(new_order)
db.session.commit()
return jsonify({"message": "Order created successfully"}), 201
return jsonify({"message": "User not found"}), 404

@app.route('/api/orders/<int:user_id>', methods=['GET'])
def get_orders(user_id):
orders = Order.query.filter_by(user_id=user_id).all()
return jsonify([{"id": o.id, "product_id": o.product_id, "quantity": o.quantity} for o in orders]), 200

@app.route('/api/create-checkout-session', methods=['POST'])
def create_checkout_session():
data = request.json
session = stripe.checkout.Session.create(
payment_method_types=['card'],
line_items=[
{
'price_data': {
'currency': 'usd',
'product_data': {
'name': data['product_name'],
},
'unit_amount': data['amount'],
},
'quantity': data['quantity'],
},
],
mode='payment',
success_url='http://localhost:5000/success',
cancel_url='http://localhost:5000/cancel',
)
return jsonify({'id': session.id})

if __name__ == '__main__':
app.run(debug=True)
Binary file added instance/store.db
Binary file not shown.
105 changes: 105 additions & 0 deletions script.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
// Fetch products from the backend
async function loadProducts() {
const response = await fetch('http://localhost:5000/api/products');
const products = await response.json();
const productList = document.getElementById('product-list');
products.forEach(product => {
const productDiv = document.createElement('div');
productDiv.className = 'product';
productDiv.innerHTML = `
<h3>${product.name}</h3>
<p>${product.description}</p>
<p>Price: $${product.price.toFixed(2)}</p>
<button onclick="addToCart('${product.name}', ${product.price})">Add to Cart</button>
`;
productList.appendChild(productDiv);
});
}

const stripe = Stripe('your_public_key_here'); // Replace with your actual Stripe public key

// Call loadProducts on shop.html
document.getElementById('payment-form').addEventListener('submit', async (event) => {
event.preventDefault();

const cardElement = document.getElementById('card-element');
const { paymentMethod, error } = await stripe.createPaymentMethod({
type: 'card',
card: cardElement,
});

if (error) {
// Show error to your customer (e.g., insufficient funds)
document.getElementById('payment-result').innerText = error.message;
} else {
// Send paymentMethod.id to your server (e.g., to create a payment)
const response = await fetch('http://localhost:5000/api/checkout', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
payment_method_id: paymentMethod.id,
amount: 5000, // Example amount in cents
}),
});

const paymentResult = await response.json();
if (paymentResult.error) {
document.getElementById('payment-result').innerText = paymentResult.error;
} else {
document.getElementById('payment-result').innerText = 'Payment successful!';
// Optionally, create an order in the database here
}
}
});
if (document.getElementById('product-list')) {
loadProducts ();
}

// Update registerUser and signInUser functions to call the backend
async function registerUser (event) {
event.preventDefault();
const username = document.getElementById('username').value;
const email = document.getElementById('email').value;
const password = document.getElementById('password').value;

const response = await fetch('http://localhost:5000/api/register', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ username, email, password }),
});

if (response.ok) {
alert("User registered successfully!");
} else {
alert("Registration failed.");
}
}

async function signInUser (event) {
event.preventDefault();
const email = document.getElementById('signinEmail').value;
const password = document.getElementById('signinPassword').value;

const response = await fetch('http://localhost:5000/api/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ email, password }),
});

if (response.ok) {
alert("User logged in successfully!");
} else {
alert("Invalid credentials.");
}
}

function addToCart(productName, productPrice) {
// Logic to add the product to the cart
alert(`${productName} added to cart at $${productPrice.toFixed(2)}`);
}
52 changes: 52 additions & 0 deletions static/styles.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
}

header {
background-color: #4CAF50;
color: white;
padding: 10px 0;
text-align: center;
}

nav ul {
list-style-type: none;
padding: 0;
}

nav ul li {
display: inline;
margin: 0 15px;
}

nav ul li a {
color: white;
text-decoration: none;
}

main {
padding: 20px;
}

.product-grid {
display: flex;
flex-wrap: wrap;
}

.product {
border: 1px solid #ccc;
margin: 10px;
padding: 10px;
width: calc(25% - 20px);
}

footer {
text-align: center;
padding: 10px 0;
background-color: #f1f1f1;
position: relative;
bottom: 0;
width: 100%;
}
Empty file added store.db
Empty file.
36 changes: 36 additions & 0 deletions templates/about.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>About Us - Kids Clothing Store</title>
```html
<link rel="stylesheet" href="/static/styles.css">
</head>
<body>
<header>
<h1>Kids Clothing Store</h1>
<nav>
<ul>
<li><a href="index.html">Home</a></li>
<li><a href="auth.html">Authentication</a></li>
<li><a href="shop.html">Shop</a></li>
<li><a href="about.html">About Us</a></li>
<li><a href="contact.html">Contact</a></li>
<li><a href="profile.html">Profile</a></li>
<li><a href="orders.html">Order History</a></li>
<li><a href="#cart" id="cart-link">Cart (<span id="cart-count">0</span>)</a></li>
</ul>
</nav>
</header>

<main>
<h2>About Us</h2>
<p>Welcome to Kids Clothing Store, your one-stop shop for stylish and comfortable clothing for children. We believe in providing high-quality products that cater to the needs of kids and their parents.</p>
</main>

<footer>
<p>&copy; 2023 Kids Clothing Store</p>
</footer>
</body>
</html>
Loading

0 comments on commit 7fb8258

Please sign in to comment.