Skip to content

Commit

Permalink
Scout game user optimisations (#4844)
Browse files Browse the repository at this point in the history
* Scout game optimizations

* Undo purchase stuff

* Undo succcess view text

* Fix validation

* Remove user if unnecessary

* Remove userSession and get only the user provider where possible

* Update user after buying a nft

* Update user on signout
  • Loading branch information
valentinludu authored Oct 21, 2024
1 parent 46effc3 commit 239f7e1
Show file tree
Hide file tree
Showing 41 changed files with 345 additions and 443 deletions.
4 changes: 1 addition & 3 deletions apps/scoutgame/app/(general)/home/page.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
import { HomePage } from 'components/home/HomePage';
import { getUserFromSession } from 'lib/session/getUserFromSession';

export default async function Home({
searchParams
}: {
searchParams: { [key: string]: string | string[] | undefined };
}) {
const tab = searchParams.tab as string;
const user = await getUserFromSession();

return <HomePage user={user || null} tab={tab || 'leaderboard'} />;
return <HomePage tab={tab || 'leaderboard'} />;
}
8 changes: 4 additions & 4 deletions apps/scoutgame/app/(general)/notifications/page.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import { getSession } from '@connect-shared/lib/session/getSession';
import { getNotifications } from '@packages/scoutgame/notifications/getNotifications';

import { NotificationsPage } from 'components/notifications/NotificationsPage';
import { getUserFromSession } from 'lib/session/getUserFromSession';

export default async function Page() {
const user = await getUserFromSession();
const { scoutId } = await getSession();

const notifications = user
const notifications = scoutId
? await getNotifications({
userId: user.id
userId: scoutId
})
: [];

Expand Down
2 changes: 1 addition & 1 deletion apps/scoutgame/app/(general)/profile/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { redirect } from 'next/navigation';

import type { ProfileTab } from 'components/profile/ProfilePage';
import { ProfilePage } from 'components/profile/ProfilePage';
import { getUserFromSession } from 'lib/session/getUserFromSession';
import { getCachedUserFromSession as getUserFromSession } from 'lib/session/getUserFromSession';
import { getUserStats } from 'lib/users/getUserStats';

export const dynamic = 'force-dynamic';
Expand Down
4 changes: 1 addition & 3 deletions apps/scoutgame/app/(general)/scout/page.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { ScoutPage } from 'components/scout/ScoutPage';
import type { BuildersSort } from 'lib/builders/getSortedBuilders';
import { getUserFromSession } from 'lib/session/getUserFromSession';

export default async function Scout({
searchParams
Expand All @@ -9,7 +8,6 @@ export default async function Scout({
}) {
const sortParam = searchParams.tab;
const sort = (sortParam && typeof sortParam === 'string' ? sortParam : 'top') as BuildersSort;
const user = await getUserFromSession();

return <ScoutPage sort={sort} user={user} />;
return <ScoutPage sort={sort} />;
}
5 changes: 1 addition & 4 deletions apps/scoutgame/app/(info)/welcome/how-it-works/page.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import type { Metadata } from 'next';

import { HowItWorksPage } from 'components/welcome/how-it-works/HowItWorksPage';
import { getUserFromSession } from 'lib/session/getUserFromSession';

export const dynamic = 'force-dynamic';

Expand All @@ -13,8 +12,6 @@ export const metadata: Metadata = {
};

export default async function HowItWorks() {
const user = await getUserFromSession();

// logic in middleware.ts ensures that user is logged in
return <HowItWorksPage username={user!.username} />;
return <HowItWorksPage />;
}
2 changes: 1 addition & 1 deletion apps/scoutgame/app/(info)/welcome/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import type { Metadata } from 'next';
import { redirect } from 'next/navigation';

import { WelcomePage } from 'components/welcome/WelcomePage';
import { getUserFromSession } from 'lib/session/getUserFromSession';
import { getCachedUserFromSession as getUserFromSession } from 'lib/session/getUserFromSession';

export const dynamic = 'force-dynamic';

Expand Down
7 changes: 1 addition & 6 deletions apps/scoutgame/app/(info)/welcome/spam-policy/page.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
import type { Metadata } from 'next';

import { SpamPolicyPage } from 'components/welcome/spam-policy/SpamPolicyPage';
import { getUserFromSession } from 'lib/session/getUserFromSession';

export const dynamic = 'force-dynamic';

export const metadata: Metadata = {
other: {
Expand All @@ -13,7 +10,5 @@ export const metadata: Metadata = {
};

export default async function SpamPolicy({ searchParams }: { searchParams: { 'profile-redirect': string } }) {
const user = await getUserFromSession();

return <SpamPolicyPage user={user} redirectToProfile={searchParams['profile-redirect'] === 'true'} />;
return <SpamPolicyPage redirectToProfile={searchParams['profile-redirect'] === 'true'} />;
}
2 changes: 1 addition & 1 deletion apps/scoutgame/app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import Script from 'next/script';
import type { ReactNode } from 'react';

import { AppProviders } from 'components/layout/AppProviders';
import { getUserFromSession } from 'lib/session/getUserFromSession';
import { getCachedUserFromSession as getUserFromSession } from 'lib/session/getUserFromSession';
import 'theme/styles.scss';

const ClientGlobals = dynamic(() => import('components/common/ClientGlobals').then((comp) => comp.ClientGlobals), {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import { currentSeason } from '@packages/scoutgame/dates';
import { getBuilderActivities } from 'lib/builders/getBuilderActivities';
import { getBuilderScouts } from 'lib/builders/getBuilderScouts';
import { getBuilderStats } from 'lib/builders/getBuilderStats';
import { getUserFromSession } from 'lib/session/getUserFromSession';
import type { BasicUserInfo } from 'lib/users/interfaces';

import { PublicBuilderProfileContainer } from './PublicBuilderProfileContainer';
Expand All @@ -19,8 +18,7 @@ export async function PublicBuilderProfile({ publicUser }: { publicUser: BasicUs
builderNft,
{ allTimePoints = 0, seasonPoints = 0, rank = 0, gemsCollected = 0 } = {},
builderActivities = [],
{ scouts = [], totalNftsSold = 0, totalScouts = 0 } = {},
user
{ scouts = [], totalNftsSold = 0, totalScouts = 0 } = {}
] = isApprovedBuilder
? await Promise.all([
prisma.builderNft.findUnique({
Expand All @@ -37,8 +35,7 @@ export async function PublicBuilderProfile({ publicUser }: { publicUser: BasicUs
}),
getBuilderStats(builderId),
getBuilderActivities({ builderId, limit: 200 }),
getBuilderScouts(builderId),
getUserFromSession()
getBuilderScouts(builderId)
])
: [];

Expand All @@ -57,7 +54,6 @@ export async function PublicBuilderProfile({ publicUser }: { publicUser: BasicUs
builderActivities={builderActivities}
gemsCollected={gemsCollected}
rank={rank}
user={user}
/>
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,6 @@ type BuilderProfileProps = {
builderActivities: BuilderActivity[];
gemsCollected?: number;
rank?: number | null;
user?: {
id: string;
username: string;
} | null;
};

const PaperContainer = styled(Paper)(({ theme }) => ({
Expand All @@ -58,8 +54,7 @@ export function PublicBuilderProfileContainer({
totalNftsSold,
builderActivities,
gemsCollected,
rank,
user
rank
}: BuilderProfileProps) {
const isDesktop = useMdScreen();

Expand Down Expand Up @@ -89,7 +84,6 @@ export function PublicBuilderProfileContainer({
hideDetails
showPurchaseButton
size='small'
userId={user?.id}
/>
</Box>
<Stack gap={1} pr={1}>
Expand Down Expand Up @@ -140,7 +134,6 @@ export function PublicBuilderProfileContainer({
gemsCollected: 0,
builderPoints: 0
}}
userId={user?.id}
hideDetails
showPurchaseButton
/>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,21 @@ import { prisma } from '@charmverse/core/prisma-client';

import { getScoutedBuilders } from 'lib/scouts/getScoutedBuilders';
import { getScoutStats } from 'lib/scouts/getScoutStats';
import { getUserFromSession } from 'lib/session/getUserFromSession';
import type { BasicUserInfo } from 'lib/users/interfaces';
import { BasicUserInfoSelect } from 'lib/users/queries';

import { PublicScoutProfileContainer } from './PublicScoutProfileContainer';

export async function PublicScoutProfile({ publicUser }: { publicUser: BasicUserInfo }) {
const [scout, { allTimePoints, seasonPoints, nftsPurchased }, scoutedBuilders, user] = await Promise.all([
const [scout, { allTimePoints, seasonPoints, nftsPurchased }, scoutedBuilders] = await Promise.all([
prisma.scout.findUniqueOrThrow({
where: {
id: publicUser.id
},
select: BasicUserInfoSelect
}),
getScoutStats(publicUser.id),
getScoutedBuilders({ scoutId: publicUser.id }),
getUserFromSession()
getScoutedBuilders({ scoutId: publicUser.id })
]);

return (
Expand All @@ -31,7 +29,6 @@ export async function PublicScoutProfile({ publicUser }: { publicUser: BasicUser
seasonPoints={seasonPoints}
nftsPurchased={nftsPurchased}
scoutedBuilders={scoutedBuilders}
userId={user?.id}
/>
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,16 +20,14 @@ export type ScoutProfileProps = {
seasonPoints: number;
nftsPurchased: number;
scoutedBuilders: BuilderInfo[];
userId?: string;
};

export function PublicScoutProfileContainer({
scout,
allTimePoints,
seasonPoints,
nftsPurchased,
scoutedBuilders,
userId
scoutedBuilders
}: ScoutProfileProps) {
const isDesktop = useMdScreen();
return (
Expand Down Expand Up @@ -68,12 +66,7 @@ export function PublicScoutProfileContainer({
Scouted Builders
</Typography>
{scoutedBuilders.length > 0 ? (
<BuildersGallery
builders={scoutedBuilders}
columns={5}
size={isDesktop ? 'large' : 'small'}
userId={userId}
/>
<BuildersGallery builders={scoutedBuilders} columns={5} size={isDesktop ? 'large' : 'small'} />
) : (
<Typography>This Scout hasn't discovered any Builders yet. Check back to see who they find!</Typography>
)}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,13 @@ export function BuilderCard({
showPurchaseButton = false,
hideDetails = false,
showHotIcon = false,
size = 'medium',
userId
size = 'medium'
}: {
size?: 'x-small' | 'small' | 'medium' | 'large';
builder: BuilderInfo;
hideDetails?: boolean;
showPurchaseButton?: boolean;
showHotIcon?: boolean;
userId?: string;
}) {
return (
<Card
Expand All @@ -48,7 +46,7 @@ export function BuilderCard({
</BuilderCardNftDisplay>
{typeof builder.price !== 'undefined' && showPurchaseButton && (
<Stack px={{ xs: 1, md: 0 }} pt={{ xs: 1, md: 2 }} pb={{ xs: 1, md: 0 }}>
<ScoutButton builder={builder} isAuthenticated={!!userId} />
<ScoutButton builder={builder} />
</Stack>
)}
</Card>
Expand Down
6 changes: 2 additions & 4 deletions apps/scoutgame/components/common/Gallery/BuildersGallery.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,12 @@ export function BuildersGallery({
builders,
columns = 6,
showHotIcon = false,
size = 'medium',
userId
size = 'medium'
}: {
builders: BuilderInfo[];
columns?: number;
showHotIcon?: boolean;
size?: 'small' | 'medium' | 'large';
userId?: string;
}) {
return (
<Box sx={{ flexGrow: 1 }}>
Expand All @@ -32,7 +30,7 @@ export function BuildersGallery({
X {builder.nftsSoldToScout ?? 0}
</Typography>
)}
<BuilderCard builder={builder} showPurchaseButton showHotIcon={showHotIcon} size={size} userId={userId} />
<BuilderCard builder={builder} showPurchaseButton showHotIcon={showHotIcon} size={size} />
</Box>
</Grid>
))}
Expand Down
3 changes: 2 additions & 1 deletion apps/scoutgame/components/common/Header/Header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,12 @@ import { InstallAppMenuItem } from './components/InstallAppMenuItem';

export function Header() {
const router = useRouter();
const { user } = useUser();
const { user, refreshUser } = useUser();
const [anchorElUser, setAnchorElUser] = useState<null | HTMLElement>(null);

const { execute: logoutUser, isExecuting: isExecutingLogout } = useAction(logoutAction, {
onSuccess: async () => {
await refreshUser();
revalidatePathAction();
router.push('/');
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ export function NFTPurchaseForm(props: NFTPurchaseProps) {
}

export function NFTPurchaseFormContent({ builder }: NFTPurchaseProps) {
const { user } = useUser();
const { user, refreshUser } = useUser();
const builderId = builder.id;
const initialQuantities = [1, 11, 111];
const pricePerNft = builder.price ? convertCostToPoints(builder.price).toLocaleString() : '';
Expand Down Expand Up @@ -147,6 +147,7 @@ export function NFTPurchaseFormContent({ builder }: NFTPurchaseProps) {
async onSuccess(res) {
if (res.data?.id) {
await checkDecentTransaction({ pendingTransactionId: res.data.id });
await refreshUser();
log.info('NFT minted', { chainId, builderTokenId, purchaseCost });
} else {
log.warn('NFT minted but no transaction id returned', {
Expand Down
12 changes: 4 additions & 8 deletions apps/scoutgame/components/common/ScoutButton/ScoutButton.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import Image from 'next/image';
import { useState } from 'react';

import type { NFTPurchaseProps } from 'components/common/NFTPurchaseDialog/components/NFTPurchaseForm';
import type { MinimalUserInfo } from 'lib/users/interfaces';
import { useUser } from 'components/layout/UserProvider';

import { DynamicLoadingContext, LoadingComponent } from '../DynamicLoading';

Expand All @@ -21,16 +21,12 @@ const NFTPurchaseDialog = dynamic(
}
);

export function ScoutButton({
builder,
isAuthenticated = true
}: {
builder: NFTPurchaseProps['builder'];
isAuthenticated?: boolean;
}) {
export function ScoutButton({ builder }: { builder: NFTPurchaseProps['builder'] }) {
const [isPurchasing, setIsPurchasing] = useState<boolean>(false);
const [authPopup, setAuthPopup] = useState<boolean>(false);
const [dialogLoadingStatus, setDialogLoadingStatus] = useState<boolean>(false);
const { user } = useUser();
const isAuthenticated = Boolean(user?.id);

const handleClick = () => {
if (isAuthenticated) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import { WarpcastIcon } from './WarpcastIcon';
export function WarpcastLoginButton({ children, ...props }: ButtonProps) {
const popupState = usePopupState({ variant: 'popover', popupId: 'warpcast-login' });
const router = useRouter();
const { setUser } = useUser();
const { refreshUser } = useUser();
const { isAuthenticated } = useProfile();
const searchParams = useSearchParams();
const redirectUrlEncoded = searchParams.get('redirectUrl');
Expand All @@ -44,7 +44,7 @@ export function WarpcastLoginButton({ children, ...props }: ButtonProps) {
return;
}

setUser(data.user);
await refreshUser(data.user);

await revalidatePath();
router.push(nextPage);
Expand Down
Loading

0 comments on commit 239f7e1

Please sign in to comment.