diff --git a/graphql-contracts b/graphql-contracts index 93b8e21..571a2c8 160000 --- a/graphql-contracts +++ b/graphql-contracts @@ -1 +1 @@ -Subproject commit 93b8e213252c42a02f432b96a813cb6816e3d354 +Subproject commit 571a2c81725a5d6ba301061cb43eaef4e2af3208 diff --git a/src/schema.ts b/src/schema.ts index f4b280d..8f6544c 100644 --- a/src/schema.ts +++ b/src/schema.ts @@ -58,6 +58,11 @@ export const typeDefs = `#graphql categoryName: String! unit: String! imageUrl: String + offersCount: Int + averagePrice: Float + priceVariationPercent: Float + priceSeries: [Float!]! + currency: String description: String isActive: Boolean! createdAt: String! @@ -167,6 +172,34 @@ function productData(input: ProductInput) { } } +async function productWithPriceSummary(uuid: string) { + const product = await prisma.product.findUnique({ where: { uuid } }) + if (product === null) return null + + const quotes = await prisma.quote.findMany({ + where: { productId: product.id, status: 'active' }, + select: { pricePerUnit: true, currency: true }, + orderBy: { pricePerUnit: 'asc' }, + take: 100, + }) + const priceSeries = quotes.map(quote => Number(quote.pricePerUnit)) + const averagePrice = priceSeries.length === 0 + ? null + : priceSeries.reduce((sum, price) => sum + price, 0) / priceSeries.length + const priceVariationPercent = averagePrice === null || averagePrice <= 0 + ? 0 + : ((priceSeries.at(-1)! - priceSeries[0]) / 2 / averagePrice) * 100 + + return { + ...product, + offersCount: quotes.length, + averagePrice, + priceVariationPercent, + priceSeries, + currency: quotes[0]?.currency ?? 'USD', + } +} + async function quoteData(input: QuoteInput) { const supplier = await prisma.supplier.findUnique({ where: { uuid: input.supplierUuid } }) if (supplier === null) throw new Error(`Supplier ${input.supplierUuid} does not exist`) @@ -219,8 +252,7 @@ export const resolvers = { orderBy: { name: 'asc' }, }), - product: (_: unknown, args: { uuid: string }) => - prisma.product.findUnique({ where: { uuid: args.uuid } }), + product: (_: unknown, args: { uuid: string }) => productWithPriceSummary(args.uuid), quotes: async (_: unknown, args: { productUuid?: string; supplierUuid?: string; status?: string; limit?: number; offset?: number }) => { const product = args.productUuid ? await prisma.product.findUnique({ where: { uuid: args.productUuid } }) : null