Enhance dashboard functionality with new payment and device management features

- Added new PaymentPage component for processing payments and displaying devices to pay.
- Introduced DeviceDetails component for viewing individual device information.
- Implemented PriceCalculator component for calculating costs based on user input.
- Integrated Jotai for state management across components, including device cart functionality.
- Updated layout to include Jotai Provider for state management.
- Enhanced DevicesTable with AddDevicesToCartButton for adding devices to the cart.
- Refactored sidebar to include a link to the new Price Calculator page.
- Updated Prisma schema to include Payment and BillFormula models for better data handling.
- Added new UI components for device cart management and drawer functionality.
- Improved overall user experience with responsive design adjustments and new UI elements.
This commit is contained in:
i701 2024-12-06 14:16:05 +05:00
parent 9021f01ff4
commit c6f45710ca
23 changed files with 2545 additions and 50 deletions

View File

@ -0,0 +1,39 @@
import prisma from '@/lib/db'
import React from 'react'
export default async function DeviceDetails({ params }: {
params: Promise<{ deviceId: string }>
}) {
const deviceId = (await params)?.deviceId
const device = await prisma.device.findUnique({
where: {
id: deviceId,
},
})
return (
<div>
<div className="flex flex-col justify-between items-start border-b-2 text-gray-500 title-bg py-4 px-2 mb-4">
<h3 className='text-2xl font-bold'>
{device?.name}
</h3>
<span>{device?.mac}</span>
</div>
<div
id="user-filters"
className=" border-b-2 pb-4 gap-4 flex sm:flex-row flex-col items-start justify-start"
>
{/* <Search /> */}
{/* <Filter
options={sortfilterOptions}
defaultOption="asc"
queryParamKey="sortBy"
/> */}
</div>
{/* <Suspense key={query} fallback={"loading...."}>
<DevicesTable searchParams={searchParams} />
</Suspense> */}
</div>
)
}

View File

