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

Add possibility to add multiple grep codes with comma as separator #2818

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
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
87 changes: 64 additions & 23 deletions src/containers/FormikForm/GrepCodesField.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import { FormField } from "../../components/FormField";
import { searchGrepCodes } from "../../modules/search/searchApi";
import { useSearchGrepCodes } from "../../modules/search/searchQueries";
import { isGrepCodeValid } from "../../util/articleUtil";
import handleError from "../../util/handleError";
import { usePaginatedQuery } from "../../util/usePaginatedQuery";

const StyledList = styled("ul", {
Expand All @@ -34,7 +35,8 @@ export const convertGrepCodesToObject = async (grepCodes: string[]): Promise<Rec

interface GrepCode {
code: string;
title: string;
title?: string;
status: "success" | "error";
}

interface Props {
Expand All @@ -58,33 +60,72 @@ const GrepCodesField = ({ prefixFilter }: Props) => {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

const fetchGrepCodeTitles = async (grepCode: string): Promise<GrepCode | undefined> => {
const grepCodeTitle = await searchGrepCodes({ codes: [grepCode] });
const isGrepCodeSaved = grepCodes[grepCode];
if (grepCodeTitle.results.length && !isGrepCodeSaved && isGrepCodeValid(grepCode, prefixFilter)) {
return {
code: grepCode,
title: `${grepCode} - ${grepCodeTitle.results[0].title.title}`,
};
} else if (!isGrepCodeSaved) {
setTimeout(() => {
helpers.setError(`${t("errorMessage.grepCodes")}${grepCode}`);
}, 0);
const fetchGrepCodeTitles = async (newGrepCodes: string[]): Promise<GrepCode[]> => {
try {
const withoutSavedAndInvalid = newGrepCodes.filter(
(code) => !grepCodes[code] && isGrepCodeValid(code, prefixFilter),
);
if (!withoutSavedAndInvalid.length) return [];
const grepCodesData = await searchGrepCodes({ codes: withoutSavedAndInvalid });

const codes = grepCodesData.results.map((grepCode) => {
return {
code: grepCode.code,
title: `${grepCode.code} - ${grepCode.title.title}`,
status: "success",
} as GrepCode;
});

const withFailed = codes.concat(
newGrepCodes
.filter((code) => !codes.some((c) => c?.code === code))
.map((code) => ({ code: code, status: "error" }) as GrepCode),
);
return withFailed;
} catch (e) {
handleError(e);
helpers.setError(t("errorMessage.genericError"));
return [];
}
};

const updateGrepCodes = async (newValue: string) => {
const delimitedValues = newValue.split(",");
helpers.setError(undefined);
const trimmedValue = newValue.toUpperCase().trim();
if (field.value.includes(trimmedValue)) {
const { [trimmedValue]: _, ...remaining } = grepCodes;
setGrepCodes(remaining);
helpers.setValue(field.value.filter((v) => v !== trimmedValue));
} else {
const grepCodeWithName = await fetchGrepCodeTitles(trimmedValue);
if (!grepCodeWithName) return;
setGrepCodes({ ...grepCodes, [grepCodeWithName.code]: grepCodeWithName.title });
helpers.setValue([...field.value, grepCodeWithName.code]);

const addedGrepCodes = delimitedValues.reduce((acc, v) => {
const trimmedValue = v.toUpperCase().trim();
// Delete grep code
if (field.value.includes(trimmedValue)) {
const { [trimmedValue]: _, ...remaining } = grepCodes;
setGrepCodes(remaining);
helpers.setValue(field.value.filter((v) => v !== trimmedValue));
return acc;
}
//Add grep code
return [...acc, trimmedValue];
}, [] as string[]);
if (!addedGrepCodes.length) return;

const grepCodesWithName = await fetchGrepCodeTitles(addedGrepCodes);
const [success, error] = [
grepCodesWithName.filter((obj) => obj?.status === "success"),
grepCodesWithName.filter((obj) => obj?.status === "error"),
];

const updatedGrepCodes = success.reduce(
(acc, v) => {
helpers.setValue([...field.value, v.code]);
return { ...acc, [v.code]: v.title } as Record<string, string>;
},
grepCodes as Record<string, string>,
);
setGrepCodes(updatedGrepCodes);

if (error.length) {
setTimeout(() => {
helpers.setError(`${t("errorMessage.grepCodes")}${error.map((e) => e.code).join(", ")}`);
}, 0);
}
};

Expand Down
2 changes: 1 addition & 1 deletion src/phrases/phrases-en.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1274,7 +1274,7 @@ const phrases = {
label: "Competences and core elements",
placeholder: "Type code",
description:
"Type in codes using the correct format ({{ codes }}) followed by one or more digits. Non existing codes will not be created. Texts will be displayed in norwegian here but will be shown correct in frontend.",
"Type in codes using the correct format ({{ codes }}) followed by one or more digits. Non existing codes will not be created. Separate multiple codes with comma. Texts will be displayed in norwegian here but will be shown correct in frontend.",
},
resourceTypes: {
label: "Resource type and properties",
Expand Down
2 changes: 1 addition & 1 deletion src/phrases/phrases-nb.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1274,7 +1274,7 @@ const phrases = {
label: "Kompetansemål og kjerneelementer",
placeholder: "Skriv inn kode",
description:
"Skriv inn koder som starter på riktig format ({{ codes }}) fulgt av ett eller flere siffer. Koder som ikke finnes vil ikke bli opprettet. Tekstene vises på bokmål i ed men korrekt i artikkelvisning.",
"Skriv inn koder som starter på riktig format ({{ codes }}) fulgt av ett eller flere siffer. Koder som ikke finnes vil ikke bli opprettet. Separer flere koder med komma. Tekstene vises på bokmål i ed men korrekt i artikkelvisning.",
},
resourceTypes: {
label: "Innholdstype og egenskaper",
Expand Down
2 changes: 1 addition & 1 deletion src/phrases/phrases-nn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1274,7 +1274,7 @@ const phrases = {
label: "Kompetansemål og kjerneelementer",
placeholder: "Skriv inn kode",
description:
"Skriv inn koder som starter på riktig format ({{ codes }} fulgt av eit eller fleire siffer. Koder som ikkje eksisterer vil ikkje bli oppretta. Tekstene visast på bokmål i ed, men korrekt i artikkelvisning.",
"Skriv inn koder som starter på riktig format ({{ codes }} fulgt av eit eller fleire siffer. Koder som ikkje eksisterer vil ikkje bli oppretta. Separer fleire koder med komma. Tekstene visast på bokmål i ed, men korrekt i artikkelvisning.",
},
resourceTypes: {
label: "Innhaldstype og egenskaper",
Expand Down
Loading