Advertisement
RupeshAcharya60

fa

Oct 6th, 2024
12
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.78 KB | None | 0 0
  1. import { faker } from "@faker-js/faker";
  2. import {
  3. AvailableOrderStatuses,
  4. AvailablePaymentProviders,
  5. UserRolesEnum,
  6. } from "../constants.js";
  7. import { User } from "../models/apps/auth/user.models.js";
  8. import { Address } from "../models/apps/ecommerce/address.models.js";
  9. import { Category } from "../models/apps/ecommerce/category.models.js";
  10. import { Coupon } from "../models/apps/ecommerce/coupon.models.js";
  11. import { EcomOrder } from "../models/apps/ecommerce/order.models.js";
  12. import { Product } from "../models/apps/ecommerce/product.models.js";
  13. import { EcomProfile } from "../models/apps/ecommerce/profile.models.js";
  14. import { ApiError } from "../utils/ApiError.js";
  15. import { ApiResponse } from "../utils/ApiResponse.js";
  16. import { asyncHandler } from "../utils/asyncHandler.js";
  17. import { getRandomNumber } from "../utils/helpers.js";
  18. import {
  19. ADDRESSES_COUNT,
  20. CATEGORIES_COUNT,
  21. COUPONS_COUNT,
  22. ORDERS_COUNT,
  23. ORDERS_RANDOM_ITEMS_COUNT,
  24. PRODUCTS_COUNT,
  25. PRODUCTS_SUB_IMAGES_COUNT,
  26. } from "./_constants.js";
  27.  
  28. // Clothing categories
  29. const clothingCategories = [
  30. "T-shirts",
  31. "Jeans",
  32. "Dresses",
  33. "Sweaters",
  34. "Jackets",
  35. "Skirts",
  36. "Shorts",
  37. "Hoodies",
  38. "Suits",
  39. "Activewear",
  40. ];
  41.  
  42. // Generate fake categories
  43. const categories = clothingCategories.slice(0, CATEGORIES_COUNT).map((category) => ({
  44. name: category.toLowerCase(),
  45. }));
  46.  
  47. // Generate fake addresses
  48. const addresses = new Array(ADDRESSES_COUNT).fill("_").map(() => ({
  49. addressLine1: faker.location.streetAddress(),
  50. addressLine2: faker.location.street(),
  51. city: faker.location.city(),
  52. country: faker.location.country(),
  53. pincode: faker.location.zipCode("######"),
  54. state: faker.location.state(),
  55. }));
  56.  
  57. // Generate fake coupons
  58. const coupons = new Array(COUPONS_COUNT).fill("_").map(() => {
  59. const discountValue = faker.number.int({
  60. max: 1000,
  61. min: 100,
  62. });
  63.  
  64. return {
  65. name: faker.lorem.word({
  66. length: {
  67. max: 15,
  68. min: 8,
  69. },
  70. }),
  71. couponCode:
  72. faker.lorem.word({
  73. length: {
  74. max: 8,
  75. min: 5,
  76. },
  77. }) + `${discountValue}`,
  78. discountValue: discountValue,
  79. isActive: faker.datatype.boolean(),
  80. minimumCartValue: discountValue + 300,
  81. startDate: faker.date.anytime(),
  82. expiryDate: faker.date.future({
  83. years: 3,
  84. }),
  85. };
  86. });
  87.  
  88. // Generate fake products
  89. const products = new Array(PRODUCTS_COUNT).fill("_").map(() => {
  90. const category = faker.helpers.arrayElement(clothingCategories);
  91. return {
  92. name: `${faker.commerce.productAdjective()} ${category} ${faker.commerce.productMaterial()}`,
  93. description: faker.commerce.productDescription(),
  94. mainImage: {
  95. url: faker.image.urlLoremFlickr({
  96. category: "fashion",
  97. width: 800,
  98. height: 600,
  99. }),
  100. localPath: "",
  101. },
  102. price: +faker.commerce.price({ dec: 0, min: 1000, max: 10000 }),
  103. stock: +faker.commerce.price({ dec: 0, min: 10, max: 200 }),
  104. subImages: new Array(PRODUCTS_SUB_IMAGES_COUNT).fill("_").map(() => ({
  105. url: faker.image.urlLoremFlickr({
  106. category: "fashion",
  107. width: 800,
  108. height: 600,
  109. }),
  110. localPath: "",
  111. })),
  112. };
  113. });
  114.  
  115. const orders = new Array(ORDERS_COUNT).fill("_").map(() => {
  116. const paymentProvider =
  117. AvailablePaymentProviders[
  118. getRandomNumber(AvailablePaymentProviders.length)
  119. ];
  120. return {
  121. status:
  122. AvailableOrderStatuses[getRandomNumber(AvailableOrderStatuses.length)],
  123. paymentProvider: paymentProvider === "UNKNOWN" ? "PAYPAL" : paymentProvider,
  124. paymentId: faker.string.alphanumeric({
  125. casing: "mixed",
  126. length: 24,
  127. }),
  128. isPaymentDone: true,
  129. };
  130. });
  131.  
  132. const seedEcomProfiles = async () => {
  133. const profiles = await EcomProfile.find();
  134. const ecomProfileUpdatePromise = profiles.map(async (profile) => {
  135. await EcomProfile.findByIdAndUpdate(profile._id, {
  136. $set: {
  137. firstName: faker.person.firstName(),
  138. lastName: faker.person.lastName(),
  139. countryCode: "+91",
  140. phoneNumber: faker.phone.number("9#########"),
  141. },
  142. });
  143. });
  144. await Promise.all(ecomProfileUpdatePromise);
  145. };
  146.  
  147. const seedEcomCategories = async (owner) => {
  148. await Category.deleteMany({});
  149. await Category.insertMany(
  150. categories.map((cat) => ({ ...cat, owner: owner }))
  151. );
  152. };
  153.  
  154. const seedEcomAddresses = async () => {
  155. const users = await User.find();
  156. await Address.deleteMany({});
  157. await Address.insertMany(
  158. addresses.map((add, i) => {
  159. return {
  160. ...add,
  161. owner: users[i] ?? users[getRandomNumber(users.length)],
  162. };
  163. })
  164. );
  165. };
  166.  
  167. const seedEcomCoupons = async (owner) => {
  168. await Coupon.deleteMany({});
  169. await Coupon.insertMany(
  170. coupons.map((coupon) => ({ ...coupon, owner: owner }))
  171. );
  172. };
  173.  
  174. const seedEcomProducts = async () => {
  175. const users = await User.find();
  176. const categories = await Category.find();
  177.  
  178. await Product.deleteMany({});
  179. await Product.insertMany(
  180. products.map((product) => ({
  181. ...product,
  182. owner: users[getRandomNumber(users.length)],
  183. category: categories[getRandomNumber(categories.length)],
  184. }))
  185. );
  186. };
  187.  
  188. const seedEcomOrders = async () => {
  189. const customers = await User.find();
  190. const coupons = await Coupon.find();
  191. const products = await Product.find();
  192. const addresses = await Address.find();
  193.  
  194. const orderPayload = new Array(ORDERS_RANDOM_ITEMS_COUNT)
  195. .fill("_")
  196. .map(() => {
  197. const totalOrderProducts = getRandomNumber(5);
  198.  
  199. const orderItems = products
  200. .slice(0, totalOrderProducts > 1 ? totalOrderProducts : 2)
  201. .map((prod) => ({
  202. productId: prod._id,
  203. quantity: +faker.commerce.price({ dec: 0, min: 1, max: 5 }),
  204. price: prod.price,
  205. }));
  206.  
  207. const orderPrice = orderItems.reduce(
  208. (prev, curr) => prev + curr.price * curr.quantity,
  209. 0
  210. );
  211.  
  212. let coupon = coupons[getRandomNumber(coupons.length + 20)] ?? null;
  213. let discountedOrderPrice = orderPrice;
  214. if (coupon && coupon.minimumCartValue <= orderPrice) {
  215. discountedOrderPrice -= coupon.discountValue;
  216. } else {
  217. coupon = null;
  218. }
  219. return {
  220. orderItems: orderItems.map((prod) => ({
  221. productId: prod.productId,
  222. quantity: prod.quantity,
  223. })),
  224. orderPrice,
  225. discountedOrderPrice,
  226. coupon,
  227. };
  228. });
  229.  
  230. await EcomOrder.deleteMany({});
  231. await EcomOrder.insertMany(
  232. orders.map((order) => {
  233. const customer = customers[getRandomNumber(customers.length)];
  234. const orderInstance = orderPayload[getRandomNumber(orderPayload.length)];
  235. return {
  236. ...order,
  237. customer,
  238. address:
  239. addresses.find(
  240. (add) => add.owner?.toString() === customer?._id.toString()
  241. ) || addresses[getRandomNumber(addresses.length)],
  242. items: orderInstance.orderItems,
  243. coupon: orderInstance.coupon,
  244. orderPrice: orderInstance.orderPrice,
  245. discountedOrderPrice: orderInstance.discountedOrderPrice,
  246. };
  247. })
  248. );
  249. };
  250.  
  251. const seedEcommerce = asyncHandler(async (req, res) => {
  252. const owner = await User.findOne({
  253. role: UserRolesEnum.ADMIN,
  254. });
  255.  
  256. if (!owner) {
  257. throw new ApiError(
  258. 500,
  259. "Something went wrong while seeding the data. Please try again once"
  260. );
  261. }
  262. await seedEcomProfiles();
  263. await seedEcomCategories(owner._id);
  264. await seedEcomAddresses();
  265. await seedEcomCoupons(owner._id);
  266. await seedEcomProducts();
  267. await seedEcomOrders();
  268. return res
  269. .status(201)
  270. .json(
  271. new ApiResponse(201, {}, "Database populated for ecommerce successfully")
  272. );
  273. });
  274.  
  275. export { seedEcommerce };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement