Skip to content

Mariano/stuff#45

Merged
Marfuen merged 4 commits into
mainfrom
mariano/stuff
Feb 12, 2025
Merged

Mariano/stuff#45
Marfuen merged 4 commits into
mainfrom
mariano/stuff

Conversation

@Marfuen
Copy link
Copy Markdown
Contributor

@Marfuen Marfuen commented Feb 12, 2025

Summary by CodeRabbit

  • Chores

    • Implemented an automated workflow to streamline database migration processes.
  • New Features

    • Introduced policy publishing directly on the dashboard, complete with an interactive button that provides real-time success notifications.
  • Style

    • Enhanced the dashboard layout by centering key elements to improve overall visual presentation.

@vercel
Copy link
Copy Markdown

vercel Bot commented Feb 12, 2025

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

Name Status Preview Comments Updated (UTC)
app ✅ Ready (Inspect) Visit Preview 💬 Add feedback Feb 12, 2025 7:11pm
web ✅ Ready (Inspect) Visit Preview 💬 Add feedback Feb 12, 2025 7:11pm

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Feb 12, 2025

Walkthrough

The pull request introduces a new GitHub Actions workflow to automate database migrations and Prisma Client generation when specific schema or migration files are modified. Additionally, it adds a new server-side action for publishing organization policies, complete with validation and error handling. On the frontend, new and updated React components integrate the policy publishing functionality, including UI elements like publish buttons and notifications. Minor layout adjustments and cleanup of unused imports have also been applied.

Changes

File(s) Change Summary
.github/workflows/database-migrations.yml New GitHub Actions workflow to automate database migrations and generate Prisma Client; triggered on changes to schema.prisma or files in the migrations directory, using Node.js "20.x".
apps/app/src/app/[locale]/(app)/(dashboard)/policies/[id]/Actions/publish-policy.ts New TypeScript file implementing the publishPolicy action with authentication, input validation (via zod), and error handling; exports PublishPolicyResponse type.
apps/app/src/app/[locale]/(app)/(dashboard)/policies/[id]/Components/PolicyOverview.tsx, apps/app/src/components/policies/policy-overview.tsx Introduction and enhancement of the PolicyOverview React components to fetch policy data, display policy content, and incorporate a publish button integrated with the publishPolicy action and toast notifications.
apps/app/src/app/[locale]/(app)/(dashboard)/policies/[id]/layout.tsx, apps/app/src/app/[locale]/(app)/(dashboard)/policies/[id]/page.tsx Minor adjustments: the layout container is now centered with an added m-auto class, and unused imports (auth and redirect) have been removed from the page component.

Sequence Diagram(s)

sequenceDiagram
    participant Dev as Developer
    participant GH as GitHub Actions
    participant Repo as Repository
    participant DB as Database

    Dev->>GH: Push commit with schema/migration changes
    GH->>Repo: Checkout repository
    GH->>GH: Setup Node.js 20.x and install dependencies
    GH->>DB: Run "npx prisma migrate deploy"
    GH->>Repo: Run "npx prisma generate"
    GH-->>Dev: Complete workflow execution
Loading
sequenceDiagram
    participant User as End User
    participant UI as PolicyOverview Component
    participant Server as publishPolicy Action
    participant DB as Database

    User->>UI: Click "Publish" button
    UI->>Server: Execute publishPolicy({ id })
    Server->>DB: Update policy status and timestamp
    DB-->>Server: Return updated policy
    Server-->>UI: Return success response
    UI->>User: Display success toast notification
Loading

Poem

I'm a happy rabbit, hopping near and far,
Code changes bloom like a shining star.
New workflows and actions lead the way,
Policies published in a brilliant display.
With every commit, my joy takes flight—
Bounding through code in the soft moonlight! 🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

🪧 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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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.

Copy link
Copy Markdown

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

🧹 Nitpick comments (5)
apps/app/src/app/[locale]/(app)/(dashboard)/policies/[id]/Components/PolicyOverview.tsx (1)

