Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
200 changes: 100 additions & 100 deletions apps/app/src/actions/policies/update-policy-action.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,111 +7,111 @@ import { authActionClient } from "../safe-action";
import { updatePolicySchema } from "../schema";

interface ContentNode {
type: string;
content?: ContentNode[];
text?: string;
attrs?: Record<string, any>;
marks?: Array<{ type: string; attrs?: Record<string, any> }>;
[key: string]: any;
type: string;
content?: ContentNode[];
text?: string;
attrs?: Record<string, any>;
marks?: Array<{ type: string; attrs?: Record<string, any> }>;
[key: string]: any;
}

// Simplified content processor that creates a new plain object
function processContent(
content: ContentNode | ContentNode[]
content: ContentNode | ContentNode[],
): ContentNode | ContentNode[] {
if (!content) return content;

// Handle arrays
if (Array.isArray(content)) {
return content.map((node) => processContent(node) as ContentNode);
}

// Create a new plain object with only the necessary properties
const processed: ContentNode = {
type: content.type,
};

if (content.text !== undefined) {
processed.text = content.text;
}

if (content.attrs) {
processed.attrs = { ...content.attrs };
}

if (content.marks) {
processed.marks = content.marks.map((mark) => ({
type: mark.type,
...(mark.attrs && { attrs: { ...mark.attrs } }),
}));
}

if (content.content) {
processed.content = processContent(content.content) as ContentNode[];
}

return processed;
if (!content) return content;

// Handle arrays
if (Array.isArray(content)) {
return content.map((node) => processContent(node) as ContentNode);
}

// Create a new plain object with only the necessary properties
const processed: ContentNode = {
type: content.type,
};

if (content.text !== undefined) {
processed.text = content.text;
}

if (content.attrs) {
processed.attrs = { ...content.attrs };
}

if (content.marks) {
processed.marks = content.marks.map((mark) => ({
type: mark.type,
...(mark.attrs && { attrs: { ...mark.attrs } }),
}));
}

if (content.content) {
processed.content = processContent(content.content) as ContentNode[];
}

return processed;
}

export const updatePolicyAction = authActionClient
.schema(updatePolicySchema)
.metadata({
name: "update-policy",
track: {
event: "update-policy",
channel: "server",
},
})
.action(async ({ parsedInput, ctx }) => {
const { id, content } = parsedInput;
const { user } = ctx;

if (!user) {
return {
success: false,
error: "Not authorized",
};
}

try {
const policy = await db.organizationPolicy.findUnique({
where: { id, organizationId: user.organizationId },
});

if (!policy) {
return {
success: false,
error: "Policy not found",
};
}

// Create a new plain object from the content
const processedContent = JSON.parse(
JSON.stringify(processContent(content as ContentNode))
);

await db.organizationPolicy.update({
where: { id },
data: { content: processedContent.content },
});

revalidatePath(`/${user.organizationId}/policies/${id}`);
revalidatePath(`/${user.organizationId}/policies`);
revalidateTag(`user_${user.id}`);

return {
success: true,
};
} catch (error) {
logger.error("Error updating policy:", {
error,
errorMessage: error instanceof Error ? error.message : "Unknown error",
errorStack: error instanceof Error ? error.stack : undefined,
});
return {
success: false,
error:
error instanceof Error ? error.message : "Failed to update policy",
};
}
});
.schema(updatePolicySchema)
.metadata({
name: "update-policy",
track: {
event: "update-policy",
channel: "server",
},
})
.action(async ({ parsedInput, ctx }) => {
const { id, content } = parsedInput;
const { user } = ctx;

if (!user) {
return {
success: false,
error: "Not authorized",
};
}

try {
const policy = await db.organizationPolicy.findUnique({
where: { id, organizationId: user.organizationId },
});

if (!policy) {
return {
success: false,
error: "Policy not found",
};
}

// Create a new plain object from the content
const processedContent = JSON.parse(
JSON.stringify(processContent(content as ContentNode)),
);

await db.organizationPolicy.update({
where: { id },
data: { content: processedContent.content },
});

revalidatePath(`/${user.organizationId}/policies/${id}`);
revalidatePath(`/${user.organizationId}/policies`);
revalidateTag(`user_${user.id}`);

return {
success: true,
};
} catch (error) {
logger.error("Error updating policy:", {
error,
errorMessage: error instanceof Error ? error.message : "Unknown error",
errorStack: error instanceof Error ? error.stack : undefined,
});
return {
success: false,
error:
error instanceof Error ? error.message : "Failed to update policy",
};
}
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
"use client";

import * as React from "react";

import {
Card,
CardContent,
CardHeader,
CardFooter,
CardTitle,
} from "@bubba/ui/card";
import { ChartContainer, ChartTooltip, ChartTooltipContent, type ChartConfig } from "@bubba/ui/chart";
import { useI18n } from "@/locales/client";
import { Bar, BarChart, XAxis, YAxis, Legend, ResponsiveContainer } from "recharts"

interface AssigneeData {
id: string;
name: string;
total: number;
published: number;
draft: number;
archived: number;
needs_review: number;
}

interface EvidenceAssigneeChartProps {
data?: AssigneeData[] | null;
}

const CHART_COLORS = {
published: "hsl(var(--chart-positive))", // green
draft: "hsl(var(--chart-neutral))", // yellow
archived: "hsl(var(--chart-warning))", // gray
needs_review: "hsl(var(--chart-destructive))", // red
};

export function EvidenceAssigneeChart({ data }: EvidenceAssigneeChartProps) {
const t = useI18n();

if (!data || data.length === 0) {
return (
<Card className="flex flex-col">
<CardHeader>
<CardTitle>
{t("evidence.dashboard.by_assignee") ||
"Evidence by Assignee"}
</CardTitle>
</CardHeader>
<CardContent className="flex-1 flex items-center justify-center">
<p className="text-center text-sm text-muted-foreground">
No evidence assigned to users
</p>
</CardContent>
<CardFooter>
<div className="flex flex-wrap gap-4 py-2" />
</CardFooter>
</Card>
);
}

// Sort assignees by total policies (descending)
const sortedData = React.useMemo(() => {
return [...data].sort((a, b) => b.total - a.total).slice(0, 4).reverse();
}, [data]);

const chartData = sortedData.map((item) => ({
name: item.name,
published: item.published,
draft: item.draft,
archived: item.archived,
needs_review: item.needs_review,
}));
Comment on lines +66 to +72

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue

Validate property naming for "archived" vs "isNotRelevant".

The chart references archived but the database property is isNotRelevant. Ensure these concepts align correctly, or rename the property to maintain consistency across files.


🛠️ Refactor suggestion

Mismatch in naming "needs_review" vs "needsReview".

Your chart data references needs_review, but the backend logic increments needsReview. This discrepancy can cause zero-increment issues. Rename the properties to match one another for correct tallying.

- needs_review: item.needs_review,
+ needs_review: item.needsReview,
📝 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 chartData = sortedData.map((item) => ({
name: item.name,
published: item.published,
draft: item.draft,
archived: item.archived,
needs_review: item.needs_review,
}));
const chartData = sortedData.map((item) => ({
name: item.name,
published: item.published,
draft: item.draft,
archived: item.archived,
needs_review: item.needsReview,
}));


const chartConfig = {
published: {
label: t("evidence.status.published"),
color: CHART_COLORS.published,
},
draft: {
label: t("evidence.status.draft"),
color: CHART_COLORS.draft,
},
archived: {
label: t("evidence.status.isNotRelevant"),
color: CHART_COLORS.archived,
},
needs_review: {
label: t("evidence.status.needs_review"),
color: CHART_COLORS.needs_review,
},
} satisfies ChartConfig;

return (
<Card className="flex flex-col">
<CardHeader>
<CardTitle>
{t("evidence.dashboard.by_assignee") ||
"Evidence by Assignee"}
</CardTitle>
</CardHeader>
<CardContent className="flex-1">
<ChartContainer config={chartConfig}>
<ResponsiveContainer width="100%" height={250}>
<BarChart
accessibilityLayer
data={chartData}
layout="vertical"
barSize={30}
barGap={8}
margin={{
top: 0,
right: 0,
bottom: 0,
left: 0
}}
>
<XAxis type="number" hide />
<YAxis
dataKey="name"
type="category"
tickLine={false}
tickMargin={10}
axisLine={false}
tickFormatter={(value) => value.split(' ')[0]}
/>
<ChartTooltip
cursor={false}
content={<ChartTooltipContent />}
/>
<Bar dataKey="published" stackId="a" fill={CHART_COLORS.published} />
<Bar dataKey="draft" stackId="a" fill={CHART_COLORS.draft} />
<Bar dataKey="archived" stackId="a" fill={CHART_COLORS.archived} />
<Bar dataKey="needs_review" stackId="a" fill={CHART_COLORS.needs_review} />
</BarChart>
</ResponsiveContainer>
</ChartContainer>
</CardContent>
<CardFooter>
<div className="flex flex-wrap gap-4 py-2">
{Object.entries(chartConfig).map(([key, config]) => (
<div key={key} className="flex items-center gap-2">
<div
className="h-3 w-3"
style={{ backgroundColor: config.color }}
/>
<span className="text-xs">{config.label}</span>
</div>
))}
</div>
</CardFooter>
</Card>
);
}
Loading