Skip to content

feat: add public profiles - #1180

Merged
Mythie merged 16 commits into
mainfrom
feat/public-profiles
Jun 27, 2024
Merged

Mythie merged 16 commits into
mainfrom
feat/public-profiles

Conversation

@dguyen

@dguyen dguyen commented Jun 6, 2024 •

Copy link
Copy Markdown
Collaborator

Description

Add public profiles

Changes

  • Add profiles settings page for users and teams
  • Add profiles page /p/<url>

Draft

  • Pending tests
  • UI changes to promote public profiles (sign up, etc)

Summary by CodeRabbit

  • New Features

    • Introduced avatar image upload and management.
    • Added public profile view and settings.
    • Implemented public templates management.
    • Provided 404 error handling for missing profiles.
  • Enhancements

    • Updated profiles with more detailed information.
    • Improved navigation to include public profile settings.
    • Enhanced team settings page titles and subtitles.
  • Bug Fixes

    • Ensured URL length checks are correctly handled in profile updates.
  • Documentation

    • Updated navigation and settings documentation to reflect new public profile features.

@vercel

vercel Bot commented Jun 6, 2024 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
stg-app ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jun 27, 2024 0:40am
stg-docs ❌ Failed (Inspect) Jun 27, 2024 0:40am
stg-marketing ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jun 27, 2024 0:40am
2 Ignored Deployments
Name Status Preview Comments Updated (UTC)
prd-app ⬜️ Ignored (Inspect) Jun 27, 2024 0:40am
prd-marketing ⬜️ Ignored (Inspect) Jun 27, 2024 0:40am

@coderabbitai

coderabbitai Bot commented Jun 6, 2024 •

Copy link
Copy Markdown
Contributor

Walkthrough

This update introduces several new features and components to manage user and team profiles, including the ability to view, update, and manage public profiles through new React components and backend functions. It also adds new functionality for avatar image management and incorporates ESLint rule modifications.

Changes

Files Change Summary
.eslintrc.cjs Added 'no-unreachable': 'error' to ESLint rules.
apps/web/src/app/.../profile/page.tsx Replaced ClaimProfileAlertDialog with AvatarImageForm.
apps/web/src/app/.../public-profile/page.tsx Introduced PublicProfilePageView component to display and manage public profiles.
apps/web/src/app/.../public-profile/public-...view.tsx Added PublicProfilePageView component for handling public profile settings.
apps/web/src/app/.../public-profile/public-...table.tsx Added PublicTemplatesDataTable component for managing public templates.
apps/web/src/app/.../layout.tsx Introduced PublicProfileLayout function component.
apps/web/src/app/.../not-found.tsx Added a component for handling 404 profile not found errors.
apps/web/src/app/.../page.tsx Introduced PublicProfilePage component for displaying a public profile page.
apps/web/src/app/.../profile-header.tsx Added ProfileHeader component for dynamic header rendering based on user authentication.
apps/web/src/app/.../settings/page.tsx Changed the title in SettingsHeader from "Team Profile" to "General settings" in team settings.
apps/web/src/app/.../settings/public-profile/page.tsx Introduced function to render public profile page view for teams.
apps/web/src/components/.../layout/desktop-nav.tsx Updated navigation to conditionally render public profile settings link.
apps/web/src/components/.../layout/mobile-nav.tsx Added conditional rendering for public profile settings button based on feature flag.
apps/web/src/components/.../layout/desktop-nav.tsx Introduced feature flag check to conditionally render public profile settings button for teams.
apps/web/src/components/forms/public-profile-form.tsx Added PublicProfileForm component for updating public profile information.
apps/web/src/components/.../public-template-dialog.tsx Introduced ManagePublicTemplateDialog component for managing public templates.
apps/web/src/components/forms/avatar-image.tsx Added AvatarImageForm component for uploading and managing avatar images.
apps/web/src/pages/api/avatar/[id].tsx Added API endpoint to retrieve avatar images based on ID.
packages/lib/constants/feature-flags.ts Added app_public_profile feature flag to the local feature flags.
packages/lib/server-only/.../get-avatar-image.ts Added getAvatarImage function to retrieve avatar images using Prisma and Sharp.
packages/lib/server-only/.../get-public-profile-....ts Added getPublicProfileByUrl function to retrieve user or team public profile by URL.
packages/lib/server-only/.../set-avatar-image.ts Added setAvatarImage function to handle setting avatar images for users or teams using Prisma and Sharp.
packages/prisma/migrations/.../migration.sql Database schema changes including adding an AvatarImage table and modifying Team and User tables.
packages/prisma/schema.prisma Renamed userProfile to profile, updated UserProfile model, added TeamProfile model, and added fields to Template.
packages/trpc/server/profile-router/router.ts Updates to the profileRouter to include bio and enabled fields and added setProfileImage procedure.
packages/trpc/server/profile-router/schema.ts Added MAX_PROFILE_BIO_LENGTH constant.

