Skip to content

fix variables conversion#810

Merged
N2D4 merged 1 commit intodevfrom
templates-migration-variables-fix
Jul 28, 2025
Merged

fix variables conversion#810
N2D4 merged 1 commit intodevfrom
templates-migration-variables-fix

Conversation

@BilalG1
Copy link
Contributor

@BilalG1 BilalG1 commented Jul 28, 2025


Important

Fix variable conversion in email templates by centralizing logic and updating function signatures and schemas.

  • Variable Conversion:
    • Introduce transformVariableName() to convert userDisplayName to user.displayName and projectDisplayName to project.displayName in convert.tsx.
    • Update convertHandlebarsToJSX() to use transformVariableName() for variable conversion.
  • Function Signatures:
    • Change generateTsxSourceFromConfiguration() to accept EmailTemplateMetadata["variables"] instead of string[].
    • Update EmailTemplate() to use Props<typeof variablesSchema.infer> for parameters.
  • Schema and Preview:
    • Rename schema to variablesSchema and update its structure.
    • Add EmailTemplate.PreviewVariables to provide example values for variables.

This description was created by Ellipsis for b0334a0. You can customize this summary. It will automatically update as commits are pushed.

Summary by CodeRabbit

  • New Features

    • Improved handling of variable names in email templates, supporting nested properties for user and project display names.
    • Added a preview feature that provides example values for email template variables.
  • Refactor

    • Updated email template components to use a unified props structure for accessing variables.
    • Enhanced schema generation for email template variables to support richer metadata.

@vercel
Copy link

vercel bot commented Jul 28, 2025

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

Name Status Preview Comments Updated (UTC)
stack-backend ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jul 28, 2025 11:20pm
stack-dashboard ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jul 28, 2025 11:20pm
stack-demo ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jul 28, 2025 11:20pm
stack-docs ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jul 28, 2025 11:20pm

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jul 28, 2025

Walkthrough

The conversion logic for transforming Handlebars variables to JSX was enhanced with a new helper for variable name mapping. The template generation functions and component signatures were updated to use richer variable metadata and a new props structure. A static property for preview variables was added, and related function signatures were modified accordingly.

Changes

Cohort / File(s) Change Summary
Handlebars to JSX Conversion Logic
apps/backend/src/app/api/latest/internal/email-templates/temp/convert.tsx
Enhanced variable transformation logic with a helper for mapping variable names; updated conversion to consistently apply new mapping for both conditional and simple replacements.
Template Generation & API Updates
apps/backend/src/app/api/latest/internal/email-templates/temp/convert.tsx
Changed generateTsxSourceFromConfiguration to use full variable metadata; updated schema generation and component props structure; added static PreviewVariables property; adjusted related function signatures and usages.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~15 minutes

Poem

In the warren where templates hop and play,
Variables now find a smarter way.
With mappings neat and props anew,
Preview carrots for every view!
Hop along, review this patch—
For emails now, there's quite a catch!
🥕✨

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch templates-migration-variables-fix

🪧 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this 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.

@BilalG1 BilalG1 enabled auto-merge (squash) July 28, 2025 23:12
Copy link
Contributor

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

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

Greptile Summary

This PR addresses a variable conversion issue in the email template migration system. The changes transform the email template variable structure from a flat approach (where variables like userDisplayName and projectDisplayName were passed as individual props) to a more organized nested structure.

The key modification is the addition of a transformVariableName function that maps legacy handlebars variable names to the new JSX/TypeScript syntax:

  • userDisplayNameuser.displayName
  • projectDisplayNameproject.displayName
  • Other variables → variables.{varName}

The PR also updates the template generation process to use EmailTemplateMetadata['variables'] type instead of a plain string array, and changes the generated template interface from individual variable props to a structured Props<T> interface with separate user, project, and variables objects. Additionally, it adds a PreviewVariables export with example values for template previews.

This change is part of a broader migration to improve type safety and organization in the email template system, ensuring that existing handlebars templates remain compatible with the new nested variable structure while providing better separation of built-in variables from custom ones.

Confidence score: 4/5

• This PR appears safe to merge as it primarily handles variable name mapping and type structure updates without affecting core functionality
• The confidence score reflects that while the logic looks correct, the change touches template generation which could have subtle effects on email rendering if the variable mapping is incomplete
• The file apps/backend/src/app/api/latest/internal/email-templates/temp/convert.tsx needs more attention to ensure all variable mappings are comprehensive and handle edge cases properly

1 file reviewed, no comments

Edit Code Review Bot Settings | Greptile

@recurseml
Copy link

recurseml bot commented Jul 28, 2025

✨ No issues found! Your code is sparkling clean! ✨

