Skip to content

The Open Source DocuSign Alternative.

feat: create a banner with custom text by admin

Ephraim Atta-Duncanc43655978755
diff --git a/apps/web/src/app/(dashboard)/admin/banner/banner-form.tsx b/apps/web/src/app/(dashboard)/admin/banner/banner-form.tsx
new file mode 100644
index 000000000..ce7e3e181
--- /dev/null
+++ b/apps/web/src/app/(dashboard)/admin/banner/banner-form.tsx
@@ -0,0 +1,119 @@
+'use client';
+
+import { useRouter } from 'next/navigation';
+
+import { zodResolver } from '@hookform/resolvers/zod';
+import { useForm } from 'react-hook-form';
+import { z } from 'zod';
+
+import { TRPCClientError } from '@documenso/trpc/client';
+import { trpc as trpcReact } from '@documenso/trpc/react';
+import { Button } from '@documenso/ui/primitives/button';
+import {
+ Form,
+ FormControl,
+ FormDescription,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from '@documenso/ui/primitives/form/form';
+import { Switch } from '@documenso/ui/primitives/switch';
+import { Textarea } from '@documenso/ui/primitives/textarea';
+import { useToast } from '@documenso/ui/primitives/use-toast';
+
+const ZBannerSchema = z.object({
+ text: z.string().optional(),
+ show: z.boolean().optional(),
+});
+
+type TBannerSchema = z.infer<typeof ZBannerSchema>;
+
+export function BannerForm({ show, text }: TBannerSchema) {
+ const router = useRouter();
+ const { toast } = useToast();
+
+ const form = useForm<TBannerSchema>({
+ resolver: zodResolver(ZBannerSchema),
+ defaultValues: {
+ show,
+ text,
+ },
+ });
+
+ const { mutateAsync: updateBanner, isLoading: isUpdatingBanner } =
+ trpcReact.banner.updateBanner.useMutation();
+
+ const onBannerUpdate = async ({ show, text }: TBannerSchema) => {
+ try {
+ await updateBanner({
+ show,
+ text,
+ });
+
+ toast({
+ title: 'Banner Updated',
+ description: 'Your banner has been updated successfully.',
+ duration: 5000,
+ });
+
+ router.refresh();
+ } catch (err) {
+ if (err instanceof TRPCClientError && err.data?.code === 'BAD_REQUEST') {
+ toast({
+ title: 'An error occurred',
+ description: err.message,
+ variant: 'destructive',
+ });
+ } else {
+ toast({
+ title: 'An unknown error occurred',
+ variant: 'destructive',
+ description:
+ 'We encountered an unknown error while attempting to reset your password. Please try again later.',
+ });
+ }
+ }
+ };
+
+ return (
+ <Form {...form}>
+ <form className="flex flex-col" onSubmit={form.handleSubmit(onBannerUpdate)}>
+ <FormField
+ control={form.control}
+ name="show"
+ render={({ field }) => (
+ <FormItem className="flex flex-row items-center justify-between rounded-lg border p-3 shadow-sm">
+ <div className="space-y-0.5">
+ <FormLabel>Show Banner</FormLabel>
+ <FormDescription>Show a banner to the users by the admin</FormDescription>
+ </div>
+ <FormControl>
+ <Switch checked={field.value} onCheckedChange={field.onChange} />
+ </FormControl>
+ </FormItem>
+ )}
+ />
+
+ <FormField
+ control={form.control}
+ name="text"
+ render={({ field }) => (
+ <FormItem className="mt-8">
+ <FormLabel className="text-base ">Banner Text</FormLabel>
+ <FormControl>
+ <Textarea placeholder="Text to show to users" className="resize-none" {...field} />
+ </FormControl>
+
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <Button type="submit" loading={isUpdatingBanner} className="mt-3 justify-end self-end">
+ Update Banner
+ </Button>
+ </form>
+ </Form>
+ );
+}
diff --git a/apps/web/src/app/(dashboard)/admin/banner/page.tsx b/apps/web/src/app/(dashboard)/admin/banner/page.tsx
new file mode 100644
index 000000000..b3370ae07
--- /dev/null
+++ b/apps/web/src/app/(dashboard)/admin/banner/page.tsx
@@ -0,0 +1,15 @@
+import { getBanner } from '@documenso/lib/server-only/banner/get-banner';
+
+import { BannerForm } from './banner-form';
+
+export default async function AdminBannerPage() {
+ const banner = await getBanner();
+
+ return (
+ <div className="space-y-8">
+ <h2 className="text-4xl font-semibold">Banner</h2>
+
+ <BannerForm show={banner?.show ?? false} text={banner?.text ?? ''} />
+ </div>
+ );
+}
diff --git a/apps/web/src/app/(dashboard)/admin/nav.tsx b/apps/web/src/app/(dashboard)/admin/nav.tsx
index 089861069..92f15e6c0 100644
--- a/apps/web/src/app/(dashboard)/admin/nav.tsx
+++ b/apps/web/src/app/(dashboard)/admin/nav.tsx
@@ -1,11 +1,11 @@
'use client';
-import { HTMLAttributes } from 'react';
+import type { HTMLAttributes } from 'react';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
-import { BarChart3, FileStack, User2, Wallet2 } from 'lucide-react';
+import { BadgeAlert, BarChart3, FileStack, User2, Wallet2 } from 'lucide-react';
import { cn } from '@documenso/ui/lib/utils';
import { Button } from '@documenso/ui/primitives/button';
@@ -78,6 +78,20 @@ export const AdminNav = ({ className, ...props }: AdminNavProps) => {
Subscriptions
</Link>
</Button>
+
+ <Button
+ variant="ghost"
+ className={cn(
+ 'justify-start md:w-full',
+ pathname?.startsWith('/admin/banner') && 'bg-secondary',
+ )}
+ asChild
+ >
+ <Link href="/admin/banner">
+ <BadgeAlert className="mr-2 h-5 w-5" />
+ Banner
+ </Link>
+ </Button>
</div>
);
};
diff --git a/apps/web/src/app/(dashboard)/layout.tsx b/apps/web/src/app/(dashboard)/layout.tsx
index 99db66c55..e3199c851 100644
--- a/apps/web/src/app/(dashboard)/layout.tsx
+++ b/apps/web/src/app/(dashboard)/layout.tsx
@@ -9,6 +9,7 @@ import { NEXT_AUTH_OPTIONS } from '@documenso/lib/next-auth/auth-options';
import { getRequiredServerComponentSession } from '@documenso/lib/next-auth/get-server-component-session';
import { getTeams } from '@documenso/lib/server-only/team/get-teams';
+import { Banner } from '~/components/(dashboard)/layout/banner';
import { Header } from '~/components/(dashboard)/layout/header';
import { VerifyEmailBanner } from '~/components/(dashboard)/layout/verify-email-banner';
import { RefreshOnFocus } from '~/components/(dashboard)/refresh-on-focus/refresh-on-focus';
@@ -37,6 +38,8 @@ export default async function AuthenticatedDashboardLayout({
<LimitsProvider>
{!user.emailVerified && <VerifyEmailBanner email={user.email} />}
+ <Banner />
+
<Header user={user} teams={teams} />
<main className="mt-8 pb-8 md:mt-12 md:pb-12">{children}</main>
diff --git a/apps/web/src/components/(dashboard)/layout/banner.tsx b/apps/web/src/components/(dashboard)/layout/banner.tsx
new file mode 100644
index 000000000..9e935abce
--- /dev/null
+++ b/apps/web/src/components/(dashboard)/layout/banner.tsx
@@ -0,0 +1,21 @@
+import { getBanner } from '@documenso/lib/server-only/banner/get-banner';
+
+export const Banner = async () => {
+ const banner = await getBanner();
+
+ return (
+ <>
+ {banner && banner.show && (
+ <div className="bg-documenso-200 dark:bg-documenso-400">
+ <div className="text-documenso-900 mx-auto flex h-auto max-w-screen-xl items-center justify-center px-4 py-3 text-sm font-medium">
+ <div className="flex items-center">{banner.text}</div>
+ </div>
+ </div>
+ )}
+ </>
+ );
+};
+
+// Banner
+// Custom Text
+// Custom Text with Custom Icon
diff --git a/packages/lib/server-only/admin/update-user.ts b/packages/lib/server-only/admin/update-user.ts
index 9013899a7..a36b1a3d6 100644
--- a/packages/lib/server-only/admin/update-user.ts
+++ b/packages/lib/server-only/admin/update-user.ts
@@ -1,5 +1,5 @@
import { prisma } from '@documenso/prisma';
-import { Role } from '@documenso/prisma/client';
+import type { Role } from '@documenso/prisma/client';
export type UpdateUserOptions = {
id: number;
diff --git a/packages/lib/server-only/banner/get-banner.ts b/packages/lib/server-only/banner/get-banner.ts
new file mode 100644
index 000000000..27c1001c2
--- /dev/null
+++ b/packages/lib/server-only/banner/get-banner.ts
@@ -0,0 +1,11 @@
+'use server';
+
+import { prisma } from '@documenso/prisma';
+
+export const getBanner = async () => {
+ return await prisma.banner.findUnique({
+ where: {
+ id: 1,
+ },
+ });
+};
diff --git a/packages/lib/server-only/banner/upsert-banner.ts b/packages/lib/server-only/banner/upsert-banner.ts
new file mode 100644
index 000000000..1cb7d5ec6
--- /dev/null
+++ b/packages/lib/server-only/banner/upsert-banner.ts
@@ -0,0 +1,28 @@
+'use server';
+
+import { prisma } from '@documenso/prisma';
+import { Role } from '@documenso/prisma/client';
+
+export type UpdateUserOptions = {
+ userId: number;
+ show?: boolean;
+ text?: string | undefined;
+};
+
+export const upsertBanner = async ({ userId, show, text }: UpdateUserOptions) => {
+ const user = await prisma.user.findUnique({
+ where: {
+ id: userId,
+ },
+ });
+
+ if (!user?.roles.includes(Role.ADMIN)) {
+ throw Error('You are unauthorised to perform this action');
+ }
+
+ return await prisma.banner.upsert({
+ where: { id: 1, user: {} },
+ update: { show, text },
+ create: { show, text: text ?? '' },
+ });
+};
diff --git a/packages/prisma/migrations/20240222183156_display_banner/migration.sql b/packages/prisma/migrations/20240222183156_display_banner/migration.sql
new file mode 100644
index 000000000..1625c7dc1
--- /dev/null
+++ b/packages/prisma/migrations/20240222183156_display_banner/migration.sql
@@ -0,0 +1,12 @@
+-- CreateTable
+CREATE TABLE "Banner" (
+ "id" SERIAL NOT NULL,
+ "text" TEXT NOT NULL,
+ "customHTML" TEXT NOT NULL,
+ "userId" INTEGER,
+
+ CONSTRAINT "Banner_pkey" PRIMARY KEY ("id")
+);
+
+-- AddForeignKey
+ALTER TABLE "Banner" ADD CONSTRAINT "Banner_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
diff --git a/packages/prisma/migrations/20240222183231_banner_show/migration.sql b/packages/prisma/migrations/20240222183231_banner_show/migration.sql
new file mode 100644
index 000000000..61b8f2dd1
--- /dev/null
+++ b/packages/prisma/migrations/20240222183231_banner_show/migration.sql
@@ -0,0 +1,2 @@
+-- AlterTable
+ALTER TABLE "Banner" ADD COLUMN "show" BOOLEAN NOT NULL DEFAULT false;
diff --git a/packages/prisma/migrations/20240222185936_remove_custom/migration.sql b/packages/prisma/migrations/20240222185936_remove_custom/migration.sql
new file mode 100644
index 000000000..67472035a
--- /dev/null
+++ b/packages/prisma/migrations/20240222185936_remove_custom/migration.sql
@@ -0,0 +1,8 @@
+/*
+ Warnings:
+
+ - You are about to drop the column `customHTML` on the `Banner` table. All the data in the column will be lost.
+
+*/
+-- AlterTable
+ALTER TABLE "Banner" DROP COLUMN "customHTML";
diff --git a/packages/prisma/schema.prisma b/packages/prisma/schema.prisma
index 2887cd6d2..f58294d65 100644
--- a/packages/prisma/schema.prisma
+++ b/packages/prisma/schema.prisma
@@ -47,6 +47,7 @@ model User {
VerificationToken VerificationToken[]
Template Template[]
securityAuditLogs UserSecurityAuditLog[]
+ Banner Banner[]
@@index([email])
}
@@ -210,15 +211,15 @@ model DocumentData {
}
model DocumentMeta {
- id String @id @default(cuid())
- subject String?
- message String?
- timezone String? @default("Etc/UTC") @db.Text
- password String?
- dateFormat String? @default("yyyy-MM-dd hh:mm a") @db.Text
- documentId Int @unique
- document Document @relation(fields: [documentId], references: [id], onDelete: Cascade)
- redirectUrl String?
+ id String @id @default(cuid())
+ subject String?
+ message String?
+ timezone String? @default("Etc/UTC") @db.Text
+ password String?
+ dateFormat String? @default("yyyy-MM-dd hh:mm a") @db.Text
+ documentId Int @unique
+ document Document @relation(fields: [documentId], references: [id], onDelete: Cascade)
+ redirectUrl String?
}
enum ReadStatus {
@@ -450,3 +451,11 @@ model Template {
@@unique([templateDocumentDataId])
}
+
+model Banner {
+ id Int @id @default(autoincrement())
+ text String
+ show Boolean @default(false)
+ user User? @relation(fields: [userId], references: [id])
+ userId Int?
+}
diff --git a/packages/trpc/server/banner-router/router.ts b/packages/trpc/server/banner-router/router.ts
new file mode 100644
index 000000000..1c8092be4
--- /dev/null
+++ b/packages/trpc/server/banner-router/router.ts
@@ -0,0 +1,27 @@
+import { TRPCError } from '@trpc/server';
+
+import { upsertBanner } from '@documenso/lib/server-only/banner/upsert-banner';
+
+import { adminProcedure, router } from '../trpc';
+import { ZCreateBannerByAdminSchema } from './schema';
+
+export const bannerRouter = router({
+ updateBanner: adminProcedure
+ .input(ZCreateBannerByAdminSchema)
+ .mutation(async ({ input, ctx }) => {
+ const { show, text } = input;
+
+ try {
+ return await upsertBanner({
+ userId: ctx.user.id,
+ show,
+ text,
+ });
+ } catch (err) {
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: 'We were unable to update your banner. Please try again.',
+ });
+ }
+ }),
+});
diff --git a/packages/trpc/server/banner-router/schema.ts b/packages/trpc/server/banner-router/schema.ts
new file mode 100644
index 000000000..d3260311b
--- /dev/null
+++ b/packages/trpc/server/banner-router/schema.ts
@@ -0,0 +1,8 @@
+import z from 'zod';
+
+export const ZCreateBannerByAdminSchema = z.object({
+ text: z.string().optional(),
+ show: z.boolean().optional(),
+});
+
+export type TCreateBannerByAdminSchema = z.infer<typeof ZCreateBannerByAdminSchema>;
diff --git a/packages/trpc/server/router.ts b/packages/trpc/server/router.ts
index aec70fd63..424b09ea3 100644
--- a/packages/trpc/server/router.ts
+++ b/packages/trpc/server/router.ts
@@ -1,5 +1,6 @@
import { adminRouter } from './admin-router/router';
import { authRouter } from './auth-router/router';
+import { bannerRouter } from './banner-router/router';
import { cryptoRouter } from './crypto/router';
import { documentRouter } from './document-router/router';
import { fieldRouter } from './field-router/router';
@@ -14,6 +15,7 @@ import { twoFactorAuthenticationRouter } from './two-factor-authentication-route
export const appRouter = router({
auth: authRouter,
+ banner: bannerRouter,
crypto: cryptoRouter,
profile: profileRouter,
document: documentRouter,