⚡️⚡️⚡️ Self-hosted collaborative bookmark manager to collect, read, annotate, and fully preserve what matters, all in one place.
TypeScript bookmarkbookmark-managercollaborationnextjsreact-nativeread-it-laterself-hostedtypescript
finalizing team support
daniel31x13665019dc59c6
diff --git a/components/ModalContent/DeleteUserModal.tsx b/components/ModalContent/DeleteUserModal.tsxindex 77931c66..c7d5a4ac 100644--- a/components/ModalContent/DeleteUserModal.tsx+++ b/components/ModalContent/DeleteUserModal.tsx@@ -3,6 +3,7 @@ import Button from "../ui/Button";import { useTranslation } from "next-i18next";import { useDeleteUser } from "@/hooks/store/admin/users";import { useState } from "react";+import { useSession } from "next-auth/react";type Props = {onClose: Function;@@ -30,25 +31,33 @@ export default function DeleteUserModal({ onClose, userId }: Props) {}};+ const { data } = useSession();+ const isAdmin = data?.user?.id === Number(process.env.NEXT_PUBLIC_ADMIN);+return (<Modal toggleModal={onClose}>- <p className="text-xl font-thin text-red-500">{t("delete_user")}</p>+ <p className="text-xl font-thin text-red-500">+ {isAdmin ? t("delete_user") : t("remove_user")}+ </p><div className="divider mb-3 mt-1"></div><div className="flex flex-col gap-3"><p>{t("confirm_user_deletion")}</p>+ <p>{t("confirm_user_removal_desc")}</p>- <div role="alert" className="alert alert-warning">- <i className="bi-exclamation-triangle text-xl" />- <span>- <b>{t("warning")}:</b> {t("irreversible_action_warning")}- </span>- </div>+ {isAdmin && (+ <div role="alert" className="alert alert-warning">+ <i className="bi-exclamation-triangle text-xl" />+ <span>+ <b>{t("warning")}:</b> {t("irreversible_action_warning")}+ </span>+ </div>+ )}<Button className="ml-auto" intent="destructive" onClick={submit}><i className="bi-trash text-xl" />- {t("delete_confirmation")}+ {isAdmin ? t("delete_confirmation") : t("confirm")}</Button></div></Modal>diff --git a/components/ModalContent/EditCollectionSharingModal.tsx b/components/ModalContent/EditCollectionSharingModal.tsxindex 16c61bee..f44336f5 100644--- a/components/ModalContent/EditCollectionSharingModal.tsx+++ b/components/ModalContent/EditCollectionSharingModal.tsx@@ -150,12 +150,12 @@ export default function EditCollectionSharingModal({<TextInputvalue={memberUsername || ""}className="bg-base-200"- placeholder={t("members_username_placeholder")}+ placeholder={t("add_member_placeholder")}onChange={(e) => setMemberUsername(e.target.value)}onKeyDown={(e) =>e.key === "Enter" &&addMemberToCollection(- user.username as string,+ user,memberUsername || "",collection,setMemberState,@@ -167,7 +167,7 @@ export default function EditCollectionSharingModal({<divonClick={() =>addMemberToCollection(- user.username as string,+ user,memberUsername || "",collection,setMemberState,diff --git a/components/ModalContent/InviteModal.tsx b/components/ModalContent/InviteModal.tsxindex 1cb92d20..6d83e83e 100644--- a/components/ModalContent/InviteModal.tsx+++ b/components/ModalContent/InviteModal.tsx@@ -49,13 +49,13 @@ export default function InviteModal({ onClose }: Props) {await addUser.mutateAsync(form, {onSettled: () => {setSubmitLoader(false);- signIn("invite", {+ },+ onSuccess: async () => {+ await signIn("invite", {email: form.email,callbackUrl: "/member-onboarding",redirect: false,});- },- onSuccess: () => {onClose();},});diff --git a/components/ProfileDropdown.tsx b/components/ProfileDropdown.tsxindex acab61e8..81e0505b 100644--- a/components/ProfileDropdown.tsx+++ b/components/ProfileDropdown.tsx@@ -12,7 +12,6 @@ export default function ProfileDropdown() {const { data: user = {} } = useUser();const isAdmin = user.id === Number(process.env.NEXT_PUBLIC_ADMIN || 1);- const DISABLE_INVITES = process.env.DISABLE_INVITES === "true";const handleToggle = () => {const newTheme = settings.theme === "dark" ? "light" : "dark";@@ -74,16 +73,16 @@ export default function ProfileDropdown() {</Link></li>)}- {!DISABLE_INVITES && (+ {!user.parentSubscriptionId && (<li><Link- href="/team"+ href="/settings/billing"onClick={() => (document?.activeElement as HTMLElement)?.blur()}tabIndex={0}role="button"className="whitespace-nowrap">- {t("manage_team")}+ {t("invite_users")}</Link></li>)}diff --git a/components/ui/Divider.tsx b/components/ui/Divider.tsxnew file mode 100644index 00000000..80f50d85--- /dev/null+++ b/components/ui/Divider.tsx@@ -0,0 +1,12 @@+import clsx from "clsx";+import React from "react";++type Props = {+ className?: string;+};++function Divider({ className }: Props) {+ return <hr className={clsx("border-neutral-content border-t", className)} />;+}++export default Divider;diff --git a/layouts/AuthRedirect.tsx b/layouts/AuthRedirect.tsxindex ad1d0be8..969427e7 100644--- a/layouts/AuthRedirect.tsx+++ b/layouts/AuthRedirect.tsx@@ -44,7 +44,6 @@ export default function AuthRedirect({ children }: Props) {{ path: "/tags", isProtected: true },{ path: "/preserved", isProtected: true },{ path: "/admin", isProtected: true },- { path: "/team", isProtected: true },{ path: "/search", isProtected: true },];diff --git a/lib/api/controllers/collections/collectionId/updateCollectionById.ts b/lib/api/controllers/collections/collectionId/updateCollectionById.tsindex 0319a650..2f78d1c9 100644--- a/lib/api/controllers/collections/collectionId/updateCollectionById.ts+++ b/lib/api/controllers/collections/collectionId/updateCollectionById.ts@@ -58,6 +58,12 @@ export default async function updateCollection(}}+ const uniqueMembers = data.members.filter(+ (e, i, a) =>+ a.findIndex((el) => el.userId === e.userId) === i &&+ e.userId !== collectionIsAccessible.ownerId+ );+const updatedCollection = await prisma.$transaction(async () => {await prisma.usersAndCollections.deleteMany({where: {@@ -91,7 +97,7 @@ export default async function updateCollection(}: undefined,members: {- create: data.members.map((e) => ({+ create: uniqueMembers.map((e) => ({user: { connect: { id: e.userId } },canCreate: e.canCreate,canUpdate: e.canUpdate,diff --git a/lib/api/controllers/public/users/getPublicUser.ts b/lib/api/controllers/public/users/getPublicUser.tsindex 68b6faba..66bf613b 100644--- a/lib/api/controllers/public/users/getPublicUser.ts+++ b/lib/api/controllers/public/users/getPublicUser.ts@@ -5,13 +5,20 @@ export default async function getPublicUser(isId: boolean,requestingId?: number) {- const user = await prisma.user.findUnique({+ const user = await prisma.user.findFirst({where: isId? {id: Number(targetId) as number,}: {- username: targetId as string,+ OR: [+ {+ username: targetId as string,+ },+ {+ email: targetId as string,+ },+ ],},include: {whitelistedUsers: {@@ -22,7 +29,7 @@ export default async function getPublicUser(},});- if (!user)+ if (!user || !user.id)return { response: "User not found or profile is private.", status: 404 };const whitelistedUsernames = user.whitelistedUsers?.map(@@ -31,7 +38,7 @@ export default async function getPublicUser(const isInAPublicCollection = await prisma.collection.findFirst({where: {- ["OR"]: [+ OR: [{ ownerId: user.id },{members: {@@ -73,6 +80,7 @@ export default async function getPublicUser(id: lessSensitiveInfo.id,name: lessSensitiveInfo.name,username: lessSensitiveInfo.username,+ email: lessSensitiveInfo.email,image: lessSensitiveInfo.image,archiveAsScreenshot: lessSensitiveInfo.archiveAsScreenshot,archiveAsMonolith: lessSensitiveInfo.archiveAsMonolith,diff --git a/lib/api/controllers/users/getUsers.ts b/lib/api/controllers/users/getUsers.tsindex dd589c52..2175fd9d 100644--- a/lib/api/controllers/users/getUsers.ts+++ b/lib/api/controllers/users/getUsers.ts@@ -1,21 +1,71 @@import { prisma } from "@/lib/api/db";+import { User } from "@prisma/client";-export default async function getUsers() {- // Get all users- const users = await prisma.user.findMany({- select: {- id: true,- username: true,- email: true,- emailVerified: true,- subscriptions: {+export default async function getUsers(user: User) {+ if (user.id === Number(process.env.NEXT_PUBLIC_ADMIN || 1)) {+ const users = await prisma.user.findMany({+ select: {+ id: true,+ username: true,+ email: true,+ emailVerified: true,+ subscriptions: {+ select: {+ active: true,+ },+ },+ createdAt: true,+ },+ });++ return {+ response: users.sort((a: any, b: any) => a.id - b.id),+ status: 200,+ };+ } else {+ let subscriptionId = (+ await prisma.subscription.findFirst({+ where: {+ userId: user.id,+ },select: {- active: true,+ id: true,},+ })+ )?.id;++ if (!subscriptionId)+ return {+ response: "Subscription not found.",+ status: 404,+ };++ const users = await prisma.user.findMany({+ where: {+ OR: [+ {+ parentSubscriptionId: subscriptionId,+ },+ {+ subscriptions: {+ id: subscriptionId,+ },+ },+ ],+ },+ select: {+ id: true,+ name: true,+ username: true,+ email: true,+ emailVerified: true,+ createdAt: true,},- createdAt: true,- },- });+ });- return { response: users.sort((a: any, b: any) => a.id - b.id), status: 200 };+ return {+ response: users.sort((a: any, b: any) => a.id - b.id),+ status: 200,+ };+ }}diff --git a/lib/api/controllers/users/userId/deleteUserById.ts b/lib/api/controllers/users/userId/deleteUserById.tsindex a4818939..2c3d864b 100644--- a/lib/api/controllers/users/userId/deleteUserById.ts+++ b/lib/api/controllers/users/userId/deleteUserById.ts@@ -4,15 +4,19 @@ import removeFolder from "@/lib/api/storage/removeFolder";import Stripe from "stripe";import { DeleteUserBody } from "@/types/global";import removeFile from "@/lib/api/storage/removeFile";+import updateSeats from "@/lib/api/stripe/updateSeats";export default async function deleteUserById(userId: number,body: DeleteUserBody,- isServerAdmin?: boolean+ isServerAdmin: boolean,+ queryId: number) {- // First, we retrieve the user from the databaseconst user = await prisma.user.findUnique({where: { id: userId },+ include: {+ subscriptions: true,+ },});if (!user) {@@ -23,21 +27,74 @@ export default async function deleteUserById(}if (!isServerAdmin) {- if (user.password) {- const isPasswordValid = bcrypt.compareSync(body.password, user.password);+ if (queryId === userId) {+ if (user.password) {+ const isPasswordValid = bcrypt.compareSync(+ body.password,+ user.password+ );- if (!isPasswordValid && !isServerAdmin) {+ if (!isPasswordValid && !isServerAdmin) {+ return {+ response: "Invalid credentials.",+ status: 401,+ };+ }+ } else {return {- response: "Invalid credentials.",- status: 401, // Unauthorized+ response:+ "User has no password. Please reset your password from the forgot password page.",+ status: 401,};}} else {- return {- response:- "User has no password. Please reset your password from the forgot password page.",- status: 401, // Unauthorized- };+ if (user.parentSubscriptionId) {+ console.log(userId, user.parentSubscriptionId);++ return {+ response: "Permission denied.",+ status: 401,+ };+ } else {+ if (!user.subscriptions) {+ return {+ response: "User has no subscription.",+ status: 401,+ };+ }++ const findChild = await prisma.user.findFirst({+ where: { id: queryId, parentSubscriptionId: user.subscriptions?.id },+ });++ if (!findChild)+ return {+ response: "Permission denied.",+ status: 401,+ };++ const removeUser = await prisma.user.update({+ where: { id: findChild.id },+ data: {+ parentSubscription: {+ disconnect: true,+ },+ },+ select: {+ id: true,+ },+ });++ await updateSeats(+ user.subscriptions.stripeSubscriptionId,+ user.subscriptions.quantity - 1+ );++ return {+ response: removeUser,+ status: 200,+ };+ }}}@@ -47,27 +104,27 @@ export default async function deleteUserById(async (prisma) => {// Delete Access Tokensawait prisma.accessToken.deleteMany({- where: { userId },+ where: { userId: queryId },});// Delete whitelisted usersawait prisma.whitelistedUser.deleteMany({- where: { userId },+ where: { userId: queryId },});// Delete linksawait prisma.link.deleteMany({- where: { collection: { ownerId: userId } },+ where: { collection: { ownerId: queryId } },});// Delete tagsawait prisma.tag.deleteMany({- where: { ownerId: userId },+ where: { ownerId: queryId },});// Find collections that the user ownsconst collections = await prisma.collection.findMany({- where: { ownerId: userId },+ where: { ownerId: queryId },});for (const collection of collections) {@@ -86,29 +143,29 @@ export default async function deleteUserById(// Delete collections after cleaning up related dataawait prisma.collection.deleteMany({- where: { ownerId: userId },+ where: { ownerId: queryId },});// Delete subscriptionif (process.env.STRIPE_SECRET_KEY)await prisma.subscription.delete({- where: { userId },+ where: { userId: queryId },}).catch((err) => console.log(err));await prisma.usersAndCollections.deleteMany({where: {- OR: [{ userId: userId }, { collection: { ownerId: userId } }],+ OR: [{ userId: queryId }, { collection: { ownerId: queryId } }],},});// Delete user's avatar- await removeFile({ filePath: `uploads/avatar/${userId}.jpg` });+ await removeFile({ filePath: `uploads/avatar/${queryId}.jpg` });// Finally, delete the userawait prisma.user.delete({- where: { id: userId },+ where: { id: queryId },});},{ timeout: 20000 }diff --git a/lib/api/controllers/users/userId/getUserById.ts b/lib/api/controllers/users/userId/getUserById.tsindex f704155e..062a70a1 100644--- a/lib/api/controllers/users/userId/getUserById.ts+++ b/lib/api/controllers/users/userId/getUserById.ts@@ -35,6 +35,7 @@ export default async function getUserById(userId: number) {whitelistedUsers: whitelistedUsernames,subscription: {active: subscriptions?.active,+ quantity: subscriptions?.quantity,},parentSubscription: {active: parentSubscription?.active,diff --git a/lib/api/controllers/users/userId/updateUserById.ts b/lib/api/controllers/users/userId/updateUserById.tsindex 49e5c4c5..6dd09a87 100644--- a/lib/api/controllers/users/userId/updateUserById.ts+++ b/lib/api/controllers/users/userId/updateUserById.ts@@ -277,6 +277,7 @@ export default async function updateUserById(image: userInfo.image ? `${userInfo.image}?${Date.now()}` : "",subscription: {active: subscriptions?.active,+ quantity: subscriptions?.quantity,},parentSubscription: {active: parentSubscription?.active,diff --git a/lib/client/addMemberToCollection.ts b/lib/client/addMemberToCollection.tsindex 4e03720e..7fa138f1 100644--- a/lib/client/addMemberToCollection.ts+++ b/lib/client/addMemberToCollection.ts@@ -2,9 +2,10 @@ import { CollectionIncludingMembersAndLinkCount, Member } from "@/types/global";import getPublicUserData from "./getPublicUserData";import { toast } from "react-hot-toast";import { TFunction } from "i18next";+import { User } from "@prisma/client";const addMemberToCollection = async (- ownerUsername: string,+ owner: User,memberUsername: string,collection: CollectionIncludingMembersAndLinkCount,setMember: (newMember: Member) => null | undefined,@@ -12,7 +13,12 @@ const addMemberToCollection = async () => {const checkIfMemberAlreadyExists = collection.members.find((e) => {const username = (e.user.username || "").toLowerCase();- return username === memberUsername.toLowerCase();+ const email = (e.user.email || "").toLowerCase();++ return (+ username === memberUsername.toLowerCase() ||+ email === memberUsername.toLowerCase()+ );});if (@@ -21,7 +27,8 @@ const addMemberToCollection = async (// member can't be emptymemberUsername.trim() !== "" &&// member can't be the owner- memberUsername.trim().toLowerCase() !== ownerUsername.toLowerCase()+ memberUsername.trim().toLowerCase() !== owner.username?.toLowerCase() &&+ memberUsername.trim().toLowerCase() !== owner.email?.toLowerCase()) {// Lookup, get data/err, list ...const user = await getPublicUserData(memberUsername.trim().toLowerCase());@@ -37,12 +44,16 @@ const addMemberToCollection = async (id: user.id,name: user.name,username: user.username,+ email: user.email,image: user.image,},});}} else if (checkIfMemberAlreadyExists) toast.error(t("user_already_member"));- else if (memberUsername.trim().toLowerCase() === ownerUsername.toLowerCase())+ else if (+ memberUsername.trim().toLowerCase() === owner.username?.toLowerCase() ||+ memberUsername.trim().toLowerCase() === owner.email?.toLowerCase()+ )toast.error(t("you_are_already_collection_owner"));};diff --git a/pages/admin.tsx b/pages/admin.tsxindex 31978b66..280e6746 100644--- a/pages/admin.tsx+++ b/pages/admin.tsx@@ -6,6 +6,7 @@ import { useTranslation } from "next-i18next";import getServerSideProps from "@/lib/client/getServerSideProps";import UserListing from "@/components/UserListing";import { useUsers } from "@/hooks/store/admin/users";+import Divider from "@/components/ui/Divider";interface User extends U {subscriptions: {@@ -88,7 +89,7 @@ export default function Admin() {</div></div>- <div className="divider my-3"></div>+ <Divider className="my-3" />{filteredUsers && filteredUsers.length > 0 && searchQuery !== "" ? (UserListing(filteredUsers, deleteUserModal, setDeleteUserModal, t)diff --git a/pages/api/v1/users/[id].ts b/pages/api/v1/users/[id].tsindex 161338d9..9cf4fc93 100644--- a/pages/api/v1/users/[id].ts+++ b/pages/api/v1/users/[id].ts@@ -11,6 +11,12 @@ const STRIPE_SECRET_KEY = process.env.STRIPE_SECRET_KEY;export default async function users(req: NextApiRequest, res: NextApiResponse) {const token = await verifyToken({ req });+ const queryId = Number(req.query.id);++ if (!queryId) {+ return res.status(400).json({ response: "Invalid request." });+ }+if (typeof token === "string") {res.status(401).json({ response: token });return null;@@ -24,12 +30,12 @@ export default async function users(req: NextApiRequest, res: NextApiResponse) {const isServerAdmin = user?.id === Number(process.env.NEXT_PUBLIC_ADMIN || 1);- const userId = isServerAdmin ? Number(req.query.id) : token.id;-- if (userId !== Number(req.query.id) && !isServerAdmin)- return res.status(401).json({ response: "Permission denied." });+ const userId = token.id;if (req.method === "GET") {+ if (userId !== queryId && !isServerAdmin)+ return res.status(401).json({ response: "Permission denied." });+const users = await getUserById(userId);return res.status(users.status).json({ response: users.response });}@@ -59,6 +65,9 @@ export default async function users(req: NextApiRequest, res: NextApiResponse) {}if (req.method === "PUT") {+ if (userId !== queryId && !isServerAdmin)+ return res.status(401).json({ response: "Permission denied." });+if (process.env.NEXT_PUBLIC_DEMO === "true")return res.status(400).json({response:@@ -74,7 +83,12 @@ export default async function users(req: NextApiRequest, res: NextApiResponse) {"This action is disabled because this is a read-only demo of Linkwarden.",});- const updated = await deleteUserById(userId, req.body, isServerAdmin);+ const updated = await deleteUserById(+ userId,+ req.body,+ isServerAdmin,+ queryId+ );return res.status(updated.status).json({ response: updated.response });}}diff --git a/pages/api/v1/users/index.ts b/pages/api/v1/users/index.tsindex 356a9f01..feebb5a2 100644--- a/pages/api/v1/users/index.ts+++ b/pages/api/v1/users/index.ts@@ -16,10 +16,9 @@ export default async function users(req: NextApiRequest, res: NextApiResponse) {} else if (req.method === "GET") {const user = await verifyUser({ req, res });- if (!user || user.id !== Number(process.env.NEXT_PUBLIC_ADMIN || 1))- return res.status(401).json({ response: "Unauthorized..." });+ if (!user) return res.status(401).json({ response: "Unauthorized..." });- const response = await getUsers();+ const response = await getUsers(user);return res.status(response.status).json({ response: response.response });}}diff --git a/pages/member-onboarding.tsx b/pages/member-onboarding.tsxindex 7e76d102..57aad687 100644--- a/pages/member-onboarding.tsx+++ b/pages/member-onboarding.tsx@@ -8,7 +8,6 @@ import { toast } from "react-hot-toast";import getServerSideProps from "@/lib/client/getServerSideProps";import { Trans, useTranslation } from "next-i18next";import { useUpdateUser, useUser } from "@/hooks/store/user";-import { useSession } from "next-auth/react";interface FormData {password: string;@@ -28,8 +27,6 @@ export default function MemberOnboarding() {const { data: user = {} } = useUser();const updateUser = useUpdateUser();- const { status } = useSession();-useEffect(() => {toast.success(t("accepted_invitation_please_fill"));}, []);@@ -146,7 +143,7 @@ export default function MemberOnboarding() {size="full"loading={submitLoader}>- {t("sign_up")}+ {t("continue_to_dashboard")}</Button></div></form>diff --git a/pages/settings/access-tokens.tsx b/pages/settings/access-tokens.tsxindex f75789d3..963b5125 100644--- a/pages/settings/access-tokens.tsx+++ b/pages/settings/access-tokens.tsx@@ -67,10 +67,18 @@ export default function AccessTokens() {)}</td><td>- {new Date(token.createdAt || "").toLocaleDateString()}+ {new Date(token.createdAt).toLocaleDateString("en-US", {+ month: "short",+ day: "numeric",+ year: "numeric",+ })}</td><td>- {new Date(token.expires || "").toLocaleDateString()}+ {new Date(token.expires).toLocaleDateString("en-US", {+ month: "short",+ day: "numeric",+ year: "numeric",+ })}</td><td><buttondiff --git a/pages/settings/billing.tsx b/pages/settings/billing.tsxindex a5abb98f..1c561e34 100644--- a/pages/settings/billing.tsx+++ b/pages/settings/billing.tsx@@ -1,8 +1,28 @@import SettingsLayout from "@/layouts/SettingsLayout";import { useRouter } from "next/router";-import { useEffect } from "react";+import InviteModal from "@/components/ModalContent/InviteModal";+import { User as U } from "@prisma/client";+import { useEffect, useState } from "react";import { useTranslation } from "next-i18next";import getServerSideProps from "@/lib/client/getServerSideProps";+import { useUsers } from "@/hooks/store/admin/users";+import DeleteUserModal from "@/components/ModalContent/DeleteUserModal";+import { useUser } from "@/hooks/store/user";+import { dropdownTriggerer } from "@/lib/client/utils";+import clsx from "clsx";+import { signIn } from "next-auth/react";+import toast from "react-hot-toast";++interface User extends U {+ subscriptions: {+ active: boolean;+ };+}++type UserModal = {+ isOpen: boolean;+ userId: number | null;+};export default function Billing() {const router = useRouter();@@ -12,6 +32,25 @@ export default function Billing() {if (!process.env.NEXT_PUBLIC_STRIPE) router.push("/settings/profile");}, []);+ const { data: users = [] } = useUsers();+ const { data: account } = useUser();++ const [searchQuery, setSearchQuery] = useState("");+ const [filteredUsers, setFilteredUsers] = useState<User[]>();++ useEffect(() => {+ if (users.length > 0) {+ setFilteredUsers(users);+ }+ }, [users]);++ const [deleteUserModal, setDeleteUserModal] = useState<UserModal>({+ isOpen: false,+ userId: null,+ });++ const [inviteModal, setInviteModal] = useState(false);+return (<SettingsLayout><p className="capitalize text-3xl font-thin inline">@@ -40,6 +79,190 @@ export default function Billing() {</a></p></div>++ <div className="flex items-center gap-2 w-full rounded-md h-8 mt-5">+ <p className="truncate w-full pr-7 text-3xl font-thin">+ {t("manage_seats")}+ </p>+ </div>++ <div className="divider my-3"></div>++ <div className="flex items-center justify-between gap-2 mb-3 relative">+ <div>+ <label+ htmlFor="search-box"+ className="inline-flex items-center w-fit absolute left-1 pointer-events-none rounded-md p-1 text-primary"+ >+ <i className="bi-search"></i>+ </label>++ <input+ id="search-box"+ type="text"+ placeholder={t("search_users")}+ value={searchQuery}+ onChange={(e) => {+ setSearchQuery(e.target.value);++ if (users) {+ setFilteredUsers(+ users.filter((user: any) =>+ JSON.stringify(user)+ .toLowerCase()+ .includes(e.target.value.toLowerCase())+ )+ );+ }+ }}+ className="border border-neutral-content bg-base-200 focus:border-primary py-1 rounded-md pl-9 pr-2 w-full max-w-[15rem] md:w-[15rem] md:max-w-full duration-200 outline-none"+ />+ </div>++ <div className="flex gap-3">+ <div+ onClick={() => setInviteModal(true)}+ className="flex items-center btn btn-accent dark:border-violet-400 text-white btn-sm px-2 h-[2.15rem] relative"+ >+ <p>{t("invite_user")}</p>+ <i className="bi-plus text-2xl"></i>+ </div>+ </div>+ </div>++ <div className="border rounded-md shadow border-neutral-content">+ <table className="table bg-base-300 rounded-md">+ <thead>+ <tr className="sm:table-row hidden border-b-neutral-content">+ {process.env.NEXT_PUBLIC_EMAIL_PROVIDER === "true" && (+ <th>{t("email")}</th>+ )}+ {process.env.NEXT_PUBLIC_STRIPE === "true" && (+ <th>{t("status")}</th>+ )}+ <th>{t("date_added")}</th>+ </tr>+ </thead>+ <tbody>+ {filteredUsers?.map((user, index) => (+ <tr+ key={index}+ className={clsx(+ "group border-b-neutral-content duration-100 w-full relative flex flex-col sm:table-row",+ user.id !== account.id &&+ "hover:bg-neutral-content hover:bg-opacity-30"+ )}+ >+ {process.env.NEXT_PUBLIC_EMAIL_PROVIDER === "true" && (+ <td className="truncate max-w-full" title={user.email || ""}>+ <p className="sm:hidden block text-neutral text-xs font-bold mb-2">+ {t("email")}+ </p>+ <p>{user.email}</p>+ </td>+ )}+ {process.env.NEXT_PUBLIC_STRIPE === "true" && (+ <td>+ <p className="sm:hidden block text-neutral text-xs font-bold mb-2">+ {t("status")}+ </p>+ {user.emailVerified ? (+ <p className="font-bold px-2 bg-green-600 text-white rounded-md w-fit">+ {t("active")}+ </p>+ ) : (+ <p className="font-bold px-2 bg-neutral-content rounded-md w-fit">+ {t("pending")}+ </p>+ )}+ </td>+ )}+ <td>+ <p className="sm:hidden block text-neutral text-xs font-bold mb-2">+ {t("date_added")}+ </p>+ <p className="whitespace-nowrap">+ {new Date(user.createdAt).toLocaleDateString("en-US", {+ month: "short",+ day: "numeric",+ year: "numeric",+ })}+ </p>+ </td>+ {user.id !== account.id && (+ <td>+ <div+ className={`dropdown dropdown-bottom font-normal dropdown-end absolute right-[0.35rem] top-[0.35rem]`}+ >+ <div+ tabIndex={0}+ role="button"+ onMouseDown={dropdownTriggerer}+ className="btn btn-ghost btn-sm btn-square duration-100"+ >+ <i+ className={"bi bi-three-dots text-lg text-neutral"}+ ></i>+ </div>+ <ul className="dropdown-content z-[30] menu shadow bg-base-200 border border-neutral-content rounded-box mt-1">+ {!user.emailVerified ? (+ <li>+ <div+ role="button"+ tabIndex={0}+ onClick={() => {+ (+ document?.activeElement as HTMLElement+ )?.blur();+ signIn("invite", {+ email: user.email,+ callbackUrl: "/member-onboarding",+ redirect: false,+ }).then(() =>+ toast.success(t("resend_invite_success"))+ );+ }}+ className="whitespace-nowrap"+ >+ {t("resend_invite")}+ </div>+ </li>+ ) : undefined}+ <li>+ <div+ role="button"+ tabIndex={0}+ onClick={() => {+ (document?.activeElement as HTMLElement)?.blur();+ setDeleteUserModal({+ isOpen: true,+ userId: user.id,+ });+ }}+ className="whitespace-nowrap"+ >+ {t("remove_user")}+ </div>+ </li>+ </ul>+ </div>+ </td>+ )}+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ <p className="text-sm text-center font-bold mt-3">+ {t("seats_purchased", { count: account?.subscription?.quantity })}+ </p>+ {inviteModal && <InviteModal onClose={() => setInviteModal(false)} />}+ {deleteUserModal.isOpen && deleteUserModal.userId && (+ <DeleteUserModal+ onClose={() => setDeleteUserModal({ isOpen: false, userId: null })}+ userId={deleteUserModal.userId}+ />+ )}</SettingsLayout>);}diff --git a/pages/team.tsx b/pages/team.tsxdeleted file mode 100644index 6f81842f..00000000--- a/pages/team.tsx+++ /dev/null@@ -1,108 +0,0 @@-import InviteModal from "@/components/ModalContent/InviteModal";-import { User as U } from "@prisma/client";-import Link from "next/link";-import { useState } from "react";-import { useTranslation } from "next-i18next";-import getServerSideProps from "@/lib/client/getServerSideProps";-import UserListing from "@/components/UserListing";-import { useUsers } from "@/hooks/store/admin/users";--interface User extends U {- subscriptions: {- active: boolean;- };-}--type UserModal = {- isOpen: boolean;- userId: number | null;-};--export default function Admin() {- const { t } = useTranslation();-- const { data: users = [] } = useUsers();-- const [searchQuery, setSearchQuery] = useState("");- const [filteredUsers, setFilteredUsers] = useState<User[]>();-- const [deleteUserModal, setDeleteUserModal] = useState<UserModal>({- isOpen: false,- userId: null,- });-- const [inviteModal, setInviteModal] = useState(false);-- return (- <div className="max-w-6xl mx-auto p-5">- <div className="flex sm:flex-row flex-col justify-between gap-2">- <div className="gap-2 inline-flex items-center">- <Link- href="/dashboard"- className="text-neutral btn btn-square btn-sm btn-ghost"- >- <i className="bi-chevron-left text-xl"></i>- </Link>- <p className="capitalize text-3xl font-thin inline">- {t("team_management")}- </p>- </div>-- <div className="flex items-center relative justify-between gap-2">- <div>- <label- htmlFor="search-box"- className="inline-flex items-center w-fit absolute left-1 pointer-events-none rounded-md p-1 text-primary"- >- <i className="bi-search"></i>- </label>-- <input- id="search-box"- type="text"- placeholder={t("search_users")}- value={searchQuery}- onChange={(e) => {- setSearchQuery(e.target.value);-- if (users) {- setFilteredUsers(- users.filter((user: any) =>- JSON.stringify(user)- .toLowerCase()- .includes(e.target.value.toLowerCase())- )- );- }- }}- className="border border-neutral-content bg-base-200 focus:border-primary py-1 rounded-md pl-9 pr-2 w-full max-w-[15rem] md:w-[15rem] md:max-w-full duration-200 outline-none"- />- </div>-- <div- onClick={() => setInviteModal(true)}- className="flex items-center btn btn-accent dark:border-violet-400 text-white btn-sm px-2 aspect-square relative"- >- <i className="bi-plus text-3xl absolute"></i>- </div>- </div>- </div>-- <div className="divider my-3"></div>-- {filteredUsers && filteredUsers.length > 0 && searchQuery !== "" ? (- UserListing(filteredUsers, deleteUserModal, setDeleteUserModal, t)- ) : searchQuery !== "" ? (- <p>{t("no_user_found_in_search")}</p>- ) : users && users.length > 0 ? (- UserListing(users, deleteUserModal, setDeleteUserModal, t)- ) : (- <p>{t("no_users_found")}</p>- )}-- {inviteModal && <InviteModal onClose={() => setInviteModal(false)} />}- </div>- );-}--export { getServerSideProps };diff --git a/prisma/migrations/20241027093300_remove_field/migration.sql b/prisma/migrations/20241027093300_remove_field/migration.sqlnew file mode 100644index 00000000..2020a272--- /dev/null+++ b/prisma/migrations/20241027093300_remove_field/migration.sql@@ -0,0 +1,11 @@+/*+ Warnings:++ - You are about to drop the column `teamRole` on the `User` table. All the data in the column will be lost.++*/+-- AlterTable+ALTER TABLE "User" DROP COLUMN "teamRole";++-- DropEnum+DROP TYPE "TeamRole";diff --git a/prisma/migrations/20241027104510_remove_field/migration.sql b/prisma/migrations/20241027104510_remove_field/migration.sqlnew file mode 100644index 00000000..a0dcd089--- /dev/null+++ b/prisma/migrations/20241027104510_remove_field/migration.sql@@ -0,0 +1,8 @@+/*+ Warnings:++ - You are about to drop the column `teamId` on the `Collection` table. All the data in the column will be lost.++*/+-- AlterTable+ALTER TABLE "Collection" DROP COLUMN "teamId";diff --git a/prisma/schema.prisma b/prisma/schema.prismaindex d06b717b..ee369ddd 100644--- a/prisma/schema.prisma+++ b/prisma/schema.prisma@@ -37,7 +37,6 @@ model User {locale String @default("en")parentSubscription Subscription? @relation("ChildUsers", fields: [parentSubscriptionId], references: [id])parentSubscriptionId Int?- teamRole TeamRole @default(ADMIN)accounts Account[]collections Collection[]tags Tag[]@@ -77,11 +76,6 @@ model WhitelistedUser {updatedAt DateTime @default(now()) @updatedAt}-enum TeamRole {- MEMBER- ADMIN-}-model VerificationToken {identifier Stringtoken String @unique@@ -114,7 +108,6 @@ model Collection {owner User @relation(fields: [ownerId], references: [id])ownerId Intmembers UsersAndCollections[]- teamId Int?createdBy User @relation("CreatedCollections", fields: [createdById], references: [id])createdById Intlinks Link[]diff --git a/public/locales/en/common.json b/public/locales/en/common.jsonindex b493c75a..6db7bb04 100644--- a/public/locales/en/common.json+++ b/public/locales/en/common.json@@ -318,7 +318,7 @@"sharable_link": "Sharable Link","copied": "Copied!","members": "Members",- "members_username_placeholder": "Username (without the '@')",+ "add_member_placeholder": "Add members by email or username","owner": "Owner","admin": "Admin","contributor": "Contributor",@@ -397,14 +397,25 @@"invalid_url_guide":"Please enter a valid Address for the Link. (It should start with http/https)","email_invalid": "Please enter a valid email address.","username_invalid_guide": "Username has to be at least 3 characters, no spaces and special characters are allowed.",- "manage_team": "Manage Team","team_management": "Team Management","invite_user": "Invite User",+ "invite_users": "Invite Users","invite_user_desc": "To invite someone to your team, please enter their email address below:",- "invite_user_note": "Please note that once the invitation is accepted, an additional seat will be used and your account will automatically be billed for this addition.",+ "invite_user_note": "Please note that once the invitation is accepted, an additional seat will be purchased and your account will automatically be billed for this addition.","send_invitation": "Send Invitation","learn_more": "Learn more","finalize_profile": "Finalize Your Profile","invitation_desc": "{{owner}} invited you to join Linkwarden. \nTo continue, please finish setting up your account.",- "accepted_invitation_please_fill": "You've accepted the invitation to join Linkwarden. Please fill out the following to finalize your account."+ "accepted_invitation_please_fill": "You've accepted the invitation to join Linkwarden. Please fill out the following to finalize your account.",+ "status": "Status",+ "pending": "Pending",+ "active": "Active",+ "manage_seats": "Manage Seats",+ "seats_purchased": "{{count}} seats purchased",+ "date_added": "Date Added",+ "resend_invite": "Resend Invitation",+ "resend_invite_success": "Invitation Resent!",+ "remove_user": "Remove User",+ "continue_to_dashboard": "Continue to Dashboard",+ "confirm_user_removal_desc": "They will need to have a subscription to access Linkwarden again."}\ No newline at end of filediff --git a/types/global.ts b/types/global.tsindex 2be9f815..39da331d 100644--- a/types/global.ts+++ b/types/global.ts@@ -32,7 +32,7 @@ export interface Member {canCreate: boolean;canUpdate: boolean;canDelete: boolean;- user: OptionalExcluding<User, "username" | "name" | "id">;+ user: OptionalExcluding<User, "email" | "username" | "name" | "id">;}export interface CollectionIncludingMembersAndLinkCount