Skip to content
Open
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
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { MetricGridRow } from "pages/MetricsPage/components/MetricsGrid/MetricsGrid.types";
import { MetricRequestBody } from "types/Metric/MetricRequestBody";
import yaml from "yaml";
import { MetricFormValues } from "./components/MetricForm/MetricForm.types";

export const convertGauges = (data: string[] | null) => data && data.toString().replace(/,/g, "\n");
Expand All @@ -14,21 +13,23 @@ export const getMetricInitialValues = (data?: MetricGridRow): MetricFormValues =
Gauges: convertGauges(data?.Metric.Gauges ?? [""]),
InitSQL: data?.Metric.InitSQL ?? "",
IsInstanceLevel: data?.Metric.IsInstanceLevel ?? false,
SQLs: yaml.stringify(data?.Metric.SQLs) ?? "",
SQLs: data?.Metric.SQLs
? Object.keys(data.Metric.SQLs).map((version) => ({
Version: Number(version),
SQL: data.Metric.SQLs[Number(version)]
}))
: [],
};
};

export const createMetricRequest = (values: MetricFormValues): MetricRequestBody => {
const sqls: Record<number, string> = {};
yaml.parse(values.SQLs, (key, value) => {
if (key) {
const version = Number(key);
if (Number.isNaN(version)) {
throw new Error("Version is not a valid number");
}
sqls[Number(key)] = String(value);
}
});

if (values.SQLs && values.SQLs.length > 0) {
values.SQLs.forEach(({ Version, SQL }) => {
sqls[Version] = SQL;
});
}

return {
Name: values.Name,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,30 @@ export const metricFormValuesValidationSchema = Yup.object({
Gauges: Yup.string().optional().nullable(),
InitSQL: Yup.string().optional().nullable(),
IsInstanceLevel: Yup.bool().required(),
SQLs: Yup.string().trim().required("SQLs is required"),
SQLs: Yup.array()
.of(
Yup.object().shape({
Version: Yup.number()
.required("Version is required")
.positive("Version must be a positive number")
.integer("Version must be an integer"),
SQL: Yup.string()
.trim()
.required("SQL is required")
})
)
.min(1, "At least one SQL version is required")
.required("SQLs is required")
.test(
"unique-versions",
"Duplicate version numbers are not allowed",
(value) => {
if (!value || value.length === 0) {
return true;
}
const versions = value.map(item => item.Version);
const uniqueVersions = new Set(versions);
return versions.length === uniqueVersions.size;
}
),
});
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,10 @@ type MetricFormSettings = {
};

type MetricFormSQL = {
SQLs: string;
SQLs: {
Version: number;
SQL: string;
}[];
};

export type MetricFormValues = MetricFormGeneral & MetricFormSettings & MetricFormSQL;
Original file line number Diff line number Diff line change
@@ -1,46 +1,167 @@
import { FormControl, FormHelperText, InputLabel, OutlinedInput } from "@mui/material";
import { useFormContext } from "react-hook-form";
import { useEffect } from "react";
import DeleteIcon from "@mui/icons-material/Delete";
import { Alert, Button, FormControl, FormHelperText, IconButton, InputLabel, OutlinedInput, Typography } from "@mui/material";
import { useFieldArray, useFormContext } from "react-hook-form";
import { useFormStyles } from "styles/form";
import { MetricFormValues } from "../MetricForm.types";

export const MetricFormStepSQL = () => {
const { register, formState: { errors } } = useFormContext<MetricFormValues>();
const { control, register, formState: { errors } } = useFormContext<MetricFormValues>();
const { classes, cx } = useFormStyles();

const hasError = (field: keyof MetricFormValues) => !!errors[field];
const { fields, append, remove } = useFieldArray({
control,
name: "SQLs"
});

const getError = (field: keyof MetricFormValues) => {
const error = errors[field];
if (error) {
return error.message;
// Initialize with one empty entry if no SQLs exist
useEffect(() => {
if (fields.length === 0) {
append({ Version: 0, SQL: "" });
}
}, []); // eslint-disable-line react-hooks/exhaustive-deps

const handleAddSQL = () => {
append({ Version: 0, SQL: "" });
};

const handleRemoveSQL = (index: number) => {
if (fields.length > 1) {
remove(index);
}
};

const getFieldError = (index: number, field: "Version" | "SQL") => {
const sqlsErrors = errors.SQLs;
if (Array.isArray(sqlsErrors) && sqlsErrors[index]) {
return sqlsErrors[index]?.[field]?.message;
}
return undefined;
};

const hasFieldError = (index: number, field: "Version" | "SQL") => {
return !!getFieldError(index, field);
};

// Get the general error for the SQLs array (like duplicate versions)
const getGeneralError = () => {
if (errors.SQLs && !Array.isArray(errors.SQLs)) {
return errors.SQLs.message;
}
return undefined;
};

return (
<div className={classes.form}>
<FormControl
className={cx(classes.formControlInput, classes.widthFull)}
error={hasError("SQLs")}
<Typography variant="body2" sx={{ mb: 1, color: "text.secondary" }}>
SQLs
</Typography>

{/* Show duplicate version error prominently */}
{getGeneralError() && (
<Alert severity="error" sx={{ mb: 2 }}>
{getGeneralError()}
</Alert>
)}

{/* Scrollable SQL entries container */}
<div
style={{
maxHeight: "400px",
overflowY: "auto",
overflowX: "hidden",
marginBottom: "16px",
paddingRight: "8px"
}}
>
{fields.map((field, index) => (
<div
key={field.id}
style={{
border: "1px solid #e0e0e0",
borderRadius: "4px",
padding: "12px",
marginBottom: "12px",
backgroundColor: "#fafafa"
}}
>
{/* SQL Entry Header */}
<div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: "12px" }}>
<Typography variant="body2" sx={{ fontWeight: 500, color: "text.secondary" }}>
SQL #{index + 1}
</Typography>
<IconButton
size="small"
onClick={() => handleRemoveSQL(index)}
disabled={fields.length === 1}
sx={{ color: "error.main" }}
title={fields.length === 1 ? "At least one SQL entry is required" : "Remove this SQL entry"}
>
<DeleteIcon fontSize="small" />
</IconButton>
</div>

{/* Version and SQL fields in a row */}
<div style={{ display: "grid", gridTemplateColumns: "120px 1fr", gap: "12px" }}>
{/* Version Input */}
<FormControl
className={cx(classes.formControlInput)}
error={hasFieldError(index, "Version")}
variant="outlined"
size="small"
>
<InputLabel htmlFor={`SQLs.${index}.Version`}>Version</InputLabel>
<OutlinedInput
{...register(`SQLs.${index}.Version`, { valueAsNumber: true })}
id={`SQLs.${index}.Version`}
label="Version"
type="number"
inputProps={{ min: 1, step: 1 }}
/>
{hasFieldError(index, "Version") && (
<FormHelperText>{getFieldError(index, "Version")}</FormHelperText>
)}
</FormControl>

{/* SQL Textarea */}
<FormControl
className={cx(classes.formControlInput)}
error={hasFieldError(index, "SQL")}
variant="outlined"
size="small"
>
<InputLabel htmlFor={`SQLs.${index}.SQL`}>SQL</InputLabel>
<OutlinedInput
{...register(`SQLs.${index}.SQL`)}
id={`SQLs.${index}.SQL`}
label="SQL"
multiline
rows={3}
inputProps={{
style: {
font: "revert",
fontSize: "0.7rem",
}
}}
/>
{hasFieldError(index, "SQL") && (
<FormHelperText>{getFieldError(index, "SQL")}</FormHelperText>
)}
</FormControl>
</div>
</div>
))}
</div>

{/* Add New SQL Button */}
<Button
variant="outlined"
onClick={handleAddSQL}
fullWidth
sx={{ mb: 1 }}
>
<InputLabel htmlFor="SQLs">SQLs</InputLabel>
<OutlinedInput
{...register("SQLs")}
id="SQLs"
label="SQLs"
aria-describedby="SQLs-error"
multiline
rows={15}
inputProps={{
style: {
font: "revert",
fontSize: "0.7rem",
}
}}
/>
<FormHelperText id="SQLs-error">{getError("SQLs")}</FormHelperText>
</FormControl>
+ Add New SQL
</Button>
</div>
);
};
Loading
Loading