Skip to content

Commit 69bc0aa

Browse files
committed
fixed the imports
1 parent 1619300 commit 69bc0aa

File tree

5 files changed

+179
-40
lines changed

5 files changed

+179
-40
lines changed

server/config/reset.js

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -163,8 +163,47 @@ const createUserAddressTable = async () => {
163163
}
164164
};
165165

166+
const createOrdersTableQuery = async () => {
167+
const createOrdersTableQuery = `
168+
id serial PRIMARY KEY,
169+
user_id integer NOT NULL,
170+
order_date timestamp DEFAULT CURRENT_TIMESTAMP,
171+
total_amount numeric(10, 2) NOT NULL,
172+
status varchar(50) DEFAULT 'Pending',
173+
FOREIGN KEY (user_id) REFERENCES users (id)
174+
`;
175+
try {
176+
const res = await pool.query(createOrdersTableQuery);
177+
console.log("🎉 Order table created successfully");
178+
} catch (err) {
179+
console.error("⚠️ error creating useraddress table", err);
180+
}
181+
};
182+
183+
const createOrderDetailTableQuery = async () => {
184+
const createOrderDetailTableQuery = `
185+
CREATE TABLE IF NOT EXISTS order_details (
186+
id serial PRIMARY KEY,
187+
order_id integer NOT NULL,
188+
sneaker_id integer NOT NULL,
189+
quantity integer NOT NULL,
190+
price_per_unit numeric(10, 2) NOT NULL,
191+
total_price numeric(10, 2) NOT NULL,
192+
FOREIGN KEY (order_id) REFERENCES orders (id),
193+
FOREIGN KEY (sneaker_id) REFERENCES sneakers (id)
194+
);`;
195+
try {
196+
const res = await pool.query(createOrderDetailTableQuery);
197+
console.log("🎉 OrderDetail table created successfully");
198+
} catch (err) {
199+
console.error("⚠️ error creating useraddress table", err);
200+
}
201+
};
202+
166203
seedSneakersTable();
167204
seedImagesTable();
168205
createReviewsTable();
169206
createUsersTable;
170207
createUserAddressTable();
208+
createOrdersTableQuery();
209+
createOrderDetailTableQuery();

server/controllers/order.js

Lines changed: 35 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,43 +1,64 @@
11
import { pool } from "../config/database.js";
22

3-
// Controller function to create an order from the user's cart
43
export const createOrderFromCart = async (req, res) => {
54
try {
65
const userId = req.user ? req.user.id : null;
6+
7+
// Get the cart from the session
78
const cart = req.session.cart || {};
89

10+
// Check if the cart is empty
911
if (Object.keys(cart).length === 0) {
1012
return res.status(400).json({ error: "Cart is empty" });
1113
}
14+
let totalAmount = 0;
15+
16+
const cartItemIds = Object.keys(cart);
17+
for (const cartItemId of cartItemIds) {
18+
const sneakerId = parseInt(cartItemId);
19+
const quantity = cart[cartItemId];
20+
const sneakerDetails = await pool.query(
21+
`SELECT price FROM sneakers WHERE id = $1`,
22+
[sneakerId]
23+
);
24+
25+
const pricePerUnit = sneakerDetails.rows[0].price;
26+
const totalPrice = quantity * pricePerUnit;
1227

13-
// Step 1: Create the order
28+
totalAmount += totalPrice;
29+
}
1430
const orderResult = await pool.query(
15-
`INSERT INTO orders (userid, createdat) VALUES ($1, NOW()) RETURNING id`,
16-
[userId]
31+
`INSERT INTO orders (user_id, order_date, total_amount, status)
32+
VALUES ($1, NOW(), $2, 'Pending') RETURNING id`,
33+
[userId, totalAmount]
1734
);
1835

1936
const orderId = orderResult.rows[0].id;
2037

21-
// Step 2: Create order items for each item in the cart
22-
const cartItemIds = Object.keys(cart);
23-
2438
for (const cartItemId of cartItemIds) {
2539
const sneakerId = parseInt(cartItemId);
2640
const quantity = cart[cartItemId];
2741

28-
await pool.query(
29-
`INSERT INTO orderitems (orderid, sneakerid, quantity, createdat)
30-
VALUES ($1, $2, $3, NOW())`,
31-
[orderId, sneakerId, quantity]
42+
// Retrieve sneaker details
43+
const sneakerDetails = await pool.query(
44+
`SELECT price FROM sneakers WHERE id = $1`,
45+
[sneakerId]
3246
);
3347

34-
// want to update stock quantities, calculate the total, etc.
35-
}
48+
const pricePerUnit = sneakerDetails.rows[0].price;
49+
const totalPrice = quantity * pricePerUnit;
3650

51+
await pool.query(
52+
`INSERT INTO order_details (order_id, sneaker_id, quantity, price_per_unit, total_price)
53+
VALUES ($1, $2, $3, $4, $5)`,
54+
[orderId, sneakerId, quantity, pricePerUnit, totalPrice]
55+
);
56+
}
3757
req.session.cart = {};
3858

3959
res.status(201).json({ message: "Order created successfully", orderId });
4060
} catch (error) {
41-
res.status(500).json({ error: error.message });
61+
console.error(error);
62+
res.status(500).json({ error: "Internal Server Error" });
4263
}
4364
};

