Skip to content
This repository has been archived by the owner on Dec 13, 2024. It is now read-only.

Commit

Permalink
- orders page template
Browse files Browse the repository at this point in the history
  • Loading branch information
mertthesamael committed Sep 14, 2023
1 parent 9e6aaf1 commit 0f1df65
Show file tree
Hide file tree
Showing 18 changed files with 205 additions and 23 deletions.
5 changes: 4 additions & 1 deletion actions/order.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,21 +12,24 @@ export const orderHandler = async (user: TUser) => {
},
});
if (targetUser) {

const res = await prisma.order.create({
data: {
products: user.basket,
userId: targetUser.id,
price: targetUser.totalPrice,
date: new Date()
},
});
if (res.id) {
let test = user.basket.length = 0
const updatedUser = await prisma.user.update({
where: {
email: user.email,
},
data: {
totalPrice: 0,
basket: [],
basket: []
},
});
return updatedUser;
Expand Down
22 changes: 22 additions & 0 deletions app/api/user/orders/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { prisma } from "@/db/client";
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";

export const dynamic = "force-dynamic";

export async function POST(request: NextRequest) {
const { userId } = await request.json();
try {
const res = await prisma.order.findMany({
where: {
userId: userId,
},
});

return NextResponse.json({ data: res });
} catch (err) {
console.log(err);
} finally {
await prisma.$disconnect();
}
}
34 changes: 34 additions & 0 deletions app/orders/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import OrdersOrdersSection from "@/containers/orders-page/orders-section";
import OrdersTitleSection from "@/containers/orders-page/title-section";
import React, { FC } from "react";
import createClient from "@/db/client";
import axios from "axios";
import { redirect } from "next/navigation";
import { getOrders } from "@/libs/endpoints";

interface OrdersPageProps {}

const getUserOrders = async (id: string) => {
const { data } = await axios.post(getOrders, {});
return data;
};
const OrdersPage: FC<OrdersPageProps> = async ({}) => {
const supabase = createClient();

const {
data: { user },
} = await supabase.auth.getUser();
if (!user) {
redirect("/");
}
const { data } = await getUserOrders(user.email ?? user.user_metadata.email);

return (
<main>
<OrdersTitleSection />
<OrdersOrdersSection orders={data} />
</main>
);
};

export default OrdersPage;
23 changes: 23 additions & 0 deletions components/Cards/OrderCard/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { TOrder } from '@/types/Order';
import React, { FC } from 'react'

interface OrderCardProps {
order:TOrder
}

const OrderCard: FC<OrderCardProps> = ({ order }) => {
return (
<div className='w-max h-max rounded-lg shadow-lg p-6'>
<div>
<h1 className='text-black text-base'>{order.date.toString(

)}</h1>
</div>
<div>

</div>
</div>
)
}

export default OrderCard;
2 changes: 1 addition & 1 deletion components/Header/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ const Header: FC<HeaderProps> = async ({ user }) => {
<HeaderNav key={_i} value={el.value} id={el.id} href={el.href} />
))}
</nav>
{targetUser && <HeaderUserActions targetUser={targetUser} />}
<HeaderUserActions targetUser={targetUser} />
<div className="flex lg:hidden">
<HamburgerButton />
</div>
Expand Down
8 changes: 3 additions & 5 deletions components/Header/user-actions/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,16 @@ import PrimaryButton from "@/components/Buttons/PrimaryButton";
import { Basket } from "@/components/Icons/Basket";
import { Profile } from "@/components/Icons/Profile";
import { handleSignOut } from "@/db/auth";
import { postBasket } from "@/libs/endpoints";
import { useUserStore } from "@/store/useUserStore";
import { TUser } from "@/types/User";
import { createClientComponentClient } from "@supabase/auth-helpers-nextjs";
import axios from "axios";
import Link from "next/link";
import { useRouter } from "next/navigation";
import React, { FC, useEffect, useState } from "react";
import { toast } from "react-toastify";

interface HeaderUserActionsProps {
targetUser: TUser;
targetUser?: TUser;
}

