Skip to content

Commit

Permalink
feat(types): synchronisation des types au niveau de l'admin (#5826)
Browse files Browse the repository at this point in the history
* fix: merge

* fix: merge

* fix: types

* fix: types

* fix: merge

* fix: merge

* fix: bug

* fix: bug

* fix: types

* fix: types

* fix: types
  • Loading branch information
maxgfr committed May 14, 2024
1 parent aa2f454 commit f878be3
Show file tree
Hide file tree
Showing 90 changed files with 265 additions and 395 deletions.
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
"description": "Code du travail",
"homepage": "https://github.com/SocialGouv/code-du-travail-numerique#readme",
"scripts": {
"build": "lerna run build --scope=@socialgouv/cdtn-ui --scope=@socialgouv/modeles-social --scope=@socialgouv/cdtn-utils --scope=@cdt/frontend --stream",
"build:npm": "lerna run build --scope=@socialgouv/cdtn-ui --scope=@socialgouv/modeles-social --scope=@socialgouv/cdtn-utils --stream",
"build": "lerna run build --scope=@socialgouv/cdtn-utils --scope=@socialgouv/cdtn-ui --scope=@socialgouv/modeles-social --scope=@cdt/frontend --stream",
"build:npm": "lerna run build --scope=@socialgouv/cdtn-utils --scope=@socialgouv/cdtn-ui --scope=@socialgouv/modeles-social --stream",
"clean": "lerna clean",
"dev:docker": "docker-compose up elasticsearch",
"dev": "lerna run dev --parallel",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ const contribution = {
idcc: "",
ccnShortTitle: "Métallurgie",
title: "La période d’essai peut-elle être renouvelée ?",
};
breadcrumbs: [],
} as any;
describe("<PageContribution />", () => {
it("should render title with cc name in it", () => {
const { getByRole } = render(
Expand Down Expand Up @@ -39,7 +40,7 @@ describe("<PageContribution />", () => {
idcc: "",
ccnShortTitle: "Métallurgie",
title: "La période d’essai peut-elle être renouvelée ?",
};
} as any;
const { getByRole } = render(
<PageContribution contribution={contribution} />
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ describe("<FicheMT />", () => {
{
label: "Santé, sécurité et conditions de travail",
slug: "/themes/6-sante-securite-et-conditions-de-travail",
position: 2,
},
],
date: "01/01/2020",
Expand All @@ -18,8 +19,7 @@ describe("<FicheMT />", () => {
sections: [
{
anchor: "t1-Visite-d-information-et-de-prevention-pour-qui",
html:
'<p>Depuis le 1er janvier 2017, la <strong>visite d’information et de prévention</strong> vient remplacer la traditionnelle visite médicale d’embauche qui devait être réalisée au plus tard avant la fin de la période d’essai.</p><p>Désormais, la visite doit être organisée dans un délai maximum de trois mois à compter de l’occupation effective du poste de travail (sauf cas de dispense). Néanmoins, pour certains salariés, comme les jeunes de moins de 18 ans ou les travailleurs de nuit, elle doit toujours avoir lieu avant la prise de fonction.</p><p><strong>Bon à savoir&nbsp;!</strong> Tout salarié affecté à un poste présentant des risques particuliers pour sa santé (exposition à l’amiante, au plomb, à des agents cancérogènes, etc.) doit passer, avant sa prise de fonction, <strong>un examen médical d’aptitude</strong> et non une simple visite d’information et de prévention.</p><p><strong>La visite d’information et de prévention</strong> permet d’interroger le salarié sur son état de santé, et d’envisager, si besoin, son orientation spécifique vers le médecin du travail. Elle vise aussi à informer le salarié sur les risques éventuels auxquels l’expose son poste de travail, et à le sensibiliser sur les moyens de prévention.</p><p><strong>Cette visite n’est pas toujours assurée par le médecin du travail lui-même</strong>. Le salarié peut être reçu par un professionnel de santé (par exemple, un infirmier) intervenant sous son autorité.. Toutefois, certains salariés comme par exemple les femmes enceintes, celles qui viennent d’accoucher ou allaitent leur enfant, ou encore les travailleurs handicapés, sont adressés au médecin du travail afin que leur soit proposé un suivi adapté à leur situation.</p><p><strong>Pour davantage de détails</strong> consultez <a href="https://travail-emploi.gouv.fr/sante-au-travail/suivi-de-la-sante-au-travail-10727/article/le-suivi-de-l-etat-de-sante-des-salaries" class="spip_in" target="_blank" rel="nofollow, noopener">notre fiche sur le suivi de l’état de santé des salariés</a>.</p>',
html: '<p>Depuis le 1er janvier 2017, la <strong>visite d’information et de prévention</strong> vient remplacer la traditionnelle visite médicale d’embauche qui devait être réalisée au plus tard avant la fin de la période d’essai.</p><p>Désormais, la visite doit être organisée dans un délai maximum de trois mois à compter de l’occupation effective du poste de travail (sauf cas de dispense). Néanmoins, pour certains salariés, comme les jeunes de moins de 18 ans ou les travailleurs de nuit, elle doit toujours avoir lieu avant la prise de fonction.</p><p><strong>Bon à savoir&nbsp;!</strong> Tout salarié affecté à un poste présentant des risques particuliers pour sa santé (exposition à l’amiante, au plomb, à des agents cancérogènes, etc.) doit passer, avant sa prise de fonction, <strong>un examen médical d’aptitude</strong> et non une simple visite d’information et de prévention.</p><p><strong>La visite d’information et de prévention</strong> permet d’interroger le salarié sur son état de santé, et d’envisager, si besoin, son orientation spécifique vers le médecin du travail. Elle vise aussi à informer le salarié sur les risques éventuels auxquels l’expose son poste de travail, et à le sensibiliser sur les moyens de prévention.</p><p><strong>Cette visite n’est pas toujours assurée par le médecin du travail lui-même</strong>. Le salarié peut être reçu par un professionnel de santé (par exemple, un infirmier) intervenant sous son autorité.. Toutefois, certains salariés comme par exemple les femmes enceintes, celles qui viennent d’accoucher ou allaitent leur enfant, ou encore les travailleurs handicapés, sont adressés au médecin du travail afin que leur soit proposé un suivi adapté à leur situation.</p><p><strong>Pour davantage de détails</strong> consultez <a href="https://travail-emploi.gouv.fr/sante-au-travail/suivi-de-la-sante-au-travail-10727/article/le-suivi-de-l-etat-de-sante-des-salaries" class="spip_in" target="_blank" rel="nofollow, noopener">notre fiche sur le suivi de l’état de santé des salariés</a>.</p>',
title: "1) Visite d’information et de prévention : pour qui ?",
},
],
Expand Down
13 changes: 6 additions & 7 deletions packages/code-du-travail-frontend/__tests__/information.test.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,15 @@
import { render, RenderResult } from "@testing-library/react";
import React from "react";

import InformationPage from "../pages/information/[slug]";
import {
import InformationPage, {
EditorialContentDataWrapper,
SectionDisplayMode,
} from "@socialgouv/cdtn-utils";
} from "../pages/information/[slug]";
import { EditorialSectionDisplayMode } from "@socialgouv/cdtn-types";

const mockedProps: EditorialContentDataWrapper = {
information: {
_source: {
breadcrumbs: [],
contents: [],
slug: "",
},
},
Expand All @@ -28,7 +26,8 @@ describe("Information Page", () => {
describe("Given a parameter sectionDisplayMode = 'tab'", () => {
beforeAll(() => {
props = { ...mockedProps };
props.information._source.sectionDisplayMode = SectionDisplayMode.tab;
props.information._source.sectionDisplayMode =
EditorialSectionDisplayMode.tab;
});
it("should contain tabs", () => {
const tabs = renderResult.queryByTestId("tabs");
Expand All @@ -39,7 +38,7 @@ describe("Information Page", () => {
beforeAll(() => {
props = { ...mockedProps };
props.information._source.sectionDisplayMode =
SectionDisplayMode.accordion;
EditorialSectionDisplayMode.accordion;
});
it("should contain accordions", () => {
const accordions = renderResult.queryByTestId("accordion");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import ModelesDeCourriers from "../pages/modeles-de-courriers/[slug]";
describe("<ModelesDeCourrier />", () => {
it("should render", () => {
const data = {
breadcrumbs: [{ label: "theme", slug: "/themes/theme" }],
breadcrumbs: [{ label: "theme", slug: "/themes/theme", position: 0 }],
date: "01/01/2020",
description: "un description",
metaDescription: "un description",
Expand Down
1 change: 1 addition & 0 deletions packages/code-du-travail-frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
"@sentry/nextjs": "^7.114.0",
"@socialgouv/cdtn-elasticsearch": "^2.5.2",
"@socialgouv/cdtn-logger": "^2.0.0",
"@socialgouv/cdtn-types": "^2.42.3",
"@socialgouv/cdtn-ui": "workspace:^",
"@socialgouv/cdtn-utils": "workspace:^",
"@socialgouv/fiches-travail-data": "^4.241.0",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Breadcrumb, getLabelBySource, SOURCES } from "@socialgouv/cdtn-utils";
import { getLabelBySource, SOURCES } from "@socialgouv/cdtn-utils";
import { Breadcrumb } from "@socialgouv/cdtn-types";
import { Alert } from "@socialgouv/cdtn-ui";
import { format } from "date-fns";
import frLocale from "date-fns/locale/fr";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import {
ElasticSearchContribution,
ElasticSearchContributionConventionnelle,
ElasticSearchContributionGeneric,
} from "@socialgouv/cdtn-utils";
} from "@socialgouv/cdtn-types";
import { handleError } from "../../src/lib/fetch-error";
import { SITE_URL } from "../../src/config";
import ContributionGeneric from "../../src/contributions/ContributionGeneric";
Expand Down Expand Up @@ -57,7 +57,9 @@ function PageContribution(props: Props): React.ReactElement {

metas = buildTitleAndDescription(
props.contribution.breadcrumbs,
props.contribution.ccnShortTitle,
"ccnShortTitle" in props.contribution
? props.contribution.ccnShortTitle
: undefined,
props.contribution.title,
props.contribution.description
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ function ConventionCollective(props: Props): JSX.Element {
{
label: "Conventions collectives",
slug: `/outils/${getRouteBySource(SOURCES.CCN)}`,
position: 0,
},
]}
date={
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import Answer from "../../src/common/Answer";
import Html from "../../src/common/Html";
import Metas from "../../src/common/Metas";
import { Layout } from "../../src/layout/Layout";
import { Breadcrumb } from "@socialgouv/cdtn-utils";
import { Breadcrumb } from "@socialgouv/cdtn-types";
import { handleError } from "../../src/lib/fetch-error";
import { SITE_URL } from "../../src/config";

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import Answer from "../../src/common/Answer";
import Metas from "../../src/common/Metas";
import References from "../../src/common/References";
import { Layout } from "../../src/layout/Layout";
import { Breadcrumb } from "@socialgouv/cdtn-utils";
import { Breadcrumb } from "@socialgouv/cdtn-types";
import { handleError } from "../../src/lib/fetch-error";
import { SITE_URL } from "../../src/config";

Expand Down
17 changes: 14 additions & 3 deletions packages/code-du-travail-frontend/pages/information/[slug].tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,22 @@ import Answer from "../../src/common/Answer";
import Metas from "../../src/common/Metas";
import References from "../../src/common/References";
import { Layout } from "../../src/layout/Layout";
import { EditorialContentDataWrapper, SOURCES } from "@socialgouv/cdtn-utils";
import { SOURCES } from "@socialgouv/cdtn-utils";
import { Contents } from "../../src/information";
import { QuestionnaireWrapper } from "../../src/questionnaire";
import { useRouter } from "next/router";
import { SITE_URL } from "../../src/config";
import {
EditorialContentBaseContentPart,
EditorialContentElasticDocument,
} from "@socialgouv/cdtn-types";

export type EditorialContentDataWrapper = {
information: {
_source: Partial<EditorialContentElasticDocument>;
relatedItems?: string[];
};
};

const Information = ({
information: {
Expand Down Expand Up @@ -56,8 +67,8 @@ const Information = ({
anchor={anchor}
sectionDisplayMode={sectionDisplayMode}
dismissalProcess={dismissalProcess}
contents={contents}
></Contents>
contents={contents as EditorialContentBaseContentPart[] | undefined}
/>
{references.map(
({ label, links }, index) =>
links.length > 0 && (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ const IntegrationPage = (props): JSX.Element => {
{
label: "Intégrer les outils du Code du travail numérique",
slug: "/integration",
position: 0,
},
]}
/>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,3 @@
import {
Agreement,
ElasticSearchItem,
SearchResponse,
} from "@socialgouv/cdtn-utils";
import {
elasticDocumentsIndex,
elasticsearchClient,
Expand All @@ -14,11 +9,15 @@ import {
getAgreementsBySlugs,
getAllAgreementsWithContributions,
} from "./queries";
import { ElasticSearchItem, SearchResponse } from "../../types";
import { ElasticAgreement } from "@socialgouv/cdtn-types";

export const getAllAgreements = async (): Promise<Agreement[]> => {
export const getAllAgreements = async (): Promise<ElasticAgreement[]> => {
const body = getAllAgreementsWithContributions();

const response = await elasticsearchClient.search<SearchResponse<Agreement>>({
const response = await elasticsearchClient.search<
SearchResponse<ElasticAgreement>
>({
body,
index: elasticDocumentsIndex,
});
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { Agreement, ElasticSearchItem } from "@socialgouv/cdtn-utils";
import { elasticDocumentsIndex, elasticsearchClient } from "../../utils";
import { getAllGenericsContributions, getContributionsByIds } from "./queries";
import { fetchAllContributions } from "./fetch";
import { ElasticSearchItem } from "../../types";
import { ElasticAgreement } from "@socialgouv/cdtn-types";

export const getGenericContributionsGroupByThemes = async () => {
const body = getAllGenericsContributions();
Expand All @@ -21,7 +22,7 @@ export const getGenericContributionsGroupByThemes = async () => {

const isGeneric = (contrib) => contrib.idcc === "0000";

function getTitle(agreements: Agreement[], contrib) {
function getTitle(agreements: ElasticAgreement[], contrib) {
const idcc = contrib.idcc ?? contrib.slug.split("-")[0];
const agreement = agreements.find((a) => a.num === parseInt(idcc));
return agreement
Expand All @@ -30,7 +31,7 @@ function getTitle(agreements: Agreement[], contrib) {
}

export const getAllContributionsGroupByQuestion = async (
agreements: Agreement[]
agreements: ElasticAgreement[]
) => {
const response = await fetchAllContributions();
const all = response.body.hits.hits.map(({ _source }) => _source);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { NextApiRequest, NextApiResponse } from "next";
import { InvalidQueryError } from "../../utils";
import { fetchEnterprises, populateAgreements } from "./service";
import { ApiEnterpriseData } from "./types";
import { ErrorResponse } from "../../types";

export class EnterprisesController {
private req: NextApiRequest;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import { Agreement, SearchResponse, SOURCES } from "@socialgouv/cdtn-utils";
import { SOURCES } from "@socialgouv/cdtn-utils";
import { Agreement } from "../../../outils/types";
import { SearchResponse } from "../../types";

type SearchAgreementsBody = {
_source: string[];
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Agreement } from "@socialgouv/cdtn-utils";
import { Agreement } from "../../../outils/types";

export type ApiEnterpriseData = {
entreprises: Enterprise[] | undefined;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ElasticSearchItem } from "@socialgouv/cdtn-utils";
import { ElasticSearchItem } from "../../types";
import { getByIdsAgreements } from "../agreements";
import { getByIdsContributions } from "../contributions";
import { getBySlugHighlights } from "../highlights";
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Agreement } from "@socialgouv/cdtn-utils";
import { Agreement } from "../../../outils/types";

export type ApiEnterpriseData = {
entreprises: Enterprise[] | undefined;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ export const getCovisitedItems = async ({ covisits }: { covisits: any }) => {
export const getSearchBasedItems = async ({
title,
settings,
slug
slug,
}: {
title: string;
settings: any;
Expand All @@ -88,7 +88,9 @@ export const getSearchBasedItems = async ({
const query_vector = await vectorizeQuery(title.toLowerCase()).catch(
(error: any) => {
if (error.message === "Cannot vectorize empty query.") {
console.log(`[WARNING] Try to vectorize an empty title: ${title} (slug: ${slug}) `)
console.log(
`[WARNING] Try to vectorize an empty title: ${title} (slug: ${slug}) `
);
} else {
console.error(error.message);
}
Expand Down Expand Up @@ -147,7 +149,7 @@ export const getRelatedItems = async ({
(item: { slug: string }) => !slug.startsWith(item.slug.split("#")[0])
)
// only return sources of interest
.filter(({ source }: { source: string }) => sources.includes(source))
.filter(({ source }: { source: any }) => sources.includes(source))
// drop duplicates (between covisits and search) using source/slug
.reduce((acc: any, related: { source: string; slug: string }) => {
const key = related.source + related.slug;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ElasticSearchItem } from "@socialgouv/cdtn-utils";
import { ElasticSearchItem } from "../../types";
import {
elasticsearchClient,
elasticDocumentsIndex,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
import {
Agreement,
ElasticSearchItem,
Tool,
EditorialContent,
} from "@socialgouv/cdtn-utils";
ElasticAgreement,
} from "@socialgouv/cdtn-types";
import { getAllAgreements } from "../agreements";
import { getAllContributionsGroupByQuestion } from "../contributions";
import { getAllModeles } from "../modeles";
import { getAllThemesAndSubThemes } from "../themes";
import { getAllTools } from "../tools";
import { getAllInformations } from "../informations";
import { ElasticSearchItem } from "../../types";

type Information = Pick<EditorialContent, "slug" | "title">;

Expand All @@ -21,7 +21,7 @@ export type GetSitemapPage = {
generic: ElasticSearchItem;
agreements: ElasticSearchItem[];
}[];
agreements: Agreement[];
agreements: ElasticAgreement[];
informations: Information[];
};

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Tool } from "@socialgouv/cdtn-utils";
import { Tool } from "@socialgouv/cdtn-types";
import {
elasticsearchClient,
elasticDocumentsIndex,
Expand Down
23 changes: 22 additions & 1 deletion packages/code-du-travail-frontend/src/api/types.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,24 @@
type ErrorResponse = {
import { Breadcrumb } from "@socialgouv/cdtn-types";

export type SearchResponse<T> = {
hits: {
total: {
value: number;
};
hits: {
_source: T;
}[];
};
};

export type ElasticSearchItem<T = void> = {
description: string;
source: string;
title: string;
slug: string;
breadcrumbs: Breadcrumb[];
} & T;

export type ErrorResponse = {
message: string;
};
2 changes: 1 addition & 1 deletion packages/code-du-travail-frontend/src/common/Answer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import { Feedback } from "./Feedback";
import Html from "./Html";
import { RelatedItems } from "./RelatedItems";
import { Share } from "./Share";
import { Breadcrumb } from "@socialgouv/cdtn-utils";
import { Breadcrumb } from "@socialgouv/cdtn-types";

const BigError = ({ children }) => (
<StyledErrorContainer>
Expand Down

0 comments on commit f878be3

Please sign in to comment.