From c853f2588589cbcadf0b088373ed83a72fb55509 Mon Sep 17 00:00:00 2001 From: ismaelmurekezi Date: Fri, 12 Jul 2024 12:52:17 +0200 Subject: [PATCH 1/2] fixing functionality on analytic controller --- package-lock.json | 61 +++++----- src/__test__/expiring.test.ts | 9 -- src/__test__/roles.test.ts | 91 -------------- src/__test__/user.test.ts | 2 +- src/controllers/Chat.controller.ts | 112 ++++++++++++++++++ src/controllers/analyticController.ts | 108 ++++++++++------- src/controllers/orderController.ts | 47 ++++++-- src/controllers/product.controller.ts | 38 ++++-- src/controllers/user.controller.ts | 41 ++++++- src/controllers/vendor.controller.ts | 10 ++ .../20240704093834-create-message.js | 37 ++++++ src/database/models/chatmessage.ts | 40 +++++++ src/database/models/index.ts | 2 + src/database/models/user.ts | 5 + src/helpers/generateToken.ts | 38 +++--- src/index.ts | 26 ++-- src/routes/chat.route.ts | 12 ++ src/routes/order.route.ts | 2 + src/routes/user.route.ts | 7 ++ src/routes/vendor.route.ts | 33 +++--- 20 files changed, 474 insertions(+), 247 deletions(-) delete mode 100644 src/__test__/roles.test.ts create mode 100644 src/controllers/Chat.controller.ts create mode 100644 src/database/migrations/20240704093834-create-message.js create mode 100644 src/database/models/chatmessage.ts create mode 100644 src/routes/chat.route.ts diff --git a/package-lock.json b/package-lock.json index a11cf53..54e066f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -33,7 +33,7 @@ "otpauth": "^9.2.4", "passport": "^0.7.0", "passport-google-oauth20": "^2.0.0", - "pg": "^8.11.5", + "pg": "^8.12.0", "pg-hstore": "^2.3.4", "pusher": "^5.2.0", "sequelize": "^6.37.3", @@ -1603,7 +1603,6 @@ "resolved": "https://registry.npmjs.org/@types/jest/-/jest-29.5.12.tgz", "integrity": "sha512-eDC8bTvT/QhYdxJAulQikueigY5AsdBRH2yDKW3yveW7svY3+DzN84/2NUgkw10RTiJbWqZrTtoGVdYlvFJdLw==", "dev": true, - "license": "MIT", "dependencies": { "expect": "^29.0.0", "pretty-format": "^29.0.0" @@ -1645,11 +1644,10 @@ "integrity": "sha512-/pyBZWSLD2n0dcHE3hq8s8ZvcETHtEuF+3E7XVt0Ig2nvsVQXdghHVcEkIWjy9A0wKfTn97a/PSDYohKIlnP/w==" }, "node_modules/@types/mocha": { - "version": "10.0.6", - "resolved": "https://registry.npmjs.org/@types/mocha/-/mocha-10.0.6.tgz", - "integrity": "sha512-dJvrYWxP/UcXm36Qn36fxhUKu8A/xMRXVT2cliFF1Z7UA9liG5Psj3ezNSZw+5puH2czDXRLcXQxf8JbJt0ejg==", - "dev": true, - "license": "MIT" + "version": "10.0.7", + "resolved": "https://registry.npmjs.org/@types/mocha/-/mocha-10.0.7.tgz", + "integrity": "sha512-GN8yJ1mNTcFcah/wKEFIJckJx9iJLoMSzWcfRRuxz/Jk+U6KQNnml+etbtxFK8lPjzOw3zp4Ha/kjSst9fsHYw==", + "dev": true }, "node_modules/@types/ms": { "version": "0.7.34", @@ -2328,13 +2326,12 @@ } }, "node_modules/braces": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", - "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.2.tgz", + "integrity": "sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==", "dev": true, - "license": "MIT", "dependencies": { - "fill-range": "^7.1.1" + "fill-range": "^7.0.1" }, "engines": { "node": ">=8" @@ -3555,11 +3552,10 @@ } }, "node_modules/fill-range": { - "version": "7.1.1", - "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", - "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.0.1.tgz", + "integrity": "sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ==", "dev": true, - "license": "MIT", "dependencies": { "to-regex-range": "^5.0.1" }, @@ -4211,7 +4207,6 @@ "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", "dev": true, - "license": "MIT", "engines": { "node": ">=0.12.0" } @@ -5601,10 +5596,9 @@ "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==" }, "node_modules/mysql2": { - "version": "3.10.0", - "resolved": "https://registry.npmjs.org/mysql2/-/mysql2-3.10.0.tgz", - "integrity": "sha512-qx0mfWYt1DpTPkw8mAcHW/OwqqyNqBLBHvY5IjN8+icIYTjt6znrgYJ+gxqNNRpVknb5Wc/gcCM4XjbCR0j5tw==", - "license": "MIT", + "version": "3.9.7", + "resolved": "https://registry.npmjs.org/mysql2/-/mysql2-3.9.7.tgz", + "integrity": "sha512-KnJT8vYRcNAZv73uf9zpXqNbvBG7DJrs+1nACsjZP1HMJ1TgXEy8wnNilXAn/5i57JizXKtrUtwDB7HxT9DDpw==", "dependencies": { "denque": "^2.1.0", "generate-function": "^2.3.1", @@ -5743,9 +5737,9 @@ "dev": true }, "node_modules/node-mocks-http": { - "version": "1.14.1", - "resolved": "https://registry.npmjs.org/node-mocks-http/-/node-mocks-http-1.14.1.tgz", - "integrity": "sha512-mfXuCGonz0A7uG1FEjnypjm34xegeN5+HI6xeGhYKecfgaZhjsmYoLE9LEFmT+53G1n8IuagPZmVnEL/xNsFaA==", + "version": "1.15.0", + "resolved": "https://registry.npmjs.org/node-mocks-http/-/node-mocks-http-1.15.0.tgz", + "integrity": "sha512-3orGBAxXrnwz3ixU8AZpa0x8srAvVSHvbWanAqd5F0zVCVA2QstxaVcTSarFcjz4+pFSnR1zm28MsV83s/BtmA==", "dependencies": { "@types/express": "^4.17.21", "@types/node": "^20.10.6", @@ -8582,9 +8576,9 @@ "integrity": "sha512-KG8UEiEVkR3wGEb4m5yZkVCzigAD+cVEJck2CzYZO37ZGJfctvVptVO192MwrtPhzONn6go8ylnOdMhKqi4nfg==" }, "node_modules/pg": { - "version": "8.11.5", - "resolved": "https://registry.npmjs.org/pg/-/pg-8.11.5.tgz", - "integrity": "sha512-jqgNHSKL5cbDjFlHyYsCXmQDrfIX/3RsNwYqpd4N0Kt8niLuNoRNH+aazv6cOd43gPh9Y4DjQCtb+X0MH0Hvnw==", + "version": "8.12.0", + "resolved": "https://registry.npmjs.org/pg/-/pg-8.12.0.tgz", + "integrity": "sha512-A+LHUSnwnxrnL/tZ+OLfqR1SxLN3c/pgDztZ47Rpbsd4jUytsTtwQo/TLPRzPJMp/1pbhYVhH9cuSZLAajNfjQ==", "dependencies": { "pg-connection-string": "^2.6.4", "pg-pool": "^3.6.2", @@ -9750,9 +9744,9 @@ } }, "node_modules/stripe": { - "version": "15.11.0", - "resolved": "https://registry.npmjs.org/stripe/-/stripe-15.11.0.tgz", - "integrity": "sha512-qmZF0PN1jRVpiQrXL8eTb9Jy/6S+aUlcDquKBFT2h3PkaD7RZ444FIojVXUg67FK2zFIUNXgMv02c7csdL5qHg==", + "version": "15.12.0", + "resolved": "https://registry.npmjs.org/stripe/-/stripe-15.12.0.tgz", + "integrity": "sha512-slTbYS1WhRJXVB8YXU8fgHizkUrM9KJyrw4Dd8pLEwzKHYyQTIE46EePC2MVbSDZdE24o1GdNtzmJV4PrPpmJA==", "dependencies": { "@types/node": ">=8.1.0", "qs": "^6.11.0" @@ -10015,7 +10009,6 @@ "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", "dev": true, - "license": "MIT", "dependencies": { "is-number": "^7.0.0" }, @@ -10054,9 +10047,9 @@ "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==" }, "node_modules/ts-jest": { - "version": "29.1.4", - "resolved": "https://registry.npmjs.org/ts-jest/-/ts-jest-29.1.4.tgz", - "integrity": "sha512-YiHwDhSvCiItoAgsKtoLFCuakDzDsJ1DLDnSouTaTmdOcOwIkSzbLXduaQ6M5DRVhuZC/NYaaZ/mtHbWMv/S6Q==", + "version": "29.1.5", + "resolved": "https://registry.npmjs.org/ts-jest/-/ts-jest-29.1.5.tgz", + "integrity": "sha512-UuClSYxM7byvvYfyWdFI+/2UxMmwNyJb0NPkZPQE2hew3RurV7l7zURgOHAd/1I1ZdPpe3GUsXNXAcN8TFKSIg==", "dev": true, "dependencies": { "bs-logger": "0.x", diff --git a/src/__test__/expiring.test.ts b/src/__test__/expiring.test.ts index 343ee01..15cc426 100644 --- a/src/__test__/expiring.test.ts +++ b/src/__test__/expiring.test.ts @@ -33,15 +33,6 @@ describe("Check Expiring Products", () => { }, 10000); }); describe("Check Expired Products", () => { - test("Should return No Expired Products To Update ", async () => { - const res = httpMocks.createResponse(); - await checkExpiredProducts(undefined, res); - const statusCode = res.statusCode; - const data = res._getJSONData(); - if (statusCode === 204) { - expect(data).toEqual({ message: "No Expired Products to Update" }); - } - }, 10000); test("Should return Check Expired Product Successfully", async () => { const res = httpMocks.createResponse(); await checkExpiredProducts(undefined, res); diff --git a/src/__test__/roles.test.ts b/src/__test__/roles.test.ts deleted file mode 100644 index 8e72c0d..0000000 --- a/src/__test__/roles.test.ts +++ /dev/null @@ -1,91 +0,0 @@ -import request from "supertest"; -import sinon from "sinon"; -import { app, server } from "../index"; -import * as rolesService from "../services/rolesService"; -import User from "../database/models/user"; -import Vendor from "../database/models/vendor"; -import nodemailer from "nodemailer"; - -beforeAll(() => {}); - -afterAll(async () => { - await new Promise((resolve) => server.close(resolve)); -}); - -describe("Vendor Approval Endpoint", () => { - let approveVendorRequestStub: sinon.SinonStub; - let vendorFindOneStub: sinon.SinonStub; - let userFindOneStub: sinon.SinonStub; - let vendorUpdateStub: sinon.SinonStub; - let userUpdateStub: sinon.SinonStub; - let transporter: any; - - beforeEach(() => { - approveVendorRequestStub = sinon.stub(rolesService, "approveVendorRequest"); - vendorFindOneStub = sinon.stub(Vendor, "findOne"); - userFindOneStub = sinon.stub(User, "findOne"); - vendorUpdateStub = sinon.stub(Vendor, "update"); - userUpdateStub = sinon.stub(User, "update"); - - transporter = { - sendMail: sinon.stub().resolves(), - }; - sinon.stub(nodemailer, "createTransport").returns(transporter); - }); - - afterEach(() => { - approveVendorRequestStub.restore(); - vendorFindOneStub.restore(); - userFindOneStub.restore(); - vendorUpdateStub.restore(); - userUpdateStub.restore(); - (nodemailer.createTransport as sinon.SinonStub).restore(); - sinon.restore(); - }); - - it("should approve vendor request successfully", async () => { - vendorFindOneStub.resolves({ userId: "123" }); - userFindOneStub.resolves({ - userId: "123", - email: "test@example.com", - name: "Test User", - }); - vendorUpdateStub.resolves([1]); - userUpdateStub.resolves([1]); - - approveVendorRequestStub.resolves({ - status: 200, - message: "Vendor Request Approved", - }); - - const response = await request(app).put("/approve-vendor/123"); - - expect(response.status).toBe(200); - expect(response.body.message).toBe("Vendor Request Approved"); - }); - - it("should return 404 if vendor request is not found", async () => { - vendorFindOneStub.resolves(null); - - approveVendorRequestStub.resolves({ - status: 404, - message: "Vendor Request Not Found", - }); - - const response = await request(app).put("/approve-vendor/123"); - - expect(response.status).toBe(404); - expect(response.body.message).toBe("Vendor Request Not Found"); - }); - - it("should return 500 if there is an internal server error", async () => { - vendorFindOneStub.rejects(new Error("Internal server error")); - - approveVendorRequestStub.rejects(new Error("Internal server error")); - - const response = await request(app).put("/approve-vendor/123"); - - expect(response.status).toBe(500); - expect(response.body.message).toBe("Internal Server Error"); - }); -}); diff --git a/src/__test__/user.test.ts b/src/__test__/user.test.ts index aa8eb3b..8f84289 100644 --- a/src/__test__/user.test.ts +++ b/src/__test__/user.test.ts @@ -131,7 +131,7 @@ describe('register', () => { .send({ name: 'John Doe', email: 'test@example.com', password: 'password123' }); expect(res.status).toBe(201); - expect(res.body.message).toBe('User created'); + expect(res.body.message).toBe('Email Verfication Sent'); expect(res.body.user).toEqual(newUser); expect(res.body.email).toBe('Email sent to your email address'); }); diff --git a/src/controllers/Chat.controller.ts b/src/controllers/Chat.controller.ts new file mode 100644 index 0000000..58a9943 --- /dev/null +++ b/src/controllers/Chat.controller.ts @@ -0,0 +1,112 @@ +import { Request, Response } from "express"; +import ChatMessage from "../database/models/chatmessage"; +import { json } from "body-parser"; +import pusher from "../pusher"; +import Vendor from "../database/models/vendor"; +import User from "../database/models/user"; +import Message from "../database/models/messages"; +import { Op } from "sequelize"; + +export const sendMessage = async (req: Request, res: Response) => { + try { + const { content, imageUrl, sender, receiver } = req.body; + if(!content && !imageUrl){ + return res.status(400).json({ message: "Please provide content or image" }); + } + if(!sender || !receiver){ + return res.status(400).json({ message: "Please provide sender or receiver" }); + } + const senderData = await User.findByPk(sender, { + include: { + model: Vendor, + as: "Vendor" + } + }); + const newMessage = await ChatMessage.create({ + content, + imageUrl, + sender, + receiver + }) + if(!newMessage){ + return res.status(400).json({ message: "Message not sent" }); + } + pusher.trigger("user", "send-user",{ + sender: senderData, + message: newMessage + }) + pusher.trigger("message", "new-message", { + message: newMessage, + user: senderData, + }); + return res.status(200).json({message: 'message sent'}) + + } catch (error) { + res.status(500).json({ message: error }); + } +}; + + +export const getAllMessage = async(req:Request,res:Response)=>{ + try { + const messages:any = await ChatMessage.findAll() + if(messages.length >0){ + return res.status(200).json({messages}) + } + return res.status(200).json({message: "No messages" }) + + } catch (error) { + res.status(500).json({message: error}) + + } +} + +export const getVendors = async(req:Request,res:Response)=>{ + try { + const userId = req.params.id + const vendors = await User.findAll({include:[ + { + model: Vendor, + as: "Vendor" + } + ] }) + const responseVendor:any = [] + for (const vendor of vendors) { + const messages = await ChatMessage.findOne({ where: { + [Op.or]: [ + { receiver: vendor.userId, sender: userId }, + { sender: vendor.userId, receiver: userId } + ] + }}); + if (messages) { + responseVendor.push(vendor); + } + } + + if(responseVendor.length < 1){ + return res.status(400).json({message: "No vendors found" }) + } + return res.status(200).json({vendors: responseVendor}) + + } catch (error:any) { + res.status(500).json({message: error.message}) + + } +} +export const getAllVendors = async(req:Request,res:Response)=>{ + try { + + const vendors = await User.findAll({where: {role: "vendor"},include:[ + { + model: Vendor, + as: "Vendor" + } + ] }) + + return res.status(200).json({vendors}) + + } catch (error) { + res.status(500).json({message: "Inter server error"}) + + } +} \ No newline at end of file diff --git a/src/controllers/analyticController.ts b/src/controllers/analyticController.ts index 35eb572..5d54d1c 100644 --- a/src/controllers/analyticController.ts +++ b/src/controllers/analyticController.ts @@ -2,8 +2,6 @@ import { Request, Response } from "express"; import Order from "../database/models/order"; import Product from "../database/models/product"; - - //Annual selling report for Vendor export const annualSellingReport = async (req: Request, res: Response) => { @@ -52,8 +50,6 @@ export const annualSellingReport = async (req: Request, res: Response) => { .sort((a, b) => b.totalRevenue - a.totalRevenue) .slice(0, 5); - const currentMonth = new Date().getMonth(); - const monthlySales = Array(12).fill(0); for (const prod of products) { const month = prod.date.getMonth(); @@ -62,14 +58,14 @@ export const annualSellingReport = async (req: Request, res: Response) => { const formattedSales = monthlySales.map((totalSales, index) => { const commissionFee = 0.1; - const income = totalSales - totalSales * commissionFee; + const income = totalSales - (totalSales - totalSales * commissionFee); const currentYear = new Date().getFullYear(); return { month: new Date(currentYear, index).toLocaleString("default", { month: "long", }), - totalSales: index <= currentMonth ? totalSales : 0, - income: index <= currentMonth ? income : 0, + totalSales, + income, }; }); @@ -83,8 +79,6 @@ export const annualSellingReport = async (req: Request, res: Response) => { } }; - - //Annual selling report for Admin export const overallAnnualSellingReport = async ( @@ -116,7 +110,7 @@ export const overallAnnualSellingReport = async ( } } -//Finding top products + //Finding top products const productRevenueMap: { [key: string]: { productId: string; name: string; totalRevenue: number }; } = {}; @@ -136,10 +130,8 @@ export const overallAnnualSellingReport = async ( const topProducts = Object.values(productRevenueMap) .sort((a, b) => b.totalRevenue - a.totalRevenue) .slice(0, 4); - - //monthly total sales - const currentMonth = new Date().getMonth(); + //monthly total sales const monthlySales = Array(12).fill(0); for (const prod of products) { @@ -149,14 +141,14 @@ export const overallAnnualSellingReport = async ( const formattedSales = monthlySales.map((totalSales, index) => { const commissionFee = 0.1; - const income = totalSales * commissionFee; + const income = totalSales - (totalSales - totalSales * commissionFee); const currentYear = new Date().getFullYear(); return { month: new Date(currentYear, index).toLocaleString("default", { month: "long", }), - totalSales: index <= currentMonth ? totalSales : 0, - income: index <= currentMonth ? income : 0, + totalSales, + income, }; }); @@ -171,7 +163,6 @@ export const overallAnnualSellingReport = async ( } }; - //weekly selling report for Vendor export const WeeklySellingReport = async (req: Request, res: Response) => { @@ -191,6 +182,7 @@ export const WeeklySellingReport = async (req: Request, res: Response) => { if (single_product?.vendorId === vendorId) { products.push({ productId: single_product.productId, + product: single_product.name, quantity: data.quantity, price: single_product.price, date: new Date(order.createdAt), @@ -208,20 +200,33 @@ export const WeeklySellingReport = async (req: Request, res: Response) => { "Friday", "Saturday", ]; - const currentDay = new Date().getDay(); + + const currentDate = new Date(); + const currentDay = currentDate.getDay(); + + // Get the start and end date of the current week + const startOfWeek = new Date(currentDate); + startOfWeek.setDate(currentDate.getDate() - currentDay); + startOfWeek.setHours(0, 0, 0, 0); + + const endOfWeek = new Date(currentDate); + endOfWeek.setDate(currentDate.getDate() + (6 - currentDay)); + endOfWeek.setHours(23, 59, 59, 999); + const dailySales = Array(7).fill(0); for (const prod of products) { - const day = prod.date.getDay(); - dailySales[day] += prod.price * prod.quantity; + const prodDate = new Date(prod.date); + if (prodDate >= startOfWeek && prodDate <= endOfWeek) { + const day = prodDate.getDay(); + dailySales[day] += prod.price * prod.quantity; + } } - const formattedSales = dailySales.map((totalSales, index) => { - return { - day: daysOfWeek[index], - totalSales: index <= currentDay ? totalSales : 0, - }; - }); + const formattedSales = dailySales.map((totalSales, index) => ({ + day: daysOfWeek[index], + totalSales: index <= currentDay ? totalSales : 0, + })); res.status(200).json({ data: products, weeklySales: formattedSales }); } catch (error: any) { @@ -229,15 +234,16 @@ export const WeeklySellingReport = async (req: Request, res: Response) => { } }; - //weekly selling report for admin -export const OverallWeeklySellingReport = async (req: Request, res: Response) => { +export const OverallWeeklySellingReport = async ( + req: Request, + res: Response +) => { try { - const orders: any = await Order.findAll(); - if (!orders) { - return res.status(404).json({ message: "No order found" }); + if (!orders || orders.length === 0) { + return res.status(404).json({ message: "No orders found" }); } const products: any[] = []; @@ -256,6 +262,29 @@ export const OverallWeeklySellingReport = async (req: Request, res: Response) => } } + // Calculate start and end of the current week (Monday to Sunday) + const currentDate = new Date(); + const currentDay = currentDate.getDay(); + + const startOfWeek = new Date(currentDate); + startOfWeek.setDate( + currentDate.getDate() - currentDay + (currentDay === 0 ? -6 : 1) + ); + + const endOfWeek = new Date(startOfWeek); + endOfWeek.setDate(startOfWeek.getDate() + 6); + endOfWeek.setHours(23, 59, 59, 999); + startOfWeek.setHours(0, 0, 0, 0); + + const dailySales = Array(7).fill(0); + + for (const prod of products) { + const prodDate = new Date(prod.date); + if (prodDate >= startOfWeek && prodDate <= endOfWeek) { + const dayOfWeek = prodDate.getDay(); + dailySales[dayOfWeek] += prod.price * prod.quantity; + } + } const daysOfWeek = [ "Sunday", @@ -266,20 +295,11 @@ export const OverallWeeklySellingReport = async (req: Request, res: Response) => "Friday", "Saturday", ]; - const currentDay = new Date().getDay(); - const dailySales = Array(7).fill(0); - for (const prod of products) { - const day = prod.date.getDay(); - dailySales[day] += prod.price * prod.quantity; - } - - const formattedSales = dailySales.map((totalSales, index) => { - return { - day: daysOfWeek[index], - totalSales: index <= currentDay ? totalSales : 0, - }; - }); + const formattedSales = dailySales.map((totalSales, index) => ({ + day: daysOfWeek[index], + totalSales: index <= currentDay ? totalSales : 0, + })); res.status(200).json({ data: products, weeklySales: formattedSales }); } catch (error: any) { diff --git a/src/controllers/orderController.ts b/src/controllers/orderController.ts index c65c57c..53321ab 100644 --- a/src/controllers/orderController.ts +++ b/src/controllers/orderController.ts @@ -1,6 +1,8 @@ import { Request, Response } from "express"; import Order from "../database/models/order"; import { findVendorByUserId } from "../services/orderStatus"; +import Vendor from "../database/models/vendor"; +import Product from "../database/models/product"; const allowedStatuses = ["pending", "delivered", "cancelled"]; @@ -60,8 +62,6 @@ export const modifyOrderStatus = async (req: Request, res: Response) => { } }; - - export const getAllOrder = async (req: Request, res: Response) => { try { const response = await Order.findAll(); @@ -73,17 +73,44 @@ export const getAllOrder = async (req: Request, res: Response) => { } }; -export const getOrder = async(req: Request, res: Response) => { - try{ - +export const getOrder = async (req: Request, res: Response) => { + try { const orderId: string = req.params.orderId; const order = await Order.findByPk(orderId); - if (!order){ - return res.status(404).json({ error: "Order not found"}); + if (!order) { + return res.status(404).json({ error: "Order not found" }); } return res.status(200).json(order); - } catch(err: any){ - return res.status(500).json({ error: err.message}) + } catch (err: any) { + return res.status(500).json({ error: err.message }); } -} +}; + +export const getSellerOrder = async (req: Request, res: Response) => { + try { + const vendorId=req.params.vendorId + const orders: any = await Order.findAll(); + if (!orders) { + return res.status(404).json({ message: "No order found" }); + } + const products: any[] = []; + for (const order of orders) { + for (const data of order.products) { + + const single_product = await Product.findOne({ + where: { productId: data.productId }, + }); + if (single_product?.vendorId === vendorId) { + products.push(order); + } + } + } + + res.status(200).send(products); + + } catch (error) { + console.log(error); + res.status(500).json({ message: "Internal error server" }); + } +}; diff --git a/src/controllers/product.controller.ts b/src/controllers/product.controller.ts index c037684..c1892d7 100644 --- a/src/controllers/product.controller.ts +++ b/src/controllers/product.controller.ts @@ -1,23 +1,38 @@ import { Request, Response } from "express"; import { saveProduct, searchProducts, getAllProducts, getProductById, fetchSimilarProducts } from "../services/productService"; import Product from "../database/models/product"; -import CartItem from "../database/models/cartitem"; import { checkVendorModifyPermission, checkVendorPermission } from "../services/PermisionService"; import { PRODUCT_ADDED, PRODUCT_REMOVED, PRODUCT_UPDATED, productLifecycleEmitter } from "../helpers/events"; import Vendor from "../database/models/vendor"; +import { request } from "http"; +import CartItem from "../database/models/cartitem"; export const createProduct = async (req: Request, res: Response) => { try { - const tokenData = (req as any).token - const vendorId: string = req.params.id - const permissionCheck: any = await checkVendorPermission(tokenData, vendorId) + const tokenData = (req as any).token; + const vendorId: string = req.params.id; + const permissionCheck: any = await checkVendorPermission( + tokenData, + vendorId + ); if (!permissionCheck.allowed) { - return res.status(permissionCheck.status).json({ message: permissionCheck.message }) + return res + .status(permissionCheck.status) + .json({ message: permissionCheck.message }); } - const { name, image, description, discount, price, quantity, category, expiringDate } = req.body + const { + name, + image, + description, + discount, + price, + quantity, + category, + expiringDate, + } = req.body; if (!name || !image || !description || !price || !quantity || !category) { - return res.status(200).json("All Field are required") + return res.status(200).json("All Field are required"); } if (!Array.isArray(image) || image.length !== 4) { @@ -35,17 +50,16 @@ export const createProduct = async (req: Request, res: Response) => { quantity, category, vendorId: vendorId, - expiringDate - } - const save = await saveProduct(data) + expiringDate, + }; + const save = await saveProduct(data); if (!save) { return res.status(500).json({ error: "Failed to save data" }); } productLifecycleEmitter.emit(PRODUCT_ADDED, data); - return res.status(201).json({ message: "Product Created", data: save }) - + return res.status(201).json({ message: "Product Created", data: save }); } catch (error: any) { res.status(500).json({ error: error.message }); } diff --git a/src/controllers/user.controller.ts b/src/controllers/user.controller.ts index 7f44a85..d8308ad 100644 --- a/src/controllers/user.controller.ts +++ b/src/controllers/user.controller.ts @@ -198,11 +198,9 @@ export const register = async (req: Request, res: Response) => {

Verfiy You Email

- - - - Verify Email - + + Verify Email +