Skip to content

feat: signature rejection - #1472

Merged
Mythie merged 3 commits into
mainfrom
feat/signature-rejection
Nov 14, 2024
Merged

Mythie merged 3 commits into
mainfrom
feat/signature-rejection

Conversation

@Mythie

@Mythie Mythie commented Nov 14, 2024 •

Copy link
Copy Markdown
Collaborator

Description

Adds support for rejecting a given document informing the document owner.

Flows for resolving a rejection don't currently exist so it's up to the document owner to reach out to the recipient and work out a way to move forward via a new document or offline agreement.

Related Issue

Changes Made

  • Added new rejection properties to the recipient schema
  • Added API endpoints to support rejection
  • Added email templates for notifying the document owner and recipient
  • Added a dialog on the signing page to start the rejection flow.

Testing Performed

  • Manually tested the flow end to end
  • Automated tests are planned

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced a document rejection feature, allowing recipients to reject documents and provide reasons.
    • Added visual indicators for rejected documents in the dashboard and recipient views.
    • Implemented a rejection confirmation dialog for users when rejecting documents.
    • Enhanced email templates to notify users of document rejections.
    • New audit log entries for tracking document rejection events.
  • Bug Fixes

    • Improved error handling for document rejection scenarios.
  • Documentation

    • Updated translation files to include new terms related to document rejection in multiple languages.

These updates enhance user interaction and provide clearer feedback regarding document statuses.

@vercel

vercel Bot commented Nov 14, 2024 •

Copy link
Copy Markdown

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

Name Status Preview Comments Updated (UTC)
prd-openpage-api ❌ Failed (Inspect) Nov 14, 2024 5:21am
stg-app ✅ Ready (Inspect) Visit Preview 💬 Add feedback Nov 14, 2024 5:21am
stg-docs ✅ Ready (Inspect) Visit Preview 💬 Add feedback Nov 14, 2024 5:21am
stg-marketing ✅ Ready (Inspect) Visit Preview 💬 Add feedback Nov 14, 2024 5:21am
3 Skipped Deployments
Name Status Preview Comments Updated (UTC)
prd-app ⬜️ Ignored (Inspect) Nov 14, 2024 5:21am
prd-docs ⬜️ Ignored (Inspect) Visit Preview Nov 14, 2024 5:21am
prd-marketing ⬜️ Ignored (Inspect) Nov 14, 2024 5:21am

@coderabbitai

coderabbitai Bot commented Nov 14, 2024 •

Copy link
Copy Markdown
Contributor

Walkthrough

The changes in this pull request introduce new functionalities and enhancements related to document rejection processes within the application. Key updates include the addition of a rejectionReason property to recipient data models, new UI elements for indicating document rejection, and the implementation of email notifications for rejected documents. Various components and schemas have been modified to accommodate these changes, enhancing the overall handling of document statuses and improving user experience through better feedback mechanisms.

Changes

File Change Summary
apps/marketing/src/app/(marketing)/singleplayer/client.tsx Added rejectionReason: null to placeholderRecipient object.
apps/web/src/app/(dashboard)/documents/[id]/document-page-view-recent-activity.tsx Imported AlertTriangle and added case for DOCUMENT_RECIPIENT_REJECTED in audit log handling.
apps/web/src/app/(dashboard)/documents/[id]/document-page-view-recipients.tsx Added AlertTriangle and conditional rendering for "Rejected" status with popover for rejection reason.
apps/web/src/app/(dashboard)/documents/data-table.tsx Changed status accessor from row.getValue('status') to row.original.status.
apps/web/src/app/(signing)/sign/[token]/page.tsx Added check for recipient.signingStatus === SigningStatus.REJECTED to redirect users appropriately.
apps/web/src/app/(signing)/sign/[token]/reject-document-dialog.tsx Introduced RejectDocumentDialog component for handling document rejection via a dialog.
apps/web/src/app/(signing)/sign/[token]/rejected/page.tsx Created RejectedSigningPage component to display rejection details and instructions.
apps/web/src/app/(signing)/sign/[token]/signing-page-view.tsx Imported RejectDocumentDialog and adjusted layout for better alignment.
apps/web/src/components/(dashboard)/avatar/stack-avatar.tsx Updated StackAvatarProps to use RecipientStatusType enum and added case for REJECTED.
apps/web/src/components/(dashboard)/avatar/stack-avatars-with-tooltip.tsx Added logic for displaying rejected recipients and updated sorting.
apps/web/src/components/document/document-history-sheet.tsx Added handling for DOCUMENT_RECIPIENT_REJECTED in audit log processing.
packages/email/template-components/template-document-invite.tsx Added "Reject Document" button linking to rejection functionality.
packages/email/template-components/template-document-rejected.tsx Created component for displaying document rejection notifications.
packages/email/template-components/template-document-rejection-confirmed.tsx Created component for confirming document rejection via email.
packages/email/templates/document-rejected.tsx Introduced DocumentRejectedEmail component for email notifications about document rejection.
packages/email/templates/document-rejection-confirmed.tsx Created DocumentRejectionConfirmedEmail for confirming rejections via email.
packages/lib/client-only/recipient-type.ts Added REJECTED status to RecipientStatusType enum.
packages/lib/jobs/client.ts Imported SEND_SIGNING_REJECTION_EMAILS_JOB_DEFINITION for handling rejection email jobs.
packages/lib/jobs/definitions/emails/send-rejection-emails.ts Defined job for sending rejection emails, including schema validation and email sending logic.
packages/lib/server-only/admin/get-recipients-stats.ts Added tracking for SigningStatus.REJECTED in recipient stats.
packages/lib/server-only/document/find-document-audit-logs.ts Updated filtering logic to include DOCUMENT_RECIPIENT_REJECTED in audit logs.
packages/lib/server-only/document/reject-document-with-token.ts Created function to handle document rejection based on token, updating status and sending notifications.
packages/lib/types/document-audit-logs.ts Added DOCUMENT_RECIPIENT_REJECTED event type to audit log types.
packages/trpc/server/recipient-router/router.ts Added rejectDocumentWithToken mutation to handle document rejection requests.
packages/trpc/server/recipient-router/schema.ts Introduced ZRejectDocumentWithTokenMutationSchema for validating rejection requests.
packages/prisma/migrations/20241112223435_add_rejection_status_and_reason_to_recipient_schema/migration.sql Migration to add REJECTED status and rejectionReason column to the database.
packages/prisma/schema.prisma Updated SigningStatus enum to include REJECTED and added rejectionReason field to Recipient.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant RejectDialog
    participant DocumentService
    participant EmailService

    User->>RejectDialog: Open Reject Document Dialog
    RejectDialog->>User: Input rejection reason
    User->>RejectDialog: Submit rejection
    RejectDialog->>DocumentService: Reject document with reason
    DocumentService->>EmailService: Send rejection notification
    EmailService-->>User: Notify rejection confirmation
Loading

Possibly related PRs

  • feat: send custom email to signers of direct template documents #1215: The addition of new features related to document audit logs and recipient statuses may connect with the changes in the main PR, which also involves enhancing data representation related to document handling.
  • feat: resend document via API #1226: This PR introduces new functionalities for document resending, which could relate to the overall management of document states, similar to the changes made in the main PR regarding recipient data.
  • feat: signing order #1290: The introduction of signing order features may relate to the overall management of document states and recipient statuses, which is a focus of the main PR.
  • feat: add french #1355: The addition of French translations may not directly relate to the code changes in the main PR but indicates a broader effort to enhance user experience, which aligns with the objectives of improving data representation in the main PR.
  • feat: add certificate translations #1440: The addition of translations for audit logs and certificates may relate to the changes in the main PR, which also focuses on enhancing the representation of recipient data.
  • chore: add translations #1444: The updates to the German translations, particularly those related to document actions, may connect with the changes in the main PR that enhance the data model for recipients.
  • feat: add signing link copy #1449: The enhancements to the document management capabilities, including sharing signing links, may relate to the overall improvements in data representation in the main PR.
  • chore: add translations #1451: The updates to translations in this PR may not directly relate to the code changes in the main PR but reflect a broader effort to improve user experience, which aligns with the objectives of the main PR.
  • chore: add translations #1461: The updates to translations in this PR may not directly relate to the code changes in the main PR but reflect ongoing efforts to enhance localization, which is a part of improving user experience.
  • chore: add translations #1463: The addition of Polish translations may not directly relate to the code changes in the main PR but indicates a broader effort to enhance user experience, which aligns with the objectives of improving data representation in the main PR.

Suggested labels

pkg: ee changes, 🚨 e2e changes 🚨

Suggested reviewers

  • dguyen

🐰 In the meadow, where changes bloom,
A document's fate, we now assume.
With reasons for rejections, clear and bright,
Our users will see, what's wrong and right.
So hop along, let’s spread the cheer,
For every rejected doc, we hold dear! 🌼✨


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>, please review it.
    • 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 gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @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 using 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.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration 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 commented Nov 14, 2024 •

Copy link
Copy Markdown
Contributor

Thank you for following the naming conventions for pull request titles! 💚🚀

@github-actions github-actions Bot added apps: web Issues related to the webapp 🚨 migrations 🚨 Be advised: PR contains database migrations - Auto-Generated by GitHub Actions on raising a PR apps: marketing labels Nov 14, 2024
@Mythie
Mythie requested a review from dguyen November 14, 2024 05:02

@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: 24

🧹 Outside diff range and nitpick comments (40)
packages/prisma/migrations/20241112223435_add_rejection_status_and_reason_to_recipient_schema/migration.sql (1)

4-5: Consider adding constraints and indexing strategy.

While the basic column addition works, consider the following improvements:

  1. Add a character limit constraint to prevent excessive text storage
  2. Consider adding an index if you plan to query by rejection status and reason frequently

Here's a suggested enhancement:

-- AlterTable
-ALTER TABLE "Recipient" ADD COLUMN     "rejectionReason" TEXT;
+ALTER TABLE "Recipient" ADD COLUMN     "rejectionReason" VARCHAR(1000);
+CREATE INDEX idx_recipient_rejection ON "Recipient"("rejectionReason") WHERE "rejectionReason" IS NOT NULL;

This would:

  • Limit rejection reasons to 1000 characters
  • Add an index for efficient querying of rejected documents
packages/email/template-components/template-document-rejected.tsx (3)

12-17: Consider maintaining consistent prop naming.

The prop recipientName is renamed to signerName in the destructuring, which creates an inconsistency between the interface and implementation. Consider using the same name throughout to improve code maintainability.

-  recipientName: signerName,
+  recipientName,

40-45: Extract button styles to a CSS module or styled component.

The button styling is directly embedded in the className prop. Consider extracting these styles to maintain better separation of concerns and reusability.


24-28: Enhance the rejection notification message.