const HeaderUserActions: FC<HeaderUserActionsProps> = ({ targetUser }) => {
Expand All @@ -32,7 +30,7 @@ const HeaderUserActions: FC<HeaderUserActionsProps> = ({ targetUser }) => {
};

const getUser = async () => {
if (!user) {
if (!user&&targetUser) {
handleUser(targetUser);
}
};
Expand All @@ -54,7 +52,7 @@ const HeaderUserActions: FC<HeaderUserActionsProps> = ({ targetUser }) => {
}, []);
return (
<div className={`gap-6 w-40 justify-end hidden lg:flex `}>
<div className="flex relative flex-col">
<div className={`flex relative flex-col ${user ? 'flex' : 'hidden'}`}>
<Link href={"/checkout"}>
<div className="flex">
<Basket />
Expand Down
12 changes: 10 additions & 2 deletions containers/checkout-page/form-section/items/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,22 @@
import { orderHandler } from "@/actions/order";
import PrimaryButton from "@/components/Buttons/PrimaryButton";
import BasketCard from "@/components/Cards/BasketCard";
import useCreateQueryString from "@/hooks/useQueryString";
import { postBasket } from "@/libs/endpoints";
import { useUserStore } from "@/store/useUserStore";
import axios from "axios";
import { useRouter } from "next/navigation";
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import React, { FC } from "react";
import { toast } from "react-toastify";

interface BasketItemsProps {}

const BasketItems: FC<BasketItemsProps> = ({}) => {
const { user, handleUser } = useUserStore();
const router = useRouter();
const searchParams = useSearchParams()
const pathname = usePathname()
const createQueryString = useCreateQueryString()
const removeBasketItems = async () => {
const { data } = await axios.post(postBasket, {
action: "wipe",
Expand Down Expand Up @@ -40,6 +45,9 @@ const BasketItems: FC<BasketItemsProps> = ({}) => {
const updatedUser = await orderHandler(user);
if (updatedUser) {
handleUser(updatedUser);
router.push(pathname + "?" + createQueryString('complate','true'))
}else{
toast.error('error')
}
};
return (
Expand All @@ -49,7 +57,7 @@ const BasketItems: FC<BasketItemsProps> = ({}) => {
</div>
<div className="flex flex-wrap justify-between self-start">
{user?.basket.map((el, _i) => (
<BasketCard item={el} />
<BasketCard key={_i} item={el} />
))}
</div>
<div className="flex gap-2">
Expand Down
24 changes: 24 additions & 0 deletions containers/orders-page/orders-section/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import OrderCard from '@/components/Cards/OrderCard';
import { TBasketItem } from '@/types/BasketItem';
import { TOrder } from '@/types/Order';
import React, { FC } from 'react'

interface OrdersOrdersSectionProps {
orders:TOrder[]
}

// WHAT A COMPONENT NAME LOL
const OrdersOrdersSection: FC<OrdersOrdersSectionProps> = ({ orders }) => {
console.log(orders)
return (
<section className="flex w-full justify-center">
<div className="flex flex-col py-10 md:py-28 items-center gap-8 md:gap-24 w-full max-w-screen-xl mx-5 md:mx-20">
{orders.map((el,_i) => (
<OrderCard key={_i} order={el}/>
))}
</div>
</section>
)
}

export default OrdersOrdersSection;
17 changes: 17 additions & 0 deletions containers/orders-page/title-section/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import React, { FC } from 'react'

interface OrdersTitleSectionProps {

}

const OrdersTitleSection: FC<OrdersTitleSectionProps> = ({ }) => {
return (
<section className="flex w-full justify-center">
<div className="flex flex-col py-10 md:py-28 items-center gap-8 md:gap-24 w-full max-w-screen-xl mx-5 md:mx-20">
<h1 className="text-2xl lg:text-6xl text-black font-bold">Your Orders</h1>
</div>
</section>
)
}

export default OrdersTitleSection;
32 changes: 18 additions & 14 deletions containers/product-page/item-section/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,20 +34,24 @@ const ItemSection: FC<ItemSectionProps> = ({ item }) => {
(color) => color === selectedColor
).length;
if (isValidColor > 0) {
const { data } = await axios.post(postBasket, {
action: "add",
user: user,
payload: {
item: item,
id: cryptoRandomString({ length: 15 }),
color: selectedColor,
},
});
if (data) {
toast.success(item.name+'Successfully added to your basket!')
return handleUser(data.result);
} else {
return toast.error("Something Went Wrong");
try {
const { data } = await axios.post(postBasket, {
action: "add",
user: user,
payload: {
item: item,
id: cryptoRandomString({ length: 15 }),
color: selectedColor,
},
});
if (data) {
toast.success(item.name + "Successfully added to your basket!");
return handleUser(data.result);
} else {
return toast.error("Something Went Wrong");
}
} catch (err) {
return toast.error("You need to Login first");
}
}
return toast.error("Wrong color");
Expand Down
5 changes: 5 additions & 0 deletions libs/endpoints.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,8 @@ export const postBasket =
(process.env.NEXT_PUBLIC_SITE_URL ??
process?.env?.NEXT_PUBLIC_VERCEL_URL ??
"http://localhost:3000") + "/api/user/basket";

export const getOrders =
(process.env.NEXT_PUBLIC_SITE_URL ??
process?.env?.NEXT_PUBLIC_VERCEL_URL ??
"http://localhost:3000") + "/api/user/orders";
8 changes: 8 additions & 0 deletions prisma/migrations/20230914090140_/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
/*
Warnings:
- Added the required column `date` to the `Order` table without a default value. This is not possible if the table is not empty.
*/
-- AlterTable
ALTER TABLE "Order" ADD COLUMN "date" TIMESTAMP(3) NOT NULL;
2 changes: 2 additions & 0 deletions prisma/migrations/20230914091101_/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "Order" ALTER COLUMN "date" SET DATA TYPE TEXT;
9 changes: 9 additions & 0 deletions prisma/migrations/20230914091541_/migration.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
/*
Warnings:
- Changed the type of `date` on the `Order` table. No cast exists, the column would be dropped and recreated, which cannot be done if there is data, since the column is required.
*/
-- AlterTable
ALTER TABLE "Order" DROP COLUMN "date",
ADD COLUMN "date" TIMESTAMP(3) NOT NULL;
1 change: 1 addition & 0 deletions prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ model Order {
user User @relation(fields: [userId], references: [id])
userId Int
price Float
date DateTime
}

enum Category {
Expand Down
13 changes: 13 additions & 0 deletions services/dateTimeFormatter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
export const formatDateToSQLDateTime = (date: Date) : string => {
// Get the ISO string of the Date object
const isoString = date.toISOString();

// Extract the date and time components
const datePart = isoString.slice(0, 10);
const timePart = isoString.slice(11, 19);

// Combine them in the SQL datetime format
const sqlDateTime = `${datePart} ${timePart}`;

return sqlDateTime;
}
10 changes: 10 additions & 0 deletions types/Order.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { TBasketItem } from "./BasketItem"


export type TOrder = {
id:number,
userId:number,
products:TBasketItem[],
price:number,
date:Date
}
1 change: 1 addition & 0 deletions types/User.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import { JsonValue } from "@prisma/client/runtime/library";
import { TProduct } from "./Product";
import { TBasketItem } from "./BasketItem";

export type TUser = TPureUser | null;

Expand Down

0 comments on commit 0f1df65

Please sign in to comment.