12-16: Consider enhancing error handling and type safety.

While the null checks are good, consider these improvements:

  1. Add error state handling for failed policy fetches
  2. Use type guards instead of type assertion for safer type conversion
  3. Add loading state handling

Here's a suggested implementation:

- if (!policy) return null;
- const content = policy.content as JSONContent;
- if (!content) return null;
+ if (!policy) {
+   return <div>Loading policy...</div>;
+ }
+ 
+ function isJSONContent(content: unknown): content is JSONContent {
+   return content !== null && typeof content === 'object';
+ }
+ 
+ if (!policy.content || !isJSONContent(policy.content)) {
+   return <div>Invalid policy content</div>;
+ }
+ 
+ const content = policy.content;
apps/app/src/app/[locale]/(app)/(dashboard)/policies/[id]/Actions/publish-policy.ts (1)

7-15: Add validation for organizationId in the schema.

The schema only validates the id parameter, but the action also requires a valid organizationId. Consider adding validation for organizationId to catch invalid requests earlier.

 const schema = z.object({
   id: z.string(),
+  organizationId: z.string(),
 });
apps/app/src/components/policies/policy-overview.tsx (1)

32-39: Enhance button state handling.

The button should be disabled during execution and could benefit from a loading spinner for better visual feedback.

         <Button
           variant="secondary"
           className="w-fit"
+          disabled={isExecuting}
           onClick={() => execute({ id: policyId })}
         >
-          {isExecuting ? "Publishing..." : "Publish"}
+          {isExecuting ? (
+            <>
+              <span className="animate-spin mr-2">⟳</span>
+              Publishing...
+            </>
+          ) : (
+            "Publish"
+          )}
         </Button>
.github/workflows/database-migrations.yml (2)

3-10: Add pull_request trigger for validation.

Consider adding a pull_request trigger to validate migrations during PR reviews. This helps catch issues before they reach main.

 on:
   push:
     branches:
       - main
     paths:
       - "packages/db/prisma/schema.prisma"
       - "packages/db/prisma/migrations/**"
   workflow_dispatch: # Allows manual triggering
+  pull_request:
+    paths:
+      - "packages/db/prisma/schema.prisma"
+      - "packages/db/prisma/migrations/**"

12-13: Use .nvmrc or package.json engines for Node.js version.

Instead of hardcoding the Node.js version, consider reading it from .nvmrc or package.json engines field for better maintainability.

-env:
-  NODE_VERSION: "20.x"
+env:
+  NODE_VERSION: ${{ steps.nvm.outputs.NVMRC }}

 jobs:
   migrate:
     name: Run Database Migrations
     runs-on: ubuntu-latest

     steps:
+      - name: Read .nvmrc
+        id: nvm
+        run: echo "NVMRC=$(cat .nvmrc)" >> $GITHUB_OUTPUT
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b5e54b9 and 4a6de50.

📒 Files selected for processing (6)
  • .github/workflows/database-migrations.yml (1 hunks)
  • apps/app/src/app/[locale]/(app)/(dashboard)/policies/[id]/Actions/publish-policy.ts (1 hunks)
  • apps/app/src/app/[locale]/(app)/(dashboard)/policies/[id]/Components/PolicyOverview.tsx (1 hunks)
  • apps/app/src/app/[locale]/(app)/(dashboard)/policies/[id]/layout.tsx (1 hunks)
  • apps/app/src/app/[locale]/(app)/(dashboard)/policies/[id]/page.tsx (0 hunks)
  • apps/app/src/components/policies/policy-overview.tsx (2 hunks)
💤 Files with no reviewable changes (1)
  • apps/app/src/app/[locale]/(app)/(dashboard)/policies/[id]/page.tsx
✅ Files skipped from review due to trivial changes (1)
  • apps/app/src/app/[locale]/(app)/(dashboard)/policies/[id]/layout.tsx
🔇 Additional comments (4)
apps/app/src/app/[locale]/(app)/(dashboard)/policies/[id]/Components/PolicyOverview.tsx (3)