The current message could be more informative. Consider adding context about what rejection means and what actions are expected from the document owner.

 <Text className="mb-4 text-base">
   <Trans>
-    {signerName} has rejected the document "{documentName}".
+    {signerName} has rejected the document "{documentName}". As the document owner, you may need to create a new document or contact the recipient for further clarification.
   </Trans>
 </Text>
packages/email/template-components/template-document-rejection-confirmed.tsx (4)

5-10: Consider adding input validation for the props.

While the interface is well-structured, consider adding runtime validation to ensure that required strings are not empty and the reason (if provided) doesn't exceed a reasonable length limit.

Example implementation using zod:

import { z } from 'zod';

const TemplateDocumentRejectionConfirmedSchema = z.object({
  recipientName: z.string().min(1),
  documentName: z.string().min(1),
  documentOwnerName: z.string().min(1),
  reason: z.string().max(500).optional(),
});

21-23: Add aria-label to improve accessibility.

The heading should have an aria-label for better screen reader support.

-        <Heading className="text-2xl font-semibold">
+        <Heading className="text-2xl font-semibold" aria-label="Document Rejection Confirmation">

38-44: Consider providing more specific next steps.

The current message about potential contact from the document owner is vague. Consider adding more specific information about the typical next steps or resolution process.

           <Trans>
             The document owner has been notified of this rejection. No further action is required
             from you at this time. The document owner may contact you with any questions regarding
-            this rejection.
+            this rejection. They may send you a new version of the document or reach out to discuss
+            alternative solutions.
           </Trans>

12-48: Consider extracting Tailwind classes into reusable components.

The component uses several Tailwind classes directly. Consider extracting these into styled components or CSS modules to maintain consistency across email templates and make future styling changes easier.

Example approach:

const StyledHeading = styled(Heading)`
  @apply text-2xl font-semibold;
`;

const PrimaryText = styled(Text)`
  @apply text-primary text-base;
`;

const SecondaryText = styled(Text)`
  @apply text-base font-medium text-slate-400;
`;
packages/lib/client-only/recipient-type.ts (1)

20-22: Consider handling REJECTED status in getExtraRecipientsType.

While the rejection handling in getRecipientType looks good, the getExtraRecipientsType function doesn't explicitly handle REJECTED status in its priority chain. Consider whether REJECTED should be treated similarly to COMPLETED or if it needs special handling.

Consider updating getExtraRecipientsType:

 export const getExtraRecipientsType = (extraRecipients: Recipient[]) => {
   const types = extraRecipients.map((r) => getRecipientType(r));
 
   if (types.includes(RecipientStatusType.UNSIGNED)) {
     return RecipientStatusType.UNSIGNED;
   }
 
   if (types.includes(RecipientStatusType.OPENED)) {
     return RecipientStatusType.OPENED;
   }
 
   if (types.includes(RecipientStatusType.WAITING)) {
     return RecipientStatusType.WAITING;
   }
 
+  if (types.includes(RecipientStatusType.REJECTED)) {
+    return RecipientStatusType.REJECTED;
+  }
+
   return RecipientStatusType.COMPLETED;
 };
packages/email/templates/document-rejected.tsx (2)

29-31: Add error handling to URL construction

The getAssetUrl function should handle invalid URLs gracefully.

  const getAssetUrl = (path: string) => {
-    return new URL(path, assetBaseUrl).toString();
+    try {
+      return new URL(path, assetBaseUrl).toString();
+    } catch (error) {
+      console.error('Invalid URL:', { path, assetBaseUrl, error });
+      return path;
+    }
  };

1-70: Consider implementing email preview functionality

Since this is a crucial notification for document rejection, it would be valuable to have a way to preview these emails during development and testing.

Consider implementing:

  1. A development route to preview email templates with mock data
  2. A way to save email templates for audit purposes
  3. Email delivery status tracking to ensure rejection notifications are received

Would you like me to help create a GitHub issue to track these improvements?

packages/email/templates/document-rejection-confirmed.tsx (2)

9-15: Add validation for required fields and URL format.

The type definition could be strengthened to ensure data integrity:

  1. Consider using zod or similar for runtime validation of non-empty strings
  2. Add URL format validation for assetBaseUrl
import { z } from 'zod';

export const DocumentRejectionConfirmedEmailSchema = z.object({
  recipientName: z.string().min(1),
  documentName: z.string().min(1),
  documentOwnerName: z.string().min(1),
  reason: z.string().min(1),
  assetBaseUrl: z.string().url().optional().default('http://localhost:3002'),
});

export type DocumentRejectionConfirmedEmailProps = z.infer<typeof DocumentRejectionConfirmedEmailSchema>;

1-70: Consider adding tests and improving email client compatibility.

As this is a critical communication component:

  1. Add unit tests to verify template rendering with different props
  2. Add snapshot tests to catch unintended template changes
  3. Test across different email clients (Outlook, Gmail, etc.)
  4. Consider adding dark mode support
  5. Add alt text translations for images

Consider implementing the following test structure:

// document-rejection-confirmed.test.tsx
import { render } from '@testing-library/react';
import { DocumentRejectionConfirmedEmail } from './document-rejection-confirmed';

describe('DocumentRejectionConfirmedEmail', () => {
  const defaultProps = {
    recipientName: 'John Doe',
    documentName: 'Contract.pdf',
    documentOwnerName: 'Jane Smith',
    reason: 'Terms need revision',
  };

  it('renders correctly with default props', () => {
    const { container } = render(<DocumentRejectionConfirmedEmail {...defaultProps} />);
    expect(container).toMatchSnapshot();
  });

  it('handles long text inputs appropriately', () => {
    const props = {
      ...defaultProps,
      documentName: 'A'.repeat(100),
    };
    const { container } = render(<DocumentRejectionConfirmedEmail {...props} />);
    expect(container).toMatchSnapshot();
  });
});
packages/trpc/server/recipient-router/schema.ts (1)

73-82: Add validation constraints for the rejection reason field.

The schema structure is well-organized and consistent with existing patterns. However, consider enhancing the validation for the reason field to ensure meaningful rejection messages.

Consider applying this improvement:

 export const ZRejectDocumentWithTokenMutationSchema = z.object({
   token: z.string(),
   documentId: z.number(),
-  reason: z.string(),
+  reason: z.string()
+    .min(1, 'Rejection reason cannot be empty')
+    .max(1000, 'Rejection reason is too long')
+    .transform((str) => str.trim())
+    .refine((str) => str.length > 0, 'Rejection reason cannot be only whitespace'),
   authOptions: ZRecipientActionAuthSchema.optional(),
 });
packages/email/template-components/template-document-invite.tsx (1)

Line range hint 1-98: Consider email template testing strategy

Given that this template is part of the critical rejection flow:

  1. Consider implementing snapshot tests for the email template to ensure consistent rendering
  2. Add E2E tests covering the entire rejection flow, including email delivery
  3. Document the rejection flow in the component's comments for future implementation of resolution flows

Would you like help setting up:

  • Snapshot tests for the email template?
  • E2E tests for the rejection flow?
  • Documentation for the rejection process?
packages/trpc/server/recipient-router/router.ts (2)

106-111: Consider adding success logging for rejections.

For better observability, consider adding success logging after the rejection is processed.

 return await rejectDocumentWithToken({
   token,
   documentId,
   reason,
   requestMetadata: extractNextApiRequestMetadata(ctx.req),
 });
+console.log(`Document ${documentId} rejected successfully with token ${token}`);

115-118: Make error message more specific.

The current error message is quite generic. Consider making it more specific to the rejection operation, similar to other mutations in this file.

-          message: 'We were unable to handle this request. Please try again later.',
+          message: 'We were unable to reject this document. Please try again later.',
apps/web/src/app/(dashboard)/documents/data-table.tsx (1)

81-81: Consider using type-safe status access

While directly accessing row.original.status works, consider using row.getValue('status') for better type safety and consistency with React Table's accessor pattern.

-        cell: ({ row }) => <DocumentStatus status={row.original.status} />,
+        cell: ({ row }) => <DocumentStatus status={row.getValue('status')} />,
apps/web/src/app/(signing)/sign/[token]/reject-document-dialog.tsx (4)

43-46: Consider adding type documentation and being more specific with types.

The interface could benefit from:

  1. JSDoc comments explaining the purpose of each prop
  2. A more specific type for token (e.g., signingToken or documentToken)
 export interface RejectDocumentDialogProps {
+  /** The document to be rejected */
   document: Pick<Document, 'id'>;
+  /** The signing token that authorizes the rejection */
-  token: string;
+  token: DocumentSigningToken;
 }

67-67: Remove outdated TODO comment.

The TODO comment can be removed as the TRPC mutation has been implemented.

-      // TODO: Add trpc mutation here

83-90: Enhance error handling with specific error messages.

The current error handling shows a generic message. Consider catching specific error types and providing more informative messages to users.

-    } catch (err) {
+    } catch (err) {
+      const errorMessage = err instanceof Error ? err.message : 'An error occurred while rejecting the document.';
       toast({
         title: 'Error',
-        description: 'An error occurred while rejecting the document. Please try again.',
+        description: errorMessage,
         variant: 'destructive',
         duration: 5000,
       });
     }

53-53: Consider syncing dialog state with URL.

The dialog state could be synchronized with the URL for better navigation handling and browser history support.

   const onRejectDocument = async ({ reason }: TRejectDocumentFormSchema) => {
     try {
       await rejectDocumentWithToken({...});
       toast({...});
-      setIsOpen(false);
-      router.push(`/sign/${token}/rejected`);
+      router.replace(`/sign/${token}/rejected`);
     } catch (err) {...}
   };

Add URL handling when dialog closes:

+  const handleOpenChange = (open: boolean) => {
+    setIsOpen(open);
+    if (!open) {
+      const params = new URLSearchParams(searchParams);
+      params.delete('reject');
+      router.replace(`?${params.toString()}`);
+    }
+  };

-  <Dialog open={isOpen} onOpenChange={setIsOpen}>
+  <Dialog open={isOpen} onOpenChange={handleOpenChange}>

Also applies to: 80-82

apps/web/src/components/(dashboard)/avatar/stack-avatars-with-tooltip.tsx (2)

53-64: Consider optimizing the sorting logic.

While the current implementation works, it could be more efficient by avoiding the need to filter the array twice.

Here's a more efficient approach:

  const sortedRecipients = useMemo(() => {
-   const otherRecipients = recipients.filter(
-     (recipient) => getRecipientType(recipient) !== RecipientStatusType.REJECTED,
-   );
-
-   return [
-     ...rejectedRecipients.sort((a, b) => a.id - b.id),
-     ...otherRecipients.sort((a, b) => {
-       return a.id - b.id;
-     }),
-   ];
+   return [...recipients].sort((a, b) => {
+     const aIsRejected = getRecipientType(a) === RecipientStatusType.REJECTED;
+     const bIsRejected = getRecipientType(b) === RecipientStatusType.REJECTED;
+     
+     // Sort rejected recipients first
+     if (aIsRejected && !bIsRejected) return -1;
+     if (!aIsRejected && bIsRejected) return 1;
+     
+     // Then sort by ID
+     return a.id - b.id;
+   });
  }, [recipients]);

