Products are nearly finished, also switched to mock api

This commit is contained in:
Thastertyn committed 2025-04-19 11:02:13 +02:00
1 parent 0986336aea
commit c60ec969d5
27 files changed
+1486 -276

No files matched your search

@@ -0,0 +1,152 @@
import React from "react";
import Placeholder from "@/assets/placeholder.svg?react";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogFooter
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Separator } from "@/components/ui/separator";
import { UseFormReturn } from "react-hook-form";
import { ProductForm } from "../hooks/use-product-form";
interface ProductDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
form: UseFormReturn<ProductForm>;
onSubmit: (e?: React.BaseSyntheticEvent) => void;
onDelete?: () => void;
onImageUpload: (e: React.ChangeEvent<HTMLInputElement>) => void;
submitLabel: string;
imagePreview?: string;
showDeleteButton?: boolean;
}
export default function ProductDialog({
open,
onOpenChange,
form,
onSubmit,
onDelete,
onImageUpload,
submitLabel,
imagePreview,
showDeleteButton = false
}: ProductDialogProps) {
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-2xl">
<DialogHeader>
<DialogTitle className="text-2xl font-semibold">
{submitLabel} Product
</DialogTitle>
</DialogHeader>
<form onSubmit={onSubmit} className="space-y-6">
{/* Main fields grid */}
<div className="grid grid-cols-1 gap-6 sm:grid-cols-2">
{/* Name field */}
<div className="flex flex-col justify-between">
<Label htmlFor="name" className="mb-1">
Product Name
</Label>
<Input
id="name"
{...form.register("name")}
placeholder="Enter product name"
/>
{form.formState.errors.name && (
<p className="text-sm text-red-500">
{form.formState.errors.name.message}
</p>
)}
<div className="flex flex-col">
<Label htmlFor="price" className="mb-1">
Price
</Label>
<Input
id="price"
type="number"
{...form.register("price", { valueAsNumber: true })}
placeholder="0.00"
/>
</div>
<div className="flex flex-col">
<Label htmlFor="stock_quantity" className="mb-1">
Stock
</Label>
<Input
id="stock_quantity"
type="number"
{...form.register("stock_quantity", { valueAsNumber: true })}
placeholder="0"
/>
</div>
</div>
{/* Image upload & preview */}
<div className="flex flex-col items-center">
<Label htmlFor="image">Image</Label>
{imagePreview ? (
<img
src={imagePreview}
alt="Preview"
className="mb-2 h-48 w-48 rounded-lg border object-cover"
/>
) : (
<Placeholder className="h-48 w-48 fill-gray-100 dark:fill-slate-900 text-slate-900 dark:text-zinc-500" />
)}
<p className="text-xs text-muted-foreground select-none">
JPG or PNG only. Max size: 2MB.
</p>
<Input
id="image"
type="file"
accept="image/png, image/jpeg"
onChange={onImageUpload}
className="pt-1"
/>
</div>
{/* Description spanning full width */}
<div className="sm:col-span-2">
<Label htmlFor="description">Description</Label>
<Textarea
id="description"
{...form.register("description")}
placeholder="Short product description"
rows={4}
/>
{form.formState.errors.description && (
<p className="text-sm text-red-500">
{form.formState.errors.description.message}
</p>
)}
</div>
</div>
<Separator />
{/* Action buttons */}
<DialogFooter className="flex justify-end space-x-3">
{showDeleteButton && onDelete && (
<Button variant="destructive" type="button" onClick={onDelete}>
Delete
</Button>
)}
<Button type="submit">{submitLabel}</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
);
}
@@ -0,0 +1,93 @@
import { Button } from "@/components/ui/button";
import { DialogFooter } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { UseFormReturn } from "react-hook-form";
import { z } from "zod";
const schema = z.object({
name: z.string().min(1, "Name is required"),
description: z.string().min(1, "Description is required"),
price: z.coerce.number().min(0),
stock_quantity: z.coerce.number().int().min(0),
image_data: z.string().optional()
});
type ProductForm = z.infer<typeof schema>;
export function ProductForm({
onSubmit,
form,
imagePreview,
onImageUpload,
submitLabel
}: {
onSubmit: () => void;
form: UseFormReturn<typeof ProductForm>;
imagePreview?: string;
onImageUpload: (e: React.ChangeEvent<HTMLInputElement>) => void;
submitLabel: string;
}) {
return (
<form onSubmit={onSubmit} className="grid gap-4 py-4">
<div className="grid gap-1">
<Label htmlFor="name">Product Name</Label>
<Input {...form.register("name")} placeholder="Product name" />
{form.formState.errors.name && (
<p className="text-sm text-red-500">
{form.formState.errors.name.message}
</p>
)}
</div>
<div className="grid gap-1">
<Label htmlFor="description">Description</Label>
<Input
{...form.register("description")}
placeholder="Short description"
/>
{form.formState.errors.description && (
<p className="text-sm text-red-500">
{form.formState.errors.description.message}
</p>
)}
</div>
<div className="grid grid-cols-2 gap-4">
<div className="grid gap-1">
<Label htmlFor="price">Price</Label>
<Input
type="number"
{...form.register("price", { valueAsNumber: true })}
placeholder="0.00"
/>
</div>
<div className="grid gap-1">
<Label htmlFor="stock">Stock</Label>
<Input
type="number"
{...form.register("stock_quantity", { valueAsNumber: true })}
placeholder="0"
/>
</div>
</div>
<div className="grid gap-1">
<Label htmlFor="image">Image</Label>
<Input
id="image"
type="file"
accept="image/jpg,image/png"
onChange={onImageUpload}
/>
{form.watch("image_data") && (
<img
src={form.watch("image_data")}
alt="Preview"
className="mt-2 h-24 w-24 rounded border object-cover"
/>
)}
</div>
<DialogFooter>
<Button type="submit">{submitLabel}</Button>
</DialogFooter>
</form>
);
}
@@ -0,0 +1,60 @@
import { ProductWithDetails } from "@/api/mock/models";
import Placeholder from "@/assets/placeholder.svg?react";
import {
Card,
CardDescription,
CardHeader,
CardTitle
} from "@/components/ui/card";
export function ProductList({
products,
isLoading,
onClick
}: {
products: ProductWithDetails[];
isLoading: boolean;
onClick: (id: number) => void;
}) {
if (isLoading) return <p className="col-span-full">Loading...</p>;
return (
<ul className="faded-bottom no-scrollbar grid grid-cols-1 gap-4 overflow-auto pb-16 pt-4 sm:grid-cols-2 md:grid-cols-4 xl:grid-cols-6 2xl:grid-cols-8">
{products.map((product) => (
<Card
key={product.id}
onClick={() => onClick(product.id)}
className="cursor-pointer overflow-hidden">
<div className="relative aspect-square w-full overflow-hidden">
{product.images.length > 0 ? (
<img
src={
product.images.length > 0
? product.images[0].image_url
: "/images/placeholder.svg"
}
alt={product.name}
className="h-full w-full object-cover"
/>
) : (
<Placeholder className="h-full w-full object-cover fill-gray-100 dark:fill-slate-900 text-slate-900 dark:text-zinc-500" />
)}
<div className="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-background/90 to-background/0 p-2">
<span className="rounded bg-secondary px-2 py-1 text-[10px] font-medium">
{product.stock_quantity} in stock
</span>
</div>
</div>
<CardHeader className="p-3 pb-2">
<CardTitle className="line-clamp-1 text-sm">
{product.name}
</CardTitle>
<CardDescription className="line-clamp-2 text-xs text-muted-foreground">
{product.description}
</CardDescription>
</CardHeader>
</Card>
))}
</ul>
);
}
-110
View File
@@ -1,110 +0,0 @@
import {
IconBrandDiscord,
IconBrandDocker,
IconBrandFigma,
IconBrandGithub,
IconBrandGitlab,
IconBrandGmail,
IconBrandMedium,
IconBrandNotion,
IconBrandSkype,
IconBrandSlack,
IconBrandStripe,
IconBrandTelegram,
IconBrandTrello,
IconBrandWhatsapp,
IconBrandZoom
} from "@tabler/icons-react";
export const apps = [
{
name: "Telegram",
logo: <IconBrandTelegram />,
connected: false,
desc: "Connect with Telegram for real-time communication."
},
{
name: "Notion",
logo: <IconBrandNotion />,
connected: true,
desc: "Effortlessly sync Notion pages for seamless collaboration."
},
{
name: "Figma",
logo: <IconBrandFigma />,
connected: true,
desc: "View and collaborate on Figma designs in one place."
},
{
name: "Trello",
logo: <IconBrandTrello />,
connected: false,
desc: "Sync Trello cards for streamlined project management."
},
{
name: "Slack",
logo: <IconBrandSlack />,
connected: false,
desc: "Integrate Slack for efficient team communication"
},
{
name: "Zoom",
logo: <IconBrandZoom />,
connected: true,
desc: "Host Zoom meetings directly from the dashboard."
},
{
name: "Stripe",
logo: <IconBrandStripe />,
connected: false,
desc: "Easily manage Stripe transactions and payments."
},
{
name: "Gmail",
logo: <IconBrandGmail />,
connected: true,
desc: "Access and manage Gmail messages effortlessly."
},
{
name: "Medium",
logo: <IconBrandMedium />,
connected: false,
desc: "Explore and share Medium stories on your dashboard."
},
{
name: "Skype",
logo: <IconBrandSkype />,
connected: false,
desc: "Connect with Skype contacts seamlessly."
},
{
name: "Docker",
logo: <IconBrandDocker />,
connected: false,
desc: "Effortlessly manage Docker containers on your dashboard."
},
{
name: "GitHub",
logo: <IconBrandGithub />,
connected: false,
desc: "Streamline code management with GitHub integration."
},
{
name: "GitLab",
logo: <IconBrandGitlab />,
connected: false,
desc: "Efficiently manage code projects with GitLab integration."
},
{
name: "Discord",
logo: <IconBrandDiscord />,
connected: false,
desc: "Connect with Discord for seamless team communication."
},
{
name: "WhatsApp",
logo: <IconBrandWhatsapp />,
connected: false,
desc: "Easily integrate WhatsApp for direct messaging."
}
];
@@ -0,0 +1,43 @@
import { ProductWithDetails } from "@/api/mock/models";
import { zodResolver } from "@hookform/resolvers/zod";
import { useEffect } from "react";
import { useForm } from "react-hook-form";
import { z } from "zod";
export const schema = z.object({
name: z.string().min(1, "Name is required"),
description: z.string().min(1, "Description is required"),
price: z.coerce.number().min(0),
stock_quantity: z.coerce.number().int().min(0),
image_data: z.string().optional()
});
export type ProductForm = z.infer<typeof schema>;
export function useProductForm(productData?: ProductWithDetails | null) {
const form = useForm<ProductForm>({
resolver: zodResolver(schema),
defaultValues: {
name: "",
description: "",
price: 0,
stock_quantity: 0,
image_data: ""
}
});
useEffect(() => {
if (productData) {
form.reset({
name: productData.name,
description: productData.description,
price: productData.price,
stock_quantity: productData.stock_quantity,
image_data: productData.images[0]?.image_url || ""
});
}
}, [productData, form]);
return form;
}
+132 -85
View File
@@ -1,55 +1,96 @@
import { useState } from "react";
import {
IconAdjustmentsHorizontal,
IconSortAscendingLetters,
IconSortDescendingLetters
IconSortDescendingLetters,
IconPlus
} from "@tabler/icons-react";
import { Header } from "@/components/layout/header";
import { Main } from "@/components/layout/main";
import { Search } from "@/components/search";
import { ThemeSwitch } from "@/components/theme-switch";
import { ProfileDropdown } from "@/components/profile-dropdown";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue
SelectValue,
SelectContent,
SelectItem
} from "@/components/ui/select";
import { Separator } from "@/components/ui/separator";
import { Header } from "@/components/layout/header";
import { Main } from "@/components/layout/main";
import { ProfileDropdown } from "@/components/profile-dropdown";
import { Search } from "@/components/search";
import { ThemeSwitch } from "@/components/theme-switch";
import { apps } from "./data/apps";
const appText = new Map<string, string>([
["all", "All Apps"],
["connected", "Connected"],
["notConnected", "Not Connected"]
]);
import { useProducts } from "@/hooks/useProducts";
import { useProduct } from "@/hooks/useProduct";
import { useState } from "react";
import { useProductForm } from "./hooks/use-product-form";
import { ProductList } from "./components/product-list";
import { ProductDialog } from "./components/product-dialog";
import { toast } from "@/hooks/useToast";
export default function Products() {
const [sort, setSort] = useState("ascending");
const [appType, setAppType] = useState("all");
const [sort, setSort] = useState<"ascending" | "descending">("ascending");
const [searchTerm, setSearchTerm] = useState("");
const [dialogOpen, setDialogOpen] = useState(false);
const [editDialogOpen, setEditDialogOpen] = useState(false);
const [selectedProductId, setSelectedProductId] = useState<
number | undefined
>(undefined);
const filteredApps = apps
.sort((a, b) =>
sort === "ascending"
? a.name.localeCompare(b.name)
: b.name.localeCompare(a.name)
)
.filter((app) =>
appType === "connected"
? app.connected
: appType === "notConnected"
? !app.connected
: true
)
.filter((app) => app.name.toLowerCase().includes(searchTerm.toLowerCase()));
const { data: products = [], isLoading } = useProducts();
const { product, createProduct, updateProduct, deleteProduct } =
useProduct(selectedProductId);
const form = useProductForm(product.data);
const handleImageUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
const reader = new FileReader();
reader.onload = () => form.setValue("image_data", reader.result as string);
reader.readAsDataURL(file);
};
const handleCreateSubmit = form.handleSubmit((data) => {
form.reset({
name: "",
description: "",
price: 0,
stock_quantity: 0,
image_data: ""
});
createProduct.mutate(data);
setDialogOpen(false);
toast({ title: `${data.name} created`, variant: "default" });
});
const handleEditSubmit = form.handleSubmit((data) => {
if (!selectedProductId) return;
updateProduct.mutate(data);
setEditDialogOpen(false);
toast({ title: `${data.name} saved`, variant: "default" });
});
const handleDelete = () => {
if (!selectedProductId) return;
deleteProduct.mutate();
setEditDialogOpen(false);
toast({ title: `${product.data?.name} deleted`, variant: "destructive" });
};
const sortedProducts = [...products].sort((a, b) =>
sort === "ascending"
? a.name.localeCompare(b.name)
: b.name.localeCompare(a.name)
);
const filteredProducts = sortedProducts.filter((product) =>
product.name.toLowerCase().includes(searchTerm.toLowerCase())
);
return (
<>
{/* ===== Top Heading ===== */}
<Header>
<Search />
<div className="ml-auto flex items-center gap-4">
@@ -58,37 +99,26 @@ export default function Products() {
</div>
</Header>
{/* ===== Content ===== */}
<Main fixed>
<div>
<h1 className="text-2xl font-bold tracking-tight">
Products
</h1>
<p className="text-muted-foreground">
Here&apos;s a list of your products!
</p>
</div>
<div className="my-4 flex items-end justify-between sm:my-0 sm:items-center">
<div className="flex flex-col gap-4 sm:my-4 sm:flex-row">
<Input
placeholder="Filter apps..."
className="h-9 w-40 lg:w-[250px]"
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
/>
<Select value={appType} onValueChange={setAppType}>
<SelectTrigger className="w-36">
<SelectValue>{appText.get(appType)}</SelectValue>
</SelectTrigger>
<SelectContent>
<SelectItem value="all">All Apps</SelectItem>
<SelectItem value="connected">Connected</SelectItem>
<SelectItem value="notConnected">Not Connected</SelectItem>
</SelectContent>
</Select>
<div className="flex items-center justify-between">
<div>
<h1 className="text-2xl font-bold tracking-tight">Products</h1>
<p className="text-muted-foreground">
Here's a list of your products!
</p>
</div>
</div>
<Select value={sort} onValueChange={setSort}>
<div className="flex flex-col gap-4 sm:my-4 sm:flex-row">
<Input
placeholder="Search products..."
className="h-9 w-40 lg:w-[250px]"
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
/>
<Select
value={sort}
onValueChange={(v) => setSort(v as "ascending" | "descending")}>
<SelectTrigger className="w-16">
<SelectValue>
<IconAdjustmentsHorizontal size={18} />
@@ -110,32 +140,49 @@ export default function Products() {
</SelectContent>
</Select>
</div>
<Separator className="shadow" />
<ul className="faded-bottom no-scrollbar grid gap-4 overflow-auto pb-16 pt-4 md:grid-cols-2 lg:grid-cols-3">
{filteredApps.map((app) => (
<li
key={app.name}
className="rounded-lg border p-4 hover:shadow-md">
<div className="mb-8 flex items-center justify-between">
<div
className={`flex size-10 items-center justify-center rounded-lg bg-muted p-2`}>
{app.logo}
</div>
<Button
variant="outline"
size="sm"
className={`${app.connected ? "border border-blue-300 bg-blue-50 hover:bg-blue-100 dark:border-blue-700 dark:bg-blue-950 dark:hover:bg-blue-900" : ""}`}>
{app.connected ? "Connected" : "Connect"}
</Button>
</div>
<div>
<h2 className="mb-1 font-semibold">{app.name}</h2>
<p className="line-clamp-2 text-gray-500">{app.desc}</p>
</div>
</li>
))}
</ul>
<ProductList
products={filteredProducts}
isLoading={isLoading}
onClick={(id) => {
setSelectedProductId(id);
setEditDialogOpen(true);
}}
/>
<Button
onClick={() => setDialogOpen(true)}
className="absolute bottom-0 z-10 mb-4 size-14 rounded-full p-0 shadow-lg hover:brightness-110"
variant="default">
<IconPlus size={28} />
</Button>
</Main>
{/* Create Dialog */}
<ProductDialog
open={dialogOpen}
onOpenChange={setDialogOpen}
form={form}
onSubmit={handleCreateSubmit}
onImageUpload={handleImageUpload}
submitLabel="Create"
imagePreview={form.watch("image_data")}
/>
{/* Edit Dialog */}
<ProductDialog
open={editDialogOpen}
onOpenChange={setEditDialogOpen}
form={form}
onSubmit={handleEditSubmit}
onImageUpload={handleImageUpload}
onDelete={handleDelete}
submitLabel="Update"
imagePreview={form.watch("image_data")}
showDeleteButton
/>
</>
);
}
@@ -15,6 +15,9 @@ import { PhoneInput } from "@/components/ui/phone-number-input";
import { Input } from "@/components/ui/input";
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
import { ScrollArea } from "@/components/ui/scroll-area";
import { useShop } from "@/hooks/useShop";
import { useEffect } from "react";
import { toast } from "@/hooks/useToast";
const shopAboutSchema = z.object({
name: z.string().min(1, "Name is required"),
@@ -25,7 +28,7 @@ const shopAboutSchema = z.object({
address: z.object({
street: z.string(),
city: z.string(),
state: z.string().optional(),
state: z.string().nullable().optional(),
postal_code: z.string(),
country: z.string()
}),
@@ -35,31 +38,24 @@ const shopAboutSchema = z.object({
type ShopAboutFormValues = z.infer<typeof shopAboutSchema>;
export function ShopAboutForm() {
const defaultValues: ShopAboutFormValues = {
name: "My Shop",
description: "This is a sample shop description.",
currency: "USD",
contact_email: "user@example.com",
contact_phone_number: "+266018975510",
address: {
street: "123 Main St",
city: "Metropolis",
state: "",
postal_code: "12345",
country: "USA"
},
status: "inactive"
};
const { shop, isLoading, updateShop } = useShop();
const form = useForm<ShopAboutFormValues>({
resolver: zodResolver(shopAboutSchema),
defaultValues,
defaultValues: shop ?? undefined,
mode: "onChange"
});
useEffect(() => {
if (shop) form.reset(shop);
}, [shop, form]);
function onSubmit(data: ShopAboutFormValues) {
console.log("Submitted shop about data:", data);
updateShop(data);
toast({title: "Saved shop data"})
}
if (isLoading) return <div className="p-4">Loading...</div>;
if (!shop) return <div className="p-4">No shop found</div>;
return (
<ScrollArea
@@ -67,9 +63,7 @@ export function ShopAboutForm() {
type="always"
className="hidden w-full min-w-40 bg-background px-1 md:block">
<Form {...form}>
<form
onSubmit={form.handleSubmit(onSubmit)}
className="space-y-6">
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
<Card>
<CardHeader>
<CardTitle className="text-xl">Basic Details</CardTitle>
@@ -123,39 +117,37 @@ export function ShopAboutForm() {
</CardHeader>
<CardContent>
<div className="grid grid-cols-2 gap-4">
<FormField
control={form.control}
name="contact_email"
render={({ field }) => (
<FormItem>
<FormLabel>Contact Email</FormLabel>
<FormControl>
<Input
type="email"
placeholder="user@example.com"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="contact_phone_number"
render={({ field }) => (
<FormItem>
<FormLabel>Phone Number</FormLabel>
<FormControl>
<PhoneInput {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="contact_email"
render={({ field }) => (
<FormItem>
<FormLabel>Contact Email</FormLabel>
<FormControl>
<Input
type="email"
placeholder="user@example.com"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="contact_phone_number"
render={({ field }) => (
<FormItem>
<FormLabel>Phone Number</FormLabel>
<FormControl>
<PhoneInput {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
</CardContent>
</Card>
@@ -198,7 +190,7 @@ export function ShopAboutForm() {
<FormItem>
<FormLabel>State/Province</FormLabel>
<FormControl>
<Input placeholder="State" {...field} />
<Input placeholder="State" {...field} value={field.value ?? ""} />
</FormControl>
<FormMessage />
</FormItem>