Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: rating distribution #2687

Open
wants to merge 1 commit into
base: feat/reviews-and-ratings
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions packages/api/src/__generated__/schema.ts

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
export interface ProductRating {
average: number
totalCount: number
starsOne: number
starsTwo: number
starsThree: number
starsFour: number
starsFive: number
}
12 changes: 11 additions & 1 deletion packages/api/src/platforms/vtex/resolvers/product.ts
Original file line number Diff line number Diff line change
Expand Up @@ -157,5 +157,15 @@ export const StoreProduct: Record<string, Resolver<Root>> & {
},
releaseDate: ({ isVariantOf: { releaseDate } }) => releaseDate ?? '',
advertisement: ({ isVariantOf: { advertisement } }) => advertisement,
rating: (item) => item.rating,
rating: (item) => ({
average: item.rating.average,
totalCount: item.rating.totalCount,
distribution: {
starsOne: item.rating.distribution?.[1] ?? 0,
starsTwo: item.rating.distribution?.[2] ?? 0,
starsThree: item.rating.distribution?.[3] ?? 0,
starsFour: item.rating.distribution?.[4] ?? 0,
starsFive: item.rating.distribution?.[5] ?? 0,
},
}),
Comment on lines +160 to +170
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: use destructuring to make it more direct, what do you think?

Suggested change
rating: (item) => ({
average: item.rating.average,
totalCount: item.rating.totalCount,
distribution: {
starsOne: item.rating.distribution?.[1] ?? 0,
starsTwo: item.rating.distribution?.[2] ?? 0,
starsThree: item.rating.distribution?.[3] ?? 0,
starsFour: item.rating.distribution?.[4] ?? 0,
starsFive: item.rating.distribution?.[5] ?? 0,
},
}),
rating: ({ rating: { average, totalCount, distribution } }) => ({
average,
totalCount,
distribution: {
starsOne: distribution?.[1] ?? 0,
starsTwo: distribution?.[2] ?? 0,
starsThree: distribution?.[3] ?? 0,
starsFour: distribution?.[4] ?? 0,
starsFive: distribution?.[5] ?? 0,
},
}),

}
14 changes: 12 additions & 2 deletions packages/api/src/platforms/vtex/resolvers/query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import {
ProductReviewsInputOrderBy,
type ProductReviewsInputOrderWay,
} from '../clients/commerce/types/ProductReview'
import { buildRatingDistribution } from '../utils/rating'