🗒️ View all ignored comments in this repo
  • The constraint 'TokenStoreType extends string' is too restrictive. It should likely be 'TokenStoreType extends string | object' to match the condition check in line 113 where TokenStoreType is checked against {}
  • Return type mismatch - the interface declares useUsers() returning ServerUser[] but the Team interface that this extends declares useUsers() returning TeamUser[]
  • There is a syntax error in the super constructor call due to the ellipsis operator used incorrectly. Objects aren't being merged correctly. This syntax usage can lead to runtime errors when trying to pass the merged object to 'super()'. Verify that the intended alterations to the object occur before or outside of the super() call if needed.
  • Throwing an error when no active span is found is too aggressive. The log function should gracefully fallback to console.log or another logging mechanism when there's no active span, since not all execution contexts will have an active span. This makes the code less resilient and could break functionality in non-traced environments.

📚 Relevant Docs

  • Function sets backendContext with a new configuration but doesn't pass 'defaultProjectKeys'. Since defaultProjectKeys is required in the type definition and cannot be updated (throws error if tried to set), this will cause a type error.
  • The schema is using array syntax for pick() which is incorrect for Yup schemas. The pick() method in Yup expects individual arguments, not an array. Should be changed to: emailConfigSchema.pick('type', 'host', 'port', 'username', 'sender_name', 'sender_email')

📚 Relevant Docs

  • Creating a refresh token with current timestamp as expiration means it expires immediately. Should set a future date for token expiration.
  • The 'tools' object is initialized as an empty object, even though 'tools' is presumably expected to contain tool definitions. This could cause the server capabilities to lack necessary tool configurations, thus potentially impacting functionalities that depend on certain tool setups.

📚 Relevant Docs

  • 'STACK_SECRET_SERVER_KEY' is potentially being included in every request header without checking its existence again here. Although it's checked during initialization, this could lead to security issues as it's exposed in all communications where the header is logged or captured.

📚 Relevant Docs

  • When adding 'use client' directive at the beginning, it doesn't check if file.text already contains the 'use client' directive. This could lead to duplicate 'use client' directives if the file already has one.

📚 Relevant Docs

Need help? Join our Discord for support!
https://discord.gg/qEjHQk64Z9

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
apps/backend/src/app/api/latest/internal/email-templates/temp/convert.tsx (1)

5-7: Consider refactoring for better readability.

The logic is correct, but the chained ternary operators can be hard to read and maintain.

Consider using a switch statement or object lookup for better readability:

-function transformVariableName(variable: string): string {
-  return variable === "userDisplayName" ? "user.displayName" : variable === "projectDisplayName" ? "project.displayName" : `variables.${variable}`;
-}
+function transformVariableName(variable: string): string {
+  switch (variable) {
+    case "userDisplayName":
+      return "user.displayName";
+    case "projectDisplayName":
+      return "project.displayName";
+    default:
+      return `variables.${variable}`;
+  }
+}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8211570 and b0334a0.

📒 Files selected for processing (1)
  • apps/backend/src/app/api/latest/internal/email-templates/temp/convert.tsx (4 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
apps/backend/src/app/api/latest/internal/email-templates/temp/convert.tsx (1)
packages/stack-emails/src/utils.tsx (1)
  • EmailTemplateMetadata (30-36)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (8)
  • GitHub Check: all-good
  • GitHub Check: build (22.x)
  • GitHub Check: docker
  • GitHub Check: build (22.x)
  • GitHub Check: docker
  • GitHub Check: lint_and_build (latest)
  • GitHub Check: setup-tests
  • GitHub Check: Security Check
🔇 Additional comments (8)
apps/backend/src/app/api/latest/internal/email-templates/temp/convert.tsx (8)

34-34: LGTM!

Correct usage of the transformVariableName helper for consistent variable transformation in conditional blocks.


38-38: LGTM!

Correct usage of the transformVariableName helper for consistent variable transformation in simple replacements.


53-53: LGTM!

The function signature change to use EmailTemplateMetadata["variables"] provides access to richer variable metadata needed for the enhanced variable handling and preview generation.


409-409: LGTM!

Adding the Props import is necessary for the new component signature structure.


411-413: LGTM!

The schema generation correctly uses variable names from the metadata and provides a clear, typed structure for the email template variables.


415-415: LGTM!

The component signature change to destructure user, project, and variables from a typed Props object is consistent with the new variable transformation approach and provides better type safety.


423-428: LGTM!

The PreviewVariables static property is a great addition that provides example values for template previewing, enhancing the developer experience. The type annotation ensures it satisfies the schema requirements.


436-436: LGTM!

Correctly passing the full metadata.variables array instead of just names enables the enhanced functionality in generateTsxSourceFromConfiguration.

@N2D4 N2D4 disabled auto-merge July 28, 2025 23:25
@N2D4 N2D4 merged commit 51b1104 into dev Jul 28, 2025
19 of 20 checks passed
@N2D4 N2D4 deleted the templates-migration-variables-fix branch July 28, 2025 23:25
madster456 pushed a commit that referenced this pull request Aug 4, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants