Skip to content

Charts#85

Merged
Marfuen merged 7 commits into
mainfrom
mariano/stuff
Feb 27, 2025
Merged

Charts#85
Marfuen merged 7 commits into
mainfrom
mariano/stuff

Conversation

@Marfuen
Copy link
Copy Markdown
Contributor

@Marfuen Marfuen commented Feb 27, 2025

Summary by CodeRabbit

  • New Features

    • Introduced an interactive Evidence Overview page featuring dynamic bar charts and animated elements for visualizing evidence insights.
    • Added a new navigation menu for streamlined access to the Evidence Overview and Evidence List.
    • Expanded multi-language support with updated and additional evidence-related text.
  • Chores

    • Upgraded key dependencies and introduced a data visualization library for enhanced performance.
    • Improved internal workflows for evidence creation and data fetching, including smoother redirection from legacy routes.

Marfuen and others added 7 commits February 27, 2025 09:44
…tracking and visualization

- Refactor evidence dashboard to include detailed status tracking (empty, draft, needs review, up to date)
- Implement dynamic bar charts for evidence distribution by department, assignee, and framework
- Add scrollable and interactive chart components with status breakdown
- Improve server-side data processing to calculate evidence statuses
- Enhance logging and debugging for evidence dashboard data
- Update types and interfaces to support new status tracking features
- Optimize chart rendering with responsive and informative visualizations
@vercel
Copy link
Copy Markdown

vercel Bot commented Feb 27, 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 27, 2025 7:11pm
2 Skipped Deployments
Name Status Preview Comments Updated (UTC)
comp-portal ⬜️ Skipped (Inspect) Feb 27, 2025 7:11pm
web ⬜️ Skipped (Inspect) Feb 27, 2025 7:11pm

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Feb 27, 2025

Walkthrough

This pull request updates several parts of the application. It bumps the framer-motion dependency version and introduces new D3 dependencies. The changes modify the evidence creation flow by updating the function signature, adding framework-specific parameters, and refining database queries. New React components, pages, and hooks are introduced for an enhanced evidence overview/dashboard. Additionally, the routing has been updated to redirect from the evidence page to the overview, localization files have been extended in multiple languages, and the Prisma schema and SQL migration now include a new framework relationship.

Changes

File(s) Change Summary
apps/app/package.json Updated framer-motion version from ^11.18.2 to ^12.4.7.
package.json Added new dependencies: "@types/d3": "^7.4.3" and "d3": "^7.9.0".
apps/app/src/actions/framework/select-frameworks-action.ts Updated createOrganizationEvidence signature to accept a new frameworkIds parameter; enhanced evidence creation logic with framework and assignee assignments.
apps/app/src/app/[locale]/(app)/(dashboard)/evidence/Components/EvidenceList.tsx Removed several console logging statements.
apps/app/src/app/[locale]/(app)/(dashboard)/evidence/[id]/Components/EvidenceDetails.tsx Replaced direct mutate() call with an asynchronous handleMutate() function in the publish action callback.
apps/app/src/app/[locale]/(app)/(dashboard)/evidence/hooks/useEvidenceTableContext.tsx Added a new mutate method to the context interface and provider.
apps/app/src/app/[locale]/(app)/(dashboard)/evidence/layout.tsx Introduced a new <SecondaryMenu> component with navigation items for evidence overview and list.
apps/app/src/app/[locale]/(app)/(dashboard)/evidence/list/page.tsx
apps/app/src/app/[locale]/(app)/(dashboard)/evidence/page.tsx
Created a new evidence list page using EvidenceTableProvider and updated the evidence page to redirect to the overview.
apps/app/src/app/[locale]/(app)/(dashboard)/evidence/overview/actions/getEvidenceDashboard.ts Added a new server-side action to fetch and process evidence dashboard data, grouping statuses and handling errors.
apps/app/src/app/[locale]/(app)/(dashboard)/evidence/overview/components/*.tsx Added several new components (AnimatedBar, AssigneeBarChart, DepartmentBarChart, EvidenceOverview, FrameworkBarChart, HorizontalBarChart) for visualizing evidence data.
apps/app/src/app/[locale]/(app)/(dashboard)/evidence/overview/hooks/useEvidenceDashboard.ts Introduced a custom hook leveraging SWR to fetch and manage evidence dashboard data.
apps/app/src/app/[locale]/(app)/(dashboard)/evidence/overview/page.tsx Added a new page component EvidenceOverviewPage to render the overview interface.
apps/app/src/components/main-menu.tsx Updated routes and icons to include a new evidence overview route and modified an existing menu entry to point to /evidence/overview.
apps/app/src/locales/{en,es,fr,no,pt}.ts Extended localization files with new keys and entries for evidence: title, list, overview, dashboard, and related labels.
packages/db/prisma/migrations/20250226222817_add_framework_id_to_org_evidence/migration.sql Added a new non-nullable frameworkId column to the OrganizationEvidence table with a foreign key constraint referencing Framework(id).
packages/db/prisma/schema.prisma Updated models: added a relationship from Framework to OrganizationEvidence, introduced new fields in OrganizationControlRequirement, and linked OrganizationEvidence to Framework via frameworkId.

Sequence Diagram(s)

sequenceDiagram
    participant U as User
    participant EP as EvidencePage
    participant EOV as EvidenceOverviewPage
    participant UDH as useEvidenceDashboard
    participant BE as Backend

    U->>EP: Navigate to Evidence Page URL
    EP->>U: Redirect to /evidence/overview
    U->>EOV: Request Evidence Overview page
    EOV->>UDH: Invoke useEvidenceDashboard hook
    UDH->>BE: Call getEvidenceDashboard action
    BE-->>UDH: Return evidence data
    UDH-->>EOV: Provide data and mutate function
    EOV->>U: Render evidence overview with charts
Loading
sequenceDiagram
    participant A as selectFrameworksAction
    participant COE as createOrganizationEvidence
    participant DB as Database
    participant U as User

    A->>COE: Invoke createOrganizationEvidence(user, frameworkIds)
    COE->>DB: Execute query with include clause (controls & framework categories)
    DB-->>COE: Return evidence results
    COE->>U: Create organization evidence record with frameworkId & assigneeId
Loading

Possibly related PRs

Poem

I'm a clever rabbit, hopping through the code,
Where frameworks and evidence share their new mode.
With charts that dance and data that sings,
I nibble on changes and cheer on new things.
In each line of code, a fresh breeze does flow,
For happy coding hops, as our project does grow!
🐇🌟

✨ Finishing Touches
  • 📝 Generate Docstrings

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 generate docstrings to generate docstrings 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.

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: 0

🔭 Outside diff range comments (2)
apps/app/src/app/[locale]/(app)/(dashboard)/evidence/[id]/Components/EvidenceDetails.tsx (1)

78-79: 💡 Verification agent

🧩 Analysis chain

Verify the redirect path for the back button

The back button still redirects to /evidence rather than the new /evidence/overview path that was updated in the main menu.

Consider updating this redirect to ensure users are taken to the correct page when clicking back.


🏁 Script executed:

#!/bin/bash
# Check if there are redirects in place from /evidence to /evidence/overview
rg -A 2 $'redirect.*evidence.*overview' --type ts

Length of output: 210


Action: Update the back button redirect in EvidenceDetails.tsx

Please update the onClick handler in the EvidenceDetails component (apps/app/src/app/[locale]/(app)/(dashboard)/evidence/[id]/Components/EvidenceDetails.tsx, lines 78-79) to match the new routing. The current code uses:

onClick={() => router.push("/evidence")}

However, as confirmed by the redirect defined in apps/app/src/app/[locale]/(app)/(dashboard)/evidence/page.tsx,

redirect("/evidence/overview");

the intended destination is now /evidence/overview. To maintain consistency, update the onClick action to navigate to /evidence/overview.

apps/app/src/app/[locale]/(app)/(dashboard)/evidence/overview/actions/getEvidenceDashboard.ts (1)

1-285: ⚠️ Potential issue

Condition for findMany returning an empty list.
findMany will return an empty array if no records exist, so !evidence here will never trigger. Use if (evidence.length === 0) if you need to check for an empty result set.

- if (!evidence) {
+ if (evidence.length === 0) {
    return {
      success: false,
      error: "Evidence not found",
    };
  }
🧹 Nitpick comments (20)
apps/app/src/app/[locale]/(app)/(dashboard)/evidence/layout.tsx (1)

9-9: Consider addressing or removing the TODO comment

There's a TODO comment about implementing i18n, but you're already using the getI18n() function. Consider removing this comment if i18n implementation is now complete.

apps/app/src/app/[locale]/(app)/(dashboard)/evidence/overview/hooks/useEvidenceDashboard.ts (3)

18-27: Remove console.log statements before production

The debugging console logs should be removed before deploying to production as they could expose internal data structures and impact performance.

-    // Debug: Log the data received from the server action
-    console.log("Evidence Dashboard Data:", result.data?.data);
-
-    // Check if the data contains status information
-    if (result.data?.data?.byAssignee) {
-      const firstAssignee = Object.values(result.data.data.byAssignee)[0];
-      if (firstAssignee && firstAssignee.length > 0) {
-        console.log("First assignee's first item:", firstAssignee[0]);
-      }
-    }
+    // Process and return the data
+    if (result.data?.data?.byAssignee) {
+      const firstAssignee = Object.values(result.data.data.byAssignee)[0];
+    }

46-49: Remove debug logging for production

Another console log that should be removed before deploying to production.

-  // Debug: Log the data in the hook
-  if (data) {
-    console.log("useEvidenceDashboard hook data:", data);
-  }

3-34: Add TypeScript interfaces for the data structure

The hook would benefit from explicit TypeScript interfaces for the dashboard data structure to improve type safety and developer experience.

// Add these interfaces at the top of the file
interface EvidenceDashboardData {
  byDepartment?: Record<string, Evidence[]>;
  byAssignee?: Record<string, Evidence[]>;
  byFramework?: Record<string, Evidence[]>;
  // Add other properties as needed
}

interface Evidence {
  id: string;
  title: string;
  status: string;
  // Add other properties as needed
}

// Then use them in the fetchEvidenceDashboard function
async function fetchEvidenceDashboard(): Promise<EvidenceDashboardData | undefined> {
  // Existing implementation...
}
apps/app/src/components/main-menu.tsx (1)

32-32: Duplicate icon definition for evidence routes

You've added a new route icon for /evidence/overview while keeping the existing /evidence route icon. Since they both use the same icon component, consider consolidating them.

If these routes should both be accessible, this is fine. However, if /evidence should redirect to /evidence/overview, you might only need one icon definition.

apps/app/src/app/[locale]/(app)/(dashboard)/evidence/overview/components/EvidenceOverview.tsx (3)

24-62: Consider using localized strings for UI text.

The component uses hardcoded English strings like "Evidence Dashboard", "By Department", etc., which should be localized using translation keys from your localization files.

-      <h2 className="text-2xl font-semibold">Evidence Dashboard</h2>
+      <h2 className="text-2xl font-semibold">{t("evidence.dashboard")}</h2>

-            <h3 className="text-lg font-medium mb-4">By Department</h3>
+            <h3 className="text-lg font-medium mb-4">{t("common.filters.department")}</h3>

-            <h3 className="text-lg font-medium mb-4">By Assignee</h3>
+            <h3 className="text-lg font-medium mb-4">{t("common.assignee.label")}</h3>

-            <h3 className="text-lg font-medium mb-4">By Framework</h3>
+            <h3 className="text-lg font-medium mb-4">{t("frameworks.title")}</h3>

You would need to import and use the translation function:

import { useTranslations } from "next-intl";

export const EvidenceOverview = () => {
  const t = useTranslations();
  // rest of the code
}

12-14: Consider enhancing the loading state UI.

The current loading indicator is a simple text. Consider using a more user-friendly loading component that matches the design system of your application.

-    return <div>Loading...</div>;
+    return (
+      <div className="flex justify-center items-center h-64">
+        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary"></div>
+      </div>
+    );

16-18: Improve error handling with more user-friendly messages.

The current error display simply shows the error message. Consider providing a more user-friendly error component with an option to retry.

-    return <div>Error: {error.message}</div>;
+    return (
+      <div className="bg-destructive/10 p-4 rounded-md">
+        <h3 className="text-lg font-medium text-destructive mb-2">Error loading dashboard</h3>
+        <p className="text-sm mb-4">{error.message}</p>
+        <button 
+          onClick={() => window.location.reload()} 
+          className="px-4 py-2 bg-primary text-primary-foreground rounded-md text-sm"
+        >
+          Retry
+        </button>
+      </div>
+    );
apps/app/src/app/[locale]/(app)/(dashboard)/evidence/overview/components/HorizontalBarChart.tsx (3)

40-42: Remove debug console logs before production

Console logs should be removed before deploying to production to avoid cluttering the browser console.

-  useEffect(() => {
-    console.log("HorizontalBarChart - data:", data);
-  }, [data]);

68-70: Remove debug console logs before production

Console logs should be removed before deploying to production.

-  useEffect(() => {
-    console.log("HorizontalBarChart - filteredData:", filteredData);
-  }, [filteredData]);

81-81: Remove unused variable

The cornerRadius variable is defined but never used in the component.

-  const cornerRadius = 0; // No rounded corners in the policies-by-assignee chart
apps/app/src/app/[locale]/(app)/(dashboard)/evidence/overview/components/DepartmentBarChart.tsx (3)

75-88: Remove debug console logs before production

These debug logs provide useful information during development but should be removed before deploying to production.

-  useEffect(() => {
-    console.log("DepartmentBarChart - byDepartment:", byDepartment);
-
-    // Check if status is present in the data
-    if (byDepartment) {
-      const firstDepartment = Object.values(byDepartment)[0];
-      if (firstDepartment && firstDepartment.length > 0) {
-        console.log(
-          "First department's first item status:",
-          firstDepartment[0].status
-        );
-      }
-    }
-  }, [byDepartment]);

114-114: Remove debug console log

Remove this debug log before production deployment.

-      console.log(`Status counts for ${department}:`, statusCounts);

136-151: Type safety could be improved for status handling

The component lacks a constraint ensuring that statusCounts object keys match the defined StatusType. Consider adding stronger typing to prevent potential runtime errors.

type StatusType = (typeof STATUS_PRIORITY)[number];

+ // Ensure statusCounts only includes valid StatusType keys
+ type StatusCounts = Record<StatusType, number>;

// Then use StatusCounts instead of the object literal type
apps/app/src/app/[locale]/(app)/(dashboard)/evidence/overview/components/AssigneeBarChart.tsx (3)

1-209: Consider throttling or debouncing scroll checks.
Frequent scroll events may cause performance issues if the checkScrollPosition function is called too often. Implementing a small throttle or debounce mechanism can smooth out performance, especially if the data set grows.

- container.addEventListener("scroll", checkScrollPosition);
+ import { throttle } from "lodash";
+ ...
+ const throttledCheckScrollPosition = throttle(checkScrollPosition, 100);
+ container.addEventListener("scroll", throttledCheckScrollPosition);

1-209: Remove or disable console.log statements in production.
Revealing internal data structures in the console can clutter the logs and potentially leak sensitive information. Consider using a logging library with configurable log levels, or removing logs entirely for production builds.


1-209: Potential improvement for large data sets.
When the number of assigned items grows, storing all chartData in a single array might become unwieldy. You could dynamically load and render only the visible portion (virtualization) to optimize rendering performance and memory usage.

apps/app/src/app/[locale]/(app)/(dashboard)/evidence/overview/components/FrameworkBarChart.tsx (2)

1-176: Use a debounce or throttle for resize events.
Rechecking the scroll position on every resize event could be improved by debouncing. Continuous invocations during window resizing can degrade performance.

- window.addEventListener("resize", checkScrollPosition);
+ import { debounce } from "lodash";
+ ...
+ const debouncedCheckScrollPosition = debounce(checkScrollPosition, 200);
+ window.addEventListener("resize", debouncedCheckScrollPosition);

1-176: Disable debug logs for production.
Similar to the AssigneeBarChart component, the debug logs in this component (console.log) can be noisy in production. Consider removing them or using a controlled logging mechanism.

apps/app/src/app/[locale]/(app)/(dashboard)/evidence/overview/actions/getEvidenceDashboard.ts (1)

1-285: Be cautious with console logs in server actions.
If console.log is left as-is, logs might reveal internal data in production logs. For sensitive or large-scale deployments, consider switching to a dedicated logger or gating logs behind environment checks.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ca74e95 and 0448430.

⛔ Files ignored due to path filters (3)
  • apps/app/languine.lock is excluded by !**/*.lock
  • bun.lockb is excluded by !**/bun.lockb
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (26)
  • apps/app/package.json (1 hunks)
  • apps/app/src/actions/framework/select-frameworks-action.ts (4 hunks)
  • apps/app/src/app/[locale]/(app)/(dashboard)/evidence/Components/EvidenceList.tsx (0 hunks)
  • apps/app/src/app/[locale]/(app)/(dashboard)/evidence/[id]/Components/EvidenceDetails.tsx (2 hunks)
  • apps/app/src/app/[locale]/(app)/(dashboard)/evidence/hooks/useEvidenceTableContext.tsx (3 hunks)
  • apps/app/src/app/[locale]/(app)/(dashboard)/evidence/layout.tsx (1 hunks)
  • apps/app/src/app/[locale]/(app)/(dashboard)/evidence/list/page.tsx (1 hunks)
  • apps/app/src/app/[locale]/(app)/(dashboard)/evidence/overview/actions/getEvidenceDashboard.ts (1 hunks)
  • apps/app/src/app/[locale]/(app)/(dashboard)/evidence/overview/components/AnimatedBar.tsx (1 hunks)
  • apps/app/src/app/[locale]/(app)/(dashboard)/evidence/overview/components/AssigneeBarChart.tsx (1 hunks)
  • apps/app/src/app/[locale]/(app)/(dashboard)/evidence/overview/components/DepartmentBarChart.tsx (1 hunks)
  • apps/app/src/app/[locale]/(app)/(dashboard)/evidence/overview/components/EvidenceOverview.tsx (1 hunks)
  • apps/app/src/app/[locale]/(app)/(dashboard)/evidence/overview/components/FrameworkBarChart.tsx (1 hunks)
  • apps/app/src/app/[locale]/(app)/(dashboard)/evidence/overview/components/HorizontalBarChart.tsx (1 hunks)
  • apps/app/src/app/[locale]/(app)/(dashboard)/evidence/overview/hooks/useEvidenceDashboard.ts (1 hunks)
  • apps/app/src/app/[locale]/(app)/(dashboard)/evidence/overview/page.tsx (1 hunks)
  • apps/app/src/app/[locale]/(app)/(dashboard)/evidence/page.tsx (1 hunks)
  • apps/app/src/components/main-menu.tsx (2 hunks)
  • apps/app/src/locales/en.ts (5 hunks)
  • apps/app/src/locales/es.ts (2 hunks)
  • apps/app/src/locales/fr.ts (2 hunks)
  • apps/app/src/locales/no.ts (2 hunks)
  • apps/app/src/locales/pt.ts (2 hunks)
  • package.json (1 hunks)
  • packages/db/prisma/migrations/20250226222817_add_framework_id_to_org_evidence/migration.sql (1 hunks)
  • packages/db/prisma/schema.prisma (3 hunks)
💤 Files with no reviewable changes (1)
  • apps/app/src/app/[locale]/(app)/(dashboard)/evidence/Components/EvidenceList.tsx
✅ Files skipped from review due to trivial changes (1)
  • apps/app/src/app/[locale]/(app)/(dashboard)/evidence/overview/page.tsx
🔇 Additional comments (43)
apps/app/package.json (1)

44-44: Updated framer-motion to enhance animation features

The upgrade to framer-motion v12.4.7 looks good and will support the new animated visualization components introduced in this PR.

package.json (1)

32-33: Addition of D3 and its type definitions

Good addition of the D3 library and its TypeScript type definitions to support the new chart components. This follows best practices by including both the library and its types.

apps/app/src/app/[locale]/(app)/(dashboard)/evidence/list/page.tsx (1)

1-10: New evidence list page with proper component structure

The new evidence list page is well-structured, using the context provider pattern to manage state for the evidence table. Good separation of concerns between the provider and the list component.

apps/app/src/app/[locale]/(app)/(dashboard)/evidence/layout.tsx (1)

14-22: Added secondary navigation menu for evidence section

Good addition of a secondary menu that improves navigation between evidence overview and list views. The internationalization of menu labels is a nice touch.

apps/app/src/app/[locale]/(app)/(dashboard)/evidence/overview/components/AnimatedBar.tsx (1)

1-26: Well-structured animation component using framer-motion

The AnimatedBar component is implemented well with proper animation configuration. Using staggered delay based on index is a nice touch for creating sequence effects when multiple bars are rendered.

A few notes on the implementation:

  • Horizontal scaling from origin point
  • Configurable stagger delay (0.075s * index)
  • Clean props interface with proper typing

This will work nicely with the bar chart components mentioned in the dependencies.

apps/app/src/locales/fr.ts (2)

725-729: French translations added correctly for evidence features

The French translations for the evidence section have been added properly, maintaining consistency with other language files.


752-754: Additional evidence translations added correctly

These translations complement the ones added to the sub_pages section, providing proper French localization for the dashboard and list views.

apps/app/src/app/[locale]/(app)/(dashboard)/evidence/overview/hooks/useEvidenceDashboard.ts (1)

36-57: SWR configuration looks good

The hook is well implemented with proper SWR configuration. Disabling revalidation on focus and reconnect is appropriate for dashboard data that doesn't need constant refreshing.

apps/app/src/app/[locale]/(app)/(dashboard)/evidence/page.tsx (1)

1-5: Appropriate use of Next.js redirect

The redirect implementation is correct for routing users to the new evidence overview page. This aligns with the new structure where the overview page is likely the main entry point for evidence management.