export const Query = {
product: async (_: unknown, { locator }: QueryProductArgs, ctx: Context) => {
Expand Down Expand Up @@ -81,7 +82,7 @@ export const Query = {

const rating = await commerce.rating(sku.itemId)

sku.rating = rating
sku.rating = buildRatingDistribution(rating)

return sku
} catch (err) {
Expand Down Expand Up @@ -113,7 +114,7 @@ export const Query = {

const enhancedSku = enhanceSku(sku, product)

enhancedSku.rating = rating
enhancedSku.rating = buildRatingDistribution(rating)

return enhancedSku
}
Expand All @@ -137,6 +138,15 @@ export const Query = {
}: QuerySearchArgs,
ctx: Context
) => {
console.log('search', {
first,
after: maybeAfter,
sort,
term,
selectedFacets,
sponsoredCount,
})

Comment on lines +141 to +149
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

todo: remember to delete the console log

Suggested change
console.log('search', {
first,
after: maybeAfter,
sort,
term,
selectedFacets,
sponsoredCount,
})

// Insert channel in context for later usage
const channel = findChannel(selectedFacets)
const locale = findLocale(selectedFacets)
Expand Down
15 changes: 14 additions & 1 deletion packages/api/src/platforms/vtex/utils/enhanceSku.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
import type { Product, Item } from '../clients/search/types/ProductSearchResult'
import { sanitizeHtml } from './sanitizeHtml'

export type ProductRating = {
average: number
totalCount: number
distribution: Record<number, number>
}

export type EnhancedSku = Item & { isVariantOf: Product } & {
rating: { average: number; totalCount: number }
rating: ProductRating
}

function sanitizeProduct(product: Product): Product {
Expand All @@ -19,6 +25,13 @@ export const enhanceSku = (item: Item, product: Product): EnhancedSku => ({
rating: {
average: 0,
totalCount: 0,
distribution: {
1: 0,
2: 0,
3: 0,
4: 0,
5: 0,
},
},
isVariantOf: sanitizeProduct(product),
})
68 changes: 68 additions & 0 deletions packages/api/src/platforms/vtex/utils/rating.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import type { ProductRating as ApiClientProductRating } from '../clients/commerce/types/ProductRating'
import type { ProductRating } from './enhanceSku'

export function buildRatingDistribution(
apiClientRating: ApiClientProductRating
): ProductRating {
const rating: ProductRating = {
average: apiClientRating.average,
totalCount: apiClientRating.totalCount,
distribution: {
1: 0,
2: 0,
3: 0,
4: 0,
5: 0,
},
}

if (rating.totalCount === 0) {
return rating
}

const percentages = [
calculateIntegerPercentage(apiClientRating.starsOne, rating.totalCount),
calculateIntegerPercentage(apiClientRating.starsTwo, rating.totalCount),
calculateIntegerPercentage(apiClientRating.starsThree, rating.totalCount),
calculateIntegerPercentage(apiClientRating.starsFour, rating.totalCount),
calculateIntegerPercentage(apiClientRating.starsFive, rating.totalCount),
]

const totalPercentage = percentages.reduce((acc, curr) => acc + curr, 0)

if (totalPercentage !== 100) {
const missingPercentage = 100 - totalPercentage
const [maxValue, matchedIndexes] = findMaxInArray(percentages)

const changingIndex =
missingPercentage > 0
? Math.max(...matchedIndexes)
: Math.min(...matchedIndexes)

percentages[changingIndex] = maxValue + missingPercentage
}

percentages.forEach(
(percentage, index) => (rating.distribution[index + 1] = percentage)
)

console.log('distribution', rating.distribution)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

todo: remember to delete the console log

Suggested change
console.log('distribution', rating.distribution)


return rating
}

function calculateIntegerPercentage(value: number, total: number): number {
return Math.round((value / total) * 100)
}

function findMaxInArray(arr: number[]): [number, number[]] {
const maxValue = Math.max(...arr)
const matchedIndexes = arr.reduce((acc: number[], curr, index) => {
if (curr === maxValue) {
acc.push(index)
}
return acc
}, [])

return [maxValue, matchedIndexes]
}
30 changes: 30 additions & 0 deletions packages/api/src/typeDefs/productRating.graphql
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,34 @@ type StoreProductRating {
Product amount of ratings received.
"""
totalCount: Int!
"""
Product rating distribution in percentages.
"""
distribution: StoreProductRatingDistribution!
}

"""
Product rating distribution in percentages.
"""
type StoreProductRatingDistribution {
"""
1 star rating percentage.
"""
starsOne: Int!
"""
2 star rating percentage.
"""
starsTwo: Int!
"""
3 star rating percentage.
"""
starsThree: Int!
"""
4 star rating percentage.
"""
starsFour: Int!
"""
5 star rating percentage.
"""
starsFive: Int!
}
22 changes: 22 additions & 0 deletions packages/core/@generated/graphql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,19 @@ export type DeliveryIds = {
warehouseId: Maybe<Scalars['String']['output']>
}

export type ICreateProductReview = {
/** Product ID. */
productId: Scalars['String']['input']
/** Review rating. */
rating: Scalars['Int']['input']
/** Review author name. */
reviewerName: Scalars['String']['input']
/** Review content. */
text: Scalars['String']['input']
/** Review title. */
title: Scalars['String']['input']
}

export type IGeoCoordinates = {
/** The latitude of the geographic coordinates. */
latitude: Scalars['Float']['input']
Expand Down Expand Up @@ -954,6 +967,8 @@ export type StoreProduct = {
offers: StoreAggregateOffer
/** Product ID, such as [ISBN](https://www.isbn-international.org/content/what-isbn) or similar global IDs. */
productID: Scalars['String']['output']
/** Product rating. */
rating: StoreProductRating
/** The product's release date. Formatted using https://en.wikipedia.org/wiki/ISO_8601 */
releaseDate: Scalars['String']['output']
/** Array with review information. */
Expand Down Expand Up @@ -1008,6 +1023,13 @@ export type StoreProductGroup = {
skuVariants: Maybe<SkuVariants>
}

export type StoreProductRating = {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

chore: This file is outdated, could you run the generate command again to update it pls?

/** Product average rating. */
average: Scalars['Float']['output']
/** Product amount of ratings received. */
totalCount: Scalars['Int']['output']
}

/** Properties that can be associated with products and products groups. */
export type StorePropertyValue = {
/** Property name. */
Expand Down
Loading