refactor: Improve code readability by formatting and simplifying filter/map functions in various components

This commit is contained in:
Nawaz Dhandala
2026-02-01 13:44:07 +00:00
parent d5f42141a0
commit 674e35dc70
7 changed files with 145 additions and 125 deletions

View File

@@ -1133,7 +1133,10 @@ const BaseAPIFeatureSet: FeatureSet = {
new BaseAPI<
IncidentEpisodeRoleMember,
IncidentEpisodeRoleMemberServiceType
>(IncidentEpisodeRoleMember, IncidentEpisodeRoleMemberService).getRouter(),
>(
IncidentEpisodeRoleMember,
IncidentEpisodeRoleMemberService,
).getRouter(),
);
app.use(

View File

@@ -409,7 +409,6 @@ const MemberRoleAssignment: FunctionComponent<ComponentProps> = (
{members.length === 0 ? "Assign" : "Add More"}
</button>
)}
</div>
{/* Dropdown for adding member */}
@@ -563,8 +562,8 @@ const MemberRoleAssignment: FunctionComponent<ComponentProps> = (
>
<p className="text-gray-500 text-sm mb-4">
Select a new user to reassign the {reassignState.role.name} role
from {reassignState.member.userName || reassignState.member.userEmail}
.
from{" "}
{reassignState.member.userName || reassignState.member.userEmail}.
</p>
<Dropdown
options={props.availableUsers
@@ -584,10 +583,12 @@ const MemberRoleAssignment: FunctionComponent<ComponentProps> = (
onChange={(value: DropdownValue | Array<DropdownValue> | null) => {
if (value && !Array.isArray(value)) {
const option: DropdownOption | undefined = props.availableUsers
.map((user: AvailableUser) => ({
value: user.id.toString(),
label: user.name || user.email,
}))
.map((user: AvailableUser) => {
return {
value: user.id.toString(),
label: user.name || user.email,
};
})
.find((opt: DropdownOption) => {
return opt.value.toString() === value.toString();
});

View File

@@ -135,10 +135,12 @@ const EpisodeMemberRoleAssignmentsFormField: FunctionComponent<
const getSelectedUsersForRole = useCallback(
(roleId: string): string[] => {
return assignments
.filter(
(a: EpisodeMemberRoleAssignment) => a.incidentRoleId === roleId,
)
.map((a: EpisodeMemberRoleAssignment) => a.userId);
.filter((a: EpisodeMemberRoleAssignment) => {
return a.incidentRoleId === roleId;
})
.map((a: EpisodeMemberRoleAssignment) => {
return a.userId;
});
},
[assignments],
);
@@ -148,8 +150,9 @@ const EpisodeMemberRoleAssignmentsFormField: FunctionComponent<
(roleId: string, userId: string): void => {
// Check if assignment already exists
const exists: boolean = assignments.some(
(a: EpisodeMemberRoleAssignment) =>
a.incidentRoleId === roleId && a.userId === userId,
(a: EpisodeMemberRoleAssignment) => {
return a.incidentRoleId === roleId && a.userId === userId;
},
);
if (exists) {
@@ -174,10 +177,9 @@ const EpisodeMemberRoleAssignmentsFormField: FunctionComponent<
const removeUserFromRole = useCallback(
(roleId: string, userId: string): void => {
const newAssignments: Array<EpisodeMemberRoleAssignment> =
assignments.filter(
(a: EpisodeMemberRoleAssignment) =>
!(a.incidentRoleId === roleId && a.userId === userId),
);
assignments.filter((a: EpisodeMemberRoleAssignment) => {
return !(a.incidentRoleId === roleId && a.userId === userId);
});
setAssignments(newAssignments);

View File

@@ -63,104 +63,103 @@ const MyOnCallPolicies: FunctionComponent<
Array<OnCallPolicyWithProject>
>([]);
const fetchOnCallPolicies: PromiseVoidFunction =
async (): Promise<void> => {
try {
setIsLoading(true);
setError("");
const fetchOnCallPolicies: PromiseVoidFunction = async (): Promise<void> => {
try {
setIsLoading(true);
setError("");
const projectsResult: ListResult<Project> =
await ModelAPI.getList<Project>({
modelType: Project,
query: {},
limit: 100,
skip: 0,
select: {
name: true,
_id: true,
},
sort: {
name: SortOrder.Ascending,
},
requestOptions: {
isMultiTenantRequest: true,
overrideRequestUrl: URL.fromString(
APP_API_URL.toString(),
).addRoute("/project/list-user-projects"),
},
});
const projectsResult: ListResult<Project> =
await ModelAPI.getList<Project>({
modelType: Project,
query: {},
limit: 100,
skip: 0,
select: {
name: true,
_id: true,
},
sort: {
name: SortOrder.Ascending,
},
requestOptions: {
isMultiTenantRequest: true,
overrideRequestUrl: URL.fromString(APP_API_URL.toString()).addRoute(
"/project/list-user-projects",
),
},
});
const projects: Array<Project> = projectsResult.data;
const onCallData: Array<OnCallPolicyWithProject> = [];
const projects: Array<Project> = projectsResult.data;
const onCallData: Array<OnCallPolicyWithProject> = [];
for (const project of projects) {
if (!project._id) {
continue;
}
try {
const response: HTTPResponse<JSONObject> | HTTPErrorResponse =
await API.get<JSONObject>({
url: URL.fromString(APP_API_URL.toString()).addRoute(
`/${new OnCallDutyPolicy().crudApiPath}/current-on-duty-escalation-policies`,
),
data: {},
headers: {
...ModelAPI.getCommonHeaders(),
tenantid: project._id.toString(),
},
});
if (response.isSuccess()) {
const result: JSONObject = response.jsonData as JSONObject;
const escalationRulesByUser: Array<OnCallDutyPolicyEscalationRuleUser> =
DatabaseBaseModel.fromJSONArray(
result["escalationRulesByUser"] as Array<JSONObject>,
OnCallDutyPolicyEscalationRuleUser,
) as Array<OnCallDutyPolicyEscalationRuleUser>;
const escalationRulesByTeam: Array<OnCallDutyPolicyEscalationRuleTeam> =
DatabaseBaseModel.fromJSONArray(
result["escalationRulesByTeam"] as Array<JSONObject>,
OnCallDutyPolicyEscalationRuleTeam,
) as Array<OnCallDutyPolicyEscalationRuleTeam>;
const escalationRulesBySchedule: Array<OnCallDutyPolicyEscalationRuleSchedule> =
DatabaseBaseModel.fromJSONArray(
result["escalationRulesBySchedule"] as Array<JSONObject>,
OnCallDutyPolicyEscalationRuleSchedule,
) as Array<OnCallDutyPolicyEscalationRuleSchedule>;
if (
escalationRulesByUser.length > 0 ||
escalationRulesByTeam.length > 0 ||
escalationRulesBySchedule.length > 0
) {
onCallData.push({
project,
escalationRulesByUser,
escalationRulesByTeam,
escalationRulesBySchedule,
});
}
}
} catch {
// Continue with other projects if one fails
}
for (const project of projects) {
if (!project._id) {
continue;
}
setOnCallPoliciesByProject(onCallData);
setIsLoading(false);
} catch (err) {
setError(
err instanceof Error
? err.message
: "An error occurred while fetching on-call policies",
);
setIsLoading(false);
try {
const response: HTTPResponse<JSONObject> | HTTPErrorResponse =
await API.get<JSONObject>({
url: URL.fromString(APP_API_URL.toString()).addRoute(
`/${new OnCallDutyPolicy().crudApiPath}/current-on-duty-escalation-policies`,
),
data: {},
headers: {
...ModelAPI.getCommonHeaders(),
tenantid: project._id.toString(),
},
});
if (response.isSuccess()) {
const result: JSONObject = response.jsonData as JSONObject;
const escalationRulesByUser: Array<OnCallDutyPolicyEscalationRuleUser> =
DatabaseBaseModel.fromJSONArray(
result["escalationRulesByUser"] as Array<JSONObject>,
OnCallDutyPolicyEscalationRuleUser,
) as Array<OnCallDutyPolicyEscalationRuleUser>;
const escalationRulesByTeam: Array<OnCallDutyPolicyEscalationRuleTeam> =
DatabaseBaseModel.fromJSONArray(
result["escalationRulesByTeam"] as Array<JSONObject>,
OnCallDutyPolicyEscalationRuleTeam,
) as Array<OnCallDutyPolicyEscalationRuleTeam>;
const escalationRulesBySchedule: Array<OnCallDutyPolicyEscalationRuleSchedule> =
DatabaseBaseModel.fromJSONArray(
result["escalationRulesBySchedule"] as Array<JSONObject>,
OnCallDutyPolicyEscalationRuleSchedule,
) as Array<OnCallDutyPolicyEscalationRuleSchedule>;
if (
escalationRulesByUser.length > 0 ||
escalationRulesByTeam.length > 0 ||
escalationRulesBySchedule.length > 0
) {
onCallData.push({
project,
escalationRulesByUser,
escalationRulesByTeam,
escalationRulesBySchedule,
});
}
}
} catch {
// Continue with other projects if one fails
}
}
};
setOnCallPoliciesByProject(onCallData);
setIsLoading(false);
} catch (err) {
setError(
err instanceof Error
? err.message
: "An error occurred while fetching on-call policies",
);
setIsLoading(false);
}
};
useEffect(() => {
fetchOnCallPolicies().catch(() => {
@@ -319,7 +318,9 @@ const MyOnCallPolicies: FunctionComponent<
<span className="font-bold">
{onCallPoliciesByProject.length}
</span>{" "}
{onCallPoliciesByProject.length === 1 ? "project" : "projects"}
{onCallPoliciesByProject.length === 1
? "project"
: "projects"}
.
</p>
</div>
@@ -366,7 +367,10 @@ const MyOnCallPolicies: FunctionComponent<
{/* Policy Items */}
<div className="divide-y divide-gray-100">
{policyItems.map(
(item: PolicyItem, itemIndex: number): ReactElement => {
(
item: PolicyItem,
itemIndex: number,
): ReactElement => {
return (
<div
key={itemIndex}
@@ -385,14 +389,17 @@ const MyOnCallPolicies: FunctionComponent<
)}
className="hover:text-indigo-600 hover:underline"
>
{item.policyName || "Unknown Policy"}
{item.policyName ||
"Unknown Policy"}
</Link>
) : (
item.policyName || "Unknown Policy"
)}
</div>
{/* Assignment Type Pill */}
{getAssignmentTypePill(item.assignmentType)}
{getAssignmentTypePill(
item.assignmentType,
)}
</div>
{/* Escalation Rule and Assignment Detail */}
@@ -425,7 +432,9 @@ const MyOnCallPolicies: FunctionComponent<
<div className="flex-shrink-0 ml-4">
<Button
title="View"
buttonStyle={ButtonStyleType.SECONDARY_LINK}
buttonStyle={
ButtonStyleType.SECONDARY_LINK
}
icon={IconProp.ChevronRight}
onClick={() => {
window.location.href = getPolicyLink(

View File

@@ -19,7 +19,6 @@ import FormFieldSchemaType from "Common/UI/Components/Forms/Types/FormFieldSchem
import Card from "Common/UI/Components/Card/Card";
import Monitor from "Common/Models/DatabaseModels/Monitor";
import OnCallDutyPolicy from "Common/Models/DatabaseModels/OnCallDutyPolicy";
import ProjectUser from "../../Utils/ProjectUser";
import ProjectUtil from "Common/UI/Utils/Project";
import Label from "Common/Models/DatabaseModels/Label";
import IncidentSeverity from "Common/Models/DatabaseModels/IncidentSeverity";
@@ -705,10 +704,12 @@ const IncidentCreate: FunctionComponent<
// Get the role IDs that already have assignments
const assignedRoleIds: Set<string> = new Set(
roleAssignmentsRef.current
.filter(
(a: RoleAssignment) => a.userIds.length > 0,
)
.map((a: RoleAssignment) => a.roleId),
.filter((a: RoleAssignment) => {
return a.userIds.length > 0;
})
.map((a: RoleAssignment) => {
return a.roleId;
}),
);
// Assign creator to primary roles that don't have anyone assigned

View File

@@ -469,10 +469,12 @@ const EpisodeCreate: FunctionComponent<
// Get the role IDs that already have assignments
const assignedRoleIds: Set<string> = new Set(
roleAssignmentsRef.current
.filter(
(a: RoleAssignment) => a.userIds.length > 0,
)
.map((a: RoleAssignment) => a.roleId),
.filter((a: RoleAssignment) => {
return a.userIds.length > 0;
})
.map((a: RoleAssignment) => {
return a.roleId;
}),
);
// Assign creator to primary roles that don't have anyone assigned

View File

@@ -685,7 +685,9 @@ const IncidentGroupingRulesPage: FunctionComponent<
(values.episodeMemberRoleAssignments as Array<EpisodeMemberRoleAssignment>) ||
[]
}
onChange={(assignments: Array<EpisodeMemberRoleAssignment>) => {
onChange={(
assignments: Array<EpisodeMemberRoleAssignment>,
) => {
if (props.onChange) {
props.onChange(assignments);
}