Skip to content

Commit

Permalink
not logged in redirect
Browse files Browse the repository at this point in the history
  • Loading branch information
yurytut1993 committed Aug 13, 2024
1 parent f6d2eef commit ae08ecb
Show file tree
Hide file tree
Showing 14 changed files with 77 additions and 130 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,12 @@ import { revalidatePath } from 'next/cache';

import {
DeleteWishlists,
deleteWishlists as deleteWishlistsClient,
deleteWishlists as deleteWishlistsMutation,
} from '~/client/mutations/delete-wishlists';

export const deleteWishlists = async (wishlists: DeleteWishlists) => {
try {
const result = await deleteWishlistsClient(wishlists);
const result = await deleteWishlistsMutation(wishlists);

revalidatePath('/account/wishlists', 'page');

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import { revalidatePath } from 'next/cache';
import { z } from 'zod';

import { createWishlist as createWishlistClient } from '~/client/mutations/create-wishlist';
import { createWishlist as createWishlistMutation } from '~/client/mutations/create-wishlist';

const CreateWishlistSchema = z.object({
name: z.string(),
Expand All @@ -20,7 +20,7 @@ export const createWishlist = async (formData: FormData) => {
};

try {
const newWishlist = await createWishlistClient({ input });
const newWishlist = await createWishlistMutation({ input });

revalidatePath('/account/wishlists', 'page');

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@ import { getLocale, getTranslations } from 'next-intl/server';

import { Pagination } from '~/components/ui/pagination';

import { getWishlistQuery } from '../../page-data';
import { getWishlists } from '../../page-data';
import { TabHeading } from '../tab-heading';

import { WishlistBook } from './wishlist-book';

type WishlistsDetails = NonNullable<Awaited<ReturnType<typeof getWishlistQuery>>>;
type WishlistsDetails = NonNullable<Awaited<ReturnType<typeof getWishlists>>>;
export type Wishlists = WishlistsDetails['wishlists'];

interface Props {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,13 +89,13 @@ const HiddenQuantity = ({ itemsQuantity }: WishlistItemsCount) => {
const Wishlist = ({ onWishlistDeleted, openModal, setOpenModal, wishlist }: WishlistProps) => {
const t = useTranslations('Account.Wishlist');
const { entityId, name } = wishlist;
const items = 'items' in wishlist ? wishlist.items : undefined;
const items = 'items' in wishlist ? wishlist.items : [];

return (
<>
<h3 className="mb-2 text-lg font-bold">{name}</h3>
<div className="flex w-full flex-col items-start justify-between lg:flex-row">
{!items ? (
{items.length === 0 ? (
<p className="flex-1 py-4 text-center">{t('noItems')}</p>
) : (
<div className="mb-4 flex gap-4 lg:me-12">
Expand Down Expand Up @@ -140,7 +140,11 @@ const Wishlist = ({ onWishlistDeleted, openModal, setOpenModal, wishlist }: Wish
<HiddenQuantity itemsQuantity={items.length} />
</div>
)}
{name !== t('favorites') && (
{name === t('favorites') ? (
<Button className="invisible w-auto" variant="secondary">
{t('delete')}
</Button>
) : (
<div>
<Modal
confirmationText={t('confirmDelete', { name })}
Expand Down
26 changes: 14 additions & 12 deletions core/app/[locale]/(default)/account/[tab]/page-data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,13 @@ import { cache } from 'react';
import { getSessionCustomerId } from '~/auth';
import { client } from '~/client';
import { FORM_FIELDS_FRAGMENT } from '~/client/fragments/form-fields';
import { PAGE_DETAILS_FRAGMENT } from '~/client/fragments/page-details';
import { graphql, VariablesOf } from '~/client/graphql';
import { PricingFragment } from '~/components/pricing';

import { GalleryFragment } from '../../product/[slug]/_components/gallery/fragment';

const WishlistQuery = graphql(
const WishlistsQuery = graphql(
`
query WishlistQuery(
$filters: WishlistFiltersInput
Expand All @@ -21,10 +22,7 @@ const WishlistQuery = graphql(
customer {
wishlists(filters: $filters, after: $after, before: $before, first: $first, last: $last) {
pageInfo {
hasNextPage
hasPreviousPage
startCursor
endCursor
...PageDetails
}
edges {
node {
Expand Down Expand Up @@ -55,22 +53,26 @@ const WishlistQuery = graphql(
}
}
`,
[GalleryFragment, PricingFragment],
[GalleryFragment, PAGE_DETAILS_FRAGMENT, PricingFragment],
);

export interface WishlistArgs {
after?: string;
before?: string;
type WishlistsVariables = VariablesOf<typeof WishlistsQuery>;
type WishlistsFiltersInput = WishlistsVariables['filters'];

interface GetWishlists {
limit?: number;
before?: string;
after?: string;
filters: WishlistsFiltersInput;
}

export const getWishlistQuery = cache(async ({ before, after, limit = 3 }: WishlistArgs) => {
export const getWishlists = cache(async ({ limit = 3, before, after, filters }: GetWishlists) => {
const customerId = await getSessionCustomerId();
const paginationArgs = before ? { last: limit, before } : { first: limit, after };

const response = await client.fetch({
document: WishlistQuery,
variables: { ...paginationArgs },
document: WishlistsQuery,
variables: { ...filters, ...paginationArgs },
fetchOptions: { cache: 'no-store' },
customerId,
});
Expand Down
4 changes: 2 additions & 2 deletions core/app/[locale]/(default)/account/[tab]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { SettingsContent } from './_components/settings-content';
import { TabHeading } from './_components/tab-heading';
import { WishlistContent, WISHLISTS_PER_PAGE } from './_components/wishlist-content';
import { TabType } from './layout';
import { getCustomerSettingsQuery, getWishlistQuery } from './page-data';
import { getCustomerSettingsQuery, getWishlists } from './page-data';

interface Props {
params: {
Expand Down Expand Up @@ -69,7 +69,7 @@ export default async function AccountTabPage({ params: { tab }, searchParams }:
case 'wishlists': {
const { before, after } = searchParams;

const wishlistDetails = await getWishlistQuery({
const wishlistDetails = await getWishlists({
...(after && { after }),
...(before && { before }),
limit: WISHLISTS_PER_PAGE,
Expand Down
13 changes: 12 additions & 1 deletion core/app/[locale]/(default)/account/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { BookUser, Eye, Gift, Mail, Package, Settings } from 'lucide-react';
import { getTranslations } from 'next-intl/server';
import { ReactNode } from 'react';

import { createWishlist } from '~/client/mutations/create-wishlist';
import { Link } from '~/components/link';
import { LocaleType } from '~/i18n';

Expand All @@ -27,14 +28,24 @@ const AccountItem = ({ children, title, description, href }: AccountItem) => {
);
};

interface SearchParams {
register?: string;
}

interface Props {
params: {
locale: LocaleType;
};
searchParams?: SearchParams;
}

export default async function AccountPage({ params: { locale } }: Props) {
export default async function AccountPage({ params: { locale }, searchParams }: Props) {
const t = await getTranslations({ locale, namespace: 'Account.Home' });
const isRegister = searchParams?.register?.toLowerCase() === 'true';

if (isRegister) {
await createWishlist({ input: { name: t('favorites'), isPublic: true } });
}

return (
<div className="mx-auto">
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
'use server';

import { isRedirectError } from 'next/dist/client/components/redirect';
import { redirect } from 'next/navigation';

import { Credentials, signIn } from '~/auth';

Expand All @@ -16,10 +15,8 @@ export const login = async (formData: FormData) => {
...credentials,
// We want to use next/navigation for the redirect as it
// follows basePath and trailing slash configurations.
redirect: false,
redirectTo: '/account?register=true',
});

redirect('/account');
} catch (error: unknown) {
if (isRedirectError(error)) {
throw error;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -187,18 +187,9 @@ export const RegisterCustomerForm = ({
const submit = await registerCustomer({ formData, reCaptchaToken });

if (submit.status === 'success') {
form.current?.reset();
setFormStatus({
status: 'success',
message: t('successMessage', {
firstName: submit.data?.firstName,
lastName: submit.data?.lastName,
}),
});
void login(formData);

setTimeout(() => {
void login(formData);
}, 3000);
return;
}

if (submit.status === 'error') {
Expand Down
16 changes: 11 additions & 5 deletions core/app/[locale]/(default)/product/[slug]/_components/details.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { removeEdgesAndNodes } from '@bigcommerce/catalyst-client';
import { useFormatter, useTranslations } from 'next-intl';
import { getFormatter, getTranslations } from 'next-intl/server';

import { auth } from '~/auth';
import { FragmentOf, graphql } from '~/client/graphql';
import { ProductForm } from '~/components/product-form';
import { ProductFormFragment } from '~/components/product-form/fragment';
Expand Down Expand Up @@ -77,15 +78,20 @@ interface Props {
wishlists: Wishlists;
}

export const Details = ({ product, wishlists }: Props) => {
const t = useTranslations('Product.Details');
const format = useFormatter();
export const Details = async ({ product, wishlists }: Props) => {
// const t = useTranslations('Product.Details');
// const format = useFormatter();
const t = await getTranslations('Product.Details');
const format = await getFormatter();
const session = await auth();

const customFields = removeEdgesAndNodes(product.customFields);

const showPriceRange =
product.prices?.priceRange.min.value !== product.prices?.priceRange.max.value;

console.log('Details Component');

return (
<div>
{product.brand && (
Expand Down Expand Up @@ -160,7 +166,7 @@ export const Details = ({ product, wishlists }: Props) => {
</div>
)}

<ProductForm data={product} wishlists={wishlists} />
<ProductForm data={product} isLogged={Boolean(session)} wishlists={wishlists} />

<div className="my-12">
<h2 className="mb-4 text-xl font-bold md:text-2xl">{t('additionalDetails')}</h2>
Expand Down
53 changes: 0 additions & 53 deletions core/client/queries/get-wishlists.ts

This file was deleted.

17 changes: 14 additions & 3 deletions core/components/product-form/index.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
'use client';

import { removeEdgesAndNodes } from '@bigcommerce/catalyst-client';
import { AlertCircle, Check, ShoppingCart } from 'lucide-react';
import { AlertCircle, Check, Heart, ShoppingCart } from 'lucide-react';
import { useTranslations } from 'next-intl';
import { FormProvider, useFormContext } from 'react-hook-form';
import { toast } from 'react-hot-toast';
Expand All @@ -11,6 +11,7 @@ import { FragmentOf } from '~/client/graphql';

import { AddToCartButton } from '../add-to-cart-button';
import { Link } from '../link';
import { Button } from '../ui/button';
import { WishlistSheet } from '../wishlist-sheet';

import { handleAddToCart } from './_actions/add-to-cart';
Expand All @@ -30,6 +31,7 @@ interface SubmitProps {

interface ProductFormProps {
data: FragmentOf<typeof ProductFormFragment>;
isLogged: boolean;
wishlists: Wishlists;
}

Expand All @@ -44,7 +46,7 @@ export const Submit = ({ data: product }: SubmitProps) => {
);
};

export const ProductForm = ({ data: product, wishlists }: ProductFormProps) => {
export const ProductForm = ({ data: product, isLogged, wishlists }: ProductFormProps) => {
const t = useTranslations('AddToCart');
const productOptions = removeEdgesAndNodes(product.productOptions);

Expand Down Expand Up @@ -123,7 +125,16 @@ export const ProductForm = ({ data: product, wishlists }: ProductFormProps) => {

<div className="mt-4 flex flex-col gap-4 @md:flex-row">
<Submit data={product} />
<WishlistSheet productId={product.entityId} wishlistsData={wishlists} />
{isLogged ? (
<WishlistSheet productId={product.entityId} wishlistsData={wishlists} />
) : (
<Button asChild type="button" variant="secondary">
<Link href="/login">
<Heart aria-hidden="true" className="mr-2" />
<span>{t('saveToWishlist')}</span>
</Link>
</Button>
)}
</div>
</form>
</FormProvider>
Expand Down
Loading

0 comments on commit ae08ecb

Please sign in to comment.