Amid the code, where changes blend,
A rabbit seeks, the bytes transcend.
New profiles gleam, avatars in place,
Public views, with elegant grace.
Templates managed, forms anew,
With each commit, horizons grew.
In settings wide, flags unfurled,
A digital hop, in a virtual world. 🌐🐇


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@github-actions github-actions Bot added apps: web Issues related to the webapp 🚨 .env changes 🚨 Be advised: PR changes .ENV - Auto-Generated by GitHub Actions on raising a PR labels Jun 6, 2024

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

Outside diff range and nitpick comments (1)
packages/trpc/server/profile-router/router.ts (1)

Line range hint 91-114: Ensure robust validation for public profile URL updates.

The validation logic for the URL length is tied to the billing status, which is a good practice. However, consider adding more comprehensive validation for the URL format itself (e.g., regex validation to ensure it's a valid URL format). This would prevent potential issues with invalid URLs being stored in the database.

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 5cdfdb1 and 19d8b4b.

Files selected for processing (2)
  • packages/prisma/schema.prisma (4 hunks)
  • packages/trpc/server/profile-router/router.ts (2 hunks)
Additional comments not posted (5)
packages/trpc/server/profile-router/router.ts (2)

Line range hint 91-114: Enhanced error handling in public profile updates.

The error handling strategy using AppError.parseErrorToTRPCError is well-implemented. It ensures that only known errors are converted and thrown as TRPC errors, providing a cleaner error response to the client. Good job maintaining consistency in error handling across the application.


Line range hint 1-238: Review of unchanged segments in profile-router.

The procedures for user management such as password updates, account deletion, and email confirmation are well implemented with proper error handling and input validation. No changes are suggested at this time.

packages/prisma/schema.prisma (3)

Line range hint 53-72: UserProfile model review.

The UserProfile model is well-structured with essential fields like id, enabled, userId, and bio. The use of @default(false) for the enabled field is a good security practice, ensuring profiles are not public by default. The relation with the User model is correctly set with onDelete: Cascade, which will help maintain data integrity.


74-80: TeamProfile model review.

The TeamProfile model follows a similar structure to the UserProfile, with fields for id, enabled, teamId, and bio. The default settings and the relation to the Team model are appropriately configured. This consistency in modeling user and team profiles is beneficial for maintaining uniformity across the application.


595-596: Consider more meaningful defaults for public profile fields.

As previously noted, the default values for publicTitle and publicDescription are empty strings. Consider setting more meaningful defaults or handling cases where these values are not provided by the user to enhance the user experience and data quality.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 12

Outside diff range and nitpick comments (2)
apps/web/src/app/(dashboard)/settings/profile/page.tsx (1)

Line range hint 6-22: Good integration of new form components.

The new AvatarImageForm and ProfileForm are well integrated. Consider adding error handling or a loading state to improve user experience during asynchronous operations.

export default async function ProfileSettingsPage() {
+  const [loading, setLoading] = useState(false);
+  const [error, setError] = useState(null);

  const { user } = await getRequiredServerComponentSession();

+  if (loading) return <p>Loading...</p>;
+  if (error) return <p>Error: {error}</p>;

  return (
    <div>
      <SettingsHeader title="Profile" subtitle="Here you can edit your personal details." />

      <AvatarImageForm className="mb-8 max-w-xl" user={user} />
      <ProfileForm className="mb-8 max-w-xl" user={user} />

      <hr className="my-4 max-w-xl" />

      <DeleteAccountDialog className="max-w-xl" user={user} />
    </div>
  );
}
packages/ui/primitives/avatar.tsx (1)

Line range hint 53-80: Enhancement: Improve accessibility and usability of AvatarWithText.

The AvatarWithText component could be improved by adding alt attributes to images for better accessibility and by ensuring that interactive elements are easily navigable and understandable.

  <Avatar
    className={cn('dark:border-border h-10 w-10 border-2 border-solid border-white', avatarClass)}
  >
+   {/* Ensure alt text is provided for better accessibility */}
    {avatarSrc && <AvatarImage src={avatarSrc} alt="User Avatar" />}
    <AvatarFallback className="text-xs text-gray-400">{avatarFallback}</AvatarFallback>
  </Avatar>
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 19d8b4b and 22c02aa.

Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
Files selected for processing (18)
  • apps/web/src/app/(dashboard)/settings/profile/page.tsx (2 hunks)
  • apps/web/src/app/(profile)/layout.tsx (1 hunks)
  • apps/web/src/app/(profile)/p/[url]/page.tsx (1 hunks)
  • apps/web/src/app/(profile)/profile-header.tsx (1 hunks)
  • apps/web/src/app/(teams)/t/[teamUrl]/settings/page.tsx (3 hunks)
  • apps/web/src/components/(dashboard)/layout/menu-switcher.tsx (4 hunks)
  • apps/web/src/components/forms/avatar-image.tsx (1 hunks)
  • apps/web/src/components/templates/manage-public-template-dialog.tsx (1 hunks)
  • apps/web/src/pages/api/avatar/[id].tsx (1 hunks)
  • packages/lib/package.json (2 hunks)
  • packages/lib/server-only/profile/get-avatar-image.ts (1 hunks)
  • packages/lib/server-only/profile/get-public-profile-by-url.ts (1 hunks)
  • packages/lib/server-only/profile/set-avatar-image.ts (1 hunks)
  • packages/prisma/migrations/20240627050809_add_avatar_image_model/migration.sql (1 hunks)
  • packages/prisma/schema.prisma (5 hunks)
  • packages/trpc/server/profile-router/router.ts (5 hunks)
  • packages/trpc/server/profile-router/schema.ts (1 hunks)
  • packages/ui/primitives/avatar.tsx (3 hunks)
Files skipped from review due to trivial changes (1)
  • packages/lib/package.json
Files skipped from review as they are similar to previous changes (2)
  • packages/prisma/schema.prisma
  • packages/trpc/server/profile-router/router.ts
Additional context used
Biome
apps/web/src/components/forms/avatar-image.tsx

[error] 156-160: Provide an explicit type prop for the button element.

The default type of a button is submit, which causes the submission of a form when placed inside a form element. This is likely not the behaviour that you want inside a React application.
Allowed button types are: submit, button or reset

(lint/a11y/useButtonType)

Additional comments not posted (9)
packages/trpc/server/profile-router/schema.ts (2)

74-77: Refinement: Clarify nullable fields in schema.

The ZSetProfileImageMutationSchema should clearly document why fields like bytes and teamId are nullable to avoid confusion and ensure correct usage.

Consider adding comments or documentation in the code to explain the circumstances under which these fields can be null.


5-5: Configuration: Validate bio length configuration.

Ensure that the MAX_PROFILE_BIO_LENGTH is configured appropriately based on user requirements and UI constraints. It's currently set to 256, which might be too long or too short depending on the application context.

Verification successful

Configuration: Validate bio length configuration.

The MAX_PROFILE_BIO_LENGTH is consistently used across both backend and frontend files, ensuring that the bio length constraint is enforced uniformly. The current length of 256 characters appears to be properly integrated into the system.

  • Backend Usage:

    • packages/trpc/server/profile-router/schema.ts
      • Line 5: export const MAX_PROFILE_BIO_LENGTH = 256;
      • Line 10: .max(MAX_PROFILE_BIO_LENGTH, { message: Bio must be shorter than ${MAX_PROFILE_BIO_LENGTH + 1} characters })
  • Frontend Usage:

    • apps/web/src/components/forms/public-profile-form.tsx
      • Line 10: MAX_PROFILE_BIO_LENGTH
      • Line 20: const remaningLength = MAX_PROFILE_BIO_LENGTH - (field.value || '').length;
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Check the usage of MAX_PROFILE_BIO_LENGTH across the frontend to ensure it aligns with UI constraints.

# Test: Search for MAX_PROFILE_BIO_LENGTH usage in frontend components. Expect: Consistent usage that matches the declared limit.
rg --type typescript 'MAX_PROFILE_BIO_LENGTH'

Length of output: 80



Script:

#!/bin/bash
# Description: Check the usage of MAX_PROFILE_BIO_LENGTH across the codebase to ensure it aligns with UI constraints.

# Test: Search for MAX_PROFILE_BIO_LENGTH usage in TypeScript files. Expect: Consistent usage that matches the declared limit.
rg --type ts 'MAX_PROFILE_BIO_LENGTH'

Length of output: 561

apps/web/src/components/forms/avatar-image.tsx (2)

32-34: Add a detailed comment explaining the purpose of ZAvatarImageFormSchema.

It's a best practice to document the purpose of schemas, especially when they are used for form validation. This helps other developers understand the context and constraints being applied.


44-188: Ensure proper error handling and user feedback mechanisms are in place.

The component handles avatar image uploads and updates. Ensure that all potential errors (e.g., network issues, server errors) are caught and appropriate user feedback is provided. This is crucial for improving user experience and debugging.

Verification successful

Proper error handling and user feedback mechanisms are in place.

The AvatarImageForm component handles errors appropriately by catching exceptions and displaying relevant error messages to the user.

  • The catch block handles TRPCClientError with specific messages for BAD_REQUEST and general messages for other errors.
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Check for proper error handling in avatar image handling.
# Test: Search for error handling patterns. Expect: Proper error handling mechanisms.

rg --type typescript "catch" "apps/web/src/components/forms/avatar-image.tsx"

Length of output: 110



Script:

#!/bin/bash
# Description: Check for proper error handling in avatar image handling.
# Test: Search for error handling patterns. Expect: Proper error handling mechanisms.

rg "catch" "apps/web/src/components/forms/avatar-image.tsx"

Length of output: 77



Script:

#!/bin/bash
# Description: Extract and review the catch block to verify error handling and user feedback.
# Test: Extract lines containing catch block and surrounding code for context.

rg -A 10 -B 10 "catch" "apps/web/src/components/forms/avatar-image.tsx"

Length of output: 626

Tools
Biome

[error] 156-160: Provide an explicit type prop for the button element.

The default type of a button is submit, which causes the submission of a form when placed inside a form element. This is likely not the behaviour that you want inside a React application.
Allowed button types are: submit, button or reset

(lint/a11y/useButtonType)

apps/web/src/app/(teams)/t/[teamUrl]/settings/page.tsx (1)

16-16: Confirm the integration of AvatarImageForm in the team settings page.

Ensure that the AvatarImageForm is properly integrated and configured to handle team-specific data. Check if the form's props are correctly passed and if it functions as expected in the team context.

Verification successful

The integration of AvatarImageForm in the team settings page is properly configured.

  • AvatarImageForm is imported and used with the necessary props (team and session.user).
  • team and session.user are correctly defined and passed to AvatarImageForm.
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the integration of AvatarImageForm in the team settings page.
# Test: Search for AvatarImageForm usage in the team settings page. Expect: Proper configuration and usage.

rg --type typescript "AvatarImageForm" "apps/web/src/app/(teams)/t/[teamUrl]/settings/page.tsx"

Length of output: 130



Script:

#!/bin/bash
# Description: Verify the integration of AvatarImageForm in the team settings page.
# Test: Search for AvatarImageForm usage in the team settings page. Expect: Proper configuration and usage.

rg "AvatarImageForm" "apps/web/src/app/(teams)/t/[teamUrl]/settings/page.tsx"

Length of output: 219



Script:

#!/bin/bash
# Description: Verify the definitions of `team` and `session.user` in the team settings page.
# Test: Search for `team` and `session.user` definitions in the team settings page. Expect: Proper configuration and usage.

rg "const team|const session" "apps/web/src/app/(teams)/t/[teamUrl]/settings/page.tsx"

Length of output: 222

apps/web/src/app/(profile)/p/[url]/page.tsx (2)

25-28: Ensure correct usage of PublicProfilePageProps.

The PublicProfilePageProps should be clearly documented and used consistently throughout the component to ensure that all necessary data is passed correctly.


42-193: Review the handling of non-existent or disabled public profiles.

Ensure that the logic for redirecting or showing a not found page when the public profile is non-existent or disabled is robust and user-friendly.

Verification successful

Review the handling of non-existent or disabled public profiles.

The logic for redirecting or showing a not found page when the public profile is non-existent or disabled is correctly implemented using the notFound function at line 54. This ensures that the user is appropriately informed when accessing an invalid profile.

  • Line 54: notFound();
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Check the handling of non-existent or disabled public profiles.
# Test: Search for logic handling non-existent or disabled profiles. Expect: Robust and user-friendly handling.

rg --type typescript "notFound" "apps/web/src/app/(profile)/p/[url]/page.tsx"

Length of output: 112



Script:

#!/bin/bash
# Description: Check the handling of non-existent or disabled public profiles.
# Test: Search for logic handling non-existent or disabled profiles. Expect: Robust and user-friendly handling.

rg --type tsx "notFound" "apps/web/src/app/(profile)/p/[url]/page.tsx"

Length of output: 98



Script:

#!/bin/bash
# Description: Check the handling of non-existent or disabled public profiles.
# Test: Search for logic handling non-existent or disabled profiles. Expect: Robust and user-friendly handling.

ast-grep --lang tsx --pattern 'notFound()' "apps/web/src/app/(profile)/p/[url]/page.tsx"

Length of output: 153

apps/web/src/components/(dashboard)/layout/menu-switcher.tsx (1)

103-105: Ensure correct avatar image URL formation.

Verify that the avatar image URL is correctly formed and handles cases where the avatar image ID might be null or undefined.

Verification successful

Ensure correct avatar image URL formation.

The avatar image URL formation correctly handles cases where the avatar image ID might be null or undefined.

  • The code checks for the existence of avatarImageId before forming the URL.
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Check the formation of avatar image URLs.
# Test: Search for avatar image URL formation logic. Expect: Correct handling of null or undefined IDs.

rg --type typescript "avatarImageId" "apps/web/src/components/(dashboard)/layout/menu-switcher.tsx"

Length of output: 134



Script:

#!/bin/bash
# Description: Check the formation of avatar image URLs.
# Test: Search for avatar image URL formation logic. Expect: Correct handling of null or undefined IDs.

# Correcting the file type for TypeScript
rg --glob '*.ts' --glob '*.tsx' "avatarImageId" "apps/web/src/components/(dashboard)/layout/menu-switcher.tsx"

Length of output: 447

apps/web/src/components/templates/manage-public-template-dialog.tsx (1)

85-429: Review the ManagePublicTemplateDialog for best practices and potential improvements.

Consider refactoring the ManagePublicTemplateDialog to separate concerns more clearly:

  1. Extract form handling into a custom hook.
  2. Move the dialog content rendering into smaller, manageable components.
    This will improve readability and maintainability.

Comment on lines +156 to +160
<button
className="bg-background/70 text-destructive absolute inset-0 flex cursor-pointer items-center justify-center text-xs opacity-0 transition-opacity hover:opacity-100"
disabled={form.formState.isSubmitting}
onClick={() => void onFormSubmit({ bytes: null })}
>

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Specify the button type to avoid form submission issues.

The button within the form does not specify its type, which can lead to unintended form submissions as the default type for a button in a form is 'submit'.

- <button className="bg-background/70 text-destructive absolute inset-0 flex cursor-pointer items-center justify-center text-xs opacity-0 transition-opacity hover:opacity-100" disabled={form.formState.isSubmitting} onClick={() => void onFormSubmit({ bytes: null })}>
+ <button type="button" className="bg-background/70 text-destructive absolute inset-0 flex cursor-pointer items-center justify-center text-xs opacity-0 transition-opacity hover:opacity-100" disabled={form.formState.isSubmitting} onClick={() => void onFormSubmit({ bytes: null })}>
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
<button
className="bg-background/70 text-destructive absolute inset-0 flex cursor-pointer items-center justify-center text-xs opacity-0 transition-opacity hover:opacity-100"
disabled={form.formState.isSubmitting}
onClick={() => void onFormSubmit({ bytes: null })}
>
<button
type="button"
className="bg-background/70 text-destructive absolute inset-0 flex cursor-pointer items-center justify-center text-xs opacity-0 transition-opacity hover:opacity-100"
disabled={form.formState.isSubmitting}
onClick={() => void onFormSubmit({ bytes: null })}
>
Tools
Biome

[error] 156-160: Provide an explicit type prop for the button element.

The default type of a button is submit, which causes the submission of a form when placed inside a form element. This is likely not the behaviour that you want inside a React application.
Allowed button types are: submit, button or reset

(lint/a11y/useButtonType)

Comment on lines +9 to +26
export const getAvatarImage = async ({ id }: GetAvatarImageOptions) => {
const avatarImage = await prisma.avatarImage.findFirst({
where: {
id,
},
});

if (!avatarImage) {
return null;
}

const bytes = Buffer.from(avatarImage.bytes, 'base64');

return {
contentType: 'image/jpeg',
content: await sharp(bytes).toFormat('jpeg').toBuffer(),
};
};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well-structured image retrieval and processing function.

The function correctly retrieves and processes avatar images. Consider adding a try-catch block around the Sharp image processing to handle any potential exceptions that might occur during the conversion.

  try {
    return {
      contentType: 'image/jpeg',
      content: await sharp(bytes).toFormat('jpeg').toBuffer(),
    };
  } catch (error) {
    console.error('Failed to process image', error);
    return null;
  }
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export const getAvatarImage = async ({ id }: GetAvatarImageOptions) => {
const avatarImage = await prisma.avatarImage.findFirst({
where: {
id,
},
});
if (!avatarImage) {
return null;
}
const bytes = Buffer.from(avatarImage.bytes, 'base64');
return {
contentType: 'image/jpeg',
content: await sharp(bytes).toFormat('jpeg').toBuffer(),
};
};
export const getAvatarImage = async ({ id }: GetAvatarImageOptions) => {
const avatarImage = await prisma.avatarImage.findFirst({
where: {
id,
},
});
if (!avatarImage) {
return null;
}
const bytes = Buffer.from(avatarImage.bytes, 'base64');
try {
return {
contentType: 'image/jpeg',
content: await sharp(bytes).toFormat('jpeg').toBuffer(),
};
} catch (error) {
console.error('Failed to process image', error);
return null;
}
};

Comment on lines +2 to +19
ALTER TABLE "Team" ADD COLUMN "avatarImageId" TEXT;

-- AlterTable
ALTER TABLE "User" ADD COLUMN "avatarImageId" TEXT;

-- CreateTable
CREATE TABLE "AvatarImage" (
"id" TEXT NOT NULL,
"bytes" TEXT NOT NULL,

CONSTRAINT "AvatarImage_pkey" PRIMARY KEY ("id")
);

-- AddForeignKey
ALTER TABLE "User" ADD CONSTRAINT "User_avatarImageId_fkey" FOREIGN KEY ("avatarImageId") REFERENCES "AvatarImage"("id") ON DELETE SET NULL ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "Team" ADD CONSTRAINT "Team_avatarImageId_fkey" FOREIGN KEY ("avatarImageId") REFERENCES "AvatarImage"("id") ON DELETE SET NULL ON UPDATE CASCADE;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider optimizing data types for foreign keys.

The use of 'TEXT' data type for 'avatarImageId' might not be optimal. Consider using 'INTEGER' or 'UUID' for better performance and compatibility with other systems.

- ALTER TABLE "Team" ADD COLUMN "avatarImageId" TEXT;
+ ALTER TABLE "Team" ADD COLUMN "avatarImageId" UUID;
- ALTER TABLE "User" ADD COLUMN "avatarImageId" TEXT;
+ ALTER TABLE "User" ADD COLUMN "avatarImageId" UUID;
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
ALTER TABLE "Team" ADD COLUMN "avatarImageId" TEXT;
-- AlterTable
ALTER TABLE "User" ADD COLUMN "avatarImageId" TEXT;
-- CreateTable
CREATE TABLE "AvatarImage" (
"id" TEXT NOT NULL,
"bytes" TEXT NOT NULL,
CONSTRAINT "AvatarImage_pkey" PRIMARY KEY ("id")
);
-- AddForeignKey
ALTER TABLE "User" ADD CONSTRAINT "User_avatarImageId_fkey" FOREIGN KEY ("avatarImageId") REFERENCES "AvatarImage"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Team" ADD CONSTRAINT "Team_avatarImageId_fkey" FOREIGN KEY ("avatarImageId") REFERENCES "AvatarImage"("id") ON DELETE SET NULL ON UPDATE CASCADE;
ALTER TABLE "Team" ADD COLUMN "avatarImageId" UUID;
-- AlterTable
ALTER TABLE "User" ADD COLUMN "avatarImageId" UUID;
-- CreateTable
CREATE TABLE "AvatarImage" (
"id" TEXT NOT NULL,
"bytes" TEXT NOT NULL,
CONSTRAINT "AvatarImage_pkey" PRIMARY KEY ("id")
);
-- AddForeignKey
ALTER TABLE "User" ADD CONSTRAINT "User_avatarImageId_fkey" FOREIGN KEY ("avatarImageId") REFERENCES "AvatarImage"("id") ON DELETE SET NULL ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Team" ADD CONSTRAINT "Team_avatarImageId_fkey" FOREIGN KEY ("avatarImageId") REFERENCES "AvatarImage"("id") ON DELETE SET NULL ON UPDATE CASCADE;

Comment on lines +5 to +34
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method !== 'GET') {
return res.status(405).json({
status: 'error',
message: 'Method not allowed',
});
}

const { id } = req.query;

if (typeof id !== 'string') {
return res.status(400).json({
status: 'error',
message: 'Missing id',
});
}

const result = await getAvatarImage({ id });

if (!result) {
return res.status(404).json({
status: 'error',
message: 'Not found',
});
}

res.setHeader('Content-Type', result.contentType);
res.setHeader('Cache-Control', 'public, max-age=31536000, immutable');
res.send(result.content);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Robust API handler but consider enhancing error handling and security.

The API handler correctly manages different HTTP methods and parameter validation. Consider adding more detailed error responses and rate limiting to enhance security and user feedback.

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
+  // Implement rate limiting here
  if (req.method !== 'GET') {
    return res.status(405).json({
      status: 'error',
      message: 'Method not allowed',
    });
  }

  const { id } = req.query;

  if (typeof id !== 'string') {
    return res.status(400).json({
      status: 'error',
      message: 'Missing id',
    });
  }

  const result = await getAvatarImage({ id });

  if (!result) {
    return res.status(404).json({
      status: 'error',
      message: 'Not found',
    });
  }

  res.setHeader('Content-Type', result.contentType);
  res.setHeader('Cache-Control', 'public, max-age=31536000, immutable');
  res.send(result.content);
}

Committable suggestion was skipped due to low confidence.

