order create and fetch with payment
This commit is contained in:
parent
145c44302c
commit
a10e0d3b7b
254
resources/Orders/CheckoutController.js
Normal file
254
resources/Orders/CheckoutController.js
Normal file
@ -0,0 +1,254 @@
|
||||
import { Order } from "./orderModel.js";
|
||||
const { PAYPAL_CLIENT_ID, PAYPAL_CLIENT_SECRET } = process.env;
|
||||
const base = "https://api-m.sandbox.paypal.com";
|
||||
import axios from "axios";
|
||||
import mongoose from "mongoose";
|
||||
//paypal client id get
|
||||
export const getClientId = async (req, res) => {
|
||||
try {
|
||||
res.status(200).json({
|
||||
success: true,
|
||||
clientId: PAYPAL_CLIENT_ID,
|
||||
});
|
||||
} catch (error) {
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
message: error.message ? error.message : "Something went Wrong",
|
||||
});
|
||||
}
|
||||
};
|
||||
//generate unique order id
|
||||
const generateOrderId = async () => {
|
||||
const currentYear = new Date().getFullYear();
|
||||
// Find the latest order to get the last serial number
|
||||
const latestOrder = await Order.findOne({}, {}, { sort: { orderID: -1 } });
|
||||
let serialNumber = 1;
|
||||
|
||||
if (latestOrder) {
|
||||
const lastYear = parseInt(latestOrder.orderID.substring(0, 4), 10);
|
||||
if (lastYear === currentYear) {
|
||||
// If the last order was in the current year, increment the serial number
|
||||
serialNumber = parseInt(latestOrder.orderID.substring(4), 10) + 1;
|
||||
}
|
||||
}
|
||||
// Pad the serial number with zeros and concatenate with the current year
|
||||
const paddedSerialNumber = serialNumber.toString().padStart(7, "0");
|
||||
const orderId = `${currentYear}${paddedSerialNumber}`;
|
||||
return orderId;
|
||||
};
|
||||
|
||||
//* Generate an OAuth 2.0 access token for authenticating with PayPal REST APIs.
|
||||
// https://developer.paypal.com/api/rest/authentication/
|
||||
// */
|
||||
const generateAccessToken = async () => {
|
||||
const credentials = `${PAYPAL_CLIENT_ID}:${PAYPAL_CLIENT_SECRET}`;
|
||||
const base64Credentials = Buffer.from(credentials).toString("base64");
|
||||
|
||||
const headers = {
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
Authorization: `Basic ${base64Credentials}`,
|
||||
};
|
||||
|
||||
const data = "grant_type=client_credentials";
|
||||
|
||||
try {
|
||||
const response = await axios.post(`${base}/v1/oauth2/token`, data, {
|
||||
headers: headers,
|
||||
});
|
||||
// console.log("response.data", response.data);
|
||||
const accessToken = response.data?.access_token;
|
||||
return accessToken;
|
||||
} catch (error) {
|
||||
console.error(
|
||||
"Error getting access token:",
|
||||
error.response ? error.response.data : error.message
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const handleResponse = async (response) => {
|
||||
try {
|
||||
if (response.status >= 200 && response.status < 300) {
|
||||
return {
|
||||
success: true,
|
||||
responseData: response.data,
|
||||
httpStatusCode: response.status,
|
||||
};
|
||||
}
|
||||
} catch (err) {
|
||||
const errorMessage = await response.statusText;
|
||||
throw new Error(errorMessage);
|
||||
}
|
||||
};
|
||||
|
||||
// https://developer.paypal.com/docs/api/orders/v2/#orders_create
|
||||
|
||||
export const createOrderCheckout = async (req, res) => {
|
||||
try {
|
||||
const { address, cart, subtotal } = req.body;
|
||||
if (cart.length < 1)
|
||||
return res.status(400).json({ message: "cart is empty!" });
|
||||
switch (true) {
|
||||
//validation
|
||||
case !address: {
|
||||
return res.status(404).json({ msg: "please provide shipping address" });
|
||||
}
|
||||
case !subtotal: {
|
||||
return res.status(404).json({ msg: "please provide product subtotal" });
|
||||
}
|
||||
}
|
||||
const orderItems = await cart.map((item) => ({
|
||||
product: item.product._id,
|
||||
name: item.product.name,
|
||||
price: item.product.price,
|
||||
image: item.product.image,
|
||||
quantity: item.quantity,
|
||||
product_subtotal: item.subtotal,
|
||||
price_With_Tax: 0,
|
||||
taxId: "",
|
||||
}));
|
||||
req.body.user = req.user._id;
|
||||
const Id = await generateOrderId();
|
||||
const order = await Order.create({
|
||||
orderID: Id,
|
||||
total_amount: subtotal,
|
||||
orderItems,
|
||||
shippingInfo: address,
|
||||
user: req.user._id,
|
||||
});
|
||||
if (order) {
|
||||
const accessToken = await generateAccessToken();
|
||||
const url = `${base}/v2/checkout/orders`;
|
||||
const createOrderRequest = {
|
||||
intent: "CAPTURE",
|
||||
purchase_units: [
|
||||
{
|
||||
amount: {
|
||||
currency_code: "USD",
|
||||
value: subtotal, //"60.00" Replace with the actual amount
|
||||
//optional product product total value
|
||||
// breakdown: {
|
||||
// item_total: {
|
||||
// currency_code: "USD",
|
||||
// value: "60.00", // Replace with the total value of all items
|
||||
// },
|
||||
// },
|
||||
},
|
||||
//optional give product product also show in paypal dashboard
|
||||
// items: [
|
||||
// {
|
||||
// name: "Apple",
|
||||
// unit_amount: {
|
||||
// currency_code: "USD",
|
||||
// value: "60.00", // Replace with the actual item price
|
||||
// },
|
||||
// quantity: 1,
|
||||
// },
|
||||
// ],
|
||||
},
|
||||
],
|
||||
};
|
||||
const response = await axios.post(
|
||||
url,
|
||||
JSON.stringify(createOrderRequest),
|
||||
{
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${accessToken}`,
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
if (response.status >= 200 && response.status < 300) {
|
||||
let paymentOrderId = await Order.findById(order?._id);
|
||||
paymentOrderId.paypal_payment_id = response.data?.id;
|
||||
await paymentOrderId.save();
|
||||
return res.status(201).json({
|
||||
success: true,
|
||||
responseData: response.data,
|
||||
product_orderId: order?._id,
|
||||
httpStatusCode: response.status,
|
||||
});
|
||||
} else {
|
||||
// Handle errors or unexpected status codes
|
||||
console.error("Error:", response.status, response.statusText);
|
||||
|
||||
// Optionally, you can parse the error response as JSON if available
|
||||
try {
|
||||
const errorData = response.data;
|
||||
console.error("Error Data:", errorData);
|
||||
} catch (error) {
|
||||
console.error("Error parsing error data:", error.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
const errorMessage = await error.message;
|
||||
return res.status(500).json({
|
||||
success: false,
|
||||
message: errorMessage,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Capture payment for the created order to complete the transaction.
|
||||
* //see https://developer.paypal.com/docs/api/orders/v2/#orders_capture
|
||||
*/
|
||||
|
||||
const captureOrder = async (orderID) => {
|
||||
const accessToken = await generateAccessToken();
|
||||
const url = `${base}/v2/checkout/orders/${orderID}/capture`;
|
||||
const response = await axios.post(
|
||||
url,
|
||||
{},
|
||||
{
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${accessToken}`,
|
||||
// Uncomment one of these to force an error for negative testing (in sandbox mode only). Documentation:
|
||||
// https://developer.paypal.com/tools/sandbox/negative-testing/request-headers/
|
||||
// "PayPal-Mock-Response": '{"mock_application_codes": "INSTRUMENT_DECLINED"}'
|
||||
// "PayPal-Mock-Response": '{"mock_application_codes": "TRANSACTION_REFUSED"}'
|
||||
// "PayPal-Mock-Response": '{"mock_application_codes": "INTERNAL_SERVER_ERROR"}'
|
||||
},
|
||||
}
|
||||
);
|
||||
return handleResponse(response);
|
||||
};
|
||||
|
||||
export const captureOrderPayment = async (req, res) => {
|
||||
try {
|
||||
const { orderID } = req.params;
|
||||
|
||||
const { responseData, httpStatusCode } = await captureOrder(orderID);
|
||||
const payment = await Order.findOne({
|
||||
paypal_payment_id: responseData?.id,
|
||||
});
|
||||
// Handle different transaction statuses
|
||||
if (responseData?.status === "COMPLETED") {
|
||||
payment.paypal_payer_id = responseData.payer?.payer_id;
|
||||
payment.paidAt = Date.now();
|
||||
payment.isPaid = true;
|
||||
payment.payment_status = "success";
|
||||
payment.orderStatus = "new";
|
||||
await payment.save();
|
||||
} else if (responseData?.status === "PENDING") {
|
||||
console.log("Payment is pending.");
|
||||
payment.paypal_payer_id = responseData.payer?.payer_id;
|
||||
payment.paidAt = Date.now();
|
||||
payment.payment_status = "pending";
|
||||
await payment.save();
|
||||
} else if (responseData?.status === "FAILED") {
|
||||
payment.paypal_payer_id = responseData.payer?.payer_id;
|
||||
payment.paidAt = Date.now();
|
||||
payment.payment_status = "failed";
|
||||
await payment.save();
|
||||
}
|
||||
|
||||
return res.status(httpStatusCode).json(responseData);
|
||||
} catch (error) {
|
||||
console.error("Failed to create order:", error);
|
||||
res.status(500).json({ error: "Failed to capture order." });
|
||||
}
|
||||
};
|
@ -1,76 +1,22 @@
|
||||
import { Order } from "./orderModel.js";
|
||||
import { generate } from "generate-password";
|
||||
const { PAYPAL_CLIENT_ID, PAYPAL_CLIENT_SECRET } = process.env;
|
||||
const base = "https://api-m.sandbox.paypal.com";
|
||||
import axios from "axios";
|
||||
|
||||
export const getClientId = async (req, res) => {
|
||||
try {
|
||||
res.status(200).json({
|
||||
success: true,
|
||||
clientId: PAYPAL_CLIENT_ID,
|
||||
});
|
||||
} catch (error) {
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
message: error.message ? error.message : "Something went Wrong",
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
export const createOrder = async (req, res) => {
|
||||
try {
|
||||
if (!req?.user) return res.status(400).json({ message: "please login !" });
|
||||
// console.log(req?.user)
|
||||
let isUnique = false;
|
||||
let order_id = generate({
|
||||
length: 9,
|
||||
numbers: true,
|
||||
lowercase: false,
|
||||
uppercase: false,
|
||||
});
|
||||
|
||||
while (!isUnique) {
|
||||
const unqOrder = await Order.findOne({ order_id });
|
||||
if (!unqOrder) {
|
||||
isUnique = true;
|
||||
} else {
|
||||
order_id = generate({
|
||||
length: 9,
|
||||
numbers: true,
|
||||
lowercase: false,
|
||||
uppercase: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
req.body.user = req.user._id;
|
||||
req.body.order_id = order_id;
|
||||
const order = await Order.create(req.body);
|
||||
|
||||
res.status(201).json({
|
||||
success: true,
|
||||
order,
|
||||
message: "order Created",
|
||||
});
|
||||
} catch (error) {
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
message: error.message ? error.message : "Something went Wrong",
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
export const getAllOrder = async (req, res) => {
|
||||
try {
|
||||
if (!req?.user) return res.status(400).json({ message: "please login !" });
|
||||
// console.log(req?.user)
|
||||
|
||||
const order = await Order.find()
|
||||
const order = await Order.find({
|
||||
payment_status: { $in: ["success", "failed"] },
|
||||
})
|
||||
.populate({
|
||||
path: "user",
|
||||
select: "name -_id",
|
||||
})
|
||||
.populate({
|
||||
path: "shippingInfo",
|
||||
|
||||
// populate: {
|
||||
// path: "Franchisee",
|
||||
// select: "banner price_Lable ",
|
||||
// },
|
||||
})
|
||||
.sort({ createdAt: -1 });
|
||||
if (order) {
|
||||
res.status(201).json({
|
||||
@ -86,6 +32,7 @@ export const getAllOrder = async (req, res) => {
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
export const getSingleOrder = async (req, res) => {
|
||||
try {
|
||||
if (!req?.user) return res.status(400).json({ message: "please login !" });
|
||||
@ -122,44 +69,21 @@ export const getSingleOrder = async (req, res) => {
|
||||
}
|
||||
};
|
||||
|
||||
export const EditOrderBeforePayment = async (req, res) => {
|
||||
//get self User Order
|
||||
export const getUserSelf = async (req, res) => {
|
||||
try {
|
||||
if (!req?.user) return res.status(400).json({ message: "please login !" });
|
||||
// console.log(req?.user)
|
||||
if (!req.params.id)
|
||||
return res.status(400).json({ message: "please Provide Order Id" });
|
||||
|
||||
const order = await Order.findById(req.params.id);
|
||||
const order = await Order.find({
|
||||
user: req.user._id,
|
||||
payment_status: "success",
|
||||
})
|
||||
.populate("shippingInfo")
|
||||
.sort({ createdAt: -1 });
|
||||
if (order) {
|
||||
if (order.isPaid === false) {
|
||||
if (order.user.toString() === req.user._id.toString()) {
|
||||
req.body.user = req.user._id;
|
||||
|
||||
const ModifyOrder = await Order.findByIdAndUpdate(
|
||||
req.params.id,
|
||||
req.body,
|
||||
|
||||
{
|
||||
new: true,
|
||||
runValidators: true,
|
||||
useFindAndModify: false,
|
||||
}
|
||||
);
|
||||
res.status(200).json({
|
||||
success: true,
|
||||
order: ModifyOrder,
|
||||
message: " Order Updated",
|
||||
});
|
||||
} else {
|
||||
return res.status(400).json({
|
||||
message: "You not created This So You Can not Edit this Order !! ",
|
||||
});
|
||||
}
|
||||
} else {
|
||||
return res
|
||||
.status(400)
|
||||
.json({ message: "order can not Edited Because Payment Done !! " });
|
||||
}
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
order,
|
||||
message: "self Order fetched",
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
res.status(500).json({
|
||||
@ -194,169 +118,3 @@ export const deleteOneOrder = async (req, res) => {
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// parse post params sent in body in json format
|
||||
|
||||
/**
|
||||
* Generate an OAuth 2.0 access token for authenticating with PayPal REST APIs.
|
||||
// https://developer.paypal.com/api/rest/authentication/
|
||||
*/
|
||||
const generateAccessToken = async () => {
|
||||
const credentials = `${PAYPAL_CLIENT_ID}:${PAYPAL_CLIENT_SECRET}`;
|
||||
const base64Credentials = Buffer.from(credentials).toString("base64");
|
||||
|
||||
const headers = {
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
Authorization: `Basic ${base64Credentials}`,
|
||||
};
|
||||
|
||||
const data = "grant_type=client_credentials";
|
||||
|
||||
try {
|
||||
const response = await axios.post(
|
||||
"https://api.sandbox.paypal.com/v1/oauth2/token",
|
||||
data,
|
||||
{
|
||||
headers: headers,
|
||||
}
|
||||
);
|
||||
// console.log("response.data", response.data);
|
||||
const accessToken = response.data?.access_token;
|
||||
return accessToken;
|
||||
// console.log("Access Token:", accessToken);
|
||||
} catch (error) {
|
||||
console.error(
|
||||
"Error getting access token:",
|
||||
error.response ? error.response.data : error.message
|
||||
);
|
||||
}
|
||||
};
|
||||
// } catch (error) {
|
||||
// console.error("Failed to generate Access Token:");
|
||||
// }
|
||||
// };
|
||||
|
||||
const handleResponse = async (response) => {
|
||||
try {
|
||||
if (response.status >= 200 && response.status < 300) {
|
||||
return {
|
||||
success: true,
|
||||
responseData: response.data,
|
||||
httpStatusCode: response.status,
|
||||
};
|
||||
}
|
||||
} catch (err) {
|
||||
const errorMessage = await response.statusText;
|
||||
throw new Error(errorMessage);
|
||||
}
|
||||
};
|
||||
|
||||
// https://developer.paypal.com/docs/api/orders/v2/#orders_create
|
||||
|
||||
export const createOrderCheckout = async (rea, res) => {
|
||||
try {
|
||||
// const { cart } = req.body;
|
||||
// use the cart information passed from the front-end to calculate the purchase unit details
|
||||
// console.log(
|
||||
// "shopping cart information passed from the frontend createOrder() callback:",
|
||||
// cart
|
||||
// );
|
||||
const accessToken = await generateAccessToken();
|
||||
const url = `https://api.sandbox.paypal.com/v2/checkout/orders`;
|
||||
const createOrderRequest = {
|
||||
intent: "CAPTURE",
|
||||
purchase_units: [
|
||||
{
|
||||
amount: {
|
||||
currency_code: "USD",
|
||||
value: "60.00", // Replace with the actual amount
|
||||
breakdown: {
|
||||
item_total: {
|
||||
currency_code: "USD",
|
||||
value: "60.00", // Replace with the total value of all items
|
||||
},
|
||||
},
|
||||
},
|
||||
items: [
|
||||
{
|
||||
name: "Apple",
|
||||
unit_amount: {
|
||||
currency_code: "USD",
|
||||
value: "60.00", // Replace with the actual item price
|
||||
},
|
||||
quantity: 1,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
const response = await axios.post(url, JSON.stringify(createOrderRequest), {
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${accessToken}`,
|
||||
},
|
||||
});
|
||||
|
||||
if (response.status >= 200 && response.status < 300) {
|
||||
return res.status(201).json({
|
||||
success: true,
|
||||
responseData: response.data,
|
||||
httpStatusCode: response.status,
|
||||
});
|
||||
} else {
|
||||
// Handle errors or unexpected status codes
|
||||
console.error("Error:", response.status, response.statusText);
|
||||
|
||||
// Optionally, you can parse the error response as JSON if available
|
||||
try {
|
||||
const errorData = response.data;
|
||||
console.error("Error Data:", errorData);
|
||||
} catch (error) {
|
||||
console.error("Error parsing error data:", error.message);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
const errorMessage = await response.statusText;
|
||||
return res.status(500).json({
|
||||
success: false,
|
||||
message: errorMessage,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Capture payment for the created order to complete the transaction.
|
||||
* //see https://developer.paypal.com/docs/api/orders/v2/#orders_capture
|
||||
*/
|
||||
|
||||
const captureOrder = async (orderID) => {
|
||||
const accessToken = await generateAccessToken();
|
||||
const url = `${base}/v2/checkout/orders/${orderID}/capture`;
|
||||
const response = await axios.post(
|
||||
url,
|
||||
{},
|
||||
{
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${accessToken}`,
|
||||
// Uncomment one of these to force an error for negative testing (in sandbox mode only). Documentation:
|
||||
// https://developer.paypal.com/tools/sandbox/negative-testing/request-headers/
|
||||
// "PayPal-Mock-Response": '{"mock_application_codes": "INSTRUMENT_DECLINED"}'
|
||||
// "PayPal-Mock-Response": '{"mock_application_codes": "TRANSACTION_REFUSED"}'
|
||||
// "PayPal-Mock-Response": '{"mock_application_codes": "INTERNAL_SERVER_ERROR"}'
|
||||
},
|
||||
}
|
||||
);
|
||||
return handleResponse(response);
|
||||
};
|
||||
|
||||
export const captureOrderPayment = async (req, res) => {
|
||||
try {
|
||||
const { orderID } = req.params;
|
||||
const { responseData, httpStatusCode } = await captureOrder(orderID);
|
||||
return res.status(httpStatusCode).json(responseData);
|
||||
} catch (error) {
|
||||
console.error("Failed to create order:", error);
|
||||
res.status(500).json({ error: "Failed to capture order." });
|
||||
}
|
||||
};
|
||||
|
@ -1,158 +1,110 @@
|
||||
import mongoose from "mongoose";
|
||||
|
||||
|
||||
const orderSchema = new mongoose.Schema(
|
||||
{
|
||||
order_id: { type: String },
|
||||
user: {
|
||||
type: mongoose.Schema.ObjectId,
|
||||
ref: "User",
|
||||
required: true,
|
||||
},
|
||||
|
||||
shippingInfo: {
|
||||
name: { type: String, required: true, },
|
||||
address: {
|
||||
type: String,
|
||||
default: '',
|
||||
},
|
||||
contact_Person_Name: { type: String, default: "" },
|
||||
city: {
|
||||
type: String,
|
||||
|
||||
default: ''
|
||||
},
|
||||
|
||||
state: {
|
||||
type: String,
|
||||
default: ''
|
||||
},
|
||||
|
||||
|
||||
pinCode: {
|
||||
type: Number,
|
||||
default: '',
|
||||
},
|
||||
contact_Number: {
|
||||
type: Number,
|
||||
default: ''
|
||||
},
|
||||
|
||||
Franchisee: {
|
||||
type: mongoose.Schema.ObjectId,
|
||||
ref: "Temple",
|
||||
},
|
||||
},
|
||||
orderItems: [
|
||||
{
|
||||
name: {
|
||||
type: String,
|
||||
default: ''
|
||||
},
|
||||
price: {
|
||||
type: Number,
|
||||
default: ''
|
||||
},
|
||||
quantity: {
|
||||
type: Number,
|
||||
default: '',
|
||||
default: 1
|
||||
},
|
||||
image: {
|
||||
type: String,
|
||||
default: '',
|
||||
},
|
||||
|
||||
|
||||
price_With_Tax: {
|
||||
type: Number,
|
||||
default: '',
|
||||
},
|
||||
|
||||
taxId: {
|
||||
type: String,
|
||||
default: ''
|
||||
},
|
||||
|
||||
product: {
|
||||
type: mongoose.Schema.ObjectId,
|
||||
ref: "Product",
|
||||
|
||||
},
|
||||
},
|
||||
],
|
||||
|
||||
shipping_charge: { type: Number, default: 0 },
|
||||
tax_amount: { type: Number, default: 0 },
|
||||
total_amount: { type: Number, default: 0 },
|
||||
weight: { type: Number, default: 0 },
|
||||
|
||||
paymentMode: {
|
||||
type: String,
|
||||
default: ''
|
||||
},
|
||||
paymentInfo: {
|
||||
id: {
|
||||
type: String,
|
||||
// required: true,
|
||||
default: ""
|
||||
},
|
||||
status: {
|
||||
type: String,
|
||||
enum: ["pending", "success", "failed"],
|
||||
},
|
||||
paymentTime: {
|
||||
type: Date,
|
||||
},
|
||||
},
|
||||
|
||||
|
||||
isPaid: {
|
||||
type: Boolean,
|
||||
default: false
|
||||
},
|
||||
paidAt: {
|
||||
type: Date,
|
||||
|
||||
},
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
orderStatus: {
|
||||
type: String,
|
||||
enum: [
|
||||
"new",
|
||||
"processing",
|
||||
"dispatched",
|
||||
"delivered",
|
||||
"cancelled",
|
||||
"returned",
|
||||
],
|
||||
default: "new",
|
||||
},
|
||||
|
||||
// razorpay_order_id: { type: String },
|
||||
// razorpay_payment_id: { type: String },
|
||||
// razorpay_signature: { type: String },
|
||||
// order_used: { type: Boolean, default: false },
|
||||
// isDelivered: { type: Boolean,required:true,default:false },
|
||||
// deliveredAt: { type: Date },
|
||||
status_timeline: {
|
||||
new: { type: Date },
|
||||
processing: { type: Date },
|
||||
dispatched: { type: Date },
|
||||
delivered: { type: Date },
|
||||
cancelled: { type: Date },
|
||||
returned: { type: Date },
|
||||
},
|
||||
// courier_name: { type: String },
|
||||
// tracking_id: { type: String },
|
||||
{
|
||||
orderID: {
|
||||
type: String,
|
||||
required: true,
|
||||
unique: true,
|
||||
},
|
||||
{ timestamps: true, versionKey: false }
|
||||
user: {
|
||||
type: mongoose.Schema.ObjectId,
|
||||
ref: "User",
|
||||
required: true,
|
||||
},
|
||||
shippingInfo: {
|
||||
type: mongoose.Schema.ObjectId,
|
||||
ref: "ShippingAddress",
|
||||
required: true,
|
||||
},
|
||||
orderItems: [
|
||||
{
|
||||
name: {
|
||||
type: String,
|
||||
default: "",
|
||||
},
|
||||
price: {
|
||||
type: Number,
|
||||
default: "",
|
||||
},
|
||||
quantity: {
|
||||
type: Number,
|
||||
default: "",
|
||||
default: 1,
|
||||
},
|
||||
image: [{}],
|
||||
|
||||
price_With_Tax: {
|
||||
type: Number,
|
||||
default: "",
|
||||
},
|
||||
|
||||
taxId: {
|
||||
type: String,
|
||||
default: "",
|
||||
},
|
||||
|
||||
product: {
|
||||
type: mongoose.Schema.ObjectId,
|
||||
ref: "Product",
|
||||
},
|
||||
},
|
||||
],
|
||||
|
||||
shipping_charge: { type: Number, default: 0 },
|
||||
tax_amount: { type: Number, default: 0 },
|
||||
total_amount: { type: Number, default: 0 },
|
||||
weight: { type: Number, default: 0 },
|
||||
|
||||
paymentMode: {
|
||||
type: String,
|
||||
enum: ["online", "cod"],
|
||||
default: "online",
|
||||
},
|
||||
|
||||
payment_status: {
|
||||
type: String,
|
||||
enum: ["pending", "success", "failed"],
|
||||
},
|
||||
isPaid: {
|
||||
type: Boolean,
|
||||
default: false,
|
||||
},
|
||||
paidAt: {
|
||||
type: Date,
|
||||
},
|
||||
|
||||
orderStatus: {
|
||||
type: String,
|
||||
enum: [
|
||||
"new",
|
||||
"processing",
|
||||
"dispatched",
|
||||
"delivered",
|
||||
"cancelled",
|
||||
"returned",
|
||||
],
|
||||
// default: "new",
|
||||
},
|
||||
|
||||
paypal_payer_id: { type: String },
|
||||
paypal_payment_id: { type: String },
|
||||
// paypal_signature: { type: String },
|
||||
// order_used: { type: Boolean, default: false },
|
||||
// isDelivered: { type: Boolean,required:true,default:false },
|
||||
// deliveredAt: { type: Date },
|
||||
status_timeline: {
|
||||
new: { type: Date },
|
||||
processing: { type: Date },
|
||||
dispatched: { type: Date },
|
||||
delivered: { type: Date },
|
||||
cancelled: { type: Date },
|
||||
returned: { type: Date },
|
||||
},
|
||||
// courier_name: { type: String },
|
||||
// tracking_id: { type: String },
|
||||
},
|
||||
{ timestamps: true }
|
||||
);
|
||||
|
||||
export const Order = mongoose.model("Order", orderSchema);
|
||||
|
@ -1,34 +1,33 @@
|
||||
import {
|
||||
captureOrderPayment,
|
||||
createOrder,
|
||||
createOrderCheckout,
|
||||
deleteOneOrder,
|
||||
EditOrderBeforePayment,
|
||||
getAllOrder,
|
||||
getSingleOrder,
|
||||
getClientId,
|
||||
getUserSelf,
|
||||
} from "./orderController.js";
|
||||
import { isAuthenticatedUser, authorizeRoles } from "../../middlewares/auth.js";
|
||||
import express from "express";
|
||||
import {
|
||||
captureOrderPayment,
|
||||
createOrderCheckout,
|
||||
getClientId,
|
||||
} from "./CheckoutController.js";
|
||||
const router = express.Router();
|
||||
router.route("/checkout/").post(createOrderCheckout);
|
||||
router.route("/clientid/get/").get(getClientId);
|
||||
|
||||
//checkout Routes-------------------------//
|
||||
router.route("/checkout/").post(isAuthenticatedUser, createOrderCheckout);
|
||||
router.route("/clientid/get/").get(isAuthenticatedUser, getClientId);
|
||||
router.route("/:orderID/capture/payment").post(captureOrderPayment);
|
||||
// ---------------------------------------------------
|
||||
//get user self
|
||||
router.route("/user/self").get(isAuthenticatedUser, getUserSelf);
|
||||
|
||||
// .capturePayment(orderID)
|
||||
router
|
||||
.route("/order/create")
|
||||
.post(isAuthenticatedUser, authorizeRoles("admin"), createOrder);
|
||||
//admin route
|
||||
router
|
||||
.route("/order/getAll")
|
||||
.get(isAuthenticatedUser, authorizeRoles("admin"), getAllOrder);
|
||||
router
|
||||
.route("/order/getOne/:id")
|
||||
.get(isAuthenticatedUser, authorizeRoles("admin"), getSingleOrder);
|
||||
router
|
||||
.route("/order/edit/:id")
|
||||
.put(isAuthenticatedUser, authorizeRoles("admin"), EditOrderBeforePayment);
|
||||
router.route("/order/getOne/:id").get(isAuthenticatedUser, getSingleOrder);
|
||||
// router
|
||||
// .route("/order/edit/:id")
|
||||
// .put(isAuthenticatedUser, authorizeRoles("admin"), EditOrderBeforePayment);
|
||||
|
||||
router
|
||||
.route("/order/delete/:id")
|
||||
|
@ -1,6 +1,4 @@
|
||||
import { shippingAddress } from "./ShippingAddressModel.js";
|
||||
import { generate } from "generate-password";
|
||||
|
||||
export const AddshippingAddress = async (req, res) => {
|
||||
try {
|
||||
const {
|
||||
@ -13,7 +11,6 @@ export const AddshippingAddress = async (req, res) => {
|
||||
postalCode,
|
||||
country,
|
||||
} = req.body;
|
||||
console.log("hiiii");
|
||||
switch (true) {
|
||||
//validation
|
||||
case !first_Name: {
|
||||
@ -41,46 +38,7 @@ export const AddshippingAddress = async (req, res) => {
|
||||
return res.status(404).json({ msg: "please provide country" });
|
||||
}
|
||||
}
|
||||
|
||||
// let isUnique = false;
|
||||
// let Machine_ID = generate({
|
||||
// length: 8,
|
||||
// numbers: true,
|
||||
// lowercase: false,
|
||||
// uppercase: false,
|
||||
// });
|
||||
// let Tablet_ID = generate({
|
||||
// length: 8,
|
||||
// numbers: true,
|
||||
// lowercase: false,
|
||||
// uppercase: false,
|
||||
// });
|
||||
|
||||
// while (!isUnique) {
|
||||
// const unqmachine = await shippingAddress.findOne({ Machine_ID });
|
||||
// if (!unqmachine) {
|
||||
// isUnique = true;
|
||||
// console.log(unqmachine);
|
||||
// } else {
|
||||
// Machine_ID = generate({
|
||||
// length: 8,
|
||||
// numbers: true,
|
||||
// lowercase: false,
|
||||
// uppercase: false,
|
||||
// });
|
||||
// Tablet_ID = generate({
|
||||
// length: 8,
|
||||
// numbers: true,
|
||||
// lowercase: false,
|
||||
// uppercase: false,
|
||||
// });
|
||||
// }
|
||||
// }
|
||||
|
||||
req.body.user = req.user._id;
|
||||
// req.body.Machine_ID = Machine_ID;
|
||||
// req.body.Tablet_ID = Tablet_ID;
|
||||
|
||||
const address = await shippingAddress.create(req.body);
|
||||
|
||||
res.status(201).json({
|
||||
@ -96,167 +54,17 @@ export const AddshippingAddress = async (req, res) => {
|
||||
}
|
||||
};
|
||||
|
||||
export const getAllmachine = async (req, res) => {
|
||||
export const getSingleUserSippingAddress = async (req, res) => {
|
||||
try {
|
||||
if (!req?.user) return res.status(400).json({ message: "please login !" });
|
||||
// console.log(req?.user)
|
||||
const UserShippingAddress = await shippingAddress
|
||||
.find({ user: req.user._id })
|
||||
|
||||
const machine = await shippingAddress
|
||||
.find()
|
||||
.populate({
|
||||
path: "user",
|
||||
select: "name -_id",
|
||||
})
|
||||
.populate({
|
||||
path: "Allocated_To",
|
||||
select: "name _id",
|
||||
})
|
||||
.sort({ createdAt: -1 });
|
||||
if (machine) {
|
||||
if (UserShippingAddress) {
|
||||
res.status(201).json({
|
||||
success: true,
|
||||
machine,
|
||||
message: "All machine Fetched",
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
message: error.message ? error.message : "Something went Wrong",
|
||||
});
|
||||
}
|
||||
};
|
||||
export const getSinglemachine = async (req, res) => {
|
||||
try {
|
||||
if (!req?.user) return res.status(400).json({ message: "please login !" });
|
||||
// console.log(req?.user)
|
||||
if (!req.params.id)
|
||||
return res.status(400).json({ message: "please Provide machine Id" });
|
||||
|
||||
const machine = await shippingAddress
|
||||
.findById(req.params.id)
|
||||
.populate({
|
||||
path: "user",
|
||||
select: "name -_id",
|
||||
})
|
||||
.populate({
|
||||
path: "Allocated_To",
|
||||
select: "name _id",
|
||||
});
|
||||
if (machine) {
|
||||
res.status(201).json({
|
||||
success: true,
|
||||
machine,
|
||||
message: " machine Fetched",
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
message: error.message ? error.message : "Something went Wrong",
|
||||
});
|
||||
}
|
||||
};
|
||||
export const EditMachine = async (req, res) => {
|
||||
try {
|
||||
if (!req?.user) return res.status(400).json({ message: "please login !" });
|
||||
// console.log(req?.user)
|
||||
|
||||
const { Allocated_To, Allocated_On } = req.body;
|
||||
switch (true) {
|
||||
//validation
|
||||
|
||||
case !Allocated_To: {
|
||||
return res.status(404).json({ msg: "please provide Allocated To" });
|
||||
}
|
||||
case !Allocated_On: {
|
||||
return res.status(404).json({ msg: "please provide AllocatedOn Date" });
|
||||
}
|
||||
}
|
||||
|
||||
const machine = await shippingAddress.findById(req.params.id);
|
||||
if (machine) {
|
||||
const Modifymachine = await shippingAddress.findByIdAndUpdate(
|
||||
req.params.id,
|
||||
req.body,
|
||||
|
||||
{
|
||||
new: true,
|
||||
runValidators: true,
|
||||
useFindAndModify: false,
|
||||
}
|
||||
);
|
||||
res.status(200).json({
|
||||
success: true,
|
||||
machine: Modifymachine,
|
||||
message: " shippingAddress Updated",
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
message: error.message ? error.message : "Something went Wrong",
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
//
|
||||
|
||||
//varification
|
||||
export const machineVarificationFromAdmin = async (req, res) => {
|
||||
try {
|
||||
if (!req?.user) return res.status(400).json({ message: "please login !" });
|
||||
// console.log(req?.user)
|
||||
if (!req.params.id)
|
||||
return res.status(400).json({ message: "please Provide machine Id" });
|
||||
const getMachine = await shippingAddress.findById(req.params.id);
|
||||
if (getMachine) {
|
||||
if (req.user.role === "admin") {
|
||||
if (getMachine.Status === false) {
|
||||
getMachine.Status = true;
|
||||
} else {
|
||||
getMachine.Status = false;
|
||||
}
|
||||
|
||||
getMachine.save();
|
||||
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
message: `shippingAddress status change successfully`,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
return res.status(400).json({ message: "Only Admin Change Status" });
|
||||
}
|
||||
} catch (err) {
|
||||
// console.log(err)
|
||||
return res
|
||||
.status(500)
|
||||
.json({ message: err.message ? err.message : "Something went wrong." });
|
||||
}
|
||||
};
|
||||
|
||||
//get machine using franchisee id
|
||||
|
||||
export const getMachineDetails = async (req, res) => {
|
||||
try {
|
||||
if (!req?.franchi)
|
||||
return res.status(400).json({ message: "please login !" });
|
||||
|
||||
const machine = await shippingAddress
|
||||
.find({
|
||||
Allocated_To: req.franchi._id,
|
||||
Status: true,
|
||||
})
|
||||
.populate({
|
||||
path: "Allocated_To",
|
||||
select: "name _id",
|
||||
});
|
||||
if (machine) {
|
||||
res.status(201).json({
|
||||
success: true,
|
||||
machine,
|
||||
message: " machine Fetched",
|
||||
UserShippingAddress,
|
||||
message: "All User Shipping Address Fetched",
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
@ -268,27 +76,32 @@ export const getMachineDetails = async (req, res) => {
|
||||
};
|
||||
|
||||
///
|
||||
export const deleteOneMachine = async (req, res) => {
|
||||
export const deleteSelfShippingAddress = async (req, res) => {
|
||||
try {
|
||||
if (!req?.user) return res.status(400).json({ message: "please login !" });
|
||||
if (!req.params.id)
|
||||
return res
|
||||
.status(400)
|
||||
.json({ message: "please Provide shippingAddress Id" });
|
||||
const getmachine = await shippingAddress.findById(req.params.id);
|
||||
if (!getmachine) {
|
||||
.json({ message: "please Provide shipping Address Id" });
|
||||
const getselfAddress = await shippingAddress.findById(req.params.id);
|
||||
if (!getselfAddress) {
|
||||
return res.status(404).json({
|
||||
success: false,
|
||||
message: "No shippingAddress Found!",
|
||||
message: "No shipping Address Found!",
|
||||
});
|
||||
}
|
||||
if (getselfAddress?.user.toString() === req.user._id.toString()) {
|
||||
const address = await shippingAddress.findByIdAndDelete(req.params.id);
|
||||
await address.remove();
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
message: "shipping Address Deleted Successfully!!",
|
||||
});
|
||||
} else {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: "you can only delete self shipping address!!",
|
||||
});
|
||||
}
|
||||
const machine = await shippingAddress.findByIdAndDelete(req.params.id);
|
||||
|
||||
await machine.remove();
|
||||
res.status(200).json({
|
||||
success: true,
|
||||
message: "shippingAddress Deleted Successfully!!",
|
||||
});
|
||||
} catch (error) {
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
|
@ -1,30 +1,19 @@
|
||||
import express from "express";
|
||||
import { AddshippingAddress } from "./ShippingAddressController.js";
|
||||
import {
|
||||
AddshippingAddress,
|
||||
getSingleUserSippingAddress,
|
||||
deleteSelfShippingAddress,
|
||||
} from "./ShippingAddressController.js";
|
||||
import { isAuthenticatedUser } from "../../middlewares/auth.js";
|
||||
const router = express.Router();
|
||||
|
||||
router.route("/new").post(isAuthenticatedUser, AddshippingAddress);
|
||||
// router
|
||||
// .route("/getAll")
|
||||
// .get(isAuthenticatedUser, getAllmachine);
|
||||
// router
|
||||
// .route("/getOne/:id")
|
||||
// .get(isAuthenticatedUser, getSinglemachine);
|
||||
// router
|
||||
// .route("/edit/:id")
|
||||
// .put(isAuthenticatedUser, EditMachine);
|
||||
router
|
||||
.route("/user/address/")
|
||||
.get(isAuthenticatedUser, getSingleUserSippingAddress);
|
||||
|
||||
// router
|
||||
// .route("/delete/:id")
|
||||
// .delete(isAuthenticatedUser, deleteOneMachine);
|
||||
// router
|
||||
// .route("/admin/verify/:id")
|
||||
// .get(
|
||||
// isAuthenticatedUser,
|
||||
// authorizeRoles("admin"),
|
||||
// machineVarificationFromAdmin
|
||||
// );
|
||||
|
||||
//
|
||||
router
|
||||
.route("/delete/:id")
|
||||
.delete(isAuthenticatedUser, deleteSelfShippingAddress);
|
||||
|
||||
export default router;
|
||||
|
Loading…
Reference in New Issue
Block a user