@ -43,7 +43,7 @@ export default async function Devices({
<div
id="user-filters"
className=" border-b-2 pb-4 gap-4 flex items-center justify-start"
className=" border-b-2 pb-4 gap-4 flex sm:flex-row flex-col items-start justify-start"
>
<Search />
<Filter

View File

@ -0,0 +1,24 @@
import DevicesToPay from '@/components/devices-to-pay';
import prisma from '@/lib/db';
import React from 'react'
export default async function PaymentPage() {
const formula = await prisma.billFormula.findFirst();
return (
<div>
<div className="flex justify-between items-center border-b-2 text-gray-500 text-2xl font-bold title-bg py-4 px-2 mb-4">
<h3>
Payment
</h3>
</div>
<div
id="user-filters"
className="pb-4 gap-4 flex sm:flex-row flex-col items-start justify-start"
>
<DevicesToPay billFormula={formula ?? undefined} />
</div>
</div>
)
}

View File

@ -0,0 +1,125 @@
"use client";
import {
discountPercentageAtom,
formulaResultAtom,
initialPriceAtom,
numberOfDaysAtom,
numberOfDevicesAtom,
} from "@/lib/atoms";
import { useAtom } from "jotai";
import { Minus, Plus } from "lucide-react";
import { useEffect } from "react";
import {
Button,
Group,
Input,
Label,
NumberField,
} from "react-aria-components";
export default function PriceCalculator() {
const [initialPrice, setInitialPrice] = useAtom(initialPriceAtom);
const [discountPercentage, setDiscountPercentage] = useAtom(
discountPercentageAtom,
);
const [numberOfDevices, setNumberOfDevices] = useAtom(numberOfDevicesAtom);
const [numberOfDays, setNumberOfDays] = useAtom(numberOfDaysAtom);
const [formulaResult, setFormulaResult] = useAtom(formulaResultAtom);
useEffect(() => {
const basePrice = initialPrice + (numberOfDevices - 1) * discountPercentage;
setFormulaResult(
`Price for ${numberOfDevices} device(s) over ${numberOfDays} day(s): MVR ${basePrice.toFixed(2)}`,
);
}, [
initialPrice,
discountPercentage,
numberOfDevices,
numberOfDays,
setFormulaResult,
]);
return (
<div className="border p-2 rounded-xl">
<div className="flex flex-col justify-between items-start text-gray-500 title-bg p-2 mb-4">
<h3 className="text-2xl font-semibold">Price Calculator</h3>
</div>
<div className="grid grid-cols-1 gap-4 md:grid-cols-2">
{/* Initial Price Input */}
<NumberInput
label="Initial Price"
value={initialPrice}
onChange={(value) => setInitialPrice(value)}
/>
{/* Number of Devices Input */}
<NumberInput
label="Number of Devices"
value={numberOfDevices}
onChange={(value) => setNumberOfDevices(value)}
/>
{/* Number of Days Input */}
<NumberInput
label="Number of Days"
value={numberOfDays}
onChange={(value) => setNumberOfDays(value)}
/>
{/* Discount Percentage Input */}
<NumberInput
label="Discount Percentage"
value={discountPercentage}
onChange={(value) => setDiscountPercentage(value)}
/>
</div>
<div className="mt-4">
<div className="title-bg relative rounded-lg border border-input shadow-sm shadow-black/5 transition-shadow focus-within:border-ring focus-within:outline-none focus-within:ring-[3px] focus-within:ring-ring/20 has-[:disabled]:cursor-not-allowed has-[:disabled]:opacity-50 [&:has(input:is(:disabled))_*]:pointer-events-none">
<label
htmlFor=""
className="block px-3 pt-2 text-md font-medium text-foreground"
>
Total
</label>
<input
className="flex font-mono font-semibold h-10 w-full bg-transparent px-3 pb-2 text-sm text-foreground placeholder:text-muted-foreground/70 focus-visible:outline-none"
value={formulaResult}
readOnly
placeholder={"Result"}
/>
</div>
</div>
</div>
);
}
// Dependencies: pnpm install lucide-react react-aria-components
function NumberInput({
label,
value,
onChange,
}: { label: string; value: number; onChange: (value: number) => void }) {
return (
<NumberField value={value} minValue={0} onChange={onChange}>
<div className="space-y-2">
<Label className="text-sm font-medium text-foreground">{label}</Label>
<Group className="relative inline-flex h-9 w-full items-center overflow-hidden whitespace-nowrap rounded-lg border border-input text-sm shadow-sm shadow-black/5 transition-shadow data-[focus-within]:border-ring data-[disabled]:opacity-50 data-[focus-within]:outline-none data-[focus-within]:ring-[3px] data-[focus-within]:ring-ring/20">
<Button
slot="decrement"
className="-ms-px flex aspect-square h-[inherit] items-center justify-center rounded-s-lg border border-input bg-background text-sm text-muted-foreground/80 transition-shadow hover:bg-accent hover:text-foreground disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50"
>
<Minus size={16} strokeWidth={2} aria-hidden="true" />
</Button>
<Input className="w-full grow bg-background px-3 py-2 text-center tabular-nums text-foreground focus:outline-none" />
<Button
slot="increment"
className="-me-px flex aspect-square h-[inherit] items-center justify-center rounded-e-lg border border-input bg-background text-sm text-muted-foreground/80 transition-shadow hover:bg-accent hover:text-foreground disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50"
>
<Plus size={16} strokeWidth={2} aria-hidden="true" />
</Button>
</Group>
</div>
</NumberField>
);
}

View File

@ -1,4 +1,5 @@
import { ThemeProvider } from "@/components/theme-provider";
import { Provider } from "jotai";
import type { Metadata } from "next";
import { Barlow } from "next/font/google";
@ -25,16 +26,18 @@ export default function RootLayout({
return (
<html lang="en" suppressHydrationWarning>
<body className={`${barlow.variable} antialiased font-sans`}>
<NextTopLoader showSpinner={false} zIndex={9999} />
<Toaster richColors />
<ThemeProvider
attribute="class"
defaultTheme="system"
enableSystem
disableTransitionOnChange
>
<QueryProvider>{children}</QueryProvider>
</ThemeProvider>
<Provider>
<NextTopLoader showSpinner={false} zIndex={9999} />
<Toaster richColors />
<ThemeProvider
attribute="class"
defaultTheme="system"
enableSystem
disableTransitionOnChange
>
<QueryProvider>{children}</QueryProvider>
</ThemeProvider>
</Provider>
</body>
</html>
);

View File

@ -0,0 +1,32 @@
'use client'
import { deviceCartAtom } from '@/lib/atoms'
import type { Device } from '@prisma/client'
import { useAtomValue, useSetAtom } from 'jotai'
import { BadgePlus, CheckCheck } from 'lucide-react'
import React from 'react'
import { Button } from './ui/button'
export default function AddDevicesToCartButton({ device }: { device: Device }) {
const setDeviceCart = useSetAtom(deviceCartAtom)
const devices = useAtomValue(deviceCartAtom)
return (
<Button
disabled={devices.some((d) => d.id === device.id)}
onClick={() => setDeviceCart((prev) => [...prev, device])}
>
{devices.some((d) => d.id === device.id) ? (
<>
Added
<CheckCheck />
</>
) : (
<>
Add to cart
<BadgePlus />
</>
)}
</Button>
)
}

View File

@ -1,13 +1,7 @@
import { DeviceCartDrawer } from "@/components/device-cart";
import { ModeToggle } from "@/components/theme-toggle";
import { AppSidebar } from "@/components/ui/app-sidebar";
import {
Breadcrumb,
BreadcrumbItem,
BreadcrumbLink,
BreadcrumbList,
BreadcrumbPage,
BreadcrumbSeparator,
} from "@/components/ui/breadcrumb";
import { Separator } from "@/components/ui/separator";
import {
SidebarInset,
@ -33,20 +27,10 @@ export async function ApplicationLayout({
<div className="flex items-center gap-2 ">
<SidebarTrigger className="-ml-1" />
<Separator orientation="vertical" className="mr-2 h-4" />
<Breadcrumb>
<BreadcrumbList>
<BreadcrumbItem className="hidden md:block">
<BreadcrumbLink href="#">MENU</BreadcrumbLink>
</BreadcrumbItem>
<BreadcrumbSeparator className="hidden md:block" />
<BreadcrumbItem>
<BreadcrumbPage>Sar Link Portal v1.0.0</BreadcrumbPage>
</BreadcrumbItem>
</BreadcrumbList>
</Breadcrumb>
</div>
<div className="flex items-center gap-2">
<DeviceCartDrawer />
<ModeToggle />
<AccountPopover />
</div>

109
components/device-cart.tsx Normal file
View File

@ -0,0 +1,109 @@
"use client"
import * as React from "react"
import { Button } from "@/components/ui/button"
import {
Drawer,
DrawerClose,
DrawerContent,
DrawerDescription,
DrawerFooter,
DrawerHeader,
DrawerTitle,
DrawerTrigger,
} from "@/components/ui/drawer"
import { cartDrawerOpenAtom, deviceCartAtom } from "@/lib/atoms"
import type { Device } from "@prisma/client"
import { useAtom, useAtomValue, useSetAtom } from "jotai"
import { CircleDollarSign, ShoppingCart, Trash2 } from "lucide-react"
import Link from "next/link"
import { usePathname } from "next/navigation"
export function DeviceCartDrawer() {
const pathname = usePathname()
const devices = useAtomValue(deviceCartAtom)
const setDeviceCart = useSetAtom(deviceCartAtom)
const [isOpen, setIsOpen] = useAtom(cartDrawerOpenAtom)
if (pathname === "/payment") {
return null
}
return (
<Drawer open={isOpen} onOpenChange={setIsOpen}>
<DrawerTrigger asChild>
<Button
onClick={() => setIsOpen(!isOpen)}
variant="outline">
<ShoppingCart />
Cart {devices.length > 0 && `(${devices.length})`}
</Button>
</DrawerTrigger>
<DrawerContent>
<div className="mx-auto w-full max-w-sm">
<DrawerHeader>
<DrawerTitle>Cart Devices</DrawerTitle>
<DrawerDescription>Devices in your cart to pay.</DrawerDescription>
</DrawerHeader>
<div className="flex max-h-[calc(100svh-200px)] flex-col overflow-auto px-4 pb-4 gap-4">
{devices.map((device) => (
<DeviceCard key={device.id} device={device} />
))}
</div>
<DrawerFooter>
<Link aria-disabled={devices.length === 0} href={devices.length === 0 ? "#" : "/payment"}>
<Button
onClick={() => {
setIsOpen(!isOpen)
}}
className="w-full" disabled={devices.length === 0}>
Go to payment
<CircleDollarSign />
</Button>
</Link>
<DrawerClose asChild>
<Button variant="outline">Cancel</Button>
</DrawerClose>
<Button
onClick={() => {
setDeviceCart([])
}}
variant="outline">Reset Cart</Button>
</DrawerFooter>
</div>
</DrawerContent>
</Drawer>
)
}
function DeviceCard({ device }: { device: Device }) {
const setDeviceCart = useSetAtom(deviceCartAtom)
return (
<div className="relative flex h-full w-full items-center pr-4 justify-between rounded-lg border border-input bg-background shadow-sm shadow-black/5 transition-shadow focus-within:border-ring focus-within:outline-none focus-within:ring-[3px] focus-within:ring-ring/20 has-[:disabled]:cursor-not-allowed has-[:disabled]:opacity-50 [&:has(input:is(:disabled))_*]:pointer-events-none">
<div>
<label htmlFor="input-33" className="block px-3 pt-2 text-xs font-medium text-foreground">
{device.name}
</label>
<input
className="flex h-10 w-full bg-transparent px-3 pb-2 text-sm text-foreground placeholder:text-muted-foreground/70 focus-visible:outline-none"
value={device.mac}
readOnly
placeholder={"MAC Address"}
/>
</div>
<Button
onClick={() => {
setDeviceCart((prev) => prev.filter((d) => d.id !== device.id))
}}
variant={"destructive"}>
Remove
<Trash2 />
</Button>
</div>
)
}

View File

@ -9,6 +9,7 @@ import {
TableRow,
} from "@/components/ui/table";
import prisma from "@/lib/db";
import AddDevicesToCartButton from "./add-devices-to-cart-button";
import Pagination from "./pagination";
export async function DevicesTable({
@ -38,8 +39,6 @@ export async function DevicesTable({
mode: "insensitive",
},
},
],
},
});
@ -63,8 +62,6 @@ export async function DevicesTable({
mode: "insensitive",
},
},
],
},
@ -75,7 +72,6 @@ export async function DevicesTable({
},
});
return (
<div>
{devices.length === 0 ? (
@ -90,20 +86,16 @@ export async function DevicesTable({
<TableRow>
<TableHead>Device Name</TableHead>
<TableHead>MAC Address</TableHead>
<TableHead>Status</TableHead>
<TableHead>Actions</TableHead>
</TableRow>
</TableHeader>
<TableBody className="overflow-scroll">
{devices.map((device) => (
<TableRow
key={device.id}
>
<TableRow key={device.id}>
<TableCell className="font-medium">{device.name}</TableCell>
<TableCell className="font-medium">{device.mac}</TableCell>
<TableCell>
Parental Controls
<AddDevicesToCartButton device={device} />
</TableCell>
</TableRow>
))}

View File

@ -0,0 +1,61 @@
'use client'
import {
Table,
TableBody,
TableCaption,
TableCell,
TableFooter,
TableRow,
} from "@/components/ui/table"
import { deviceCartAtom } from '@/lib/atoms'
import type { BillFormula } from "@prisma/client"
import { useAtomValue } from 'jotai'
import React from 'react'
export default function DevicesToPay({ billFormula }: { billFormula?: BillFormula }) {
const devices = useAtomValue(deviceCartAtom)
if (devices.length === 0) {
return null
}
const baseAmount = billFormula?.baseAmount ?? 100
const discountPercentage = billFormula?.discountPercentage ?? 75
// 100+(n1)×75
const total = baseAmount + (devices.length - 1) * discountPercentage
return (
<div className='w-full'>
<div className='p-2 flex flex-col gap-2'>
<h3 className='title-bg my-1 font-semibold text-lg'>Devices to pay</h3>
<div className="flex flex-col gap-2">
{devices.map((device) => (
<div key={device.id} className="bg-muted border rounded p-2 flex gap-2 items-center">
<div className="flex flex-col">
<div className="text-sm font-medium">{device.name}</div>
<div className="text-xs text-muted-foreground">
{device.mac}
</div>
</div>
</div>
))}
</div>
</div>
<div className='m-2 flex items-end justify-end p-2 text-sm text-foreground border rounded'>
<Table>
<TableCaption>Please send the following amount to the payment address</TableCaption>
<TableBody>
<TableRow>
<TableCell>Total Devices</TableCell>
<TableCell className="text-right">{devices.length}</TableCell>
</TableRow>
</TableBody>
<TableFooter>
<TableRow>
<TableCell colSpan={1}>Total</TableCell>
<TableCell className="text-right">{total.toFixed(2)}</TableCell>
</TableRow>
</TableFooter>
</Table>
</div>
</div>
)
}

View File

@ -1,4 +1,5 @@
import {
Calculator,
ChevronRight,
Coins,
CreditCard,
@ -72,6 +73,11 @@ const data = {
url: "/user-payments",
icon: <Coins size={16} />,
},
{
title: "Price Calculator",
url: "/price-calculator",
icon: <Calculator size={16} />,
},
],
},
],
@ -84,7 +90,7 @@ export function AppSidebar({
return (
<Sidebar {...props} className="z-50">
<SidebarHeader>
<h4 className="p-2 rounded shadow text-center uppercase ">
<h4 className="p-2 rounded title-bg border text-center uppercase ">
Sar Link Portal
</h4>
</SidebarHeader>

118
components/ui/drawer.tsx Normal file
View File

@ -0,0 +1,118 @@
"use client"
import * as React from "react"
import { Drawer as DrawerPrimitive } from "vaul"
import { cn } from "@/lib/utils"
const Drawer = ({
shouldScaleBackground = true,
...props
}: React.ComponentProps<typeof DrawerPrimitive.Root>) => (
<DrawerPrimitive.Root
shouldScaleBackground={shouldScaleBackground}
{...props}
/>
)
Drawer.displayName = "Drawer"
const DrawerTrigger = DrawerPrimitive.Trigger
const DrawerPortal = DrawerPrimitive.Portal
const DrawerClose = DrawerPrimitive.Close
const DrawerOverlay = React.forwardRef<
React.ElementRef<typeof DrawerPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof DrawerPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<DrawerPrimitive.Overlay
ref={ref}
className={cn("fixed inset-0 z-50 bg-black/80", className)}
{...props}
/>
))
DrawerOverlay.displayName = DrawerPrimitive.Overlay.displayName
const DrawerContent = React.forwardRef<
React.ElementRef<typeof DrawerPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DrawerPrimitive.Content>
>(({ className, children, ...props }, ref) => (
<DrawerPortal>
<DrawerOverlay />
<DrawerPrimitive.Content
ref={ref}
className={cn(
"fixed inset-x-0 bottom-0 z-50 mt-24 flex h-auto flex-col rounded-t-[10px] border bg-background",
className
)}
{...props}
>
<div className="mx-auto mt-4 h-2 w-[100px] rounded-full bg-muted" />
{children}
</DrawerPrimitive.Content>
</DrawerPortal>
))
DrawerContent.displayName = "DrawerContent"
const DrawerHeader = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn("grid gap-1.5 p-4 text-center sm:text-left", className)}
{...props}
/>
)
DrawerHeader.displayName = "DrawerHeader"
const DrawerFooter = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn("mt-auto flex flex-col gap-2 p-4", className)}
{...props}
/>
)
DrawerFooter.displayName = "DrawerFooter"
const DrawerTitle = React.forwardRef<
React.ElementRef<typeof DrawerPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof DrawerPrimitive.Title>
>(({ className, ...props }, ref) => (
<DrawerPrimitive.Title
ref={ref}
className={cn(
"text-lg font-semibold leading-none tracking-tight",
className
)}
{...props}
/>
))
DrawerTitle.displayName = DrawerPrimitive.Title.displayName
const DrawerDescription = React.forwardRef<
React.ElementRef<typeof DrawerPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof DrawerPrimitive.Description>
>(({ className, ...props }, ref) => (
<DrawerPrimitive.Description
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
))
DrawerDescription.displayName = DrawerPrimitive.Description.displayName
export {
Drawer,
DrawerPortal,
DrawerOverlay,
DrawerTrigger,
DrawerClose,
DrawerContent,
DrawerHeader,
DrawerFooter,
DrawerTitle,
DrawerDescription,
}

View File

@ -1,6 +1,7 @@
"use client";
import { Slot } from "@radix-ui/react-slot";
import * as VisuallyHidden from "@radix-ui/react-visually-hidden";
import { type VariantProps, cva } from "class-variance-authority";
import { PanelLeft } from "lucide-react";
import * as React from "react";
@ -8,7 +9,12 @@ import * as React from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Separator } from "@/components/ui/separator";
import { Sheet, SheetContent, SheetTitle } from "@/components/ui/sheet";
import {
Sheet,
SheetContent,
SheetDescription,
SheetTitle,
} from "@/components/ui/sheet";
import { Skeleton } from "@/components/ui/skeleton";
import {
Tooltip,
@ -214,6 +220,10 @@ const Sidebar = React.forwardRef<
}
side={side}
>
<VisuallyHidden.Root>
<SheetDescription>Description goes here</SheetDescription>
</VisuallyHidden.Root>
<SheetTitle className="hidden">Menu</SheetTitle>
<div className="flex h-full w-full flex-col">{children}</div>
</SheetContent>

8
hooks/use-formula.ts Normal file
View File

@ -0,0 +1,8 @@
"use server";
import prisma from "@/lib/db";
export async function useFormula() {
const formula = await prisma.billFormula.findFirst();
return formula;
}

24
lib/atoms.ts Normal file
View File

@ -0,0 +1,24 @@
import type { Device } from "@prisma/client";
import { atom, createStore } from "jotai";
// Create a single store instance
export const store = createStore();
// Create atoms with the store
export const initialPriceAtom = atom(100);
export const discountPercentageAtom = atom(75);
export const numberOfDevicesAtom = atom(1);
export const numberOfDaysAtom = atom(30);
export const formulaResultAtom = atom("");
export const deviceCartAtom = atom<Device[]>([]);
export const cartDrawerOpenAtom = atom(false);
// Export the atoms with their store
export const atoms = {
initialPriceAtom,
discountPercentageAtom,
numberOfDevicesAtom,
numberOfDaysAtom,
formulaResultAtom,
deviceCartAtom,
cartDrawerOpenAtom,
};

1829
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -33,12 +33,14 @@
"clsx": "^2.1.1",
"cmdk": "^1.0.0",
"date-fns": "^4.1.0",
"jotai": "^2.8.0",
"lucide-react": "^0.460.0",
"next": "15.0.3",
"next-themes": "^0.4.3",
"nextjs-toploader": "^3.7.15",
"prisma": "^5.22.0",
"react": "19.0.0-rc-66855b96-20241106",
"react-aria-components": "^1.5.0",
"react-day-picker": "^8.10.1",
"react-dom": "19.0.0-rc-66855b96-20241106",
"react-hook-form": "^7.53.2",
@ -46,6 +48,7 @@
"sonner": "^1.7.0",
"tailwind-merge": "^2.5.4",
"tailwindcss-animate": "^1.0.7",
"vaul": "^1.1.1",
"zod": "^3.23.8"
},
"devDependencies": {

View File

@ -0,0 +1,29 @@
-- AlterTable
ALTER TABLE "user" ADD COLUMN "policyAccepted" BOOLEAN NOT NULL DEFAULT false,
ADD COLUMN "termsAccepted" BOOLEAN NOT NULL DEFAULT false;
-- CreateTable
CREATE TABLE "Bill" (
"id" TEXT NOT NULL,
"name" TEXT NOT NULL,
"amount" INTEGER NOT NULL,
"paid" BOOLEAN NOT NULL DEFAULT false,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
"deviceId" TEXT,
CONSTRAINT "Bill_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "BillFormula" (
"id" TEXT NOT NULL,
"formula" TEXT NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "BillFormula_pkey" PRIMARY KEY ("id")
);
-- AddForeignKey
ALTER TABLE "Bill" ADD CONSTRAINT "Bill_deviceId_fkey" FOREIGN KEY ("deviceId") REFERENCES "Device"("id") ON DELETE SET NULL ON UPDATE CASCADE;

View File

@ -0,0 +1,10 @@
/*
Warnings:
- Added the required column `baseAmount` to the `BillFormula` table without a default value. This is not possible if the table is not empty.
- Added the required column `discountPercentage` to the `BillFormula` table without a default value. This is not possible if the table is not empty.
*/
-- AlterTable
ALTER TABLE "BillFormula" ADD COLUMN "baseAmount" DOUBLE PRECISION NOT NULL,
ADD COLUMN "discountPercentage" DOUBLE PRECISION NOT NULL;

View File

@ -0,0 +1,2 @@
-- AlterTable
ALTER TABLE "Device" ADD COLUMN "isActive" BOOLEAN NOT NULL DEFAULT false;

View File

@ -0,0 +1,33 @@
/*
Warnings:
- You are about to drop the `Bill` table. If the table is not empty, all the data it contains will be lost.
*/
-- DropForeignKey
ALTER TABLE "Bill" DROP CONSTRAINT "Bill_deviceId_fkey";
-- AlterTable
ALTER TABLE "Device" ADD COLUMN "billId" TEXT;
-- DropTable
DROP TABLE "Bill";
-- CreateTable
CREATE TABLE "Payment" (
"id" TEXT NOT NULL,
"name" TEXT NOT NULL,
"amount" INTEGER NOT NULL,
"paid" BOOLEAN NOT NULL DEFAULT false,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
"userId" TEXT NOT NULL,
CONSTRAINT "Payment_pkey" PRIMARY KEY ("id")
);
-- AddForeignKey
ALTER TABLE "Device" ADD CONSTRAINT "Device_billId_fkey" FOREIGN KEY ("billId") REFERENCES "Payment"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Payment" ADD CONSTRAINT "Payment_userId_fkey" FOREIGN KEY ("userId") REFERENCES "user"("id") ON DELETE RESTRICT ON UPDATE CASCADE;

View File

@ -41,6 +41,7 @@ model User {
lang String?
atollId String?
islandId String?
Bill Payment[]
@@map("user")
}
@ -108,12 +109,36 @@ model Island {
}
model Device {
id String @id @default(cuid())
name String
mac String
id String @id @default(cuid())
name String
mac String
isActive Boolean @default(false)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
User User? @relation(fields: [userId], references: [id])
userId String?
Bill Payment? @relation(fields: [billId], references: [id])
billId String?
}
model Payment {
id String @id @default(cuid())
name String
amount Int
paid Boolean @default(false)
user User @relation(fields: [userId], references: [id])
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
devices Device[]
userId String
}
model BillFormula {
id String @id @default(cuid())
formula String
baseAmount Float
discountPercentage Float
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}

View File

@ -6,6 +6,25 @@ const prisma = new PrismaClient();
const DEFAULT_ISLANDS = ["Dharanboodhoo", "Feeali", "Nilandhoo", "Magoodhoo"];
async function main() {
await prisma.user.upsert({
where: {
phoneNumber: "+9607780588",
},
update: {},
create: {
name: "Admin",
email: "admin@sarlink.net",
emailVerified: true,
firstPaymentDone: true,
verified: true,
address: "Dharanboodhoo",
id_card: "A265117",
dob: new Date("1990-01-01"),
phoneNumber: "+9607780588",
phoneNumberVerified: true,
role: "ADMIN",
},
});
const users = Array.from({ length: 25 }, () => ({
name: `${faker.person.fullName().split(" ")[1]} House-${crypto
.randomUUID()
@ -25,8 +44,18 @@ async function main() {
role: "USER",
}));
await prisma.user.createMany({
data: users,
const seedUsers = await Promise.all(
users.map((user) => prisma.user.create({ data: user })),
);
const FAKE_DEVICES = Array.from({ length: 25 }, () => ({
name: faker.commerce.productName(),
mac: faker.internet.mac(),
userId: seedUsers[Math.floor(Math.random() * seedUsers.length)].id,
}));
await prisma.device.createMany({
data: FAKE_DEVICES,
});
const FAAFU_ATOLL = await prisma.atoll.create({
data: {