server/package-lock.json

Lines changed: 49 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

server/package.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
"passport": "^0.6.0",
2121
"passport-google-oauth20": "^2.0.0",
2222
"passport-google-oidc": "^0.1.0",
23-
"pg": "^8.11.3"
23+
"pg": "^8.11.3",
24+
"stripe": "^14.4.0"
2425
}
2526
}

server/server.js

Lines changed: 54 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -50,16 +50,20 @@ app.use("api/auth", authRoutes);
5050
app.use("/api/sneakers", sneakersRoutes);
5151
app.use("/api/reviews", reviewRoutes);
5252
app.use("/api/cart", cartRoutes);
53-
// Payment Setup
54-
const stripe = require("stripe")(process.env.STRIPE_KEY);
53+
54+
// Payment Setupimport createStripe from "stripe";
55+
import { pool } from "./config/database.js";
56+
import createStripe from "stripe";
57+
const stripe = createStripe(process.env.STRIPE_KEY);
58+
5559
app.post("/create-checkout-session", async (req, res) => {
5660
try {
57-
const userId = req.user ? req.user.id : null; // Assuming user authentication
58-
const orderId = req.body.orderId; // Pass the order ID from your front end
61+
const userId = req.user ? req.user.id : null;
62+
const orderId = req.body.orderId;
5963

60-
// Fetch order details from the database, adjust the query based on your schema
64+
// Fetch order details from the database
6165
const orderResult = await pool.query(
62-
"SELECT * FROM ordedetails WHERE orderid = $1 AND userid = $2",
66+
"SELECT * FROM order_details WHERE order_id = $1 AND user_id = $2",
6367
[orderId, userId]
6468
);
6569

@@ -71,26 +75,51 @@ app.post("/create-checkout-session", async (req, res) => {
7175

7276
const totalAmount = calculateTotalAmount(order);
7377

74-
const session = await stripe.checkout.sessions.create({
75-
payment_method_types: ["card"],
76-
line_items: order.items.map((item) => ({
77-
price_data: {
78-
currency: "usd",
79-
product_data: {
80-
name: item.sneaker_name, // Adjust based on your schema
78+
// Start a database transaction
79+
const client = await pool.connect();
80+
try {
81+
// Insert payment information into the payments table
82+
const paymentResult = await client.query(
83+
"INSERT INTO payments (order_id, payment_date, amount, status) VALUES ($1, NOW(), $2,'Paid') RETURNING id",
84+
[orderId, totalAmount]
85+
);
86+
87+
const paymentId = paymentResult.rows[0].id;
88+
89+
// Create a payment session with Stripe
90+
const session = await stripe.checkout.sessions.create({
91+
payment_method_types: ["card"],
92+
line_items: order.items.map((item) => ({
93+
price_data: {
94+
currency: "usd",
95+
product_data: {
96+
name: item.sneaker_name,
97+
},
98+
unit_amount: item.price * 100,
8199
},
82-
unit_amount: item.price * 100, // Amount in cents
83-
},
84-
quantity: item.quantity,
85-
})),
86-
mode: "payment",
87-
success_url: `${DOMAIN}?success=true`,
88-
cancel_url: `${DOMAIN}?canceled=true`,
89-
});
90-
91-
res.status(200).json({ sessionId: session.id });
100+
quantity: item.quantity,
101+
})),
102+
mode: "payment",
103+
success_url: `${DOMAIN}?success=true&paymentId=${paymentId}`,
104+
cancel_url: `${DOMAIN}?canceled=true`,
105+
});
106+
107+
// Commit the transaction
108+
await client.query("COMMIT");
109+
110+
res.status(200).json({ sessionId: session.id, paymentId });
111+
} catch (error) {
112+
// Rollback the transaction in case of an error
113+
await client.query("ROLLBACK");
114+
console.error(error);
115+
res.status(500).json({ error: "Internal Server Error" });
116+
} finally {
117+
// Release the client back to the pool
118+
client.release();
119+
}
92120
} catch (error) {
93-
res.status(500).json({ error: error.message });
121+
console.error(error);
122+
res.status(500).json({ error: "Internal Server Error" });
94123
}
95124
});
96125

@@ -101,6 +130,7 @@ function calculateTotalAmount(order) {
101130
0
102131
);
103132
}
133+
104134
const PORT = process.env.PORT || 3001;
105135

106136
app.listen(PORT, () => {

0 commit comments

Comments
 (0)