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

Feature/favourites page #504

Open
wants to merge 6 commits into
base: main
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
38 changes: 38 additions & 0 deletions packages/backend/src/api/routes/profile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,44 @@ export const initProfileRoutes = (
}),
);

/**
* @openapi
* /profile/favourites-list:
* get:
* description: Get user's favourites items data
* security:
* - Bearer: []
* tags: [Items]
* produces:
* - application/json
* responses:
* 200:
* description: Ok
* content:
* application/json:
* schema:
* type: object
* $ref: "#/definitions/MyListItem"
* 4**:
* description: Something went wrong
* content:
* application/json:
* schema:
* $ref: "#/definitions/Response400"
*/
router.get(
apiPath(path, AccountApiRoutes.FAVOURITES_LIST),
authMiddleware,
wrap(async (req: Request) => {
const { userId } = req;
await profileService.getUser({
userId,
});

return await myListService.getFavourites({ userId });
}),
);

/**
* @openapi
* /profile/save:
Expand Down
54 changes: 36 additions & 18 deletions packages/backend/src/repositories/my-list.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,7 @@
import type {
Prisma,
PrismaClient,
PrismaPromise,
Product,
} from '@prisma/client';
import type { Prisma, PrismaClient, Product } from '@prisma/client';
import { ProductStatus } from '@prisma/client';
import { Order } from '@vse-bude/shared';
import type { Item } from 'common/types/my-list-items';
import type { Item } from '@types';

export class MyListRepository {
private _dbClient: PrismaClient;
Expand All @@ -15,7 +10,7 @@ export class MyListRepository {
itemId,
}: {
itemId: string;
}): PrismaPromise<Prisma.BatchPayload> {
}): Promise<Prisma.BatchPayload> {
return this._dbClient.bid.deleteMany({
where: {
productId: itemId,
Expand All @@ -27,7 +22,7 @@ export class MyListRepository {
this._dbClient = prismaClient;
}

public getSoldItems({ userId }: { userId: string }): PrismaPromise<Item[]> {
public getSoldItems({ userId }: { userId: string }): Promise<Item[]> {
return this._dbClient.product.findMany({
where: {
authorId: userId,
Expand Down Expand Up @@ -57,7 +52,7 @@ export class MyListRepository {
});
}

public getPostedItems({ userId }: { userId: string }): PrismaPromise<Item[]> {
public getPostedItems({ userId }: { userId: string }): Promise<Item[]> {
return this._dbClient.product.findMany({
where: {
authorId: userId,
Expand All @@ -80,11 +75,7 @@ export class MyListRepository {
});
}

public getDraftedItems({
userId,
}: {
userId: string;
}): PrismaPromise<Item[]> {
public getDraftedItems({ userId }: { userId: string }): Promise<Item[]> {
return this._dbClient.product.findMany({
where: {
authorId: userId,
Expand All @@ -106,7 +97,7 @@ export class MyListRepository {
});
}

public getArchived({ userId }: { userId: string }): PrismaPromise<Item[]> {
public getArchived({ userId }: { userId: string }): Promise<Item[]> {
return this._dbClient.product.findMany({
where: {
authorId: userId,
Expand Down Expand Up @@ -135,7 +126,7 @@ export class MyListRepository {
}: {
itemId: string;
postDate: string;
}): PrismaPromise<Item> {
}): Promise<Item> {
return this._dbClient.product.update({
where: {
id: itemId,
Expand Down Expand Up @@ -164,7 +155,7 @@ export class MyListRepository {
}: {
itemId: string;
updatedAt: string;
}): PrismaPromise<Item> {
}): Promise<Item> {
this._deleteBids({ itemId });

return this._dbClient.product.update({
Expand Down Expand Up @@ -207,6 +198,33 @@ export class MyListRepository {
});
}

public getFavourites({
userId,
}: {
userId: string;
}): Promise<{ product: Item }[]> {
return this._dbClient.favoriteProducts.findMany({
where: {
userId,
},
select: {
product: {
select: {
id: true,
title: true,
description: true,
price: true,
type: true,
status: true,
endDate: true,
updatedAt: true,
imageLinks: true,
},
},
},
});
}

public deleteProduct({ productId }: { productId: string }): Promise<Product> {
return this._dbClient.product.delete({
where: {
Expand Down
20 changes: 20 additions & 0 deletions packages/backend/src/services/my-list.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,26 @@ export class MyListService {
});
}

public async getFavourites({
userId,
}: {
userId: string;
}): Promise<Item[] | []> {
const items = await this._myListRepository.getFavourites({ userId });
if (items.length) {
const mapped = items.reduce((prev, item) => {
const favItem = { ...item.product };
prev.push(favItem);

return prev;
}, []);

return mapped;
}

return [];
}

public async deleteProduct({
productId,
}: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { useRouter } from 'next/router';
import { IconName, IconColor, Routes } from '@enums';
import { useEffect } from 'react';
import { fetchUserNotifications } from '@store';
import { NOTIFICATIONS_FILTER } from '@vse-bude/shared';
import { NOTIFICATIONS_FILTER, AccountApiRoutes } from '@vse-bude/shared';
import * as styles from './styles';
import { DownArrow } from './sub-components/dropdown';
import { PopoverContent } from './sub-components/popover-content';
Expand Down Expand Up @@ -39,7 +39,10 @@ export const ProfileInfo = ({ load }: ProfileInfoProps) => {
<div css={styles.profileInfo} profile-load={load.toString()}>
<div css={styles.iconsWrapper}>
{/* change link */}
<InternalLink href={Routes.DEFAULT} cssExtend={styles.icons}>
<InternalLink
href={`${Routes.PROFILE}${AccountApiRoutes.FAVOURITES_LIST}`}
cssExtend={styles.icons}
>
<Icon
icon={IconName.STAR_OUTLINED}
size="md"
Expand Down
1 change: 1 addition & 0 deletions packages/frontend/components/item/countdown-timer/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './component';
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './component';
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './component';
2 changes: 2 additions & 0 deletions packages/frontend/components/item/image-slider/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * from './image-slider-large';
export * from './image-slider-small';
1 change: 1 addition & 0 deletions packages/frontend/components/item/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export * from './component';
export * from './countdown-timer';
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { Container } from '@components/primitives';