packages/db/prisma/migrations/20250226222817_add_framework_id_to_org_evidence/migration.sql (3)

1-6: Warning: Migration may fail with existing data

The migration explicitly warns that adding a required column without a default value will fail if the table already contains data.

If this is being deployed to a database with existing OrganizationEvidence records, consider one of the following approaches:

  1. Add a default value for the new column
  2. Make the column nullable initially, then populate it with data before making it required in a subsequent migration
  3. Ensure you have a data migration script that will run before this schema migration

Would you like me to help with modifying this migration to accommodate existing data?


10-11: CASCADE delete behavior may lead to data loss

The foreign key constraint is set to CASCADE on DELETE and UPDATE operations. This means if a Framework is deleted, all associated OrganizationEvidence records will also be deleted.

Confirm this is the intended behavior. If you want to preserve evidence records when a framework is deleted, consider using SET NULL (if column is nullable) or RESTRICT instead.


8-8:

Details

❓ Verification inconclusive

Verify referential integrity plan

The new column is correctly being added to the table, but ensure you have a plan for populating this field for existing records.


🏁 Script executed:

#!/bin/bash
# Check if there are existing records in the OrganizationEvidence table
# that would be affected by this migration
rg -A 2 $'OrganizationEvidence.*\n.*find' --type ts