1-8: LGTM! Imports are well-organized.

All necessary dependencies are properly imported, and the client directive is correctly placed.


9-10: LGTM! Component structure follows best practices.

The component is well-structured with proper TypeScript typing for the props.


18-29: ⚠️ Potential issue

Implement the missing publishing functionality.

The AI summary mentions publishing functionality using useAction and toast notifications, but these features are not implemented in the code. The Publish button is currently non-functional.

Add the missing functionality:

+ import { useAction } from "next-safe-action/hooks";
+ import { publishPolicy } from "@/app/[locale]/(app)/(dashboard)/policies/[id]/Actions/publish-policy";
+ import { toast } from "sonner";

 export function PolicyOverview({ policyId }: { policyId: string }) {
   const { data: policy } = usePolicy({ policyId });
+  const { execute, isExecuting } = useAction(publishPolicy, {
+    onSuccess: () => {
+      toast.success("Policy published successfully");
+    },
+  });

   // ... existing code ...

   <Button 
     variant="secondary" 
     className="w-fit"
+    onClick={() => execute({ id: policyId })}
+    disabled={isExecuting}
   >
-    Publish
+    {isExecuting ? "Publishing..." : "Publish"}
   </Button>

Likely an incorrect or invalid review comment.

apps/app/src/app/[locale]/(app)/(dashboard)/policies/[id]/Actions/publish-policy.ts (1)

17-25: LGTM! Good tracking setup.

The action metadata is well-structured with appropriate tracking information.

Comment on lines +37 to +58
try {
const policy = await db.organizationPolicy.update({
where: {
id,
organizationId: user.organizationId!,
},
data: {
status: "published",
updatedAt: new Date(),
},
});

return {
success: true,
data: policy,
};
} catch (error) {
return {
success: false,
error: "Failed to publish policy",
};
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve error handling and add policy existence check.

The current implementation has two areas for improvement:

  1. No validation that the policy exists before attempting to update
  2. Generic error message that doesn't help with debugging
     try {
+      const existingPolicy = await db.organizationPolicy.findUnique({
+        where: {
+          id,
+          organizationId: user.organizationId!,
+        },
+      });
+
+      if (!existingPolicy) {
+        return {
+          success: false,
+          error: "Policy not found",
+        };
+      }
+
       const policy = await db.organizationPolicy.update({
         where: {
           id,
           organizationId: user.organizationId!,
         },
         data: {
           status: "published",
           updatedAt: new Date(),
         },
       });

       return {
         success: true,
         data: policy,
       };
     } catch (error) {
+      console.error('Failed to publish policy:', error);
       return {
         success: false,
-        error: "Failed to publish policy",
+        error: `Failed to publish policy: ${error instanceof Error ? error.message : 'Unknown error'}`,
       };
     }
📝 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
try {
const policy = await db.organizationPolicy.update({
where: {
id,
organizationId: user.organizationId!,
},
data: {
status: "published",
updatedAt: new Date(),
},
});
return {
success: true,
data: policy,
};
} catch (error) {
return {
success: false,
error: "Failed to publish policy",
};
}
try {
const existingPolicy = await db.organizationPolicy.findUnique({
where: {
id,
organizationId: user.organizationId!,
},
});
if (!existingPolicy) {
return {
success: false,
error: "Policy not found",
};
}
const policy = await db.organizationPolicy.update({
where: {
id,
organizationId: user.organizationId!,
},
data: {
status: "published",
updatedAt: new Date(),
},
});
return {
success: true,
data: policy,
};
} catch (error) {
console.error('Failed to publish policy:', error);
return {
success: false,
error: `Failed to publish policy: ${error instanceof Error ? error.message : 'Unknown error'}`,
};
}

Comment on lines +30 to +35
if (!user.organizationId) {
return {
success: false,
error: "Not authorized - no organization found",
};
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add permission check for policy publishing.

The current authorization only checks if the user has an organization. Consider adding a permission check to verify if the user has the right to publish policies.

   if (!user.organizationId) {
     return {
       success: false,
       error: "Not authorized - no organization found",
     };
   }
+
+  if (!user.permissions?.includes('PUBLISH_POLICY')) {
+    return {
+      success: false,
+      error: "Not authorized - insufficient permissions",
+    };
+  }
📝 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
if (!user.organizationId) {
return {
success: false,
error: "Not authorized - no organization found",
};
}
if (!user.organizationId) {
return {
success: false,
error: "Not authorized - no organization found",
};
}
if (!user.permissions?.includes('PUBLISH_POLICY')) {
return {
success: false,
error: "Not authorized - insufficient permissions",
};
}

Comment on lines +14 to +21
const { execute, isExecuting } = useAction(
() => publishPolicy({ id: policyId }),
{
onSuccess: () => {
toast.success("Policy published successfully");
},
}
);
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add error handling and loading feedback.

The current implementation only shows success feedback. Consider adding error handling and loading state feedback for better user experience.

   const { execute, isExecuting } = useAction(
     () => publishPolicy({ id: policyId }),
     {
       onSuccess: () => {
         toast.success("Policy published successfully");
       },
+      onError: (error) => {
+        toast.error(error.message || "Failed to publish policy");
+      },
+      onExecute: () => {
+        toast.loading("Publishing policy...");
+      },
     }
   );
📝 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 { execute, isExecuting } = useAction(
() => publishPolicy({ id: policyId }),
{
onSuccess: () => {
toast.success("Policy published successfully");
},
}
);
const { execute, isExecuting } = useAction(
() => publishPolicy({ id: policyId }),
{
onSuccess: () => {
toast.success("Policy published successfully");
},
onError: (error) => {
toast.error(error.message || "Failed to publish policy");
},
onExecute: () => {
toast.loading("Publishing policy...");
},
}
);

Comment on lines +33 to +43
- name: Apply database migrations
env:
DATABASE_URL: ${{ secrets.DATABASE_URL_PROD }}
run: |
cd packages/db
npx prisma migrate deploy

- name: Generate Prisma Client
run: |
cd packages/db
npx prisma generate
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add safety measures for database migrations.

Consider adding these safety measures:

  1. Verify migrations can be applied using prisma migrate reset in a test environment
  2. Create a database backup before applying migrations
  3. Add a rollback plan in case of failures
       - name: Apply database migrations
         env:
           DATABASE_URL: ${{ secrets.DATABASE_URL_PROD }}
         run: |
           cd packages/db
+          # Create backup
+          npx prisma db pull --schema backup_$(date +%Y%m%d_%H%M%S).prisma
+
+          # Verify migrations
+          npx prisma migrate reset --force --skip-seed --preview-feature
+
+          # Apply migrations
           npx prisma migrate deploy
+
+          # Verify database state
+          npx prisma db pull --schema after_migration.prisma
+          if ! diff backup_*.prisma after_migration.prisma > migration_changes.diff; then
+            echo "Migration changes:"
+            cat migration_changes.diff
+          fi
📝 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
- name: Apply database migrations
env:
DATABASE_URL: ${{ secrets.DATABASE_URL_PROD }}
run: |
cd packages/db
npx prisma migrate deploy
- name: Generate Prisma Client
run: |
cd packages/db
npx prisma generate
- name: Apply database migrations
env:
DATABASE_URL: ${{ secrets.DATABASE_URL_PROD }}
run: |
cd packages/db
# Create backup
npx prisma db pull --schema backup_$(date +%Y%m%d_%H%M%S).prisma
# Verify migrations
npx prisma migrate reset --force --skip-seed --preview-feature
# Apply migrations
npx prisma migrate deploy
# Verify database state
npx prisma db pull --schema after_migration.prisma
if ! diff backup_*.prisma after_migration.prisma > migration_changes.diff; then
echo "Migration changes:"
cat migration_changes.diff
fi
- name: Generate Prisma Client
run: |
cd packages/db
npx prisma generate

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.

1 participant