This approach:

  1. Avoids multiple array iterations
  2. Maintains the same sorting behavior
  3. Is more memory efficient

98-120: Consider extracting the recipient card into a reusable component.

The recipient card structure is duplicated across different recipient sections (completed, rejected, waiting, etc.).

Consider creating a shared component to reduce duplication:

type RecipientCardProps = {
  recipient: Recipient;
  showAvatar?: boolean;
};

const RecipientCard = ({ recipient, showAvatar = true }: RecipientCardProps) => (
  <div className="my-1 flex items-center gap-2">
    {showAvatar && (
      <StackAvatar
        first={true}
        key={recipient.id}
        type={getRecipientType(recipient)}
        fallbackText={recipientAbbreviation(recipient)}
      />
    )}
    <div>
      <p className="text-muted-foreground text-sm">{recipient.email}</p>
      <p className="text-muted-foreground/70 text-xs">
        {_(RECIPIENT_ROLES_DESCRIPTION[recipient.role].roleName)}
      </p>
    </div>
  </div>
);

Then use it in each section:

  {rejectedRecipients.length > 0 && (
    <div>
      <h1 className="text-base font-medium">
        <Trans>Rejected</Trans>
      </h1>
-     {rejectedRecipients.map((recipient: Recipient) => (
-       <div key={recipient.id} className="my-1 flex items-center gap-2">
-         <StackAvatar
-           first={true}
-           key={recipient.id}
-           type={getRecipientType(recipient)}
-           fallbackText={recipientAbbreviation(recipient)}
-         />
-         <div>
-           <p className="text-muted-foreground text-sm">{recipient.email}</p>
-           <p className="text-muted-foreground/70 text-xs">
-             {_(RECIPIENT_ROLES_DESCRIPTION[recipient.role].roleName)}
-           </p>
-         </div>
-       </div>
-     ))}
+     {rejectedRecipients.map((recipient) => (
+       <RecipientCard key={recipient.id} recipient={recipient} />
+     ))}
    </div>
  )}

This would:

  1. Reduce code duplication
  2. Make the code more maintainable
  3. Make it easier to update the card layout across all sections
apps/web/src/app/(dashboard)/documents/[id]/document-page-view-recipients.tsx (1)

135-153: LGTM with suggestions for enhancement.

The rejection status UI implementation is well-integrated with the existing status badge patterns and maintains consistency in styling and translations. Consider these improvements:

  1. Add handling for empty rejection reasons
  2. Add max-width/height constraints for the popover content
  3. Enhance accessibility with aria labels

Consider applying these enhancements:

 <PopoverHover
   trigger={
-    <Badge variant="destructive">
+    <Badge 
+      variant="destructive"
+      aria-label={`Rejected - ${recipient.rejectionReason || 'No reason provided'}`}
+    >
       <AlertTriangle className="mr-1 h-3 w-3" />
       <Trans>Rejected</Trans>
     </Badge>
   }
 >
-  <p className="text-sm">
+  <div className="max-w-xs max-h-48 overflow-auto">
+    <p className="text-sm">
     <Trans>Reason for rejection: </Trans>
-  </p>
+    </p>

-  <p className="text-muted-foreground mt-1 text-sm">
-    {recipient.rejectionReason}
-  </p>
+    <p className="text-muted-foreground mt-1 text-sm">
+      {recipient.rejectionReason || <Trans>No reason provided</Trans>}
+    </p>
+  </div>
 </PopoverHover>
apps/web/src/app/(dashboard)/documents/[id]/document-page-view-recent-activity.tsx (1)

136-140: Consider enhancing accessibility for rejection status.

The implementation is well-structured and consistent with other status indicators. However, we could improve screen reader support.

Consider adding a descriptive title attribute to the AlertTriangle icon:

-<AlertTriangle className="h-3 w-3" aria-hidden="true" />
+<AlertTriangle className="h-3 w-3" aria-hidden="true" title="Document Rejected" />
packages/lib/server-only/document/send-completed-email.ts (1)

Line range hint 63-70: Fix redundant and potentially conflicting URL formatting logic.

The current implementation has two different approaches to formatting the document URL:

  1. Using formatDocumentsPath utility
  2. Directly constructing the URL with team URL

This redundancy could lead to inconsistent URL structures and maintenance issues.

Consider consolidating the URL formatting logic:

-  let documentOwnerDownloadLink = `${NEXT_PUBLIC_WEBAPP_URL()}${formatDocumentsPath(
-    document.team?.url,
-  )}/${document.id}`;
-
-  if (document.team?.url) {
-    documentOwnerDownloadLink = `${NEXT_PUBLIC_WEBAPP_URL()}/t/${document.team.url}/documents/${
-      document.id
-    }`;
-  }
+  const documentOwnerDownloadLink = `${NEXT_PUBLIC_WEBAPP_URL()}${formatDocumentsPath(
+    document.team?.url,
+  )}/${document.id}`;

This change:

  1. Eliminates redundant logic
  2. Ensures consistent URL formatting through the utility function
  3. Improves maintainability
apps/web/src/app/(signing)/sign/[token]/signing-page-view.tsx (2)

61-83: Consider adding ARIA labels for better accessibility.

The layout structure is well-organized with proper spacing and text truncation. However, consider adding ARIA labels to improve accessibility for screen readers.

 <div className="mt-2.5 flex flex-wrap items-center justify-between gap-x-6">
-  <div>
+  <div role="contentinfo" aria-label="Document sender information">

85-85: Consider adding a user notice about rejection resolution.

Since the PR objectives mention that rejection resolution flows are not yet established, consider adding a notice in the rejection dialog to inform users that they'll need to handle next steps offline or through direct communication.

packages/lib/utils/document-audit-logs.ts (1)

352-361: Consider including rejection reason in the audit message.

The audit message could be more informative by including the rejection reason. This would provide better context in the audit trail.

 .with({ type: DOCUMENT_AUDIT_LOG_TYPE.DOCUMENT_RECIPIENT_REJECTED }, ({ data }) => {
   const userName = prefix || _(msg`Recipient`);

-  const result = msg`${userName} rejected the document`;
+  const result = data.reason
+    ? msg`${userName} rejected the document: ${data.reason}`
+    : msg`${userName} rejected the document`;

   return {
     anonymous: result,
     identified: result,
   };
 })
apps/web/src/components/document/document-history-sheet.tsx (1)

172-172: Consider adding tests and documenting event flow.

While the implementation is correct, consider:

  1. Adding unit tests to verify the handling of rejection audit logs
  2. Documenting how this audit log type integrates with the email notification system mentioned in the PR objectives

This will help ensure the rejection feature remains robust as the codebase evolves.

Would you like help creating unit tests for this component?

packages/prisma/schema.prisma (2)

418-418: Consider adding field constraints for rejectionReason

While the implementation is correct, consider adding a maximum length constraint to prevent excessive storage usage and ensure consistent data handling.

-  rejectionReason   String?
+  rejectionReason   String?   @db.VarChar(1000)

Line range hint 421-424: Consider adding an index on signingStatus

Since the application will likely need to query documents by their signing status (especially to filter rejected documents), adding an index on signingStatus could improve query performance.

  readStatus        ReadStatus    @default(NOT_OPENED)
  signingStatus     SigningStatus @default(NOT_SIGNED)
  sendStatus        SendStatus    @default(NOT_SENT)
+ 
+ @@index([signingStatus])
packages/lib/translations/en/common.po (2)

205-207: Inconsistent quote usage in translation strings.

The message uses single quotes for 'documentName' while other similar messages in the file use double quotes. Consider standardizing quote usage across translation strings for consistency.

-msgid "{recipientName} has rejected the document '{documentName}'"
+msgid "{recipientName} has rejected the document \"{documentName}\""

1184-1186: Consider adding translator context.

While the message is clear, adding a translator comment would help provide context about where and how this message is displayed in the UI.

Add a translator comment above the message:

+#. Displayed in the rejection confirmation email to show the reason provided by the recipient
msgid "Reason for rejection: {rejectionReason}"
msgstr "Reason for rejection: {rejectionReason}"
packages/lib/translations/de/common.po (1)

1359-1359: Inconsistent translation of "Signing Complete!"

The translation for "Signing Complete!" appears to be inconsistent with the formal tone used in other translations.

Consider updating the translation to maintain consistency:

msgid "Signing Complete!"
-msgstr "Unterzeichnung abgeschlossen!"
+msgstr "Signierung abgeschlossen!"

Also applies to: 1395-1396

packages/lib/server-only/document/reject-document-with-token.ts (1)

31-34: Remove unnecessary inclusion of User in the recipient query

The User field within Document is not used in this function. Removing it from the query can improve performance by reducing unnecessary data fetching.

apps/web/src/app/(signing)/sign/[token]/rejected/page.tsx (1)

103-106: Consider displaying the 'Return Home' button for all users

Currently, the "Return Home" button is only displayed if the user is logged in. Unauthenticated users might also benefit from a convenient way to navigate back to the home page after rejecting a document.

packages/lib/jobs/definitions/emails/send-rejection-emails.ts (2)

82-82: Use documentOwner instead of document.User for consistency

Since User has been destructured as documentOwner, use documentOwner.name and documentOwner.email for consistency and readability.

Apply this diff to update the variable usage:

-        documentOwnerName: document.User.name || document.User.email,
+        documentOwnerName: documentOwner.name || documentOwner.email,

78-113: Refactor duplicate email sending logic into a reusable function

The logic for rendering and sending emails to the recipient and the document owner is duplicated. Extract this logic into a helper function to improve maintainability and reduce code duplication.

Consider creating a function like sendEmail({ template, recipientInfo, subject }) to handle the common operations.

Also applies to: 116-153

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between f2439ab and aa916d2.

📒 Files selected for processing (43)
  • apps/marketing/src/app/(marketing)/singleplayer/client.tsx (1 hunks)
  • apps/web/src/app/(dashboard)/documents/[id]/document-page-view-recent-activity.tsx (2 hunks)
  • apps/web/src/app/(dashboard)/documents/[id]/document-page-view-recipients.tsx (3 hunks)
  • apps/web/src/app/(dashboard)/documents/data-table.tsx (1 hunks)
  • apps/web/src/app/(signing)/sign/[token]/page.tsx (1 hunks)
  • apps/web/src/app/(signing)/sign/[token]/reject-document-dialog.tsx (1 hunks)
  • apps/web/src/app/(signing)/sign/[token]/rejected/page.tsx (1 hunks)
  • apps/web/src/app/(signing)/sign/[token]/signing-page-view.tsx (2 hunks)
  • apps/web/src/components/(dashboard)/avatar/stack-avatar.tsx (3 hunks)
  • apps/web/src/components/(dashboard)/avatar/stack-avatars-with-tooltip.tsx (3 hunks)
  • apps/web/src/components/document/document-history-sheet.tsx (1 hunks)
  • packages/email/template-components/template-document-invite.tsx (3 hunks)
  • packages/email/template-components/template-document-rejected.tsx (1 hunks)
  • packages/email/template-components/template-document-rejection-confirmed.tsx (1 hunks)
  • packages/email/templates/document-rejected.tsx (1 hunks)
  • packages/email/templates/document-rejection-confirmed.tsx (1 hunks)
  • packages/lib/client-only/recipient-type.ts (2 hunks)
  • packages/lib/jobs/client.ts (2 hunks)
  • packages/lib/jobs/definitions/emails/send-rejection-emails.ts (1 hunks)
  • packages/lib/server-only/admin/get-recipients-stats.ts (1 hunks)
  • packages/lib/server-only/document/find-document-audit-logs.ts (1 hunks)
  • packages/lib/server-only/document/reject-document-with-token.ts (1 hunks)
  • packages/lib/server-only/document/send-completed-email.ts (2 hunks)
  • packages/lib/translations/de/common.po (21 hunks)
  • packages/lib/translations/de/marketing.po (0 hunks)
  • packages/lib/translations/de/web.js (0 hunks)
  • packages/lib/translations/de/web.po (22 hunks)
  • packages/lib/translations/en/common.po (22 hunks)
  • packages/lib/translations/en/web.js (0 hunks)
  • packages/lib/translations/en/web.po (22 hunks)
  • packages/lib/translations/es/common.po (21 hunks)
  • packages/lib/translations/es/marketing.po (0 hunks)
  • packages/lib/translations/es/web.po (22 hunks)
  • packages/lib/translations/fr/common.po (21 hunks)
  • packages/lib/translations/fr/marketing.po (0 hunks)
  • packages/lib/translations/fr/web.js (0 hunks)
  • packages/lib/translations/fr/web.po (22 hunks)
  • packages/lib/types/document-audit-logs.ts (3 hunks)
  • packages/lib/utils/document-audit-logs.ts (1 hunks)
  • packages/prisma/migrations/20241112223435_add_rejection_status_and_reason_to_recipient_schema/migration.sql (1 hunks)
  • packages/prisma/schema.prisma (2 hunks)
  • packages/trpc/server/recipient-router/router.ts (3 hunks)
  • packages/trpc/server/recipient-router/schema.ts (1 hunks)
💤 Files with no reviewable changes (6)
  • packages/lib/translations/de/marketing.po
  • packages/lib/translations/de/web.js
  • packages/lib/translations/en/web.js
  • packages/lib/translations/es/marketing.po
  • packages/lib/translations/fr/marketing.po
  • packages/lib/translations/fr/web.js
🔇 Additional comments (56)
packages/prisma/migrations/20241112223435_add_rejection_status_and_reason_to_recipient_schema/migration.sql (1)

1-2: LGTM! Enum addition is clean and necessary.

The addition of 'REJECTED' to SigningStatus enum is appropriate and aligns with the new rejection feature requirements.

packages/lib/server-only/admin/get-recipients-stats.ts (2)

16-16: LGTM! The REJECTED status is properly integrated.

The addition of [SigningStatus.REJECTED]: 0 is correctly implemented and will work seamlessly with the existing aggregation logic.


Line range hint 1-32: Verify impact on downstream statistics consumers.

Since this function adds a new signing status to the statistics, we should verify that any downstream consumers of these statistics (e.g., dashboards, reports) properly handle this new status.

✅ Verification successful

Let me check the content of these dashboard components to understand how they handle signing status.


No impact on statistics consumers - safe to proceed

After analyzing the consumers of getRecipientsStats, I can confirm that the statistics are safely consumed:

  • The admin stats page (apps/web/src/app/(dashboard)/admin/stats/page.tsx) only displays positive metrics like "Signatures Collected" (recipientStats.SIGNED) and doesn't rely on specific status values
  • The chart components (signer-conversion-chart.tsx and user-with-document.tsx) don't directly use the signing status values
  • No other components in the codebase directly consume the signing status statistics

The addition of a new signing status won't affect any existing displays or calculations.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Look for potential consumers of getRecipientsStats that might need updates

# Search for direct usage of the function
echo "Direct function usage:"
rg -l "getRecipientsStats"

# Search for components that might display signing status statistics
echo -e "\nPotential statistics displays:"
rg -l "SigningStatus.*statistics|stats.*SigningStatus"

# Look for dashboard components that might need updates
echo -e "\nDashboard components:"
fd -e tsx -e ts --full-path "dashboard.*stats|statistics"

Length of output: 622


Script:

#!/bin/bash
# Check the admin stats page implementation
echo "=== Admin Stats Page ==="
cat "apps/web/src/app/(dashboard)/admin/stats/page.tsx"

echo -e "\n=== Signer Conversion Chart ==="
cat "apps/web/src/app/(dashboard)/admin/stats/signer-conversion-chart.tsx"

echo -e "\n=== User With Document ==="
cat "apps/web/src/app/(dashboard)/admin/stats/user-with-document.tsx"

Length of output: 9938

packages/lib/jobs/client.ts (2)

21-21: LGTM! Job definition properly integrated.

The rejection emails job definition is correctly added to the jobs client array, maintaining the as const assertion for proper type inference. This aligns with the PR's objective of implementing document rejection notifications.


3-3: Verify the existence and implementation of the rejection emails job definition.

The import follows the established pattern for email job definitions.

Let's verify the implementation:

✅ Verification successful

The rejection emails job definition is properly implemented and follows best practices.

The verification shows that:

  • The job definition exists at the correct location
  • It follows the established pattern with proper type definitions and schema validation
  • Implements comprehensive email notifications:
    • Sends confirmation to the recipient who rejected
    • Notifies document owner about the rejection
    • Updates recipient status after sending emails
  • Includes proper error handling and type safety
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if the rejection emails job definition exists and is properly implemented

# Check if the file exists and examine its implementation
fd "send-rejection-emails.ts" --type f --exec cat {}

# Look for any related test files
fd "send-rejection-emails.test.ts" --type f

Length of output: 5642

packages/email/template-components/template-document-rejected.tsx (3)

1-10: LGTM! Well-structured interface design.

The interface clearly defines the required props with appropriate types, and the optional rejectionReason aligns with the business requirement where rejection reasons may not always be provided.


18-48: LGTM! Good accessibility and i18n implementation.

The component demonstrates good practices:

  • Proper semantic HTML structure
  • Comprehensive internationalization using Trans components
  • Accessible button styling with good contrast

41-41: Verify document URL validity.

The documentUrl prop is used directly in the href attribute without validation. We should ensure the URL is properly sanitized to prevent potential security issues.

apps/web/src/components/(dashboard)/avatar/stack-avatar.tsx (3)

16-16: LGTM! Good type safety improvement.

Using RecipientStatusType enum instead of string literals enhances type safety and maintainability.


31-45: LGTM! Well-structured status handling.

The switch statement is properly updated to use enum values, and the new rejection status follows the established styling patterns with appropriate color choices.


43-45: Verify integration with rejection flow UI.

Let's ensure this component is properly integrated with the rejection dialog mentioned in the PR objectives.

✅ Verification successful

Integration with rejection flow UI is properly implemented

The StackAvatar component is correctly integrated into the rejection flow through the StackAvatarsWithTooltip component, which:

  • Properly filters and displays rejected recipients
  • Uses the correct styling for rejected status (via StackAvatar)
  • Shows rejected recipients in a dedicated section with appropriate labeling
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for usage of StackAvatar component in rejection-related UI components
rg -l "StackAvatar.*REJECTED" --type tsx

# Look for rejection dialog components that might use this avatar
rg -l "rejection.*dialog" --type tsx

Length of output: 137


Script:

#!/bin/bash
# Search for usage of StackAvatar component in rejection-related UI components
rg -l "StackAvatar.*REJECTED"

# Look for rejection dialog components that might use this avatar
rg -l "rejection.*dialog"

# Search for files containing both StackAvatar and rejection-related terms
rg -l "StackAvatar" | xargs rg -l "reject"

# Find all TypeScript/React files that might contain rejection-related UI
fd "\.(tsx?|jsx?)$" | xargs rg -l "reject"

Length of output: 1766


Script:

#!/bin/bash
# Check the implementation of reject-document-dialog.tsx and its usage of avatars
rg -A 5 "StackAvatar" "apps/web/src/app/(signing)/sign/[token]/reject-document-dialog.tsx"

# Check how StackAvatar is used in document-page-view-recipients.tsx
rg -A 5 "StackAvatar" "apps/web/src/app/(dashboard)/documents/[id]/document-page-view-recipients.tsx"

# Check the implementation of stack-avatars-with-tooltip.tsx which contains both StackAvatar and reject
cat "apps/web/src/components/(dashboard)/avatar/stack-avatars-with-tooltip.tsx"

Length of output: 5584

packages/email/template-components/template-document-rejection-confirmed.tsx (1)

1-3: LGTM! Clean and well-organized imports.

The imports are appropriately separated between third-party and local dependencies.

packages/lib/client-only/recipient-type.ts (2)

20-22: Verify SigningStatus.REJECTED enum exists.

The code references SigningStatus.REJECTED. Let's verify this enum value exists in the Prisma schema.

#!/bin/bash
# Description: Verify SigningStatus.REJECTED exists in Prisma schema

# Search for SigningStatus enum definition
rg "enum SigningStatus" -A 10 "schema.prisma"

9-9: LGTM! Verify enum usage across the codebase.

The addition of the REJECTED status to RecipientStatusType is well-structured and consistent with existing patterns.

Let's verify that this new status is properly handled throughout the codebase:

✅ Verification successful

Based on the shell script results, I can now generate the final response:

The REJECTED status is properly handled across the codebase

The verification shows that the new REJECTED status is correctly integrated:

  • Handled in the switch statement in stack-avatar.tsx with appropriate styling
  • Used in stack-avatars-with-tooltip.tsx for recipient filtering
  • Properly implemented in the core recipient-type.ts logic
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for places that switch/match on RecipientStatusType to ensure they handle REJECTED

# Search for switch/case or pattern matching on RecipientStatusType
rg -l "RecipientStatusType\." | xargs rg "switch.*RecipientStatusType|case.*RecipientStatusType|match.*RecipientStatusType" -A 10