Comment on lines +91 to +103
// TODO: Audit Logs
} else {
await prisma.user.update({
where: {
id: userId,
},
data: {
avatarImageId: newAvatarImageId,
},
});

// TODO: Audit Logs
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

TODO: Address audit logging.

The TODO comment about audit logs is critical for maintaining traceability and accountability, especially for operations that alter user or team data.

Would you like assistance in implementing the audit logging functionality? I can provide sample code or open a GitHub issue to track this task.

Comment on lines +49 to +51
if (!team) {
throw new Error('Team not found');
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Error Handling: Improve team not found error handling.

Similar to the user not found error, consider logging additional details when a team is not found.

  if (!team) {
+   // Consider logging this error to help with debugging or tracking issues with team data retrieval.
    throw new Error('Team not found');
  }

Committable suggestion was skipped due to low confidence.

Comment on lines +28 to +43
bio: z
.string()
.max(MAX_PROFILE_BIO_LENGTH, {
message: `Bio must be shorter than ${MAX_PROFILE_BIO_LENGTH + 1} characters`,
})
.optional(),
enabled: z.boolean().optional(),
url: z
.string()
.trim()
.toLowerCase()
.min(1, { message: 'Please enter a valid username.' })
.regex(/^[a-z0-9-]+$/, {
message: 'Username can only container alphanumeric characters and dashes.',
}),
})
.optional(),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Refinement: Enhance URL validation logic.

