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

Justerer validering av notifications (++) #353

Merged
merged 4 commits into from
Jul 2, 2024
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
6 changes: 3 additions & 3 deletions packages/client/src/faro.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@
* This adds information about decorator parameters to the Grafana faro. To aid with debugging.
* */
export function addFaroMetaData() {
if (!window.faro) return;
if (!window.faro) {
return;
}

window.faro.api.setSession({
attributes: {
decorator_env: JSON.stringify(window.__DECORATOR_DATA__.env),
decorator_params: JSON.stringify(window.__DECORATOR_DATA__.params),
},
});

console.log("Faro: Adding metadata");
}
4 changes: 2 additions & 2 deletions packages/server/src/handlers/auth-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { LogoutIcon } from "decorator-shared/views/icons/logout";
import { match } from "ts-pattern";
import { clientEnv, env } from "../env/server";
import i18n from "../i18n";
import { getNotifications } from "../notifications";
import { fetchNotifications } from "../notifications";
import { AnchorIconButton } from "../views/anchor-icon-button";
import { ArbeidsgiverUserMenuDropdown } from "../views/header/arbeidsgiver-user-menu-dropdown";
import { UserMenuDropdown } from "../views/header/user-menu-dropdown";
Expand Down Expand Up @@ -68,7 +68,7 @@ const buildUsermenuHtml = async (
// @TODO: Tests for important urls, like logout
const template = await match(params.context)
.with("privatperson", async () => {
const notificationsResult = await getNotifications({ cookie });
const notificationsResult = await fetchNotifications({ cookie });

return UserMenuDropdown({
name: auth.name,
Expand Down
2 changes: 1 addition & 1 deletion packages/server/src/handlers/search-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ const resultSchema = z.object({
)
.catch((ctx) => {
console.error(
`Error validating search hit - ${ctx.error.message}`,
`Error validating search hit - ${JSON.stringify(ctx.input)}`,
);
return undefined;
}),
Expand Down
22 changes: 20 additions & 2 deletions packages/server/src/notifications.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { env } from "./env/server";
import {
Varsler,
archiveNotification,
getNotifications,
fetchNotifications,
} from "./notifications";
import { expectOK } from "./test-expect";

Expand Down Expand Up @@ -42,6 +42,15 @@ describe("notifications", () => {
tekst: "wat",
link: "http://example.com",
},
{
eventId: "c",
type: "invalidtype",
tidspunkt: "2023-07-05T11:43:02.280367+02:00",
isMasked: false,
eksternVarslingKanaler: ["SMS", "EPOST"],
tekst: "Invalid oppgave",
link: "http://example.com",
},
],
beskjeder: [
{
Expand All @@ -66,7 +75,7 @@ describe("notifications", () => {
afterAll(() => server.close());

test("returns transformed notifications", async () => {
const result = await getNotifications({
const result = await fetchNotifications({
cookie: "cookie",
});

Expand Down Expand Up @@ -108,4 +117,13 @@ describe("notifications", () => {
expectOK(response);
expect(response.data).toEqual("eventId");
});

test("Should filter out invalid notification", async () => {
const response = await fetchNotifications({
cookie: "cookie",
});

expectOK(response);
expect(response.data).not.toContain({ tekst: "Invalid oppgave" });
});
});
83 changes: 49 additions & 34 deletions packages/server/src/notifications.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,31 @@ import { env } from "./env/server";
import { Result, ResultType } from "./result";
import { fetchAndValidateJson } from "./lib/fetch-and-validate";

const varselSchema = z.object({
eventId: z.string(),
type: z.enum(["oppgave", "beskjed", "innboks"]),
tidspunkt: z.string(),
isMasked: z.boolean(),
tekst: z.string().nullable(),
link: z.string().nullable(),
eksternVarslingKanaler: z.array(z.string()),
});
const varselSchema = z
.object({
eventId: z.string(),
type: z.enum(["oppgave", "beskjed", "innboks"]),
tidspunkt: z.string(),
isMasked: z.boolean(),
tekst: z.string().nullable(),
link: z.string().nullable(),
eksternVarslingKanaler: z.array(z.string()),
})
.nullable()
.catch((ctx) => {
console.error(
`Error validating notification - ${JSON.stringify(ctx.input)}`,
);
return null;
});

const varslerSchema = z.object({
oppgaver: z.array(varselSchema),
beskjeder: z.array(varselSchema),
});

type Varsel = z.infer<typeof varselSchema>;
type VarselNullable = z.infer<typeof varselSchema>;
type Varsel = NonNullable<VarselNullable>;

export type Varsler = z.infer<typeof varslerSchema>;

Expand Down Expand Up @@ -50,34 +59,37 @@ const translateNotificationType = {
innboks: "inbox",
};

const sortVarslerNewestFirst = (a: Varsel, b: Varsel) =>
const sortNewestFirst = (a: Varsel, b: Varsel) =>
a.tidspunkt > b.tidspunkt ? -1 : 1;

const filterAndSort = (varsler: VarselNullable[]): Varsel[] =>
varsler
.filter((varsel): varsel is Varsel => !!varsel)
.sort(sortNewestFirst);

const varslerToNotifications = (varsler: Varsler): Notification[] =>
[
varsler.oppgaver.sort(sortVarslerNewestFirst),
varsler.beskjeder.sort(sortVarslerNewestFirst),
].flatMap((list) =>
list.map(
(varsel: Varsel): Notification => ({
id: varsel.eventId,
type: translateNotificationType[
varsel.type
] as NotificationType,
date: varsel.tidspunkt,
channels: varsel.eksternVarslingKanaler,
...(varsel.isMasked
? { masked: true }
: {
masked: false,
text: varsel.tekst ?? "",
link: varsel.link ?? undefined,
}),
}),
),
[filterAndSort(varsler.oppgaver), filterAndSort(varsler.beskjeder)].flatMap(
(list) =>
list.map(
(varsel): Notification => ({
id: varsel.eventId,
type: translateNotificationType[
varsel.type
] as NotificationType,
date: varsel.tidspunkt,
channels: varsel.eksternVarslingKanaler,
...(varsel.isMasked
? { masked: true }
: {
masked: false,
text: varsel.tekst ?? "",
link: varsel.link ?? undefined,
}),
}),
),
);

export const getNotifications = async ({
export const fetchNotifications = async ({
cookie,
}: {
cookie: string;
Expand All @@ -90,7 +102,10 @@ export const getNotifications = async ({
varslerSchema,
).then((result) =>
result.ok
? { ...result, data: varslerToNotifications(result.data) }
? {
...result,
data: varslerToNotifications(result.data as Varsler),
}
: result,
);
};
Expand Down
5 changes: 3 additions & 2 deletions packages/server/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import { csrAssets } from "./views";
import { MainMenu } from "./views/header/main-menu";
import { texts } from "./texts";
import { clientTextsKeys } from "decorator-shared/types";
import { trimTrailingSlash } from "hono/trailing-slash";

const app = new Hono();

Expand All @@ -34,6 +35,7 @@ if (env.NODE_ENV === "development" || env.IS_LOCAL_PROD) {
}

app.use(headers);
app.use(trimTrailingSlash());

app.get("/public/assets/*", serveStatic({}));

Expand Down Expand Up @@ -164,9 +166,8 @@ app.get("/", async ({ req, html }) => {
});

app.route("/decorator-next", app);
app.route("/decorator-next/", app);
app.route("/dekoratoren", app);
app.route("/dekoratoren/", app);
app.route("/common-html/v4/navno", app);

export default {
...app,
Expand Down
4 changes: 2 additions & 2 deletions packages/server/src/texts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ const nb = {
delskjerm_modal_stengt:
"Skjermdeling er for øyeblikket stengt, prøv igjen senere.",
security_level_info:
"Du har logget inn med Min ID. Hvis du logger inn med et høyere sikkerhetsnivå, får du se mer innhold og flere tjenester.",
"Du har logget inn med MinID. Hvis du logger inn med et høyere sikkerhetsnivå, får du se mer innhold og flere tjenester.",
security_level_link: "Logg inn med BankID, Buypass, eller Commfides.",
go_to_my_page: "Gå til Min side",
my_page: "Min side",
Expand Down Expand Up @@ -179,7 +179,7 @@ const en = {
delskjerm_modal_stengt:
"Screen sharing is currently closed, please try again later.",
security_level_info:
"You are logged in with Min ID. If you log in with a higher security level, you will see more content and additional services.",
"You are logged in with MinID. If you log in with a higher security level, you will see more content and additional services.",
security_level_link: "Log in with BankID, Buypass, or Commfides.",
go_to_my_page: "Go to my page",
my_page: "My page",
Expand Down