# Search for direct comparisons with RecipientStatusType
rg "RecipientStatusType\.(COMPLETED|OPENED|WAITING|UNSIGNED)" -l | xargs rg "RecipientStatusType"

Length of output: 5334

packages/email/templates/document-rejected.tsx (3)

17-23: LGTM! Clean props destructuring

The component declaration and props destructuring follow React best practices.


38-65: LGTM! Well-structured email template

The component follows email template best practices with proper container structure and responsive design using Tailwind classes.


70-70: LGTM! Clean export

The default export follows React component export best practices.

packages/email/templates/document-rejection-confirmed.tsx (1)

70-70: LGTM!

The default export follows React conventions.

packages/lib/server-only/document/find-document-audit-logs.ts (1)

69-69: LGTM! Verify the enum value exists.

The addition of DOCUMENT_RECIPIENT_REJECTED to the recent activity filter is appropriate and aligns with the document rejection feature.

Let's verify the enum value exists:

✅ Verification successful

✓ The enum value DOCUMENT_RECIPIENT_REJECTED is properly defined

The DOCUMENT_RECIPIENT_REJECTED enum value is correctly defined in the ZDocumentAuditLogTypeSchema and is being used consistently across the codebase, including proper type definitions and schema validation for the rejection event data.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the DOCUMENT_RECIPIENT_REJECTED enum value exists
# Expected: Find the enum definition with DOCUMENT_RECIPIENT_REJECTED

# Search for the enum definition
rg -A 10 "export enum DOCUMENT_AUDIT_LOG_TYPE" || \
rg -A 10 "enum DOCUMENT_AUDIT_LOG_TYPE" || \
rg -A 10 "DOCUMENT_AUDIT_LOG_TYPE.*=.*{" || \
ast-grep --pattern 'enum DOCUMENT_AUDIT_LOG_TYPE { $$$ }'

Length of output: 315


Script:

#!/bin/bash
# Let's try different approaches to find the enum definition

# Search for any file containing DOCUMENT_AUDIT_LOG_TYPE
rg "DOCUMENT_AUDIT_LOG_TYPE" -l

# Search for DOCUMENT_RECIPIENT_REJECTED specifically
rg "DOCUMENT_RECIPIENT_REJECTED"

# Search for enum definitions in TypeScript files
fd -e ts -x rg -l "enum.*DOCUMENT_AUDIT_LOG_TYPE"

Length of output: 2876


Script:

#!/bin/bash
# Let's check the content of the types file which likely contains the enum definition
cat packages/lib/types/document-audit-logs.ts

Length of output: 16042

packages/email/template-components/template-document-invite.tsx (2)

1-1: LGTM: Clean import addition

The useMemo import is appropriately placed and correctly used for URL manipulation.


92-98: 🛠️ Refactor suggestion

Review button placement and styling for better UX

The reject button implementation raises several UX concerns:

  1. The aggressive red background might not render well in email clients
  2. Placing the destructive action before the primary action could lead to accidental clicks
  3. Both buttons have equal visual weight

Consider these improvements:

  <Button
-   className="mr-4 inline-flex items-center justify-center rounded-lg bg-red-500 px-6 py-3 text-center text-sm font-medium text-black no-underline"
+   className="mr-4 inline-flex items-center justify-center rounded-lg border border-red-500 px-6 py-3 text-center text-sm font-medium text-red-500 no-underline"
    href={rejectDocumentLink}
  >
    <Trans>Reject Document</Trans>
  </Button>

Let's verify the rejection flow implementation:

✅ Verification successful

Based on the search results, I can see that there is a proper rejection flow implementation with confirmation emails in place. The search revealed:

  1. A dedicated template component template-document-rejection-confirmed.tsx for rejection confirmation
  2. A job handler in send-rejection-emails.ts that sends confirmation emails
  3. Proper i18n support for rejection-related messages
  4. Rejection reason handling is implemented

UX suggestions for button styling remain valid but rejection flow is properly implemented

The original styling concerns about the red button in email templates are valid, but the rejection flow itself is well-implemented with proper confirmation emails and user notifications. Consider the suggested styling changes to improve visual hierarchy while maintaining the existing robust rejection flow:

  <Button
-   className="mr-4 inline-flex items-center justify-center rounded-lg bg-red-500 px-6 py-3 text-center text-sm font-medium text-black no-underline"
+   className="mr-4 inline-flex items-center justify-center rounded-lg border border-red-500 px-6 py-3 text-center text-sm font-medium text-red-500 no-underline"
    href={rejectDocumentLink}
  >
    <Trans>Reject Document</Trans>
  </Button>
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for rejection confirmation dialog implementation

# Look for rejection dialog component
ast-grep --pattern 'export const RejectDocumentDialog = $_'

# Check for rejection confirmation handling
rg -A 5 'reject.*confirm|confirm.*reject'

Length of output: 17244

packages/trpc/server/recipient-router/router.ts (4)

4-4: LGTM! Import follows established patterns.

The import is correctly placed and follows the server-only pattern for document operations.


100-102: LGTM! Mutation setup follows tRPC patterns.

The procedure setup and input schema usage align with existing patterns.


14-14: Verify schema implementation for rejection mutation.

The schema import is present, but let's verify its implementation.

✅ Verification successful

Schema implementation verified and complete

The schema is properly implemented in packages/trpc/server/recipient-router/schema.ts with all expected fields:

  • token (string)
  • documentId (number)
  • reason (string)
  • Optional authOptions using ZRecipientActionAuthSchema
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the schema implementation and its properties
# Expected: Schema should define token, documentId, and reason fields

# Search for the schema definition
rg -A 10 "ZRejectDocumentWithTokenMutationSchema.*=.*" --type typescript

Length of output: 109


Script:

#!/bin/bash
# Search for the schema definition without file type restriction
rg -A 10 "ZRejectDocumentWithTokenMutationSchema.*=.*"

Length of output: 842


100-120: Verify token validation and reason handling.

Please ensure:

  1. Token validation is properly implemented in the imported rejectDocumentWithToken function
  2. The reason field has appropriate length/content validation in the schema
✅ Verification successful

Based on the gathered information, I can now provide the final response:

Token and reason validation are properly implemented

  1. Token validation is handled in rejectDocumentWithToken function through:

    • Database validation to ensure token and documentId match a valid recipient
    • Proper error handling with TRPCError if token/document is not found
  2. The reason field is validated through:

    • Basic string validation in ZRejectDocumentWithTokenMutationSchema
    • Additional validation in the UI component RejectDocumentDialog where reason is required to be:
      • Minimum 5 characters
      • Maximum 500 characters
      • Non-empty string
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify token validation and reason handling implementation

# Check for token validation in rejectDocumentWithToken
echo "Checking token validation..."
rg -A 10 "rejectDocumentWithToken.*=.*" --type typescript

# Check for reason validation in schema
echo "Checking reason validation..."
rg "reason.*:.*" --type typescript

Length of output: 302


Script:

#!/bin/bash
# Let's try without file type filtering since typescript extension isn't recognized
# Check for token validation in rejectDocumentWithToken implementation
echo "Checking token validation implementation..."
rg -A 10 "export.*rejectDocumentWithToken"

# Check schema definition for ZRejectDocumentWithTokenMutationSchema
echo "Checking schema definition..."
rg "ZRejectDocumentWithTokenMutationSchema.*=.*" -A 10

# Check for any validation related to reason field
echo "Checking reason field validation..."
rg "reason.*z\." 

Length of output: 2350


Script:

#!/bin/bash
# Let's check the complete implementation of rejectDocumentWithToken to see token validation
echo "Checking complete rejectDocumentWithToken implementation..."
rg -l "rejectDocumentWithToken" | xargs cat

# Let's also check if there are any string validations in the schema file
echo "Checking for string validations in schema..."
rg "z\.string\(\)\.+" -A 2

Length of output: 46498

apps/web/src/app/(dashboard)/documents/data-table.tsx (1)

81-81: Verify rejection status handling in DocumentStatus component

The change to access status directly is valid. However, let's ensure the DocumentStatus component properly handles the new REJECTED status.

apps/web/src/app/(signing)/sign/[token]/reject-document-dialog.tsx (2)

1-41: LGTM! Well-structured imports and form validation schema.

The form validation schema with translation support is well implemented with appropriate constraints (5-500 characters).


48-170: Overall implementation is well-structured and functional.

The component successfully implements the document rejection flow with:

  • Proper form validation and error handling
  • Accessible UI components
  • Loading state management
  • Clear user feedback through toasts

While there are some suggested improvements, the core functionality is solid and meets the PR objectives.

apps/web/src/app/(signing)/sign/[token]/page.tsx (1)

102-104: LGTM! Verify the rejection flow integration.

The placement of this check is logically sound - it's after access validation but before other status checks, ensuring rejected documents are properly redirected.

Let's verify the complete rejection flow integration:

✅ Verification successful

The rejection flow is properly implemented and integrated

The verification confirms that:

  • The rejection flow is complete with both the redirect logic and dedicated rejected page (/apps/web/src/app/(signing)/sign/[token]/rejected/page.tsx)
  • The reject dialog component (reject-document-dialog.tsx) handles the rejection action and redirects correctly
  • The rejected page provides appropriate feedback to users with proper error handling and authentication checks
  • Multiple files across the codebase reference SigningStatus.REJECTED, indicating consistent integration
  • The redirect path in the original code matches the implemented rejected page location

The implementation follows a coherent flow: rejection action → status check → redirect → dedicated rejection page.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the rejection flow implementation
# Check for the rejected page component and related components

# Check if the rejected page component exists
fd -e tsx "rejected/page.tsx" apps/web/src/app

# Verify the rejection dialog component
fd -e tsx "reject-document-dialog.tsx" apps/web/src/app

# Check for any missing imports of SigningStatus.REJECTED
rg -l "SigningStatus[^R]*REJECTED" --type tsx

Length of output: 245


Script:

#!/bin/bash
# Let's verify the rejection flow with correct file type flags and patterns

# Check if the rejected page component exists
fd "rejected/page" apps/web/src/app

# Check for SigningStatus.REJECTED usage with proper ripgrep flags
rg -t typescript -t tsx "SigningStatus\.REJECTED"

# Look for any redirect patterns to the rejected page
rg -t typescript -t tsx "redirect.*rejected"

# Check the content of the reject-document-dialog component
cat "apps/web/src/app/(signing)/sign/[token]/reject-document-dialog.tsx"

Length of output: 4825


Script:

#!/bin/bash
# Let's try with simpler commands and proper file extensions

# Look for files with .ts or .tsx extension containing SigningStatus
find . -type f \( -name "*.ts" -o -name "*.tsx" \) -exec grep -l "SigningStatus" {} \;

# Look for the rejected page
find . -type f -name "page.tsx" -path "*/rejected/*"