The regex for validating URLs could be made more robust to include other valid characters such as underscores or periods, depending on the application's requirements.

- .regex(/^[a-z0-9-]+$/, {
+ .regex(/^[a-z0-9-_\.]+$/, {
    message: 'Username can only container alphanumeric characters, dashes, underscores, and periods.',
  })
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
bio: z
.string()
.max(MAX_PROFILE_BIO_LENGTH, {
message: `Bio must be shorter than ${MAX_PROFILE_BIO_LENGTH + 1} characters`,
})
.optional(),
enabled: z.boolean().optional(),
url: z
.string()
.trim()
.toLowerCase()
.min(1, { message: 'Please enter a valid username.' })
.regex(/^[a-z0-9-]+$/, {
message: 'Username can only container alphanumeric characters and dashes.',
}),
})
.optional(),
bio: z
.string()
.max(MAX_PROFILE_BIO_LENGTH, {
message: `Bio must be shorter than ${MAX_PROFILE_BIO_LENGTH + 1} characters`,
})
.optional(),
enabled: z.boolean().optional(),
url: z
.string()
.trim()
.toLowerCase()
.min(1, { message: 'Please enter a valid username.' })
.regex(/^[a-z0-9-_\.]+$/, {
message: 'Username can only container alphanumeric characters, dashes, underscores, and periods.',
})
.optional(),

