merge sharafat and rahat branch

This commit is contained in:
sharafat
2026-04-30 21:45:27 +06:00
10 changed files with 435 additions and 69 deletions
@@ -0,0 +1,92 @@
import manageResponse from "../../utils/manage_response";
import { Request, Response } from "express";
import catchAsync from "../../utils/catch_async";
import { statictics_service } from "./statictics.service";
const get_seller_stats = catchAsync(async (req: Request, res: Response) => {
const shopAccountId = req.user?.accountId;
if (!shopAccountId) {
return res.status(401).json({
success: false,
message: "Unauthorized",
});
}
const range = (req.query.range as "7d" | "30d" | "all") || "7d";
const result = await statictics_service.get_seller_stats_fromDb(
shopAccountId,
range,
);
manageResponse(res, {
success: true,
statusCode: 200,
message: "All statictics fetched successfully.",
data: result,
meta: {},
});
});
// const get_all_statictics = catchAsync(async (req, res) => {
// const result = await statictics_service.get_all_statictics_from_db(req);
// manageResponse(res, {
// success: true,
// statusCode: 200,
// message: "All statictics fetched successfully.",
// data: result,
// meta: {},
// });
// });
// const get_single_statictics = catchAsync(async (req, res) => {
// const result = await statictics_service.get_single_statictics_from_db(req);
// manageResponse(res, {
// success: true,
// statusCode: 200,
// message: "Single statictics fetched successfully.",
// data: result,
// meta: {},
// });
// });
// const create_statictics = catchAsync(async (req, res) => {
// const result = await statictics_service.create_statictics_into_db(req);
// manageResponse(res, {
// success: true,
// statusCode: 200,
// message: "statictics created successfully.",
// data: result,
// meta: {},
// });
// });
// const update_statictics = catchAsync(async (req, res) => {
// const result = await statictics_service.update_statictics_into_db(req);
// manageResponse(res, {
// success: true,
// statusCode: 200,
// message: "statictics updated successfully.",
// data: result,
// meta: {},
// });
// });
// const delete_statictics = catchAsync(async (req, res) => {
// const result = await statictics_service.delete_statictics_from_db(req);
// manageResponse(res, {
// success: true,
// statusCode: 200,
// message: "statictics deleted successfully.",
// data: result,
// meta: {},
// });
// });
export const statictics_controller = {
get_seller_stats,
// get_all_statictics,
// get_single_statictics,
// create_statictics,
// update_statictics,
// delete_statictics,
};
@@ -0,0 +1,24 @@
import { Router } from "express";
import auth from "../../middlewares/auth.js";
import { statictics_controller } from "./statictics.controller.js";
// import { statictics_controller } from "./statictics.controller";
// import { statictics_validations } from "./statictics.validation";
const router = Router();
router.get("/seller", auth("USER"), statictics_controller.get_seller_stats);
// router.post(
// "/",
// RequestValidator(statictics_validations.create_statictics),
// statictics_controller.create_statictics,
// );
// router.get("/:id", statictics_controller.get_single_statictics);
// router.patch(
// "/:id",
// RequestValidator(statictics_validations.update_statictics),
// statictics_controller.update_statictics,
// );
// router.delete("/:id", statictics_controller.delete_statictics);
export const staticticsRoute = router;
@@ -0,0 +1,151 @@
// import { Request } from "express";
// import { prisma } from "../../lib/prisma";
import { prisma } from "../../lib/prisma";
type Range = "7d" | "30d" | "all";
const get_seller_stats_fromDb = async (shopAccountId: string, range: Range) => {
let createdAtFilter: any = {};
if (range !== "all") {
const days = range === "7d" ? 7 : 30;
const from = new Date();
from.setDate(from.getDate() - days);
createdAtFilter = { gte: from };
}
const baseWhere: any = {
shopAccountId,
...(range !== "all" && { createdAt: createdAtFilter }),
};
const [
totalOrders,
completedOrders,
pendingOrders,
rejectedOrders,
revenueResult,
last7DaysRejected,
ordersForChart,
] = await Promise.all([
prisma.order.count({ where: baseWhere }),
prisma.order.count({
where: { ...baseWhere, status: "DELIVERED" },
}),
prisma.order.count({
where: {
...baseWhere,
status: { in: ["INITIATED", "CONFIRMED", "ONGOING"] },
},
}),
prisma.order.count({
where: { ...baseWhere, status: "CANCELLED" },
}),
prisma.order.aggregate({
where: { ...baseWhere, status: "DELIVERED" },
_sum: { productPrice: true },
}),
prisma.order.count({
where: {
shopAccountId,
status: "CANCELLED",
createdAt: {
gte: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000),
},
},
}),
range !== "all"
? prisma.order.findMany({
where: {
shopAccountId,
status: "DELIVERED",
createdAt: createdAtFilter,
},
select: {
productPrice: true,
createdAt: true,
},
})
: Promise.resolve([]),
]);
const totalRevenue = revenueResult._sum.productPrice || 0;
const avgOrderValue =
completedOrders > 0 ? totalRevenue / completedOrders : 0;
const dailyMap: Record<string, number> = {};
for (const o of ordersForChart) {
const date = o.createdAt.toISOString().split("T")[0];
if (!dailyMap[date]) dailyMap[date] = 0;
dailyMap[date] += o.productPrice;
}
const dailyRevenue = Object.entries(dailyMap).map(([date, revenue]) => ({
date,
revenue,
}));
return {
totalOrders,
completedOrders,
pendingOrders,
rejectedOrders,
totalRevenue,
avgOrderValue,
last7DaysRejected,
dailyRevenue,
};
};
// const get_all_statictics_from_db = async (req: Request) => {
// // define your own login here
// const result = await prisma.statictics.findMany();
// return result;
// };
// const get_single_statictics_from_db = async (req: Request) => {
// // define your own login here
// const { id } = req.params;
// const result = await prisma.statictics.findUnique({where:{id}});
// return result;
// };
// const create_statictics_into_db = async (req: Request) => {
// // define your own login here
// const result = await prisma.statictics.create({data:req.body});
// return result;
// };
// const update_statictics_into_db = async (req: Request) => {
// // define your own login here
// const { id } = req.params;
// const result = await prisma.statictics.update({where:{id},data:req.body});
// return result;
// };
// const delete_statictics_from_db = async (req: Request) => {
// // define your own login here
// const { id } = req.params;
// const result = await prisma.statictics.delete({where:{id}});
// return result;
// };
export const statictics_service = {
get_seller_stats_fromDb,
// get_all_statictics_from_db,
// get_single_statictics_from_db,
// create_statictics_into_db,
// update_statictics_into_db,
// delete_statictics_from_db,
};
@@ -6,7 +6,6 @@ export const staticticsSwaggerDocs = {
summary: "Create new statictics", summary: "Create new statictics",
description: "", description: "",
requestBody: { requestBody: {
required: true, required: true,
content: { content: {
"application/json": { "application/json": {
@@ -71,6 +70,7 @@ export const staticticsSwaggerDocs = {
description: "Unauthorized", description: "Unauthorized",
}, },
}, },
}, },
}, },
@@ -136,3 +136,6 @@ export const staticticsSwaggerDocs = {
}, },
}, },
}; };
@@ -0,0 +1,10 @@
import { z } from "zod";
const create_statictics = z.object({});
const update_statictics = z.object({});
export const statictics_validations = {
create_statictics,
update_statictics,
};
+34 -18
View File
@@ -1,17 +1,14 @@
import { Request, Response } from "express"; import { Request, Response } from "express";
import catchAsync from "../../utils/catch_async.js"; import catchAsync from "../../utils/catch_async.js";
import manageResponse from "../../utils/manage_response.js"; import manageResponse from "../../utils/manage_response.js";
import { support_service } from "./support.service.js"; import { support_service } from "./support.service.js";
const createSupport = catchAsync(async (req: Request, res: Response) => { const createSupport = catchAsync(async (req: Request, res: Response) => {
const id = req?.user?.accountId; const id = req?.user?.accountId;
const data = { const data = {
...req.body, ...req.body,
storeAccountId: id as string storeAccountId: id as string,
} };
const result = await support_service.createSupportIntoDB(data); const result = await support_service.createSupportIntoDB(data);
manageResponse(res, { manageResponse(res, {
@@ -23,31 +20,43 @@ const createSupport = catchAsync(async (req: Request, res: Response) => {
}); });
}); });
const getAllSupport = catchAsync(async (req: Request, res: Response) => { const getAllSupport = catchAsync(async (req: Request, res: Response) => {
const role = req?.user?.role; const role = req?.user?.role;
const id = req?.user?.accountId; const id = req?.user?.accountId;
const search = req?.query?.search; const search = req?.query?.search;
const type = req?.query?.type; const type = req?.query?.type;
const status = req?.query?.status; const status = req?.query?.status;
const page = Number(req?.query?.page) || 1;
const limit = Number(req?.query?.limit) || 10;
const result = await support_service.getAllSupportFromDB(id as string, role as string, search as string, type as string, status as string); const result = await support_service.getAllSupportFromDB(
id as string,
role as string,
search as string,
type as string,
status as string,
page,
limit
);
manageResponse(res, { manageResponse(res, {
success: true, success: true,
statusCode: 200, statusCode: 200,
message: "All support fetched successfully.", message: "All support fetched successfully.",
data: result, data: result.data,
meta: {}, meta: result.meta,
}); });
}); });
const get_single_support = catchAsync(async (req, res) => { const get_single_support = catchAsync(async (req, res) => {
const { id } = req.params; const { id } = req.params;
const userId = req?.user?.accountId; const userId = req?.user?.accountId;
const role = req?.user?.role const role = req?.user?.role;
const result = await support_service.getSingleSupportFromDB(
const result = await support_service.getSingleSupportFromDB(id as string, userId as string, role as string); id as string,
userId as string,
role as string,
);
manageResponse(res, { manageResponse(res, {
success: true, success: true,
statusCode: 200, statusCode: 200,
@@ -57,15 +66,18 @@ const get_single_support = catchAsync(async (req, res) => {
}); });
}); });
const update_support = catchAsync(async (req, res) => { const update_support = catchAsync(async (req, res) => {
const { id } = req.params; const { id } = req.params;
const userId = req?.user?.accountId; const userId = req?.user?.accountId;
const role = req?.user?.role; const role = req?.user?.role;
const data = req.body const data = req.body;
const result = await support_service.updateSupportIntoDB(
const result = await support_service.updateSupportIntoDB(id as string, userId as string, role as string, data); id as string,
userId as string,
role as string,
data,
);
manageResponse(res, { manageResponse(res, {
success: true, success: true,
statusCode: 200, statusCode: 200,
@@ -78,9 +90,13 @@ const update_support = catchAsync(async (req, res) => {
const delete_support = catchAsync(async (req, res) => { const delete_support = catchAsync(async (req, res) => {
const { id } = req.params; const { id } = req.params;
const userId = req?.user?.accountId; const userId = req?.user?.accountId;
const role = req?.user?.role const role = req?.user?.role;
const result = await support_service.deleteSupportFromDB(id as string, userId as string, role as string); const result = await support_service.deleteSupportFromDB(
id as string,
userId as string,
role as string,
);
manageResponse(res, { manageResponse(res, {
success: true, success: true,
statusCode: 200, statusCode: 200,
+24 -5
View File
@@ -13,6 +13,8 @@ const getAllSupportFromDB = async (
search?: string, search?: string,
type?: string, type?: string,
status?: string, status?: string,
page: number = 1,
limit: number = 10,
) => { ) => {
const andCondition: Prisma.SupportWhereInput[] = []; const andCondition: Prisma.SupportWhereInput[] = [];
@@ -55,14 +57,31 @@ const getAllSupportFromDB = async (
const whereCondition: Prisma.SupportWhereInput = const whereCondition: Prisma.SupportWhereInput =
andCondition.length > 0 ? { AND: andCondition } : {}; andCondition.length > 0 ? { AND: andCondition } : {};
const result = await prisma.support.findMany({ const skip = (page - 1) * limit;
const [data, total] = await Promise.all([
prisma.support.findMany({
where: whereCondition, where: whereCondition,
skip,
take: limit,
orderBy: { orderBy: {
createdAt: "desc", createdAt: "desc",
}, },
}); }),
prisma.support.count({
where: whereCondition,
}),
]);
return result; return {
meta: {
page,
limit,
total,
totalPage: Math.ceil(total / limit),
},
data,
};
}; };
const getSingleSupportFromDB = async ( const getSingleSupportFromDB = async (
@@ -125,8 +144,8 @@ const deleteSupportFromDB = async (
} }
const result = await prisma.support.delete({ const result = await prisma.support.delete({
where: {id} where: { id },
}) });
return result; return result;
}; };
+57 -10
View File
@@ -1,18 +1,18 @@
export const supportSwaggerDocs = { export const supportSwaggerDocs = {
"/api/support": { "/api/support": {
post: { post: {
tags: ["support"], tags: ["support"],
summary: "Create new support", summary: "Create new support",
description: "", description:
"type must be: TECHNICAL | BILLING | DOMAIN | TEMPLATE | PAYMENT | ACCOUNT | FEATURE_REQUEST | BUG | OTHER",
requestBody: { requestBody: {
required: true, required: true,
content: { content: {
"application/json": { "application/json": {
example: JSON.stringify({ example: JSON.stringify({
"issueName": "Your issue name", issueName: "Your issue name",
"description": "Issue description", description: "Issue description",
"type": "Issue Type" type: "Issue Type",
}), // put your request body }), // put your request body
}, },
}, },
@@ -39,6 +39,45 @@
required: false, required: false,
schema: { type: "number" }, schema: { type: "number" },
}, },
{
name: "search",
in: "query",
required: false,
description: "Search by issue name or description",
schema: {
type: "string",
},
},
{
name: "type",
in: "query",
required: false,
description: "Filter by support type",
schema: {
type: "string",
enum: [
"TECHNICAL",
"BILLING",
"DOMAIN",
"TEMPLATE",
"PAYMENT",
"ACCOUNT",
"FEATURE_REQUEST",
"BUG",
"OTHER",
],
},
},
{
name: "status",
in: "query",
required: false,
description: "Filter by support status",
schema: {
type: "string",
enum: ["OPEN", "IN_PROGRESS", "RESOLVED", "REJECTED"],
},
},
], ],
responses: { responses: {
200: { description: "support fetched successfully" }, 200: { description: "support fetched successfully" },
@@ -68,7 +107,11 @@
patch: { patch: {
tags: ["support"], tags: ["support"],
summary: "Update support", summary: "Update support",
description: "", description: `type(enum): TECHNICAL | BILLING | DOMAIN | TEMPLATE | PAYMENT | ACCOUNT | FEATURE_REQUEST | BUG | OTHER \n
status(enum): OPEN
| IN_PROGRESS
| RESOLVED
| REJECTED`,
parameters: [ parameters: [
{ {
name: "id", name: "id",
@@ -81,7 +124,14 @@
required: true, required: true,
content: { content: {
"application/json": { "application/json": {
example: JSON.stringify({}), // put your request body example: JSON.stringify({
issueName: "Your issue name",
description: "Issue description",
type: "Issue Type",
status: "issue current status",
resolvedBy: "dataTime()",
resolvedAt: "dateTime()",
}), // put your request body
}, },
}, },
}, },
@@ -109,6 +159,3 @@
}, },
}, },
}; };
+3 -1
View File
@@ -4,12 +4,14 @@ import orderRoute from "./app/modules/order/order.route.js";
import planRoute from "./app/modules/plan/plan.route.js"; import planRoute from "./app/modules/plan/plan.route.js";
import profileRoute from "./app/modules/profile/profile.route.js"; import profileRoute from "./app/modules/profile/profile.route.js";
import supportRoute from "./app/modules/support/support.route.js"; import supportRoute from "./app/modules/support/support.route.js";
import templateRoute from "./app/modules/template/template.route"; import templateRoute from "./app/modules/template/template.route.js";
import { staticticsRoute } from "./app/modules/statictics/statictics.route.js";
const appRouter = Router(); const appRouter = Router();
const moduleRoutes = [ const moduleRoutes = [
{ path: "/template", route: templateRoute }, { path: "/template", route: templateRoute },
{ path: "/statictics", route: staticticsRoute },
{ path: "/order", route: orderRoute }, { path: "/order", route: orderRoute },
{ path: "/support", route: supportRoute }, { path: "/support", route: supportRoute },
{ path: "/plan", route: planRoute }, { path: "/plan", route: planRoute },
+3 -1
View File
@@ -6,7 +6,8 @@ import { orderSwaggerDocs } from "./app/modules/order/order.swagger.js";
import { planSwaggerDocs } from "./app/modules/plan/plan.swagger.js"; import { planSwaggerDocs } from "./app/modules/plan/plan.swagger.js";
import { profileSwaggerDocs } from "./app/modules/profile/profile.swagger.js"; import { profileSwaggerDocs } from "./app/modules/profile/profile.swagger.js";
import { supportSwaggerDocs } from "./app/modules/support/support.swagger.js"; import { supportSwaggerDocs } from "./app/modules/support/support.swagger.js";
import { templateSwaggerDocs } from "./app/modules/template/template.swagger"; import { templateSwaggerDocs } from "./app/modules/template/template.swagger.js";
import { staticticsSwaggerDocs } from "./app/modules/statictics/statictics.swagger.js";
const __filename = fileURLToPath(import.meta.url); const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename); const __dirname = path.dirname(__filename);
@@ -26,6 +27,7 @@ export const swaggerOptions = {
...profileSwaggerDocs, ...profileSwaggerDocs,
...supportSwaggerDocs, ...supportSwaggerDocs,
...templateSwaggerDocs, ...templateSwaggerDocs,
...staticticsSwaggerDocs,
}, },
servers: servers:
configs.env === "production" configs.env === "production"