# Check for any router.push or redirect calls to the rejected page
find . -type f \( -name "*.ts" -o -name "*.tsx" \) -exec grep -l "rejected.*push\|redirect.*rejected" {} \;

Length of output: 2698


Script:

#!/bin/bash
# Let's check the content of the rejected page and the SigningStatus usage

# Check the rejected page implementation
cat "./apps/web/src/app/(signing)/sign/[token]/rejected/page.tsx"

# Check SigningStatus definition and REJECTED enum value
find . -type f \( -name "*.ts" -o -name "*.tsx" \) -exec grep -A 5 "enum.*SigningStatus" {} \;

Length of output: 3686

apps/web/src/components/(dashboard)/avatar/stack-avatars-with-tooltip.tsx (2)

11-11: LGTM! Good TypeScript practice.

Using the type keyword for type imports is a good practice as it ensures better type safety and optimal bundle size.


49-51: LGTM! Consistent implementation.

The rejected recipients filter follows the same pattern as other recipient filters, maintaining code consistency.

apps/web/src/app/(dashboard)/documents/[id]/document-page-view-recipients.tsx (1)

7-15: LGTM: Import statements are well-organized.

The new imports for AlertTriangle and PopoverHover are properly organized and necessary for the rejection status UI implementation.

Also applies to: 26-26

apps/web/src/app/(dashboard)/documents/[id]/document-page-view-recent-activity.tsx (2)

7-7: LGTM! Import changes are appropriate.

The AlertTriangle icon is a semantically appropriate choice for representing rejection status in the activity log.


136-140: Verify audit log type integration.

Let's ensure the new rejection audit log type is properly defined and handled throughout the system.

✅ Verification successful

Audit log type is properly integrated and handled

The verification shows that DOCUMENT_RECIPIENT_REJECTED is:

  • Defined as a constant in packages/lib/types/document-audit-logs.ts
  • Has a proper Zod schema validation (ZDocumentAuditLogEventDocumentRecipientRejectedSchema)
  • Used in the audit log handler (reject-document-with-token.ts)
  • Properly handled in the UI components for history and recent activity
  • Included in the list of valid audit log types in find-document-audit-logs.ts
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the audit log type definition and its usage

# Check if the audit log type is defined
rg "DOCUMENT_RECIPIENT_REJECTED" -A 5 -B 5

# Check for any related audit log handlers
ast-grep --pattern 'function $_(auditLog: $_) {
  $$$
  DOCUMENT_RECIPIENT_REJECTED
  $$$
}'

Length of output: 8266

packages/lib/server-only/document/send-completed-email.ts (2)

20-20: LGTM! Good practice using a dedicated utility for URL formatting.

The addition of formatDocumentsPath helps maintain consistent URL structures across the application.


Line range hint 1-1: Verify implementation of rejection email notifications.

Given that this PR implements document rejection functionality, we should verify that similar email notification logic exists for rejection scenarios.

✅ Verification successful

Let me check the implementation details of the rejection email functionality to ensure it's properly implemented.


Let me check one final piece - the email sending job implementation to ensure the rejection emails are properly triggered.


Rejection email notifications are properly implemented ✅

The codebase has a complete implementation for document rejection emails:

  • Email template with rejection reason support (DocumentRejectedEmail)
  • Rejection handling function that triggers email notifications (rejectDocumentWithToken)
  • TRPC router endpoint for rejection
  • Email job definition for sending rejection notifications
  • Well-structured template component for the rejection email content
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for the existence of rejection email related files and implementations

# Check for rejection email template
echo "Checking for rejection email template..."
fd -e tsx -e ts "document-rejected" 

# Check for rejection email sending function
echo "Checking for rejection email sending function..."
rg -l "sendRejection|rejectDocument|documentRejected" --type ts

# Check for rejection email tests
echo "Checking for rejection email tests..."
fd -e test.tsx -e test.ts -e spec.tsx -e spec.ts "reject|rejection"

Length of output: 810


Script:

#!/bin/bash
# Check the implementation of rejection email template and sending logic

# Check rejection email template implementation
echo "Checking rejection email template implementation..."
cat packages/email/templates/document-rejected.tsx

# Check document rejection function implementation
echo -e "\nChecking document rejection function..."
cat packages/lib/server-only/document/reject-document-with-token.ts

# Check if rejection email is sent in the router
echo -e "\nChecking router implementation for rejection..."
cat packages/trpc/server/recipient-router/router.ts

Length of output: 8757


Script:

#!/bin/bash
# Check the email sending job implementation
echo "Checking email sending job implementation..."
rg -A 10 "send.signing.rejected.emails" --type ts

# Also check the template component
echo -e "\nChecking template component implementation..."
cat packages/email/template-components/template-document-rejected.tsx

Length of output: 3467

apps/web/src/app/(signing)/sign/[token]/signing-page-view.tsx (2)

34-34: LGTM: Import statement is properly structured.

The import follows the established pattern for local component imports.


85-85: Verify token usage in rejection flow.

While the placement of the RejectDocumentDialog is appropriate, let's ensure the token is properly validated in the rejection flow to prevent unauthorized rejections.

apps/marketing/src/app/(marketing)/singleplayer/client.tsx (1)

166-166: LGTM: Type-level change for model consistency.

The addition of rejectionReason property to placeholderRecipient maintains consistency with the main application's Recipient model while correctly initializing it as null for this demo mode where rejection isn't applicable.

packages/lib/utils/document-audit-logs.ts (1)

352-361: LGTM! Implementation follows established patterns.

The new case for DOCUMENT_RECIPIENT_REJECTED is well-integrated into the existing match statement and follows the same patterns used throughout the file for handling audit logs.

apps/web/src/components/document/document-history-sheet.tsx (1)

172-172: LGTM! The audit log type integration looks good.

The addition of DOCUMENT_RECIPIENT_REJECTED to the pattern match case is consistent with similar audit log types that don't require additional UI elements. This change properly integrates with the document rejection feature.

packages/lib/types/document-audit-logs.ts (4)

370-375: LGTM! Schema structure is well-defined

The schema correctly extends the base recipient data with a required reason field, maintaining consistency with other audit log event schemas.


501-501: LGTM! Union type updated correctly

The new rejection schema is properly integrated into the document audit log union type, maintaining the alphabetical ordering.


36-36: Verify Prisma migration for new audit log type

The addition of the new enum value 'DOCUMENT_RECIPIENT_REJECTED' will require a database migration since audit log data is stored as JSON in Prisma.

✅ Verification successful

Let's also check if there are any TypeScript files that might indicate where migrations should be created:


Looking at the migration files output, I found the relevant migration 20241112223435_add_rejection_status_and_reason_to_recipient_schema.sql that adds the rejection functionality. Let me verify its contents:


Let me try a different approach to find the migration content:


Migration exists for the new audit log type

The database schema changes for document rejection functionality are properly handled through migration 20241112223435_add_rejection_status_and_reason_to_recipient_schema which adds:

  • New REJECTED value to the SigningStatus enum
  • New rejectionReason column to the Recipient table

Since the audit log types are stored as an enum in TypeScript and not in the database (as evidenced by the file being in types/ directory), no database migration is required for the new audit log type DOCUMENT_RECIPIENT_REJECTED. The existing JSON column in the database will accept the new enum value.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if a migration exists for the new audit log type

# Look for migration files that might contain the new audit log type
rg -l "DOCUMENT_RECIPIENT_REJECTED" --type sql

Length of output: 46


Script:

#!/bin/bash
# Let's check for any recent migration files and their content
fd "\.sql$" --exec head -n 5 {}

# Also check for any pending migration files in a migrations directory
fd "migrations?"

Length of output: 26390


Script:

#!/bin/bash
# Search for migration-related configuration or setup files
rg -l "prisma.*migrate" --type ts

# Look for any migration documentation or guidelines
rg -l "migration" README.md

Length of output: 63


Script:

#!/bin/bash
# Check the content of the rejection-related migration
cat packages/prisma/migrations/20241112223435_add_rejection_status_and_reason_to_recipient_schema.sql

Length of output: 233


Script:

#!/bin/bash
# Search for any files containing rejection-related schema changes
rg "REJECTED|rejectionReason" --type sql

# Also check for any enum type modifications related to signing status
rg "ALTER TYPE.*SigningStatus" --type sql

Length of output: 571


Line range hint 36-501: Verify integration with related components

The audit log type changes are part of a larger document rejection feature. Let's verify the integration with related components.

✅ Verification successful

Integration points for document rejection are properly implemented

The new DOCUMENT_RECIPIENT_REJECTED audit log type is well integrated across the codebase:

  • UI components properly handle and display rejection events in both history sheet and page view
  • Server-side implementation correctly creates audit logs with recipient details and rejection reason
  • Audit log filtering system includes the new type in relevant queries
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check integration points for the new rejection functionality

# Check for UI components using the new audit log type
echo "Checking UI components..."
rg -A 5 "DOCUMENT_RECIPIENT_REJECTED" --type tsx

# Check for email notification handlers
echo "Checking email handlers..."
rg -A 5 "DOCUMENT_RECIPIENT_REJECTED" --type ts --glob "*/email*"

# Check for API endpoints using the new type
echo "Checking API endpoints..."
rg -A 5 "DOCUMENT_RECIPIENT_REJECTED" --glob "*/api/*"

Length of output: 531


Script:

#!/bin/bash
# Let's try a different approach using more reliable commands

# Search for files with .tsx extension
echo "Checking UI components..."
fd -e tsx -x rg -l "DOCUMENT_RECIPIENT_REJECTED" {}

# Search for email-related files
echo "Checking email handlers..."
fd -t f -e ts | rg "email|notification" | xargs rg -l "DOCUMENT_RECIPIENT_REJECTED"

# Search for API endpoints
echo "Checking API routes and handlers..."
fd -t f -e ts | rg "api|route|handler" | xargs rg -l "DOCUMENT_RECIPIENT_REJECTED"

# Search for any TypeScript files using this enum
echo "Checking all TypeScript files..."
fd -e ts -x rg -l "DOCUMENT_RECIPIENT_REJECTED" {}

Length of output: 918


Script:

#!/bin/bash
# Let's examine the integration points we found

# Check document history sheet implementation
echo "=== Document History Sheet Implementation ==="
rg -A 10 "DOCUMENT_RECIPIENT_REJECTED" "./apps/web/src/components/document/document-history-sheet.tsx"

# Check document page view implementation
echo "=== Document Page View Implementation ==="
rg -A 10 "DOCUMENT_RECIPIENT_REJECTED" "./apps/web/src/app/(dashboard)/documents/[id]/document-page-view-recent-activity.tsx"

# Check reject document implementation
echo "=== Reject Document Implementation ==="
rg -A 10 "DOCUMENT_RECIPIENT_REJECTED" "./packages/lib/server-only/document/reject-document-with-token.ts"

