Skip to content

The complete open source platform to run your entire marketplace. Storefront, vendor panel, admin console, and integrations in one enterprise-grade platform you own.

feat(seller,offer): add getStatistics and admin statistics routes (#1659)

Viktor Holika7b13faa66a7
diff --git a/integration-tests/http/offer/admin/offer-statistics.spec.ts b/integration-tests/http/offer/admin/offer-statistics.spec.ts
new file mode 100644
index 000000000..442fe90fb
--- /dev/null
+++ b/integration-tests/http/offer/admin/offer-statistics.spec.ts
@@ -0,0 +1,186 @@
+import { medusaIntegrationTestRunner } from "@medusajs/test-utils"
+import { MedusaContainer } from "@medusajs/framework/types"
+import { IOfferModuleService, MercurModules } from "@mercurjs/types"
+
+import {
+ adminHeaders,
+ createAdminUser,
+} from "../../../helpers/create-admin-user"
+import { createSellerUser } from "../../../helpers/create-seller-user"
+import { createShippingProfile } from "../../../helpers/create-shipping-profile"
+import { createVendorProduct } from "../../../helpers/create-product"
+
+jest.setTimeout(90000)
+
+type OfferServiceUnderTest = IOfferModuleService & {
+ softDeleteOffers(ids: string[]): Promise<unknown>
+}
+
+medusaIntegrationTestRunner({
+ testSuite: ({ getContainer, api, dbConnection }) => {
+ describe("GET /admin/offers/statistics", () => {
+ let container: MedusaContainer
+ let offerService: OfferServiceUnderTest
+ let seller1: any
+ let seller1Headers: any
+ let seller2: any
+ let seller2Headers: any
+ let offerIds: string[]
+
+ const createOffer = async (
+ headers: any,
+ sku: string,
+ variantId: string,
+ shippingProfileId: string
+ ) => {
+ const response = await api.post(
+ "/vendor/offers",
+ {
+ sku,
+ variant_id: variantId,
+ shipping_profile_id: shippingProfileId,
+ inventory_items: [{}],
+ prices: [{ amount: 1000, currency_code: "usd" }],
+ },
+ headers
+ )
+ expect(response.status).toEqual(201)
+ return response.data.offer.id as string
+ }
+
+ const getStatistics = async (query = "") => {
+ const response = await api.get(
+ `/admin/offers/statistics${query}`,
+ adminHeaders
+ )
+ expect(response.status).toEqual(200)
+ return response.data.statistics
+ }
+
+ beforeAll(() => {
+ container = getContainer()
+ offerService = container.resolve(MercurModules.OFFER)
+ })
+
+ beforeEach(async () => {
+ await createAdminUser(dbConnection, adminHeaders, container)
+
+ const r1 = await createSellerUser(container, {
+ email: "[email protected]",
+ name: "Stats Seller One",
+ })
+ seller1 = r1.seller
+ seller1Headers = r1.headers
+
+ const r2 = await createSellerUser(container, {
+ email: "[email protected]",
+ name: "Stats Seller Two",
+ })
+ seller2 = r2.seller
+ seller2Headers = r2.headers
+
+ const productA = await createVendorProduct(api, seller1Headers, {
+ title: `Stats Product A ${Date.now()}`,
+ variants: [{ title: "Default" }],
+ })
+ const productB = await createVendorProduct(api, seller1Headers, {
+ title: `Stats Product B ${Date.now()}`,
+ variants: [{ title: "Default" }],
+ })
+
+ const profile1 = await createShippingProfile(container, {
+ name: "Stats Profile One",
+ })
+ const profile2 = await createShippingProfile(container, {
+ name: "Stats Profile Two",
+ })
+
+ offerIds = [
+ await createOffer(
+ seller1Headers,
+ "STATS-S1-A",
+ productA.variants[0].id,
+ profile1.id
+ ),
+ await createOffer(
+ seller1Headers,
+ "STATS-S1-B",
+ productB.variants[0].id,
+ profile1.id
+ ),
+ await createOffer(
+ seller2Headers,
+ "STATS-S2-A",
+ productA.variants[0].id,
+ profile2.id
+ ),
+ ]
+ })
+
+ it("returns the offer envelope with distinct sellers and products", async () => {
+ const statistics = await getStatistics()
+
+ expect(statistics).toEqual({ offers: 3, sellers: 2, products: 2 })
+ })
+
+ it("excludes offers created after `at`", async () => {
+ await dbConnection.raw(
+ `UPDATE offer SET created_at = '2030-01-01T00:00:00Z' WHERE id = ?`,
+ [offerIds[2]]
+ )
+
+ const statistics = await getStatistics(
+ `?at=${encodeURIComponent("2029-12-31T00:00:00Z")}`
+ )
+
+ expect(statistics).toEqual({ offers: 2, sellers: 1, products: 2 })
+ })
+
+ it("counts an offer deleted after `at` and skips one deleted before", async () => {
+ await offerService.softDeleteOffers([offerIds[0], offerIds[1]])
+ await dbConnection.raw(
+ `UPDATE offer SET created_at = '2020-01-01T00:00:00Z' WHERE id IN (?, ?, ?)`,
+ offerIds
+ )
+ await dbConnection.raw(
+ `UPDATE offer SET deleted_at = '2025-01-01T00:00:00Z' WHERE id = ?`,
+ [offerIds[0]]
+ )
+ await dbConnection.raw(
+ `UPDATE offer SET deleted_at = '2023-01-01T00:00:00Z' WHERE id = ?`,
+ [offerIds[1]]
+ )
+
+ const now = await getStatistics()
+ expect(now).toEqual({ offers: 1, sellers: 1, products: 1 })
+
+ const between = await getStatistics(
+ `?at=${encodeURIComponent("2024-01-01T00:00:00Z")}`
+ )
+ expect(between).toEqual({ offers: 2, sellers: 2, products: 1 })
+ })
+
+ it("narrows the count with the seller_id filter", async () => {
+ expect(await getStatistics(`?seller_id=${seller1.id}`)).toEqual({
+ offers: 2,
+ sellers: 1,
+ products: 2,
+ })
+
+ expect(
+ await getStatistics(
+ `?seller_id[]=${seller1.id}&seller_id[]=${seller2.id}`
+ )
+ ).toEqual({ offers: 3, sellers: 2, products: 2 })
+ })
+
+ it("rejects an unparseable `at`", async () => {
+ const response = await api
+ .get("/admin/offers/statistics?at=not-a-date", adminHeaders)
+ .catch((error: { response: unknown }) => error.response)
+
+ expect(response.status).toEqual(400)
+ })
+ })
+ },
+})
diff --git a/integration-tests/http/seller/admin/seller-statistics.spec.ts b/integration-tests/http/seller/admin/seller-statistics.spec.ts
new file mode 100644
index 000000000..f1a3b0e15
--- /dev/null
+++ b/integration-tests/http/seller/admin/seller-statistics.spec.ts
@@ -0,0 +1,154 @@
+import { medusaIntegrationTestRunner } from "@medusajs/test-utils"
+import { ConfigModule, MedusaContainer } from "@medusajs/framework/types"
+import { asValue } from "@medusajs/framework/awilix"
+import { ContainerRegistrationKeys } from "@medusajs/framework/utils"
+import {
+ IPermissionResolver,
+ ISellerModuleService,
+ MercurModules,
+ PERMISSIONS_MODULE,
+ PermissionMap,
+ SellerStatus,
+} from "@mercurjs/types"
+
+import {
+ adminHeaders,
+ createAdminUser,
+} from "../../../helpers/create-admin-user"
+import { createSellerUser } from "../../../helpers/create-seller-user"
+
+jest.setTimeout(60000)
+
+type SellerServiceUnderTest = ISellerModuleService & {
+ updateSellers(data: {
+ id: string
+ status?: SellerStatus
+ is_premium?: boolean
+ }): Promise<unknown>
+ softDeleteSellers(ids: string[]): Promise<unknown>
+}
+
+medusaIntegrationTestRunner({
+ testSuite: ({ getContainer, api, dbConnection }) => {
+ describe("GET /admin/sellers/statistics", () => {
+ let container: MedusaContainer
+ let sellerService: SellerServiceUnderTest
+ let granted: PermissionMap = {}
+
+ const resolver: IPermissionResolver = {
+ resolvePermissions: async () => granted,
+ }
+
+ const modulesConfig = () => {
+ const config = container.resolve<ConfigModule>(
+ ContainerRegistrationKeys.CONFIG_MODULE
+ )
+ config.modules ??= {}
+ return config.modules as Record<string, unknown>
+ }
+
+ const createSeller = async (
+ tag: string,
+ data: { status: SellerStatus; is_premium?: boolean }
+ ) => {
+ const { seller } = await createSellerUser(container, {
+ email: `${tag}@statistics.test`,
+ name: `Seller ${tag}`,
+ })
+ await sellerService.updateSellers({ id: seller.id, ...data })
+ return seller
+ }
+
+ beforeAll(() => {
+ container = getContainer()
+ sellerService = container.resolve(MercurModules.SELLER)
+ })
+
+ beforeEach(async () => {
+ await createAdminUser(dbConnection, adminHeaders, container)
+ })
+
+ afterEach(() => {
+ delete modulesConfig()[PERMISSIONS_MODULE]
+ })
+
+ it("counts sellers by status and premium sellers", async () => {
+ await createSeller("open", {
+ status: SellerStatus.OPEN,
+ is_premium: true,
+ })
+ await createSeller("pending", { status: SellerStatus.PENDING_APPROVAL })
+ await createSeller("suspended", { status: SellerStatus.SUSPENDED })
+ await createSeller("terminated", { status: SellerStatus.TERMINATED })
+
+ const response = await api.get("/admin/sellers/statistics", adminHeaders)
+
+ expect(response.status).toEqual(200)
+ expect(response.data).toEqual({
+ statistics: {
+ total: 4,
+ premium: 1,
+ by_status: {
+ open: 1,
+ pending_approval: 1,
+ suspended: 1,
+ terminated: 1,
+ },
+ },
+ })
+ })
+
+ it("does not count soft-deleted sellers", async () => {
+ const kept = await createSeller("kept", { status: SellerStatus.OPEN })
+ const removed = await createSeller("removed", {
+ status: SellerStatus.OPEN,
+ is_premium: true,
+ })
+ await sellerService.softDeleteSellers([removed.id])
+
+ const response = await api.get("/admin/sellers/statistics", adminHeaders)
+
+ expect(response.status).toEqual(200)
+ expect(response.data.statistics).toEqual(
+ expect.objectContaining({
+ total: 1,
+ premium: 0,
+ by_status: expect.objectContaining({ open: 1 }),
+ })
+ )
+ expect(kept.id).toBeDefined()
+ })
+
+ it("returns every status key even when no seller has it", async () => {
+ const response = await api.get("/admin/sellers/statistics", adminHeaders)
+
+ expect(response.status).toEqual(200)
+ expect(response.data.statistics).toEqual({
+ total: 0,
+ premium: 0,
+ by_status: {
+ open: 0,
+ pending_approval: 0,
+ suspended: 0,
+ terminated: 0,
+ },
+ })
+ })
+
+ it("requires sellers:view", async () => {
+ granted = { orders: "view" }
+ modulesConfig()[PERMISSIONS_MODULE] = { resolve: "test-permissions" }
+ container.register(PERMISSIONS_MODULE, asValue(resolver))
+
+ const response = await api
+ .get("/admin/sellers/statistics", adminHeaders)
+ .catch((error: { response: unknown }) => error.response)
+
+ expect(response.status).toEqual(403)
+ expect(response.data).toEqual(
+ expect.objectContaining({ permission: "sellers", right: "view" })
+ )
+ })
+ })
+ },
+})
diff --git a/packages/cli/routes-manifest.json b/packages/cli/routes-manifest.json
index af53fec08..c4cac0dc2 100644
--- a/packages/cli/routes-manifest.json
+++ b/packages/cli/routes-manifest.json
@@ -95,6 +95,7 @@
"/admin/offers": "typeof import(\"@mercurjs/core/api/admin/offers/route\")",
"/admin/offers/:id": "typeof import(\"@mercurjs/core/api/admin/offers/[id]/route\")",
"/admin/offers/batch": "typeof import(\"@mercurjs/core/api/admin/offers/batch/route\")",
+ "/admin/offers/statistics": "typeof import(\"@mercurjs/core/api/admin/offers/statistics/route\")",
"/admin/order-changes/:id": "typeof import(\"@medusajs/medusa/api/admin/order-changes/[id]/route\")",
"/admin/order-edits": "typeof import(\"@medusajs/medusa/api/admin/order-edits/route\")",
"/admin/order-edits/:id": "typeof import(\"@medusajs/medusa/api/admin/order-edits/[id]/route\")",
@@ -262,6 +263,7 @@
"/admin/sellers/:id/terminate": "typeof import(\"@mercurjs/core/api/admin/sellers/[id]/terminate/route\")",
"/admin/sellers/:id/unsuspend": "typeof import(\"@mercurjs/core/api/admin/sellers/[id]/unsuspend/route\")",
"/admin/sellers/:id/unterminate": "typeof import(\"@mercurjs/core/api/admin/sellers/[id]/unterminate/route\")",
+ "/admin/sellers/statistics": "typeof import(\"@mercurjs/core/api/admin/sellers/statistics/route\")",
"/admin/shipping-option-types": "typeof import(\"@medusajs/medusa/api/admin/shipping-option-types/route\")",
"/admin/shipping-option-types/:id": "typeof import(\"@medusajs/medusa/api/admin/shipping-option-types/[id]/route\")",
"/admin/shipping-options": "typeof import(\"@medusajs/medusa/api/admin/shipping-options/route\")",
diff --git a/packages/core/.mercur/routes.d.ts b/packages/core/.mercur/routes.d.ts
index 3c1b0cea1..7694ad987 100644
--- a/packages/core/.mercur/routes.d.ts
+++ b/packages/core/.mercur/routes.d.ts
@@ -165,6 +165,7 @@ export type Routes = {
offers: typeof import("../src/api/admin/offers/route") & {
$id: typeof import("../src/api/admin/offers/[id]/route");
batch: typeof import("../src/api/admin/offers/batch/route");
+ statistics: typeof import("../src/api/admin/offers/statistics/route");
};
orderChanges: {
$id: typeof import("@medusajs/medusa/api/admin/order-changes/[id]/route");
@@ -430,6 +431,7 @@ export type Routes = {
unsuspend: typeof import("../src/api/admin/sellers/[id]/unsuspend/route");
unterminate: typeof import("../src/api/admin/sellers/[id]/unterminate/route");
};
+ statistics: typeof import("../src/api/admin/sellers/statistics/route");
};
shippingOptionTypes: typeof import("@medusajs/medusa/api/admin/shipping-option-types/route") & {
$id: typeof import("@medusajs/medusa/api/admin/shipping-option-types/[id]/route");
diff --git a/packages/core/src/api/admin/offers/middlewares.ts b/packages/core/src/api/admin/offers/middlewares.ts
index d857f2951..cd04349a1 100644
--- a/packages/core/src/api/admin/offers/middlewares.ts
+++ b/packages/core/src/api/admin/offers/middlewares.ts
@@ -10,6 +10,7 @@ import { adminOfferQueryConfig } from "./query-config"
import {
AdminCreateOffersBatch,
AdminGetOfferParams,
+ AdminGetOfferStatisticsParams,
AdminGetOffersParams,
} from "./validators"
@@ -43,6 +44,14 @@ export const adminOffersMiddlewares: MiddlewareRoute[] = [
),
],
},
+ {
+ method: ["GET"],
+ matcher: "/admin/offers/statistics",
+ middlewares: [
+ requirePermission("offers", "view"),
+ validateAndTransformQuery(AdminGetOfferStatisticsParams, {}),
+ ],
+ },
{
method: ["GET"],
matcher: "/admin/offers/:id",
diff --git a/packages/core/src/api/admin/offers/statistics/route.ts b/packages/core/src/api/admin/offers/statistics/route.ts
new file mode 100644
index 000000000..21a0e19a6
--- /dev/null
+++ b/packages/core/src/api/admin/offers/statistics/route.ts
@@ -0,0 +1,22 @@
+import {
+ AuthenticatedMedusaRequest,
+ MedusaResponse,
+} from "@medusajs/framework/http"
+import { HttpTypes, IOfferModuleService, MercurModules } from "@mercurjs/types"
+
+import { AdminGetOfferStatisticsParamsType } from "../validators"
+
+export const GET = async (
+ req: AuthenticatedMedusaRequest<{}, HttpTypes.AdminOfferStatisticsParams>,
+ res: MedusaResponse<HttpTypes.AdminOfferStatisticsResponse>
+) => {
+ const offerService = req.scope.resolve<IOfferModuleService>(
+ MercurModules.OFFER
+ )
+ const { at, ...filters } =
+ req.filterableFields as AdminGetOfferStatisticsParamsType
+
+ const statistics = await offerService.getStatistics({ at, filters })
+
+ res.json({ statistics })
+}
diff --git a/packages/core/src/api/admin/offers/validators.ts b/packages/core/src/api/admin/offers/validators.ts
index 399b18b82..09c303c1d 100644
--- a/packages/core/src/api/admin/offers/validators.ts
+++ b/packages/core/src/api/admin/offers/validators.ts
@@ -89,3 +89,11 @@ const CreateOffersBatch = z
export type AdminCreateOffersBatchType = z.infer<typeof CreateOffersBatch> &
AdditionalData
export const AdminCreateOffersBatch = WithAdditionalData(CreateOffersBatch)
+
+export type AdminGetOfferStatisticsParamsType = z.infer<
+ typeof AdminGetOfferStatisticsParams
+>
+export const AdminGetOfferStatisticsParams = z.object({
+ at: z.coerce.date().optional(),
+ seller_id: z.union([z.string(), z.array(z.string())]).optional(),
+})
diff --git a/packages/core/src/api/admin/sellers/middlewares.ts b/packages/core/src/api/admin/sellers/middlewares.ts
index f1a9f6cbf..99decf0d0 100644
--- a/packages/core/src/api/admin/sellers/middlewares.ts
+++ b/packages/core/src/api/admin/sellers/middlewares.ts
@@ -4,6 +4,7 @@ import {
validateAndTransformBody,
validateAndTransformQuery,
} from "@medusajs/framework"
+import { z } from "zod"
import {
adminSellerQueryConfig,
@@ -63,6 +64,14 @@ export const adminSellersMiddlewares: MiddlewareRoute[] = [
),
],
},
+ {
+ method: ["GET"],
+ matcher: "/admin/sellers/statistics",
+ middlewares: [
+ requirePermission("sellers", "view"),
+ validateAndTransformQuery(z.object({}), {}),
+ ],
+ },
{
method: ["GET"],
matcher: "/admin/sellers/:id",
diff --git a/packages/core/src/api/admin/sellers/statistics/route.ts b/packages/core/src/api/admin/sellers/statistics/route.ts
new file mode 100644
index 000000000..3d04786c7
--- /dev/null
+++ b/packages/core/src/api/admin/sellers/statistics/route.ts
@@ -0,0 +1,18 @@
+import {
+ AuthenticatedMedusaRequest,
+ MedusaResponse,
+} from "@medusajs/framework/http"
+import { HttpTypes, ISellerModuleService, MercurModules } from "@mercurjs/types"
+
+export const GET = async (
+ req: AuthenticatedMedusaRequest<{}, {}>,
+ res: MedusaResponse<HttpTypes.AdminSellerStatisticsResponse>
+) => {
+ const sellerService = req.scope.resolve<ISellerModuleService>(
+ MercurModules.SELLER
+ )
+
+ const statistics = await sellerService.getStatistics()
+
+ res.json({ statistics })
+}
diff --git a/packages/core/src/modules/offer/repositories/index.ts b/packages/core/src/modules/offer/repositories/index.ts
new file mode 100644
index 000000000..1760eb1ce
--- /dev/null
+++ b/packages/core/src/modules/offer/repositories/index.ts
@@ -0,0 +1 @@
+export { OfferStatisticsRepository } from "./offer-statistics"
diff --git a/packages/core/src/modules/offer/repositories/offer-statistics.ts b/packages/core/src/modules/offer/repositories/offer-statistics.ts
new file mode 100644
index 000000000..1926f77e4
--- /dev/null
+++ b/packages/core/src/modules/offer/repositories/offer-statistics.ts
@@ -0,0 +1,41 @@
+import { SqlEntityManager } from "@medusajs/framework/mikro-orm/postgresql"
+import { Context } from "@medusajs/framework/types"
+import { DALUtils } from "@medusajs/framework/utils"
+import { OfferStatisticsInput } from "@mercurjs/types"
+
+export type OfferCountRow = {
+ offers: string | number
+ sellers: string | number
+ products: string | number
+}
+
+export class OfferStatisticsRepository extends DALUtils.MikroOrmBase {
+ constructor() {
+ // @ts-ignore
+ // eslint-disable-next-line prefer-rest-params
+ super(...arguments)
+ }
+
+ async countAt(
+ { at, filters }: { at: Date; filters?: OfferStatisticsInput["filters"] },
+ sharedContext: Context = {}
+ ): Promise<OfferCountRow> {
+ const knex = this.getActiveManager<SqlEntityManager>(sharedContext).getKnex()
+
+ const q = knex("offer")
+ .where("created_at", "<=", at)
+ .andWhere((w) => w.whereNull("deleted_at").orWhere("deleted_at", ">", at))
+
+ const sellerIds = filters?.seller_id
+ if (sellerIds) {
+ q.whereIn("seller_id", Array.isArray(sellerIds) ? sellerIds : [sellerIds])
+ }
+
+ const [row] = (await q
+ .count({ offers: "*" })
+ .countDistinct({ sellers: "seller_id" })
+ .countDistinct({ products: "product_id" })) as OfferCountRow[]
+
+ return row
+ }
+}
diff --git a/packages/core/src/modules/offer/service.ts b/packages/core/src/modules/offer/service.ts
index fb271c4d1..c90e1afc2 100644
--- a/packages/core/src/modules/offer/service.ts
+++ b/packages/core/src/modules/offer/service.ts
@@ -5,19 +5,58 @@ import {
} from "@medusajs/framework/utils"
import { Context, FindConfig } from "@medusajs/framework/types"
import { SqlEntityManager } from "@medusajs/framework/mikro-orm/postgresql"
-import { OfferDTO } from "@mercurjs/types"
+import {
+ IOfferModuleService,
+ OfferDTO,
+ OfferStatisticsInput,
+ OfferStatisticsOutput,
+} from "@mercurjs/types"
import { Offer, OfferCondition } from "./models"
+import { OfferStatisticsRepository } from "./repositories"
+
+type InjectedDependencies = {
+ offerStatisticsRepository: OfferStatisticsRepository
+}
type OfferFilters = Record<string, unknown> & { group_by_seller?: boolean }
const toArray = (value: unknown): string[] =>
(Array.isArray(value) ? value : [value]).map(String)
-class OfferModuleService extends MedusaService({
- Offer,
- OfferCondition,
-}) {
+class OfferModuleService
+ extends MedusaService({
+ Offer,
+ OfferCondition,
+ })
+ implements IOfferModuleService
+{
+ protected readonly offerStatisticsRepository_: OfferStatisticsRepository
+
+ constructor({ offerStatisticsRepository }: InjectedDependencies) {
+ // @ts-ignore
+ // eslint-disable-next-line prefer-rest-params
+ super(...arguments)
+ this.offerStatisticsRepository_ = offerStatisticsRepository
+ }
+
+ @InjectManager()
+ async getStatistics(
+ input: OfferStatisticsInput = {},
+ @MedusaContext() sharedContext: Context = {}
+ ): Promise<OfferStatisticsOutput> {
+ const row = await this.offerStatisticsRepository_.countAt(
+ { at: input.at ?? new Date(), filters: input.filters },
+ sharedContext
+ )
+
+ return {
+ offers: Number(row.offers),
+ sellers: Number(row.sellers),
+ products: Number(row.products),
+ }
+ }
+
@InjectManager()
// @ts-ignore - override narrows the generated signature
async listOffers(
diff --git a/packages/core/src/modules/seller/repositories/index.ts b/packages/core/src/modules/seller/repositories/index.ts
index 687b36767..562acc05d 100644
--- a/packages/core/src/modules/seller/repositories/index.ts
+++ b/packages/core/src/modules/seller/repositories/index.ts
@@ -1,3 +1,2 @@
-export {
- OrderGroupRepository,
-} from "./order-group"
+export { OrderGroupRepository } from "./order-group"
+export { SellerStatisticsRepository } from "./seller-statistics"
diff --git a/packages/core/src/modules/seller/repositories/seller-statistics.ts b/packages/core/src/modules/seller/repositories/seller-statistics.ts
new file mode 100644
index 000000000..149451d68
--- /dev/null
+++ b/packages/core/src/modules/seller/repositories/seller-statistics.ts
@@ -0,0 +1,28 @@
+import { SqlEntityManager } from "@medusajs/framework/mikro-orm/postgresql"
+import { Context } from "@medusajs/framework/types"
+import { DALUtils } from "@medusajs/framework/utils"
+
+export type SellerStatusCountRow = {
+ status: string
+ count: string | number
+ premium: string | number | null
+}
+
+export class SellerStatisticsRepository extends DALUtils.MikroOrmBase {
+ constructor() {
+ // @ts-ignore
+ // eslint-disable-next-line prefer-rest-params
+ super(...arguments)
+ }
+
+ async countByStatus(sharedContext: Context = {}): Promise<SellerStatusCountRow[]> {
+ const knex = this.getActiveManager<SqlEntityManager>(sharedContext).getKnex()
+
+ return (await knex("seller")
+ .whereNull("deleted_at")
+ .select("status")
+ .count({ count: "*" })
+ .sum({ premium: knex.raw("CASE WHEN is_premium THEN 1 ELSE 0 END") })
+ .groupBy("status")) as SellerStatusCountRow[]
+ }
+}
diff --git a/packages/core/src/modules/seller/service.ts b/packages/core/src/modules/seller/service.ts
index 5962fe011..1d0be71fb 100644
--- a/packages/core/src/modules/seller/service.ts
+++ b/packages/core/src/modules/seller/service.ts
@@ -22,13 +22,24 @@ import {
MemberInvite,
OrderGroup,
} from "./models"
-import { OrderGroupRepository } from "./repositories"
-import { MemberDTO, MemberInviteDTO, OrderGroupDTO, SellerDTO, SellerModuleOptions } from "@mercurjs/types"
+import { OrderGroupRepository, SellerStatisticsRepository } from "./repositories"
+import {
+ ISellerModuleService,
+ MemberDTO,
+ MemberInviteDTO,
+ OrderGroupDTO,
+ SellerDTO,
+ SellerModuleOptions,
+ SellerStatisticsInput,
+ SellerStatisticsOutput,
+ SellerStatus,
+} from "@mercurjs/types"
const DEFAULT_INVITE_VALID_DURATION_SECONDS = 60 * 60 * 24 * 7 // 7 days
type InjectedDependencies = {
orderGroupRepository: OrderGroupRepository
+ sellerStatisticsRepository: SellerStatisticsRepository
baseRepository: DAL.RepositoryService
}
@@ -41,19 +52,25 @@ class SellerModuleService extends MedusaService({
SellerMember,
MemberInvite,
OrderGroup,
-}) {
+}) implements ISellerModuleService {
protected readonly orderGroupRepository_: OrderGroupRepository
+ protected readonly sellerStatisticsRepository_: SellerStatisticsRepository
protected readonly baseRepository_: DAL.RepositoryService
protected readonly options_: SellerModuleOptions
constructor(
- { orderGroupRepository, baseRepository }: InjectedDependencies,
+ {
+ orderGroupRepository,
+ sellerStatisticsRepository,
+ baseRepository,
+ }: InjectedDependencies,
protected readonly moduleDeclaration?: InternalModuleDeclaration,
) {
// @ts-ignore
// eslint-disable-next-line prefer-rest-params
super(...arguments)
this.orderGroupRepository_ = orderGroupRepository
+ this.sellerStatisticsRepository_ = sellerStatisticsRepository
this.baseRepository_ = baseRepository
const opts = (moduleDeclaration?.options as SellerModuleOptions) ?? {}
@@ -66,6 +83,29 @@ class SellerModuleService extends MedusaService({
}
}
+ @InjectManager()
+ async getStatistics(
+ _input: SellerStatisticsInput = {},
+ @MedusaContext() sharedContext: Context = {},
+ ): Promise<SellerStatisticsOutput> {
+ const rows = await this.sellerStatisticsRepository_.countByStatus(sharedContext)
+
+ const by_status = Object.fromEntries(
+ Object.values(SellerStatus).map((status) => [status, 0]),
+ ) as Record<SellerStatus, number>
+ let premium = 0
+ for (const row of rows) {
+ by_status[row.status as SellerStatus] = Number(row.count)
+ premium += Number(row.premium ?? 0)
+ }
+
+ return {
+ total: Object.values(by_status).reduce((sum, count) => sum + count, 0),
+ premium,
+ by_status,
+ }
+ }
+
@InjectTransactionManager()
// @ts-ignore
async createSellers<T extends any | any[]>(
diff --git a/packages/types/src/http/offer.ts b/packages/types/src/http/offer.ts
index 135cb326e..c6a075da5 100644
--- a/packages/types/src/http/offer.ts
+++ b/packages/types/src/http/offer.ts
@@ -4,6 +4,7 @@ import {
CreateOfferPriceDTO,
OfferConditionDTO,
OfferDTO,
+ OfferStatisticsOutput,
UpsertOfferPriceDTO,
} from "../offer"
@@ -94,6 +95,15 @@ export type AdminOfferListResponse = PaginatedResponse<{
offers: OfferDTO[]
}>
+export interface AdminOfferStatisticsParams {
+ at?: string
+ seller_id?: string | string[]
+}
+
+export interface AdminOfferStatisticsResponse {
+ statistics: OfferStatisticsOutput
+}
+
/*
* --------------------------------------------------------------------
* Offer conditions
diff --git a/packages/types/src/http/seller.ts b/packages/types/src/http/seller.ts
index 5024b5c2f..7054d0c9b 100644
--- a/packages/types/src/http/seller.ts
+++ b/packages/types/src/http/seller.ts
@@ -1,5 +1,10 @@
import { DeleteResponse, PaginatedResponse } from "@medusajs/types"
-import { MemberInviteDTO, SellerDTO, SellerMemberDTO } from "../seller"
+import {
+ MemberInviteDTO,
+ SellerDTO,
+ SellerMemberDTO,
+ SellerStatisticsOutput,
+} from "../seller"
import { PermissionMap } from "../permissions"
export interface VendorSellerResponse {
@@ -75,3 +80,7 @@ export interface AdminSellerResponse {
export type AdminSellerListResponse = PaginatedResponse<{
sellers: SellerDTO[]
}>
+
+export interface AdminSellerStatisticsResponse {
+ statistics: SellerStatisticsOutput
+}
diff --git a/packages/types/src/offer/common.ts b/packages/types/src/offer/common.ts
index d3f03f824..eae98033a 100644
--- a/packages/types/src/offer/common.ts
+++ b/packages/types/src/offer/common.ts
@@ -120,3 +120,19 @@ export interface OfferDTO {
*/
calculated_price?: StoreCalculatedPrice
}
+
+export interface OfferStatisticsInput {
+ /**
+ * Count offers as they existed at this instant. Defaults to now.
+ */
+ at?: Date
+ filters?: {
+ seller_id?: string | string[]
+ }
+}
+
+export interface OfferStatisticsOutput {
+ offers: number
+ sellers: number
+ products: number
+}
diff --git a/packages/types/src/offer/index.ts b/packages/types/src/offer/index.ts
index 5d3c3b82a..0c7365656 100644
--- a/packages/types/src/offer/index.ts
+++ b/packages/types/src/offer/index.ts
@@ -1,2 +1,3 @@
export * from "./common"
export * from "./mutations"
+export * from "./service"
diff --git a/packages/types/src/offer/service.ts b/packages/types/src/offer/service.ts
new file mode 100644
index 000000000..4fc4a81aa
--- /dev/null
+++ b/packages/types/src/offer/service.ts
@@ -0,0 +1,15 @@
+import { Context, IModuleService } from "@medusajs/types"
+import { OfferStatisticsInput, OfferStatisticsOutput } from "./common"
+
+export interface IOfferModuleService extends IModuleService {
+ /**
+ * Counts offers, and the distinct sellers and products behind them, as of `at`.
+ *
+ * @example
+ * const { offers, sellers } = await offerModuleService.getStatistics({ at: new Date("2026-10-01") })
+ */
+ getStatistics(
+ input?: OfferStatisticsInput,
+ sharedContext?: Context
+ ): Promise<OfferStatisticsOutput>
+}
diff --git a/packages/types/src/seller/common.ts b/packages/types/src/seller/common.ts
index a82574be7..b4e91437d 100644
--- a/packages/types/src/seller/common.ts
+++ b/packages/types/src/seller/common.ts
@@ -211,3 +211,11 @@ export interface SellerDTO {
updated_at: Date
deleted_at: Date | null
}
+
+export interface SellerStatisticsInput {}
+
+export interface SellerStatisticsOutput {
+ total: number
+ premium: number
+ by_status: Record<SellerStatus, number>
+}
diff --git a/packages/types/src/seller/index.ts b/packages/types/src/seller/index.ts
index a717a5435..282e8fb90 100644
--- a/packages/types/src/seller/index.ts
+++ b/packages/types/src/seller/index.ts
@@ -1,2 +1,3 @@
export * from "./common"
export * from "./mutation"
+export * from "./service"
diff --git a/packages/types/src/seller/service.ts b/packages/types/src/seller/service.ts
new file mode 100644
index 000000000..5368ffeb8
--- /dev/null
+++ b/packages/types/src/seller/service.ts
@@ -0,0 +1,15 @@
+import { Context, IModuleService } from "@medusajs/types"
+import { SellerStatisticsInput, SellerStatisticsOutput } from "./common"
+
+export interface ISellerModuleService extends IModuleService {
+ /**
+ * Counts sellers by status, plus premium sellers.
+ *
+ * @example
+ * const { by_status } = await sellerModuleService.getStatistics()
+ */
+ getStatistics(
+ input?: SellerStatisticsInput,
+ sharedContext?: Context
+ ): Promise<SellerStatisticsOutput>
+}