Skip to content

Commit

Permalink
chore: handle the feedback changes
Browse files Browse the repository at this point in the history
  • Loading branch information
rajesh-jonnalagadda committed Oct 7, 2024
1 parent a236b95 commit d90e52d
Show file tree
Hide file tree
Showing 4 changed files with 101 additions and 35 deletions.
49 changes: 40 additions & 9 deletions keep-ui/app/alerts/quality/alert-quality-table.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,8 @@ import { useSearchParams } from "next/navigation";
import { AlertKnownKeys } from "../models";

const tabs = [
{ name: "All", value: "alltime" },
{ name: "Installed", value: "last_30d" },
{ name: "Linked", value: "last_7d" },
{ name: "All", value: "all" },
{ name: "Installed", value: "installed" },
];

const ALERT_QUALITY_FILTERS = [
Expand Down Expand Up @@ -65,7 +64,8 @@ interface AlertMetricQuality {
[key: string]: number;
}

type FinalAlertQuality = (Provider & AlertMetricQuality)[];
type FinalAlertQuality = (Provider &
AlertMetricQuality & { provider_display_name: string })[];
interface Pagination {
limit: number;
offset: number;
Expand Down Expand Up @@ -143,7 +143,7 @@ const QualityTable = ({
const baseColumns = [
{
header: "Provider Name",
accessorKey: "display_name",
accessorKey: "provider_display_name",
},
{
header: "Alerts Received",
Expand Down Expand Up @@ -185,9 +185,6 @@ const QualityTable = ({
case 1:
providers = providersMeta?.installed_providers || providers;
break;
case 2:
providers = providersMeta?.linked_providers || providers;
break;
default:
providers = providersMeta?.providers || providers;
break;
Expand All @@ -197,9 +194,41 @@ const QualityTable = ({
return null;
}

const groupedMetrics: { [key: string]: any } = {};

if (tab === 0) {
// Iterate over each provider in the alertsMetrics object
for (const provider in alertsQualityMetrics) {
const metrics = alertsQualityMetrics[provider];
const providerType = metrics.provider_type;

// If the provider_type doesn't exist in the result, initialize it
if (!groupedMetrics[providerType]) {
groupedMetrics[providerType] = {
total_alerts: 0,
correlated_alerts: 0,
};
}

// Aggregate the values for total_alerts, correlated_alerts, etc.
groupedMetrics[providerType].total_alerts += metrics.total_alerts;
groupedMetrics[providerType].correlated_alerts +=
metrics.correlated_alerts;

fields.forEach((field) => {
const key = `${field}_count`;
groupedMetrics[providerType][key] =
groupedMetrics[providerType][key] || 0;
groupedMetrics[providerType][key] += metrics[key];
});
}
}

const innerData: FinalAlertQuality = providers.map((provider) => {
const providerId = provider.id;
const providerType = provider.type;
const alertQuality = alertsQualityMetrics[providerType];
const key =`${providerId}_${providerType}`;
const alertQuality = tab ===0 ? groupedMetrics[providerType] : alertsQualityMetrics[key];
const totalAlertsReceived = alertQuality?.total_alerts ?? 0;
const correlated_alerts = alertQuality?.correlated_alerts ?? 0;
const correltedPert =
Expand Down Expand Up @@ -229,6 +258,8 @@ const QualityTable = ({
alertsCorrelatedToIncidentsPercentage: correltedPert,
alertsWithSeverityPercentage: severityPert,
...dynamicFieldPercentages, // Add dynamic field percentages here
provider_display_name:
provider?.details?.name ? `${provider.details.name} (${provider.display_name})` : provider.display_name || "",
} as FinalAlertQuality[number];
});

Expand Down
56 changes: 46 additions & 10 deletions keep-ui/app/dashboard/GridItem.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import { Card } from "@tremor/react";
import MenuButton from "./MenuButton";
import { WidgetData } from "./types";
import AlertQuality from "app/alerts/quality/alert-quality-table";
import { useSearchParams } from "next/navigation";
import { format, parseISO } from "date-fns";

interface GridItemProps {
item: WidgetData;
Expand All @@ -11,6 +13,14 @@ interface GridItemProps {
}

const GridItem: React.FC<GridItemProps> = ({ item, onEdit, onDelete }) => {
const searchParams = useSearchParams();
let timeStampParams = searchParams?.get("time_stamp") ?? "{}";
let timeStamp: { start?: string; end?: string } = {};
try {
timeStamp = JSON.parse(timeStampParams as string);
} catch (e) {
timeStamp = {};
}
const getColor = () => {
let color = "#000000";
for (let i = item.thresholds.length - 1; i >= 0; i--) {
Expand All @@ -25,35 +35,61 @@ const GridItem: React.FC<GridItemProps> = ({ item, onEdit, onDelete }) => {
function getGenericMterics(item: WidgetData) {
switch (item.genericMetrics) {
case "alert_quality":
return <AlertQuality isDashBoard={true}/>;
return <AlertQuality isDashBoard={true} />;

default:
return null;
}
}

const getDateRange = () => {
if (item.preset) {
return "";
}

if (timeStamp &&timeStamp.start && timeStamp.end) {
const startDateUTC = parseISO(timeStamp.start);
const endDateUTC = parseISO(timeStamp.end);
return ` (${format(startDateUTC, "MM/dd/yyyy")} - ${format(
endDateUTC,
"MM/dd/yyyy"
)})`;
}

return "";
};

return (
<Card className="relative w-full h-full p-4">
<div className="flex flex-col h-full">
<div className={`flex-none flex items-center justify-between p-2 ${item.preset ? 'h-1/5':'h-[10%]'}`}>
<div
className={`flex-none flex items-center justify-between p-2 ${
item.preset ? "h-1/5" : "h-[10%]"
}`}
>
{/* For table view we need intract with table filter and pagination.so we aare dragging the widget here */}
<span className={`text-lg font-semibold truncate ${item.preset ? "" : "grid-item__widget"}`}>{item.name}</span>
<span
className={`text-lg font-semibold truncate ${
item.preset ? "" : "grid-item__widget"
}`}
>
{item.name}
{getDateRange()}
</span>
<MenuButton
onEdit={() => onEdit(item.i)}
onDelete={() => onDelete(item.i)}
/>
</div>
{item.preset && (
//We can remove drag and drop style and make it same as table view. if we want to maintain consistency.
<div className="flex-1 h-4/5 flex items-center justify-center grid-item__widget">
<div className="text-4xl font-bold" style={{ color: getColor() }}>
{item.preset.alerts_count}
//We can remove drag and drop style and make it same as table view. if we want to maintain consistency.
<div className="flex-1 h-4/5 flex items-center justify-center grid-item__widget">
<div className="text-4xl font-bold" style={{ color: getColor() }}>
{item.preset.alerts_count}
</div>
</div>
)}
<div className="w-full h-[90%]">
{getGenericMterics(item)}
</div>
<div className="w-full h-[90%]">{getGenericMterics(item)}</div>
</div>
</Card>
);
Expand Down
1 change: 0 additions & 1 deletion keep-ui/app/dashboard/WidgetModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,6 @@ const WidgetModal: React.FC<WidgetModalProps> = ({ isOpen, onClose, onAddWidget,
{[
{ key: 'preset', value: 'Preset' },
{ key: 'generic_metrics', value: 'Generic Metrics' },
{ key: 'custom_metrics', value: 'Custom Metrics' }
].map(({ key, value }) => (
<SelectItem key={key} value={key}>
{value}
Expand Down
30 changes: 15 additions & 15 deletions keep/api/core/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -3290,12 +3290,6 @@ def get_alerts_metrics_by_provider(
fields: Optional[List[str]] = []
) -> Dict[str, Dict[str, Any]]:

# Set default dates to the last 30 days if not provided
if start_date is None:
start_date = datetime.now() - timedelta(days=7)
if end_date is None:
end_date = datetime.now()

dynamic_field_sums = [
func.sum(
case(
Expand All @@ -3312,31 +3306,37 @@ def get_alerts_metrics_by_provider(
for field in fields
]

#if the below query is not perfomring well, we can try to optimise the query using Venn Diagram or similar(for now we are using the below query)
with Session(engine) as session:
results = (
query = (
session.query(
Alert.provider_type,
Alert.provider_id,
func.count(Alert.id).label("total_alerts"),
func.sum(case([(AlertToIncident.alert_id.isnot(None), 1)], else_=0)).label("correlated_alerts"),
*dynamic_field_sums
)
.outerjoin(AlertToIncident, Alert.id == AlertToIncident.alert_id)
.filter(
Alert.tenant_id == tenant_id,
Alert.timestamp >= start_date,
Alert.timestamp <= end_date,
Alert.provider_type.isnot(None)
)
.group_by(Alert.provider_type)
.all()
)

# Add timestamp filter only if both start_date and end_date are provided
if start_date and end_date:
query = query.filter(
Alert.timestamp >= start_date,
Alert.timestamp <= end_date
)

results = query.group_by(Alert.provider_id, Alert.provider_type).all()

return {
row.provider_type: {
f"{row.provider_id}_{row.provider_type}": {
"total_alerts": row.total_alerts,
"correlated_alerts": row.correlated_alerts,
"provider_type": row.provider_type,
**{f"{field}_count": getattr(row, f"{field}_count") for field in fields} # Add field-specific counts
}
for row in results
}
}

0 comments on commit d90e52d

Please sign in to comment.