# Check audit logs implementation
echo "=== Audit Logs Implementation ==="
rg -A 10 "DOCUMENT_RECIPIENT_REJECTED" "./packages/lib/server-only/document/find-document-audit-logs.ts"

Length of output: 2732

packages/prisma/schema.prisma (2)

396-396: LGTM! SigningStatus enum addition

The addition of REJECTED status aligns well with the existing signing states and supports the new rejection functionality.


Line range hint 396-424: Verify rejection handling in related components

The schema changes look good, but ensure these changes are properly handled in:

  1. Document listing/filtering components
  2. Email notification templates
  3. Document status transitions
  4. API endpoints for rejection
✅ Verification successful

Let me gather more specific information about the implementation details to ensure proper rejection handling.


Rejection handling is properly implemented across all required components

The verification shows comprehensive implementation of rejection handling:

  • Sign page redirects rejected documents appropriately
  • Document view displays rejection status with reason in a popover
  • Email notifications are implemented with dedicated templates and branding
  • API properly updates signing status, rejection reason, and creates audit logs
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the implementation of rejection handling in related components

# Check for rejection handling in components
echo "Checking components handling document rejection..."
rg -l "SigningStatus.*REJECTED" --type-add 'component:*.{tsx,jsx}'

# Check for rejection-related API endpoints
echo "Checking API endpoints for rejection..."
rg -l "rejection.*api|api.*rejection" --type-add 'api:*.{ts,js}'

# Check for email templates handling rejection
echo "Checking email templates..."
rg -l "rejection.*email|email.*rejection" --type-add 'email:*.{tsx,jsx}'

Length of output: 1180


Script:

#!/bin/bash
# Check document rejection implementation details
echo "Checking rejection implementation in sign page..."
rg -A 5 "REJECTED|rejection" "apps/web/src/app/(signing)/sign/[token]/page.tsx"

echo "Checking rejection handling in document view..."
rg -A 5 "REJECTED|rejection" "apps/web/src/app/(dashboard)/documents/[id]/document-page-view-recipients.tsx"

echo "Checking rejection email implementation..."
rg -A 5 "REJECTED|rejection" "packages/lib/jobs/definitions/emails/send-rejection-emails.ts"

echo "Checking rejection API implementation..."
rg -A 5 "REJECTED|rejection" "packages/lib/server-only/document/reject-document-with-token.ts"

Length of output: 3274

packages/lib/translations/en/common.po (3)

209-211: LGTM! Well-structured rejection notification message.

The message follows proper i18n formatting and uses consistent variable interpolation.


1220-1222: LGTM! Clear and consistent action button text.

The message follows the established pattern for action buttons in the application.


1224-1230: LGTM! Well-structured confirmation messages.

The messages properly handle variable interpolation and maintain consistency with other confirmation messages in the application.

packages/lib/translations/de/common.po (1)

Line range hint 1-24: LGTM: PO file metadata is correctly formatted

The PO file metadata section contains all required fields and is properly formatted:

  • Correct charset and encoding settings
  • Language and plural forms are properly specified
  • Project metadata is complete
packages/lib/translations/en/web.po (3)

652-652: LGTM: Document rejection translations are clear and consistent

The new translations for document rejection functionality are well-written and maintain a consistent tone throughout the application. The messages effectively communicate the rejection workflow to users.

Also applies to: 660-662, 2699-2701, 2819-2820, 2823-2824, 2879-2883, 2885-2888


2507-2507: LGTM: Status indicator translations are accurate

The new status indicator translations ("Opened", "Uncompleted", "Viewed", "Waiting") are concise and accurately reflect the document states.

Also applies to: 4175-4175, 4420-4420, 4425-4425


2303-2303: LGTM: Recipient action translations are clear

The translations for recipient actions ("Modify recipients", "Ready") are straightforward and effectively communicate the available actions to users.

Also applies to: 2811-2811

packages/lib/translations/fr/web.po (1)

Line range hint 1-5000: LGTM! Existing translations are well maintained

The existing French translations demonstrate good quality with:

  • Consistent translation patterns
  • Proper handling of placeholders (e.g., {0}, {1})
  • Correct preservation of HTML tags
  • Appropriate formal tone for a business application
apps/web/src/app/(signing)/sign/[token]/rejected/page.tsx (1)

1-102: Implementation meets requirements and is well-structured

The RejectedSigningPage component effectively handles token validation, session retrieval, document fetching, recipient authorization, and renders the appropriate UI for a rejected document. Error handling and conditional rendering are appropriately implemented. The UI provides clear feedback to the user.

Also applies to: 107-110

Comment on lines +28 to +29
console.log({ type, fallbackText });

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.

⚠️ Potential issue

Remove debug console.log statement.

Debug logging should not be committed to production code.

-  console.log({ type, fallbackText });
📝 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
console.log({ type, fallbackText });

Comment on lines +25 to +30
<Text className="text-primary text-base">
<Trans>
This email confirms that you have rejected the document{' '}
<strong className="font-bold">"{documentName}"</strong> sent by {documentOwnerName}.
</Trans>
</Text>

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.

⚠️ Potential issue

Sanitize user input before rendering.

The documentName and documentOwnerName are rendered directly in the template. Consider sanitizing these inputs to prevent potential XSS attacks in email clients.

-            <strong className="font-bold">"{documentName}"</strong> sent by {documentOwnerName}.
+            <strong className="font-bold">"{sanitizeHtml(documentName)}"</strong> sent by {sanitizeHtml(documentOwnerName)}.

Committable suggestion skipped: line range outside the PR's diff.

documentName,
documentUrl,
rejectionReason,
assetBaseUrl = 'http://localhost:3002',

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.

⚠️ Potential issue

Consider making the default assetBaseUrl configurable

The hardcoded localhost URL could cause issues in different environments. Consider making this configurable through environment variables.

-  assetBaseUrl = 'http://localhost:3002',
+  assetBaseUrl = process.env.NEXT_PUBLIC_ASSET_BASE_URL ?? 'http://localhost:3002',
📝 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
assetBaseUrl = 'http://localhost:3002',
assetBaseUrl = process.env.NEXT_PUBLIC_ASSET_BASE_URL ?? 'http://localhost:3002',

const { _ } = useLingui();
const branding = useBranding();

const previewText = _(msg`${recipientName} has rejected the document '${documentName}'`);

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.

🛠️ Refactor suggestion

Avoid template literals in translations

Using template literals within translations can lead to issues with word order in different languages. Consider using lingui's variable interpolation instead.

-  const previewText = _(msg`${recipientName} has rejected the document '${documentName}'`);
+  const previewText = _(
+    msg({
+      id: 'email.document.rejected.preview',
+      message: '{recipient} has rejected the document '{document}'',
+      values: {
+        recipient: recipientName,
+        document: documentName,
+      },
+    })
+  );
📝 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
const previewText = _(msg`${recipientName} has rejected the document '${documentName}'`);
const previewText = _(
msg({
id: 'email.document.rejected.preview',
message: '{recipient} has rejected the document '{document}'',
values: {
recipient: recipientName,
document: documentName,
},
})
);

const { _ } = useLingui();
const branding = useBranding();

const previewText = _(msg`You have rejected the document '${documentName}'`);

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.

⚠️ Potential issue

Sanitize user inputs in preview text.

The document name is directly interpolated into the preview text without sanitization, which could lead to display issues.

-  const previewText = _(msg`You have rejected the document '${documentName}'`);
+  const previewText = _(msg`You have rejected the document '${sanitizeText(documentName)}'`);

Consider adding a utility function:

const sanitizeText = (text: string) => {
  return text.replace(/[<>&'"]/g, (char) => {
    const entities: Record<string, string> = {
      '<': '&lt;',
      '>': '&gt;',
      '&': '&amp;',
      "'": '&#39;',
      '"': '&quot;'
    };
    return entities[char];
  });
};