export const FavouritesItems = () => (
<Container>
<div>{'Favourites'}</div>;
</Container>
);
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './component';
1 change: 1 addition & 0 deletions packages/frontend/components/profile/user-account/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export { PersonalInfo } from './personal-info';
export { MyListInfo } from './my-list';
export { FavouritesItems } from './favourites-list';
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ export const Archived = ({ data }: CardProps) => {
const [showSeeItemTooltip, setSeeItemTooltip] = useState(false);
const { t } = useTranslation();
const { id, title, imageLinks, price, description, updatedAt, type } = data;

const dispatch = useAppDispatch();
const router = useRouter();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ export const Sold = ({ data }: CardProps) => {
const [showSeeItemTooltip, setSeeItemTooltip] = useState(false);
const router = useRouter();
const { t } = useTranslation();

const {
id: itemId,
title,
Expand All @@ -31,6 +32,7 @@ export const Sold = ({ data }: CardProps) => {
updatedAt,
type,
} = data;

const { id, avatar, firstName, lastName } = winner;

const onSeeItemClick = () => {
Expand All @@ -43,6 +45,7 @@ export const Sold = ({ data }: CardProps) => {
<div css={styles.leftContent}>
<ItemImage src={imageLinks[0]} title={title} />
<ItemDate size="lg" time={updatedAt} />

<div css={styles.buttonWrapper}>
{showSeeItemTooltip ? (
<Tooltip>{t('my-list:card.tooltip-seeItem')}</Tooltip>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,6 @@ export type ItemCard = {
imageLinks: string[];
price: number;
type: string;
recommendedPrice?: number;
minimalBid?: number;
author: UserProfileDto;
winner: UserProfileDto;
views: number;
Expand Down
5 changes: 4 additions & 1 deletion packages/frontend/hooks/favorite-product.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import type { RootState } from '@types';
import { useMemo } from 'react';
import { useTypedSelector } from './store';

export const useInFavorite = (productId: string) => {
const { productsIds } = useTypedSelector((state) => state.favoriteProduct);
const productsIds = useTypedSelector(
(state: RootState) => state.favoriteProduct.productsIds,
);

return useMemo(
() => productsIds.includes(productId),
Expand Down
42 changes: 42 additions & 0 deletions packages/frontend/pages/profile/favourites-list.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
import { withProtected } from '@hocs';
import { AuthHelper, CookieStorage } from '@helpers';
import { Http } from '@vse-bude/shared';
import { fetchFavouritesSSR, wrapper } from 'store';
import { Layout } from '@components/layout';
import { FavouritesItems } from '@components/profile/user-account';

export const getServerSideProps = withProtected(
wrapper.getServerSideProps((store) => async (ctx) => {
const { locale } = ctx;
const cookieStorage = new CookieStorage(ctx);
const auth = new AuthHelper(cookieStorage);

const httpClient = new Http(
process.env.NEXT_PUBLIC_API_ROUTE,
locale,
auth,
);

await store.dispatch(fetchFavouritesSSR({ http: httpClient }));

return {
props: {
...(await serverSideTranslations(locale, [
'common',
'account',
'personal-info',
'my-list',
])),
},
};
}),
);

const FavouritesPage = () => (
<Layout>
<FavouritesItems />
</Layout>
);

export default FavouritesPage;
2 changes: 1 addition & 1 deletion packages/frontend/public/locales/en/item.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@
},
"buttons": {
"editBtn": "Edit",
"placeBid": "Place Bid",
"placeBid": "Place a Bid",
"buyBtn": "Buy",
"tooltips": {
"favBtn": "You can add product to your favorites list for a quick availability!",
Expand Down
1 change: 1 addition & 0 deletions packages/frontend/services/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@ export * from './auth';
export * from './account';
export * from './profile';
export * from './my-list';
export * from './product';
5 changes: 5 additions & 0 deletions packages/frontend/services/my-list.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,11 @@ export const addProductToPosted = ({ data }: { data: ProductPost }) =>
body: data,
});

export const getFavouritesSSR = (params: { http: Http }) =>
params.http.get({
url: `${ApiRoutes.PROFILE}${AccountApiRoutes.FAVOURITES_LIST}`,
});

export const deleteProduct = ({
productId,
}: {
Expand Down
1 change: 1 addition & 0 deletions packages/frontend/store/favorite-product/action-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@ export enum FavoriteProductActions {
ADD_PRODUCT_TO_FAVORITES = 'product/add-to-favorites',
DELETE_PRODUCT_FROM_FAVORITES = 'product/delete-from-favorites',
GET_FAVORITE_PRODUCT_IDS = 'product/get-favorite-ids',
FETCH_FAVOURITES = 'favourites/list',
}
19 changes: 18 additions & 1 deletion packages/frontend/store/favorite-product/actions.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import { createAsyncThunk } from '@reduxjs/toolkit';
import { addToast } from 'store/toast/actions';
import type { Http } from '@vse-bude/shared';
import {
addToFavorites,
deleteFromFavorites,
fetchFavoriteProductsIds,
} from '../../services/product';
getFavouritesSSR,
} from '@services';
import { FavoriteProductActions } from './action-types';

export const getFavoriteIds = createAsyncThunk(
Expand Down Expand Up @@ -70,3 +72,18 @@ export const deleteProductFromFavorites = createAsyncThunk(
}
},
);

export const fetchFavouritesSSR = createAsyncThunk(
FavoriteProductActions.FETCH_FAVOURITES,
async (params: { http: Http }, { rejectWithValue, dispatch }) =>
getFavouritesSSR(params).catch((e) => {
dispatch(
addToast({
level: 'error',
description: e.message,
}),
);

return rejectWithValue(e.message);
}),
);
Loading