Length of output: 243


Please verify the data backfill strategy for existing OrganizationEvidence records

  • The migration (in packages/db/prisma/migrations/20250226222817_add_framework_id_to_org_evidence/migration.sql) successfully adds the non-nullable frameworkId column.
  • A script was attempted to check for any logic that may backfill this new column; however, the initial search failed due to regex/multiline issues.
  • Ensure you have a plan (or accompanying code) to populate frameworkId for existing records, and if such logic exists elsewhere, please manually verify its correctness.
apps/app/src/components/main-menu.tsx (1)

179-182: Updated navigation path for evidence menu item

The evidence menu path has been updated from /evidence to /evidence/overview, which aligns with the new route structure and overview dashboard.

Make sure that any direct links to /evidence in the application have been updated to point to the new route or that appropriate redirects are in place.

apps/app/src/locales/es.ts (2)

724-729: Added localization entries for evidence section

New localization entries have been added for the evidence section, including title, list, and overview translations, improving the user experience for Spanish-speaking users.

These additions align with the new navigation structure for evidence management. Ensure that similar changes have been made to all other supported language files to maintain consistency across the application.


752-754: Enhanced evidence section localization

Additional translations have been added for the evidence dashboard and list views, improving the Spanish localization coverage for the new evidence features.

These entries correspond to the new routes and UI components, making the application more accessible to Spanish-speaking users.

apps/app/src/app/[locale]/(app)/(dashboard)/evidence/[id]/Components/EvidenceDetails.tsx (6)

4-17: Import statements reorganized and simplified

The imports have been restructured, removing unnecessary components and organizing related imports together.

The changes improve code clarity by removing unused imports and reorganizing the remaining ones in a more logical way.


25-25: Updated mutate call to use new handler function

The direct mutate() call has been replaced with the handleMutate() function, which provides better encapsulation of the mutation logic.

This change allows for better error handling and makes the code more maintainable. The handler function properly awaits the mutation.


38-40: Added explicit mutate handler function

A new handleMutate function has been extracted to encapsulate the mutation logic, improving code organization and reuse.

This is a good refactoring that allows the same mutation logic to be used in multiple places (currently on publishing evidence and in other UI interactions). The function properly uses async/await for better error handling.


123-124: Using the new mutate handler for ReviewSection

The handleMutate function is properly passed to the ReviewSection component as the onSuccess callback.

This is a consistent application of the new mutation pattern, ensuring all components use the same approach to trigger data refetching.


139-140: Using the new mutate handler for FileSection

The handleMutate function is properly passed to the FileSection component as the onSuccess callback.

The consistent use of the mutation handler across different components demonstrates good code organization and maintainability.


145-146: Using the new mutate handler for UrlSection

The handleMutate function is properly passed to the UrlSection component as the onSuccess callback.

The consistent application of the mutation pattern across all sections maintains code quality and ensures a uniform approach to data updates.

apps/app/src/locales/pt.ts (2)

725-729: Good addition of localization strings for evidence overview.

The new localization entries for the evidence section are well-structured and consistent with the application's internationalization approach.


752-754: LGTM: Dashboard and list translations match the English equivalents.

These translations properly correspond to their English counterparts and maintain consistency across the application's language files.

apps/app/src/app/[locale]/(app)/(dashboard)/evidence/overview/components/EvidenceOverview.tsx (2)

1-8: LGTM: Clean imports and client directive.

The "use client" directive is appropriately placed at the top of the file, and imports are organized well.


9-23: Good handling of loading and error states.

The component properly handles all possible states (loading, error, and no data) before rendering the main content.

apps/app/src/locales/en.ts (3)

194-198: LGTM: Good addition of English localization strings.

The new evidence-related localization entries match well with the Portuguese translations and provide a complete set of strings for the new evidence overview feature.


152-152: Proper syntax correction with trailing commas.

The added commas improve code consistency and prevent potential syntax errors during object manipulation.

Also applies to: 211-211


773-774: LGTM: Dashboard and list translations are consistent.

These translations match the corresponding entries in the Portuguese file and use clear, descriptive labels.

apps/app/src/app/[locale]/(app)/(dashboard)/evidence/hooks/useEvidenceTableContext.tsx (3)

36-36: Good addition of mutate function to the context interface.

The addition of a mutate function to the interface correctly documents the new capability in the type definition.


87-87: LGTM: Proper extraction of mutate from hook.

Correctly extracting the mutate function from the useOrganizationEvidenceTasks hook to make it available in the context.


179-179: LGTM: Exposing mutate in the context value.

The mutate function is properly included in the context value, making it available to consumers of the context.

apps/app/src/locales/no.ts (2)

725-729: Good addition of localized evidence subpages

The new evidence-related translations in Norwegian are well-structured and follow the existing patterns in the localization file.


752-754: Properly extended the evidence section

The modifications to the existing evidence object with added comma and new entries maintain consistent formatting and structure.

apps/app/src/actions/framework/select-frameworks-action.ts (4)

47-47: Updated function call correctly

The function call now includes the frameworkIds parameter, matching the updated function signature.


276-279: Function signature properly updated

The function signature now accepts the additional frameworkIds parameter, aligning with how it's called.


288-298: Good inclusion of related data

The expanded query includes necessary related entities for establishing framework relationships.


308-309: Consider handling potential null/undefined values more robustly

The fallback to an empty string for frameworkId might cause issues if foreign key constraints are enforced.

-      frameworkId: evidence.control.frameworkCategory?.framework.id || "",
+      frameworkId: evidence.control.frameworkCategory?.framework.id || null,

Verify if the column allows NULL values or implement more explicit handling if a valid frameworkId is required.

apps/app/src/app/[locale]/(app)/(dashboard)/evidence/overview/components/HorizontalBarChart.tsx (1)

1-153: Well-implemented chart component with good separation of concerns

The component is well-structured with clear interfaces, sensible defaults, and good handling of edge cases. It properly processes the data, assigns colors, and renders both the chart and legend in a visually organized way.

apps/app/src/app/[locale]/(app)/(dashboard)/evidence/overview/components/DepartmentBarChart.tsx (2)

109-111: Good use of for...of loop

Using a for...of loop is more efficient than forEach for this scenario, good choice.


175-187: Nice scroll indicators for better UX

The scroll indicators provide helpful visual cues to users, enhancing the user experience with the scrollable content.

packages/db/prisma/schema.prisma (2)

774-792:

Details

❓ Verification inconclusive

Verify non-null frameworkId presence.
The new non-null frameworkId field in OrganizationEvidence will require all existing rows to be assigned a corresponding Framework record. Ensure that the corresponding migration either sets a default placeholder Framework or has a strategy to backfill the frameworkId values for existing data. Otherwise, this may break or prevent database inserts for older records without a framework.


🏁 Script executed:

#!/bin/bash
# Searches for all references to OrganizationEvidence creation or updates
rg -A 5 "OrganizationEvidence.create"
rg -A 5 "OrganizationEvidence.update"

Length of output: 75


Action Required: Verify Framework ID Migration Strategy

The non-null frameworkId on OrganizationEvidence mandates that all existing rows tie to a valid Framework record. Please ensure that the migration strategy either assigns a default placeholder Framework or implements a backfill for the frameworkId values. The initial search for references to OrganizationEvidence.create and .update returned no output, which could mean that such updates aren’t explicitly covered, so it’s crucial to manually verify or recheck that all affected code paths and migration files correctly handle this field.

  • Migration Files: Confirm that any new migration (likely under packages/db/prisma/migrations) includes logic for setting or backfilling frameworkId for existing data.
  • Update Paths: Verify that creation/update operations for OrganizationEvidence always provide a valid frameworkId.
  • Test Coverage: Ensure that tests cover scenarios with legacy records to avoid unexpected insert failures.

706-717:

Details

❓ Verification inconclusive

Ensure optional fields and cascading behavior align with usage.
The newly added organizationPolicyId and organizationEvidenceId fields are optional, but make sure that the onDelete: Cascade relationships align with the desired behavior. If these records are sometimes shared or are needed elsewhere, a cascading deletion may cause unintended data loss.

Run this script to confirm if there's any usage of these fields that might be affected by cascading deletions:


🏁 Script executed:

#!/bin/bash
# Searches for references to OrganizationControlRequirement usage that might be impacted by the new optional fields

rg -A 8 "OrganizationControlRequirement"

Length of output: 31791


Verify Cascading Deletion Settings for OrganizationControlRequirement

After reviewing the migration scripts and usage references across the codebase, the newly added optional fields organizationPolicyId and organizationEvidenceId are configured with ON DELETE CASCADE. This means that when a related policy or evidence record is removed, the corresponding entries in the OrganizationControlRequirement table will also be deleted.

Before finalizing, please ensure that this cascading behavior aligns with the intended design—particularly if any of these related records might be shared or referenced elsewhere in the system. Consider the following:

  • Migration Review:

    • Check the migration file 20250218202303_add_organization_policy_to_org_control_req/migration.sql to confirm the cascade settings for organizationPolicyId.
    • Verify the cascade setup in 20250225000803_add_org_ev_relation_to_org_ctrl_req/migration.sql for organizationEvidenceId.
  • Usage Analysis:

    • Confirm that application modules (e.g., queries in controls, evidence actions, and data table components) do not depend on these records being preserved beyond their immediate relationship.
    • If the related policies or evidence might be shared or needed across different parts of the system, re-evaluate whether cascading deletion is appropriate to avoid unintended data loss.

Please verify that this behavior is deliberate and that it won’t inadvertently impact other parts of the application.

apps/app/src/app/[locale]/(app)/(dashboard)/evidence/overview/actions/getEvidenceDashboard.ts (1)

1-285: Ensure frequency-based nextReviewDate logic matches business rules.
The date increment logic looks correct for monthly, quarterly, and yearly. Verify that these intervals align with business expectations. You may want to handle additional edge cases or frequencies (e.g., weekly, semiannual) in the future.

Would you like to expand frequency options or keep them fixed for now?

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