1
0
mirror of https://github.com/oceanprotocol/market.git synced 2024-12-02 05:57:29 +01:00

restored "Publishers with most sales" section (#1540)

* updated subgraph query

* rework AccountList

* fix missing 'a' elem in dom (<Link> is not rendering correct markup)

* restore PublishersWithMostSales section

* removed unnecessary params in AssetList

* use Blockies for all profile.image

* changed logic on getTopAssetsPublishers

* added aggregations op to getTopAssetsPublishers method

* fix build issues

* improve logic & added correct total sales on profile

* removed complex logic to unify query

* typography & markup cleanup

Co-authored-by: Matthias Kretschmann <m@kretschmann.io>
This commit is contained in:
EnzoVezzaro 2022-07-05 14:49:35 +02:00 committed by GitHub
parent 2d2ad78f89
commit 42956a3441
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
12 changed files with 177 additions and 118 deletions

View File

@ -9,6 +9,7 @@ interface BaseQueryParams {
nestedQuery?: any
esPaginationOptions?: EsPaginationOptions
sortOptions?: SortOptions
aggs?: any
filters?: FilterTerm[]
ignorePurgatory?: boolean
}

View File

@ -3,4 +3,5 @@ interface PagedAssets {
page: number
totalPages: number
totalResults: number
aggregations: any
}

View File

@ -5,7 +5,8 @@ export enum SortDirectionOptions {
export enum SortTermOptions {
Created = 'metadata.created',
Relevance = '_score'
Relevance = '_score',
Stats = 'stats.orders'
}
// Note: could not figure out how to get `enum` to be ambiant
@ -43,5 +44,6 @@ declare global {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
query: any
sort?: { [jsonPath: string]: SortDirectionOptions }
aggs?: any
}
}

View File

@ -55,6 +55,10 @@ export function generateBaseQuery(
}
} as SearchQuery
if (baseQueryParams.aggs !== undefined) {
generatedQuery.aggs = baseQueryParams.aggs
}
if (baseQueryParams.sortOptions !== undefined)
generatedQuery.sort = {
[baseQueryParams.sortOptions.sortBy]:
@ -74,12 +78,15 @@ export function transformQueryResult(
results: [],
page: 0,
totalPages: 0,
totalResults: 0
totalResults: 0,
aggregations: []
}
result.results = (queryResult.hits.hits || []).map(
(hit) => hit._source as Asset
)
result.aggregations = queryResult.aggregations
result.totalResults = queryResult.hits.total.value
result.totalPages =
result.totalResults / size < 1
@ -307,6 +314,13 @@ export async function getPublishedAssets(
sortBy: SortTermOptions.Created,
sortDirection: SortDirectionOptions.Descending
},
aggs: {
totalOrders: {
sum: {
field: SortTermOptions.Stats
}
}
},
esPaginationOptions: {
from: (Number(page) - 1 || 0) * 9,
size: 9
@ -314,6 +328,62 @@ export async function getPublishedAssets(
} as BaseQueryParams
const query = generateBaseQuery(baseQueryParams)
try {
const result = await queryMetadata(query, cancelToken)
return result
} catch (error) {
if (axios.isCancel(error)) {
LoggerInstance.log(error.message)
} else {
LoggerInstance.error(error.message)
}
}
}
export async function getTopPublishers(
chainIds: number[],
cancelToken: CancelToken,
page?: number,
type?: string,
accesType?: string
): Promise<PagedAssets> {
const filters: FilterTerm[] = []
accesType !== undefined &&
filters.push(getFilterTerm('services.type', accesType))
type !== undefined && filters.push(getFilterTerm('metadata.type', type))
const baseQueryParams = {
chainIds,
filters,
sortOptions: {
sortBy: SortTermOptions.Created,
sortDirection: SortDirectionOptions.Descending
},
aggs: {
topPublishers: {
terms: {
field: 'nft.owner.keyword',
order: { totalSales: 'desc' }
},
aggs: {
totalSales: {
sum: {
field: SortTermOptions.Stats
}
}
}
}
},
esPaginationOptions: {
from: (Number(page) - 1 || 0) * 9,
size: 9
}
} as BaseQueryParams
const query = generateBaseQuery(baseQueryParams)
try {
const result = await queryMetadata(query, cancelToken)
return result

View File

@ -18,7 +18,7 @@ import { OpcFeesQuery as OpcFeesData } from '../@types/subgraph/OpcFeesQuery'
import { calcSingleOutGivenPoolIn } from './pool'
import Decimal from 'decimal.js'
import { MAX_DECIMALS } from './constants'
import { getPublishedAssets, getTopPublishers } from '@utils/aquarius'
export interface UserLiquidity {
price: string
oceanBalance: string
@ -172,19 +172,11 @@ const UserSalesQuery = gql`
}
`
// TODO: figure out some way to get this
const TopSalesQuery = gql`
query TopSalesQuery {
users(
first: 20
orderBy: sharesOwned
orderDirection: desc
where: { tokenBalancesOwned_not: "0" }
) {
users(first: 20, orderBy: totalSales, orderDirection: desc) {
id
tokenBalancesOwned {
value
}
totalSales
}
}
`
@ -419,20 +411,10 @@ export async function getUserSales(
accountId: string,
chainIds: number[]
): Promise<number> {
const variables = { user: accountId?.toLowerCase() }
try {
const userSales = await fetchDataForMultipleChains(
UserSalesQuery,
variables,
chainIds
)
let salesSum = 0
for (let i = 0; i < userSales.length; i++) {
if (userSales[i].users.length > 0) {
salesSum += parseInt(userSales[i].users[0].totalSales)
}
}
return salesSum
const result = await getPublishedAssets(accountId, chainIds, null)
const { totalOrders } = result.aggregations
return totalOrders.value
} catch (error) {
LoggerInstance.error('Error getUserSales', error.message)
}
@ -442,33 +424,19 @@ export async function getTopAssetsPublishers(
chainIds: number[],
nrItems = 9
): Promise<AccountTeaserVM[]> {
const publisherSales: AccountTeaserVM[] = []
const publishers: AccountTeaserVM[] = []
for (const chain of chainIds) {
const queryContext = getQueryContext(Number(chain))
const fetchedUsers: OperationResult<UsersSalesList> = await fetchData(
TopSalesQuery,
null,
queryContext
)
for (let i = 0; i < fetchedUsers.data.users.length; i++) {
const publishersIndex = publisherSales.findIndex(
(user) => fetchedUsers.data.users[i].id === user.address
)
if (publishersIndex === -1) {
const publisher: AccountTeaserVM = {
address: fetchedUsers.data.users[i].id,
nrSales: fetchedUsers.data.users[i].totalSales
}
publisherSales.push(publisher)
} else {
publisherSales[publishersIndex].nrSales +=
publisherSales[publishersIndex].nrSales
}
}
const result = await getTopPublishers(chainIds, null)
const { topPublishers } = result.aggregations
for (let i = 0; i < topPublishers.buckets.length; i++) {
publishers.push({
address: topPublishers.buckets[i].key,
nrSales: parseInt(topPublishers.buckets[i].totalSales.value)
})
}
publisherSales.sort((a, b) => b.nrSales - a.nrSales)
publishers.sort((a, b) => b.nrSales - a.nrSales)
return publisherSales.slice(0, nrItems)
return publishers.slice(0, nrItems)
}

View File

@ -1,5 +1,5 @@
import React, { ReactElement } from 'react'
import styles from './AssetList.module.css'
import styles from './index.module.css'
import classNames from 'classnames/bind'
import Loader from '../atoms/Loader'
import { useUserPreferences } from '@context/UserPreferences'
@ -29,7 +29,7 @@ export default function AccountList({
const { chainIds } = useUserPreferences()
const styleClasses = cx({
assetList: true,
accountList: true,
[className]: className
})

View File

@ -0,0 +1,24 @@
.accountList {
display: grid;
grid-template-columns: 1fr;
gap: calc(var(--spacer) / 2);
}
@media screen and (min-width: 25rem) {
.accountList {
grid-template-columns: repeat(auto-fit, minmax(20rem, 1fr));
gap: var(--spacer);
}
}
.empty {
color: var(--color-secondary);
font-size: var(--font-size-small);
font-style: italic;
}
.loaderWrap {
display: flex;
justify-content: center;
align-items: center;
}

View File

@ -1,46 +1,39 @@
.blockies {
aspect-ratio: 1/1;
width: 13%;
height: 13%;
width: calc(var(--font-size-large) * 2) !important;
height: calc(var(--font-size-large) * 2) !important;
border-radius: 50%;
margin-left: 0;
margin-right: calc(var(--spacer) / 4);
margin-right: calc(var(--spacer) / 3);
}
.teaser {
max-width: 40rem;
height: 100%;
}
.link {
composes: box from '../atoms/Box.module.css';
padding: calc(var(--spacer) / 2) !important;
font-size: var(--font-size-mini);
height: 90%;
padding: calc(var(--spacer) / 3) calc(var(--spacer) / 2);
color: var(--color-secondary);
position: relative;
display: flex;
align-items: center;
}
.link span {
font-size: var(--font-size-large);
margin-right: calc(var(--spacer) / 3);
}
.name {
margin-bottom: 0;
font-size: var(--font-size-base) !important;
padding-top: calc(var(--spacer) / 4);
}
.header {
display: flex;
flex-direction: row;
align-items: center;
}
.sales {
font-size: small;
margin-top: -5px !important;
margin-bottom: clac(var(--spacer) / 2);
.place {
font-size: var(--font-size-large);
margin-right: calc(var(--spacer) / 2);
}
.name {
margin-bottom: 0;
font-size: var(--font-size-base);
padding-top: calc(var(--spacer) / 5);
color: var(--font-color-text);
}
.sales {
margin: 0;
}
.sales span {
font-weight: var(--font-weight-bold);
color: var(--font-color-text);
}

View File

@ -33,34 +33,26 @@ export default function AccountTeaser({
}, [accountTeaserVM, newCancelToken])
return (
<article className={styles.teaser}>
<Link href={`/profile/${accountTeaserVM.address}`}>
<header className={styles.header}>
{place && <span>{place}</span>}
{profile?.image ? (
<img src={profile.image} className={styles.blockies} />
) : (
<Blockies
accountId={accountTeaserVM.address}
className={styles.blockies}
/>
)}
<div>
<Dotdotdot clamp={3}>
<h3 className={styles.name}>
{profile?.name
? profile?.name
: accountTruncate(accountTeaserVM.address)}
</h3>
</Dotdotdot>
<p className={styles.sales}>
{`${accountTeaserVM.nrSales} ${
accountTeaserVM.nrSales === 1 ? 'sale' : 'sales'
}`}
</p>
</div>
</header>
</Link>
</article>
<Link href={`/profile/${accountTeaserVM.address}`}>
<a className={styles.teaser}>
{place && <span className={styles.place}>{place}</span>}
<Blockies
accountId={accountTeaserVM.address}
className={styles.blockies}
image={profile?.image}
/>
<div>
<Dotdotdot tagName="h4" clamp={2} className={styles.name}>
{profile?.name
? profile?.name
: accountTruncate(accountTeaserVM.address)}
</Dotdotdot>
<p className={styles.sales}>
<span>{accountTeaserVM.nrSales}</span>
{`${accountTeaserVM.nrSales === 1 ? ' sale' : ' sales'}`}
</p>
</div>
</a>
</Link>
)
}

View File

@ -5,11 +5,13 @@ import styles from './index.module.css'
export interface BlockiesProps {
accountId: string
className?: string
image?: string
}
export default function Blockies({
accountId,
className
className,
image
}: BlockiesProps): ReactElement {
if (!accountId) return null
@ -18,7 +20,7 @@ export default function Blockies({
return (
<img
className={`${className || ''} ${styles.blockies} `}
src={blockies}
src={image || blockies}
alt="Blockies"
aria-hidden="true"
/>

View File

@ -1,8 +1,9 @@
import { useUserPreferences } from '@context/UserPreferences'
import { LoggerInstance } from '@oceanprotocol/lib'
import AccountList from '@shared/AccountList/AccountList'
import { getTopAssetsPublishers } from '@utils/subgraph'
import React, { ReactElement, useEffect, useState } from 'react'
import styles from './Home.module.css'
import styles from './index.module.css'
export default function PublishersWithMostSales({
title,
@ -17,18 +18,19 @@ export default function PublishersWithMostSales({
useEffect(() => {
async function init() {
setLoading(true)
if (chainIds.length === 0) {
const result: AccountTeaserVM[] = []
setResult(result)
setLoading(false)
} else {
try {
setLoading(true)
const publishers = await getTopAssetsPublishers(chainIds)
setResult(publishers)
setLoading(false)
} catch (error) {
// Logger.error(error.message)
LoggerInstance.error(error.message)
setLoading(false)
}
}
}

View File

@ -14,6 +14,7 @@ import styles from './index.module.css'
import { useIsMounted } from '@hooks/useIsMounted'
import { useCancelToken } from '@hooks/useCancelToken'
import { SortTermOptions } from '../../@types/aquarius/SearchQuery'
import PublishersWithMostSales from './PublishersWithMostSales'
async function getQueryHighest(
chainIds: number[]
@ -66,7 +67,8 @@ function SectionQueryResult({
results: [],
page: 0,
totalPages: 0,
totalResults: 0
totalResults: 0,
aggregations: undefined
}
setResult(result)
setLoading(false)
@ -153,6 +155,8 @@ export default function HomePage(): ReactElement {
</Button>
}
/>
<PublishersWithMostSales title="Publishers With Most Sales" />
</>
)
}