Comment on lines +24 to +85
export const ProfileHeader = ({ user, teams = [] }: ProfileHeaderProps) => {
const [scrollY, setScrollY] = useState(0);

useEffect(() => {
const onScroll = () => {
setScrollY(window.scrollY);
};

window.addEventListener('scroll', onScroll);

return () => window.removeEventListener('scroll', onScroll);
}, []);

if (user) {
return <AuthenticatedHeader user={user} teams={teams} />;
}

return (
<header
className={cn(
'supports-backdrop-blur:bg-background/60 bg-background/95 sticky top-0 z-[60] flex h-16 w-full items-center border-b border-b-transparent backdrop-blur duration-200',
scrollY > 5 && 'border-b-border',
)}
>
<div className="mx-auto flex w-full max-w-screen-xl items-center justify-between gap-x-4 px-4 md:px-8">
<Link
href="/"
className="focus-visible:ring-ring ring-offset-background rounded-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 md:inline"
>
<Logo className="hidden h-6 w-auto sm:block" />

<Image
src={LogoIcon}
alt="Documenso Logo"
width={48}
height={48}
className="h-10 w-auto dark:invert sm:hidden"
/>
</Link>

<div className="flex flex-row items-center justify-center">
<p className="text-muted-foreground mr-4">
<span className="text-sm sm:hidden">Want your own public profile?</span>
<span className="hidden text-sm sm:block">
Like to have your own public profile with agreements?
</span>
</p>

<Button asChild variant="secondary">
<Link href="/signup">
<div className="hidden flex-row items-center sm:flex">
<PlusIcon className="mr-1 h-5 w-5" />
Create now
</div>

<span className="sm:hidden">Create</span>
</Link>
</Button>
</div>
</div>
</header>
);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Enhancement: Optimize scroll event handling in ProfileHeader.

The scroll event listener in ProfileHeader can be optimized to prevent excessive re-renders or state updates, which could impact performance, especially on devices with lower resources.

  useEffect(() => {
    const onScroll = () => {
+     // Throttle scroll updates to reduce performance impact
+     requestAnimationFrame(() => {
        setScrollY(window.scrollY);
+     });
    };

    window.addEventListener('scroll', onScroll);
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export const ProfileHeader = ({ user, teams = [] }: ProfileHeaderProps) => {
const [scrollY, setScrollY] = useState(0);
useEffect(() => {
const onScroll = () => {
setScrollY(window.scrollY);
};
window.addEventListener('scroll', onScroll);
return () => window.removeEventListener('scroll', onScroll);
}, []);
if (user) {
return <AuthenticatedHeader user={user} teams={teams} />;
}
return (
<header
className={cn(
'supports-backdrop-blur:bg-background/60 bg-background/95 sticky top-0 z-[60] flex h-16 w-full items-center border-b border-b-transparent backdrop-blur duration-200',
scrollY > 5 && 'border-b-border',
)}
>
<div className="mx-auto flex w-full max-w-screen-xl items-center justify-between gap-x-4 px-4 md:px-8">
<Link
href="/"
className="focus-visible:ring-ring ring-offset-background rounded-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 md:inline"
>
<Logo className="hidden h-6 w-auto sm:block" />
<Image
src={LogoIcon}
alt="Documenso Logo"
width={48}
height={48}
className="h-10 w-auto dark:invert sm:hidden"
/>
</Link>
<div className="flex flex-row items-center justify-center">
<p className="text-muted-foreground mr-4">
<span className="text-sm sm:hidden">Want your own public profile?</span>
<span className="hidden text-sm sm:block">
Like to have your own public profile with agreements?
</span>
</p>
<Button asChild variant="secondary">
<Link href="/signup">
<div className="hidden flex-row items-center sm:flex">
<PlusIcon className="mr-1 h-5 w-5" />
Create now
</div>
<span className="sm:hidden">Create</span>
</Link>
</Button>
</div>
</div>
</header>
);
useEffect(() => {
const onScroll = () => {
// Throttle scroll updates to reduce performance impact
requestAnimationFrame(() => {
setScrollY(window.scrollY);
});
};
window.addEventListener('scroll', onScroll);
return () => window.removeEventListener('scroll', onScroll);
}, []);

};
}

throw new AppError(AppErrorCode.NOT_FOUND, 'Profile not found');

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Error Handling: Enhance 'Profile not found' error response.

When a profile is not found, consider providing suggestions or actions the user can take, which could improve user experience and help in troubleshooting.

  throw new AppError(AppErrorCode.NOT_FOUND, 'Profile not found');
+ // Consider adding a link to the help center or support for further assistance.

Committable suggestion was skipped due to low confidence.

Comment on lines +115 to +118
// Log as critical error.
if (user?.profile && team?.profile) {
console.error('Profile URL is ambiguous', { profileUrl, userId: user.id, teamId: team.id });
throw new AppError(AppErrorCode.INVALID_REQUEST, 'Profile URL is ambiguous');

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Error Handling: Address ambiguous profile URL issue.

The error handling for ambiguous profile URLs could be improved by providing more detailed error messages and possibly suggesting corrective actions to the user.

  if (user?.profile && team?.profile) {
    console.error('Profile URL is ambiguous', { profileUrl, userId: user.id, teamId: team.id });
+   // Provide a more user-friendly error message and possible actions to resolve the ambiguity
    throw new AppError(AppErrorCode.INVALID_REQUEST, 'The profile URL matches both a user and a team. Please specify if you are looking for a user or team profile.');
  }
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// Log as critical error.
if (user?.profile && team?.profile) {
console.error('Profile URL is ambiguous', { profileUrl, userId: user.id, teamId: team.id });
throw new AppError(AppErrorCode.INVALID_REQUEST, 'Profile URL is ambiguous');
// Log as critical error.
if (user?.profile && team?.profile) {
console.error('Profile URL is ambiguous', { profileUrl, userId: user.id, teamId: team.id });
// Provide a more user-friendly error message and possible actions to resolve the ambiguity
throw new AppError(AppErrorCode.INVALID_REQUEST, 'The profile URL matches both a user and a team. Please specify if you are looking for a user or team profile.');

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 22c02aa and d85f207.

Files selected for processing (1)
  • apps/web/src/components/forms/avatar-image.tsx (1 hunks)
Files skipped from review as they are similar to previous changes (1)
  • apps/web/src/components/forms/avatar-image.tsx

@Mythie
Mythie merged commit b08e153 into main Jun 27, 2024
@Mythie
Mythie deleted the feat/public-profiles branch June 27, 2024 12:47
This was referenced Sep 13, 2024
@coderabbitai coderabbitai Bot mentioned this pull request Nov 5, 2024

This branch had an error being deployed

1 failed and 2 active deployments
Preview – stg-app — d85f207d Deployed Jun 27, 2024 by vercel[bot]
Preview – stg-marketing — d85f207d Deployed Jun 27, 2024 by vercel[bot]
Preview – stg-docs — d85f207d Deployed Jun 27, 2024 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

apps: web Issues related to the webapp 🚨 .env changes 🚨 Be advised: PR changes .ENV - Auto-Generated by GitHub Actions on raising a PR 🚨 migrations 🚨 Be advised: PR contains database migrations - Auto-Generated by GitHub Actions on raising a PR version bump 👀

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants