-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpayment.services.ts
145 lines (136 loc) · 3.95 KB
/
payment.services.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
import { stripe } from "../controllers/paymentController";
import database_models from "../database/config/db.config";
import { Product } from "../database/models/product";
import { Sales } from "../database/models/sales";
import { cartItem } from "../types/cart";
import {
OrderCreationAttributes,
OrderModelAttributes,
PaymentsModelAttributes,
UserModelAttributes,
cartModelAttributes,
salesModelAttributes,
} from "../types/model";
import { PaymentDetails } from "../types/payment";
import { insert_function, read_function } from "../utils/db_methods";
import { EventName, myEmitter } from "../utils/nodeEvents";
import { v4 as uuidv4 } from "uuid";
export const findUserCartById = async (userId: string) => {
return await read_function<cartModelAttributes>("Cart", "findOne", {
where: { userId },
});
};
export const getOrCreateStripeCustomer = async (user: UserModelAttributes) => {
try {
const existingCustomer = await stripe.customers.list({ email: user.email });
if (existingCustomer.data.length > 0) {
return existingCustomer.data[0];
} else {
const customer = await stripe.customers.create({
name: `${user.firstName} ${user.lastName}`,
email: user.email,
address: {
country: user.country,
city: user.city,
line1: user.addressLine1,
line2: user.addressLine2,
},
});
return customer;
}
} catch (error) {
console.error(
"Error while getting or creating stripe customer:",
(error as Error).message,
);
throw error;
}
};
export const lineCartItems = (cart: cartModelAttributes) => {
const line_items = [];
const products: cartItem[] = cart.products;
for (const product of products) {
const line_item_obj = {
price_data: {
currency: "rwf",
product_data: {
name: product.name,
images: [product.image],
},
unit_amount: Math.floor(
product.price - (product.price * product.discount) / 100,
),
},
quantity: product.quantity,
};
line_items.push(line_item_obj);
}
return line_items;
};
export const getPaymentBySession = async (sessionId: string) => {
return await read_function<PaymentDetails>("Payments", "findOne", {
where: { sessionId },
});
};
export const recordPaymentDetails = async (paymentDetails: PaymentDetails) => {
const paymantDetails = await insert_function<PaymentsModelAttributes>(
"Payments",
"create",
paymentDetails,
);
if ("error" in paymantDetails) {
throw new Error("Error while recording payment details!");
}
return paymantDetails;
};
export const readOrderById = async (orderId: string) => {
return await read_function<OrderCreationAttributes>("Order", "findOne", {
where: { id: orderId },
});
};
export const orderItems = async (cart: cartModelAttributes) => {
const order = await insert_function<OrderModelAttributes>("Order", "create", {
buyerId: cart.userId,
});
const products = cart.products;
const currentDate = new Date(Date.now());
const deliveryDate = new Date(currentDate.setDate(currentDate.getDate() + 2));
for (const product of products) {
const sale_data = {
orderId: order.id,
buyerId: cart.userId,
productId: product.id,
deliveryDate,
quantitySold: product.quantity,
};
await insert_function<salesModelAttributes>("Sales", "create", sale_data);
myEmitter.emit(EventName.PRRODUCT_BOUGHT, product.id, order);
}
// Emit ORDERS_COMPLETED event only once per order
myEmitter.emit(EventName.ORDERS_COMPLETED, order, cart.products);
await database_models.Cart.update(
{ products: [], total: 0 },
{ where: { id: cart.id } },
);
return await read_function<OrderModelAttributes>("Order", "findOne", {
where: { id: order.id },
include: [
{
model: Sales,
as: "sales",
attributes: ["orderId", "status", "deliveryDate", "quantitySold"],
include: [
{
model: Product,
as: "soldProducts",
attributes: ["name", "price", "images", "isAvailable", "discount"],
},
],
},
],
});
};
export function generateUUID() {
const uuid = uuidv4();
return uuid;
}