id: recipient.id,
},
data: {
signedAt: new Date(),

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.

🛠️ Refactor suggestion

⚠️ Potential issue

Consider using a separate timestamp for rejection events

Updating signedAt when the document is rejected might be misleading, as signedAt typically indicates when the document was signed. It would be clearer to introduce a rejectedAt field to record the time of rejection.

data: {
signedAt: new Date(),
signingStatus: SigningStatus.REJECTED,
rejectionReason: reason,

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.

⚠️ Potential issue

Validate or sanitize the reason input to prevent security vulnerabilities

The reason provided by the user should be validated or sanitized to prevent potential security issues such as injection attacks, especially if the reason is used in logs or sent via email.

Comment on lines +51 to +61
const [updatedRecipient] = await prisma.$transaction([
prisma.recipient.update({
where: {
id: recipient.id,
},
data: {
signedAt: new Date(),
signingStatus: SigningStatus.REJECTED,
rejectionReason: reason,
},
}),

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.

🛠️ Refactor suggestion

Check recipient's current signing status before updating

Before updating the recipient's signingStatus to REJECTED, consider validating the current status. If the recipient has already signed or rejected the document, updating the status again might lead to inconsistent states.

Comment on lines +140 to +164
await mailer.sendMail({
to: {
name: documentOwner.name || '',
address: documentOwner.email,
},
from: {
name: FROM_NAME,
address: FROM_ADDRESS,
},
subject: i18n._(msg`Document "${document.title}" - Rejected by ${recipient.name}`),
html,
text,
});
});

await io.runTask('update-recipient', async () => {
await prisma.recipient.update({
where: {
id: recipient.id,
},
data: {
sendStatus: SendStatus.SENT,
},
});
});

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.

⚠️ Potential issue

Ensure sendStatus is updated only after successful email sending

Currently, the recipient's sendStatus is updated to SENT regardless of whether the emails were sent successfully. To prevent inaccurate status updates, consider updating sendStatus only if both emails are sent without errors.

Refactor the code to include error handling:

      // Update recipient's send status after successful email sending
-      await io.runTask('update-recipient', async () => {
+      // Proceed only if previous tasks succeeded
+      await io.successful(async () => {
          await prisma.recipient.update({
            where: {
              id: recipient.id,
            },
            data: {
              sendStatus: SendStatus.SENT,
            },
          });
+      });

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +67 to +69
const isEmailEnabled = extractDerivedDocumentEmailSettings(
document.documentMeta,
).recipientSigningRequest;

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.

💡 Codebase verification

Incorrect email setting is being checked for rejection emails

Based on the evidence from the codebase:

  1. The DocumentEmailEvents enum shows distinct events for different email notifications:

    • RecipientSigningRequest for signing requests
    • RecipientRemoved for recipient removal
    • DocumentPending for pending status
    • DocumentCompleted for completion
  2. The code in send-rejection-emails.ts is currently checking recipientSigningRequest, which is meant for signing request emails, not rejections.

  3. Looking at similar implementations in the codebase, each email type should use its corresponding setting. For example, set-recipients-for-document.ts correctly uses recipientRemoved for recipient removal notifications.

The code should be using a more appropriate email setting for rejection notifications, likely needing a new dedicated setting for rejections since there isn't one currently defined in the email events enum.

🔗 Analysis chain

Verify the correct email setting is checked

Currently, the code checks recipientSigningRequest to determine if the email should be sent. Please verify if recipientSigningRequest is the appropriate flag for sending rejection emails. If not, ensure that the correct email setting is used.

Run the following script to confirm the available email settings:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify properties returned by `extractDerivedDocumentEmailSettings`.

# Test: Retrieve the keys from the returned object. Expect: See all available email settings.
rg 'export function extractDerivedDocumentEmailSettings' -A 20 packages/lib/types/document-email.ts | rg 'return {'

Length of output: 197


Script:

#!/bin/bash
# Let's try a different approach to find the email settings

# First, let's find the implementation of extractDerivedDocumentEmailSettings
ast-grep --pattern 'export function extractDerivedDocumentEmailSettings'

# Also search for any type definitions or interfaces related to email settings
rg -A 10 'interface.*Email.*Settings'

# And look for usage of recipientSigningRequest in the context of emails
rg 'recipientSigningRequest' -A 3 -B 3

Length of output: 5229


Script:

#!/bin/bash
# Let's look for any rejection-specific email settings or types
rg -B 5 -A 5 'RecipientRemoved'

# Also check for any other email-related enums or types that might be relevant
ast-grep --pattern 'enum DocumentEmailEvents'

# Look for any other files handling rejection scenarios
rg -l 'rejection|reject' packages/lib/

Length of output: 10416

@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: 2

🧹 Outside diff range and nitpick comments (4)
packages/lib/translations/en/common.po (3)

668-674: Consider standardizing the quotation marks

The strings use different types of quotation marks - some use straight quotes (") while others use curly quotes (""). Consider standardizing to straight quotes for consistency.

-msgid "Document \"{0}\" - Rejected by {1}"
+msgid "Document \"{0}\" - Rejected by {1}"
-msgid "Document \"{0}\" - Rejection Confirmed"
+msgid "Document \"{0}\" - Rejection Confirmed"

1224-1231: Improve clarity of rejection confirmation message

The current message structure could be improved for better readability and user understanding.

-msgid "Rejection Confirmed"
+msgid "Document Rejection Confirmed"
-msgid "Rejection reason: {reason}"
+msgid "Reason for rejection: {reason}"

1480-1482: Consider breaking down the long message

The rejection confirmation message is quite long and contains multiple pieces of information. Consider breaking it into separate, more focused messages for better readability and maintainability.

-msgid "The document owner has been notified of this rejection. No further action is required from you at this time. The document owner may contact you with any questions regarding this rejection."
+msgid "The document owner has been notified of this rejection."
+msgid "No further action is required from you at this time."
+msgid "Note: The document owner may contact you with any questions regarding this rejection."
packages/lib/translations/fr/common.po (1)

413-413: Inconsistent line breaks and indentation

The file contains inconsistent line breaks and indentation in some translations.

Consider standardizing the formatting:

  • Remove extra blank lines between entries
  • Use consistent indentation for multiline translations
  • Align continuation lines with the opening quote

Also applies to: 425-425, 605-605, 613-613, 617-617, 1350-1350, 1359-1359, 1476-1479, 1739-1742

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between aa916d2 and 3875c49.

📒 Files selected for processing (12)
  • .github/workflows/publish.yml (1 hunks)
  • packages/lib/translations/de/common.po (26 hunks)
  • packages/lib/translations/de/marketing.po (0 hunks)
  • packages/lib/translations/de/web.po (22 hunks)
  • packages/lib/translations/en/common.po (27 hunks)
  • packages/lib/translations/en/web.po (22 hunks)
  • packages/lib/translations/es/common.po (26 hunks)
  • packages/lib/translations/es/marketing.po (0 hunks)
  • packages/lib/translations/es/web.po (22 hunks)
  • packages/lib/translations/fr/common.po (26 hunks)
  • packages/lib/translations/fr/marketing.po (0 hunks)
  • packages/lib/translations/fr/web.po (22 hunks)
💤 Files with no reviewable changes (3)
  • packages/lib/translations/de/marketing.po
  • packages/lib/translations/es/marketing.po
  • packages/lib/translations/fr/marketing.po
✅ Files skipped from review due to trivial changes (1)
  • .github/workflows/publish.yml
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/lib/translations/de/common.po
  • packages/lib/translations/es/web.po
🔇 Additional comments (13)
packages/lib/translations/en/common.po (3)

205-211: LGTM: Email template strings are well-formatted

The email template strings follow consistent formatting and use appropriate placeholders for dynamic content.


1567-1570: LGTM: Rejection notification message is clear and well-formatted

The message clearly communicates the rejection status and includes proper HTML formatting for the document name.


237-239: LGTM: Audit log message is concise and clear

The audit log message follows the established pattern for audit events and clearly indicates the rejection action.

packages/lib/translations/es/common.po (6)

82-82: LGTM: Invitation message translations are accurate and consistent

The translations for invitation messages maintain proper context and meaning in Spanish.

Also applies to: 102-102


154-154: LGTM: Email notification translations are accurate

The translations for email resent/sent notifications are clear and maintain the same meaning as the English versions.

Also applies to: 158-158


413-413: LGTM: Action button translations are accurate

The translations for "Add myself" and "Add Signer" buttons are clear and consistent.

Also applies to: 425-425


475-475: LGTM: Document approval translation is accurate

The translation for "Approve Document" maintains proper context and meaning in Spanish.


605-605: LGTM: Document action messages are properly translated

The translations for document action messages (continue by approving/signing/viewing) are accurate and maintain proper context.

Also applies to: 613-613, 617-617


696-697: LGTM: Document completion translations are accurate

The translations for document completion messages are clear and consistent.

packages/lib/translations/fr/common.po (1)

210-213: Missing French translations for document rejection feature

Several strings related to document rejection functionality are missing French translations.

The missing translations were previously identified and translations were suggested in a past review comment. Please refer to that comment for the proposed translations.

Also applies to: 214-217, 242-245, 673-676, 677-680, 751-754, 1219-1222, 1223-1226, 1227-1230, 1560-1563, 1776-1779

packages/lib/translations/en/web.po (1)

664-666: LGTM! The new translations for document rejection functionality are well-structured.

The added message identifiers and their translations are consistent with the PR objectives, providing clear and user-friendly messages for:

  • Rejection confirmation dialog
  • Rejection reason validation
  • Status indicators
  • Completion messages

Also applies to: 2703-2705, 2827-2829, 2889-2892, 4884-4886

packages/lib/translations/fr/web.po (1)

669-672: Missing translations for document rejection functionality

Several key translations related to the document rejection feature are missing their French translations.

This issue was previously identified in an earlier review. Please refer to the existing comment for the suggested translations.

Also applies to: 2824-2827, 2828-2831, 2884-2889, 2890-2894, 4885-4888

packages/lib/translations/de/web.po (1)

667-669: Missing translations for document rejection functionality

The missing translations for the document rejection feature have already been identified in a previous review. Please refer to the existing review comment for the suggested translations.

Also applies to: 1523-1525, 2401-2405, 2826-2828, 2830-2832, 4887-4889

Comment on lines +210 to +217
#: packages/email/templates/document-rejected.tsx:27
msgid "{recipientName} has rejected the document '{documentName}'"
msgstr ""

#: packages/email/template-components/template-document-rejected.tsx:25
msgid "{signerName} has rejected the document \"{documentName}\"."
msgstr ""

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.

⚠️ Potential issue

Add missing translations for document rejection functionality

Several strings related to document rejection functionality are missing Spanish translations. This affects the user experience for Spanish-speaking users.

Add the following translations:

msgid "{recipientName} has rejected the document '{documentName}'"
-msgstr ""
+msgstr "{recipientName} ha rechazado el documento '{documentName}'"

msgid "{signerName} has rejected the document \"{documentName}\"."
-msgstr ""
+msgstr "{signerName} ha rechazado el documento \"{documentName}\"."

msgid "{userName} rejected the document"
-msgstr ""
+msgstr "{userName} rechazó el documento"

msgid "Document \"{0}\" - Rejected by {1}"
-msgstr ""
+msgstr "Documento \"{0}\" - Rechazado por {1}"

msgid "Document \"{0}\" - Rejection Confirmed"
-msgstr ""
+msgstr "Documento \"{0}\" - Rechazo Confirmado"

msgid "Reject Document"
-msgstr ""
+msgstr "Rechazar Documento"

msgid "Rejection Confirmed"
-msgstr ""
+msgstr "Rechazo Confirmado"

msgid "Rejection reason: {reason}"
-msgstr ""
+msgstr "Motivo del rechazo: {reason}"

msgid "You can view the document and its status by clicking the button below."
-msgstr ""
+msgstr "Puede ver el documento y su estado haciendo clic en el botón de abajo."

msgid "You have rejected the document '{documentName}'"
-msgstr ""
+msgstr "Has rechazado el documento '{documentName}'"

Also applies to: 242-245, 673-680, 1219-1230, 1739-1742, 1776-1779

#: apps/web/src/app/(teams)/t/[teamUrl]/settings/preferences/document-preferences.tsx:209
msgid "\"{placeholderEmail}\" on behalf of \"{0}\" has invited you to sign \"example document\"."
msgstr "\"{placeholderEmail}\" au nom de \"{0}\" vous a invité à signer \"exemple de document\"."
msgstr ""

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.

⚠️ Potential issue

Missing translation for placeholder email template

The translation for the placeholder email template message is missing:

msgid "\"{placeholderEmail}\" on behalf of \"{0}\" has invited you to sign \"example document\"."
-msgstr ""
+msgstr "\"{placeholderEmail}\" au nom de \"{0}\" vous a invité à signer \"example document\"."
📝 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
msgstr ""
msgstr "\"{placeholderEmail}\" au nom de \"{0}\" vous a invité à signer \"example document\"."

@dguyen

dguyen commented Nov 14, 2024

Copy link
Copy Markdown
Collaborator

Pls remove po/js translation files

This branch had an error being deployed

1 failed and 3 active deployments
Preview – stg-marketing — 3875c494 Deployed Nov 14, 2024 by vercel[bot]
Preview – prd-openpage-api — 3875c494 Deployed Nov 14, 2024 by vercel[bot]
Preview – stg-docs — 3875c494 Deployed Nov 14, 2024 by vercel[bot]
Preview – stg-app — 3875c494 Deployed Nov 14, 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 🚨 migrations 🚨 Be advised: PR contains database migrations - Auto-Generated by GitHub Actions on raising a PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants