Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixing system history bugs #4146

Merged
merged 4 commits into from
Sep 26, 2023
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ The types of changes are:
- CORS configuration page [#4073](https://github.com/ethyca/fides/pull/4073)
- Refactored `fides.js` components so that they can take data structures that are not necessarily privacy notices [#3870](https://github.com/ethyca/fides/pull/3870)
- Moved the initial TCF layer to the banner [#4142](https://github.com/ethyca/fides/pull/4142)
- Misc copy changes for the system history table and modal [#4146](https://github.com/ethyca/fides/pull/4146)

### Fixed
- Allows CDN to cache empty experience responses from fides.js API [#4113](https://github.com/ethyca/fides/pull/4113)
Expand Down
222 changes: 24 additions & 198 deletions clients/admin-ui/src/features/system/history/SystemHistoryTable.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* eslint-disable no-param-reassign */
import {
Button,
Flex,
Expand All @@ -8,131 +9,58 @@ import {
Thead,
Tr,
} from "@fidesui/react";
import _ from "lodash";
import React, { useState } from "react";

import { useAppSelector } from "~/app/hooks";
import NextArrow from "~/features/common/Icon/NextArrow";
import PrevArrow from "~/features/common/Icon/PrevArrow";
import {
DictOption,
selectAllDictEntries,
useGetSystemHistoryQuery,
} from "~/features/plus/plus.slice";
import { PrivacyDeclaration, SystemHistoryResponse } from "~/types/api";
import { selectAllSystems } from "~/features/system/system.slice";
import { SystemHistoryResponse } from "~/types/api";
import { SystemResponse } from "~/types/api/models/SystemResponse";

import {
alignPrivacyDeclarations,
assignSystemNames,
assignVendorLabels,
describeSystemChange,
formatDateAndTime,
} from "./helpers";
import SystemHistoryModal from "./modal/SystemHistoryModal";

interface Props {
system: SystemResponse;
}

// Helper function to format date and time
const formatDateAndTime = (dateString: string) => {
const date = new Date(dateString);
const userLocale = navigator.language;

const timeOptions: Intl.DateTimeFormatOptions = {
hour: "2-digit",
minute: "2-digit",
hour12: true,
timeZoneName: "short",
};

const dateOptions: Intl.DateTimeFormatOptions = {
year: "numeric",
month: "long",
day: "numeric",
};

const formattedTime = date.toLocaleTimeString(userLocale, timeOptions);
const formattedDate = date.toLocaleDateString(userLocale, dateOptions);

return { formattedTime, formattedDate };
};

function alignArrays(
before: PrivacyDeclaration[],
after: PrivacyDeclaration[]
) {
const allNames = new Set([...before, ...after].map((item) => item.data_use));
const alignedBefore: PrivacyDeclaration[] = [];
const alignedAfter: PrivacyDeclaration[] = [];

allNames.forEach((data_use) => {
const firstItem = before.find((item) => item.data_use === data_use) || {
data_use: "",
data_categories: [],
};
const secondItem = after.find((item) => item.data_use === data_use) || {
data_use: "",
data_categories: [],
};
alignedBefore.push(firstItem);
alignedAfter.push(secondItem);
});

return [alignedBefore, alignedAfter];
}

const lookupVendorLabel = (vendor_id: string, options: DictOption[]) =>
options.find((option) => option.value === vendor_id)?.label ?? vendor_id;

const itemsPerPage = 10;
const ITEMS_PER_PAGE = 10;

const SystemHistoryTable = ({ system }: Props) => {
const [currentPage, setCurrentPage] = useState(1);
const { data } = useGetSystemHistoryQuery({
system_key: system.fides_key,
page: currentPage,
size: itemsPerPage,
size: ITEMS_PER_PAGE,
});
const [isModalOpen, setModalOpen] = useState(false);
const [selectedHistory, setSelectedHistory] =
useState<SystemHistoryResponse | null>(null);
const dictionaryOptions = useAppSelector(selectAllDictEntries);
const systems = useAppSelector(selectAllSystems);

const systemHistories = data?.items || [];

const openModal = (history: SystemHistoryResponse) => {
// Align the privacy_declarations arrays
const beforePrivacyDeclarations =
history?.before?.privacy_declarations || [];
const afterPrivacyDeclarations = history?.after?.privacy_declarations || [];
const [alignedBefore, alignedAfter] = alignArrays(
beforePrivacyDeclarations,
afterPrivacyDeclarations
);

// Create new initialValues objects with the aligned arrays
const alignedBeforeInitialValues = {
...history?.before,
privacy_declarations: alignedBefore,
};
const alignedAfterInitialValues = {
...history?.after,
privacy_declarations: alignedAfter,
};

if (dictionaryOptions) {
alignedBeforeInitialValues.vendor_id = lookupVendorLabel(
alignedBeforeInitialValues.vendor_id,
dictionaryOptions
);
alignedAfterInitialValues.vendor_id = lookupVendorLabel(
alignedAfterInitialValues.vendor_id,
dictionaryOptions
);
}

setSelectedHistory({
before: alignedBeforeInitialValues,
after: alignedAfterInitialValues,
edited_by: history.edited_by,
system_id: history.system_id,
created_at: history.created_at,
});
// Align the before and after privacy declaration lists so they have the same number of entries
history = alignPrivacyDeclarations(history);
// Look up the vendor labels from the vendor IDs
history = assignVendorLabels(history, dictionaryOptions);
// Look up the system names for the source and destination fides_keys
history = assignSystemNames(history, systems);

setSelectedHistory(history);
setModalOpen(true);
};

Expand All @@ -141,111 +69,9 @@ const SystemHistoryTable = ({ system }: Props) => {
setSelectedHistory(null);
};

const describeSystemChange = (history: SystemHistoryResponse) => {
// eslint-disable-next-line @typescript-eslint/naming-convention
const { edited_by, before, after, created_at } = history;

const uniqueKeys = new Set([...Object.keys(before), ...Object.keys(after)]);

const addedFields: string[] = [];
const removedFields: string[] = [];
const changedFields: string[] = [];

Array.from(uniqueKeys).forEach((key) => {
// @ts-ignore
const beforeValue = before[key];
// @ts-ignore
const afterValue = after[key];

// Handle booleans separately
if (typeof beforeValue === "boolean" || typeof afterValue === "boolean") {
if (beforeValue !== afterValue) {
changedFields.push(key);
}
return;
}

// Handle numbers separately
if (typeof beforeValue === "number" || typeof afterValue === "number") {
if (beforeValue !== afterValue) {
changedFields.push(key);
}
return;
}

// If both values are null or empty, skip
if (
(_.isNil(beforeValue) || _.isEmpty(beforeValue)) &&
(_.isNil(afterValue) || _.isEmpty(afterValue))
) {
return;
}

// For all other types
if (!_.isEqual(beforeValue, afterValue)) {
if (_.isNil(beforeValue) || _.isEmpty(beforeValue)) {
addedFields.push(key);
} else if (_.isNil(afterValue) || _.isEmpty(afterValue)) {
removedFields.push(key);
} else {
changedFields.push(key);
}
}
});

const changeDescriptions: Array<[string, JSX.Element]> = [];

if (addedFields.length > 0) {
// eslint-disable-next-line react/jsx-key
changeDescriptions.push(["added ", <b>{addedFields.join(", ")}</b>]);
}

if (removedFields.length > 0) {
// eslint-disable-next-line react/jsx-key
changeDescriptions.push(["removed ", <b>{removedFields.join(", ")}</b>]);
}

if (changedFields.length > 0) {
// eslint-disable-next-line react/jsx-key
changeDescriptions.push(["changed ", <b>{changedFields.join(", ")}</b>]);
}

if (changeDescriptions.length === 0) {
return null;
}

const lastDescription = changeDescriptions.pop();

const descriptionList =
changeDescriptions.length > 0 ? (
<>
{changeDescriptions.map((desc, i) => (
// eslint-disable-next-line react/no-array-index-key
<React.Fragment key={i}>
{desc}
{i < changeDescriptions.length - 1 ? ", " : ""}
</React.Fragment>
))}
{changeDescriptions.length >= 2 ? ", and " : " and "}
{lastDescription}
</>
) : (
lastDescription
);

const { formattedTime, formattedDate } = formatDateAndTime(created_at);

return (
<>
<b>{edited_by}</b> {descriptionList} on {formattedDate} at{" "}
{formattedTime}
</>
);
};

const { formattedTime, formattedDate } = formatDateAndTime(system.created_at);

const totalPages = data ? Math.ceil(data.total / itemsPerPage) : 0;
const totalPages = data ? Math.ceil(data.total / ITEMS_PER_PAGE) : 0;

const handleNextPage = () => {
if (currentPage < totalPages) {
Expand Down Expand Up @@ -313,8 +139,8 @@ const SystemHistoryTable = ({ system }: Props) => {
marginLeft="24px"
>
<Text fontSize="xs" lineHeight={4} fontWeight="600" paddingX={2}>
{(currentPage - 1) * itemsPerPage + 1} -{" "}
{Math.min(currentPage * itemsPerPage, data?.total || 0)} of{" "}
{(currentPage - 1) * ITEMS_PER_PAGE + 1} -{" "}
{Math.min(currentPage * ITEMS_PER_PAGE, data?.total || 0)} of{" "}
{data?.total || 0}
</Text>
<Button
Expand Down
Loading