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

feat: add commune deleguee to voie #960

Open
wants to merge 1 commit 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
16 changes: 16 additions & 0 deletions components/bal/toponyme-editor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import LanguesRegionalesForm from "@/components/langues-regionales-form";
import { BasesLocalesService, Toponyme, ToponymesService } from "@/lib/openapi";
import { CommuneType } from "@/types/commune";
import LayoutContext from "@/contexts/layout";
import SelectCommune from "../select-commune";

interface ToponymeEditorProps {
initialValue?: Toponyme;
Expand All @@ -38,6 +39,9 @@ function ToponymeEditor({
onSubmitted,
}: ToponymeEditorProps) {
const [isLoading, setIsLoading] = useState(false);
const [communeDeleguee, setCommuneDeleguee] = useState(
initialValue ? initialValue.communeDeleguee : ""
);
const [nom, onNomChange, resetNom] = useInput(initialValue?.nom || "");
const { getValidationMessage, setValidationMessages } =
useValidationMessage();
Expand Down Expand Up @@ -65,6 +69,7 @@ function ToponymeEditor({
const body = {
nom,
nomAlt: Object.keys(nomAlt).length > 0 ? nomAlt : null,
communeDeleguee: communeDeleguee,
positions: [],
parcelles: selectedParcelles,
};
Expand Down Expand Up @@ -132,6 +137,7 @@ function ToponymeEditor({
initialValue,
nom,
nomAlt,
communeDeleguee,
markers,
selectedParcelles,
setToponyme,
Expand Down Expand Up @@ -186,6 +192,16 @@ function ToponymeEditor({
validationMessage={getValidationMessage("nom")}
/>

{commune.communesDeleguees && (
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

.length > 0 ?
J'ai un switch vide qui s'affiche
Capture d’écran 2024-11-12 à 10 12 19

<SelectCommune
communes={commune.communesDeleguees}
selectedCodeCommune={communeDeleguee}
setSelectedCodeCommune={setCommuneDeleguee}
withOptionNull={true}
label="Commune déléguée"
/>
)}

<LanguesRegionalesForm
initialValue={initialValue?.nomAlt}
validationMessage={getValidationMessage("lang_alt")}
Expand Down
21 changes: 20 additions & 1 deletion components/bal/voie-editor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,16 +24,20 @@ import {
VoiesService,
} from "@/lib/openapi";
import LayoutContext from "@/contexts/layout";
import { CommuneType } from "@/types/commune";
import SelectCommune from "../select-commune";

interface VoieEditorProps {
initialValue?: Voie;
commune: CommuneType;
closeForm: () => void;
formInputRef?: React.RefObject<HTMLDivElement>;
onSubmitted?: () => void;
}

function VoieEditor({
initialValue,
commune,
closeForm,
formInputRef,
onSubmitted,
Expand All @@ -43,6 +47,9 @@ function VoieEditor({
initialValue ? initialValue.typeNumerotation === "metrique" : false
);
const [nom, onNomChange] = useInput(initialValue ? initialValue.nom : "");
const [communeDeleguee, setCommuneDeleguee] = useState(
initialValue ? initialValue.communeDeleguee : ""
);
const { getValidationMessage, setValidationMessages } =
useValidationMessage();
const [nomAlt, setNomAlt] = useState(initialValue?.nomAlt);
Expand All @@ -65,9 +72,10 @@ function VoieEditor({
nom,
nomAlt: Object.keys(nomAlt).length > 0 ? nomAlt : null,
typeNumerotation: isMetric ? "metrique" : "numerique",
communeDeleguee: communeDeleguee,
trace: data ? data.geometry : null,
};

console.log(body);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

à supprimer

// Add or edit a voie
const submit = initialValue
? toaster(
Expand Down Expand Up @@ -124,6 +132,7 @@ function VoieEditor({
},
[
baseLocale.id,
communeDeleguee,
initialValue,
nom,
isMetric,
Expand Down Expand Up @@ -189,6 +198,16 @@ function VoieEditor({
validationMessage={getValidationMessage("nom")}
/>

{commune.communesDeleguees && (
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

même remarque

<SelectCommune
communes={commune.communesDeleguees}
selectedCodeCommune={communeDeleguee}
setSelectedCodeCommune={setCommuneDeleguee}
withOptionNull={true}
label="Commune déléguée"
/>
)}

<Checkbox
checked={isMetric}
label="Cette voie utilise la numérotation métrique"
Expand Down
13 changes: 9 additions & 4 deletions components/select-commune.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { CommuneType } from "@/types/commune";
import { Pane, Select } from "evergreen-ui";
import { Pane, Select, SelectField } from "evergreen-ui";

interface SelectCommuneProps {
communes: {
Expand All @@ -8,25 +7,31 @@ interface SelectCommuneProps {
}[];
selectedCodeCommune: string;
setSelectedCodeCommune: (code: string) => void;
withOptionNull?: boolean;
label?: string;
}

function SelectCommune({
communes,
selectedCodeCommune,
setSelectedCodeCommune,
withOptionNull = false,
label = null,
}: SelectCommuneProps) {
return (
<Pane marginTop={8}>
<Select
<SelectField
value={selectedCodeCommune}
onChange={(event) => setSelectedCodeCommune(event.target.value)}
label={label}
>
{withOptionNull && <option key="null" value={null}></option>}
{communes.map(({ code, nom }) => (
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

C'est bizarre de pouvoir sélectionner l'option vide? Je vois pas trop l'intéret à partir du moment où il y'a des communes déléguées, la voie et le toponyme doivent forcément pouvoir matcher avec une d'entre elles non?
Capture d’écran 2024-11-12 à 10 27 35

Nit : aussi pourquoi a-t-on besoin d'un select dédié aux communes, j'ai l'impression qu'un générique pourrait faire le taff

<option key={code} value={code}>
{nom} ({code})
</option>
))}
</Select>
</SelectField>
</Pane>
);
}
Expand Down
2 changes: 2 additions & 0 deletions components/signalement/voie/signalement-update-voie.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ function SignalementUpdateVoie({
existingLocation,
handleSubmit,
handleClose,
commune,
}: SignalementUpdateVoieProps) {
const { nom } = signalement.changesRequested;
const formInputRef = useRef<HTMLDivElement>(null);
Expand Down Expand Up @@ -52,6 +53,7 @@ function SignalementUpdateVoie({
<Pane position="relative" height="100%">
<VoieEditor
initialValue={editorValue}
commune={commune}
closeForm={handleClose}
formInputRef={formInputRef}
onSubmitted={handleSubmit}
Expand Down
10 changes: 8 additions & 2 deletions components/voie/voie-heading.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,14 @@ import BalDataContext from "@/contexts/bal-data";
import VoieEditor from "@/components/bal/voie-editor";
import LanguagePreview from "../bal/language-preview";
import { Voie } from "@/lib/openapi";
import { CommuneType } from "@/types/commune";

interface VoieHeadingProps {
commune: CommuneType;
voie: Voie;
}

function VoieHeading({ voie }: VoieHeadingProps) {
function VoieHeading({ commune, voie }: VoieHeadingProps) {
const [hovered, setHovered] = useState(false);
const [isFormOpen, setIsFormOpen] = useState(false);

Expand All @@ -34,7 +36,11 @@ function VoieHeading({ voie }: VoieHeadingProps) {

return isFormOpen ? (
<Pane background="tint1" padding={0}>
<VoieEditor initialValue={voie} closeForm={() => setIsFormOpen(false)} />
<VoieEditor
initialValue={voie}
commune={commune}
closeForm={() => setIsFormOpen(false)}
/>
</Pane>
) : (
<Pane display="flex" flexDirection="column" background="tint1" padding={16}>
Expand Down
13 changes: 12 additions & 1 deletion layouts/editor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,10 @@ import {
ExtendedVoieDTO,
ExtentedToponymeDTO,
} from "@/lib/openapi";
import { CommuneApiGeoType } from "@/lib/geo-api/type";
import {
CommuneApiGeoType,
CommuneDelegueeApiGeoType,
} from "@/lib/geo-api/type";
import { MobileControls } from "@/components/mobile-layout/mobile-controls";
import LayoutContext from "@/contexts/layout";

Expand Down Expand Up @@ -142,6 +145,14 @@ export async function getBaseEditorProps(
);

const commune: CommuneType = { ...geoCommune, ...communeExtras };

const communesDeleguees: CommuneDelegueeApiGeoType[] =
await ApiGeoService.getCommunesDeleguee();
commune.communesDeleguees = communesDeleguees.filter(
({ chefLieu, type }) =>
chefLieu === commune.code && type === "commune-deleguee"
);

const voies: ExtendedVoieDTO[] =
await BasesLocalesService.findBaseLocaleVoies(balId);
const toponymes: ExtentedToponymeDTO[] =
Expand Down
83 changes: 48 additions & 35 deletions lib/geo-api/index.ts
Original file line number Diff line number Diff line change
@@ -1,54 +1,67 @@
/* eslint no-restricted-imports: off */
import qs from 'querystring'
import {toaster} from 'evergreen-ui'
import { CommuneApiGeoType } from './type'
import qs from "querystring";
import { toaster } from "evergreen-ui";
import { CommuneApiGeoType, CommuneDelegueeApiGeoType } from "./type";

const GEO_API_URL = process.env.NEXT_PUBLIC_GEO_API_URL || 'https://geo.api.gouv.fr'
const GEO_API_URL =
process.env.NEXT_PUBLIC_GEO_API_URL || "https://geo.api.gouv.fr";

export class ApiGeoService {

private static async request(url: string) {
try {
const res = await fetch(`${GEO_API_URL}${url}`)
return res.json()
const res = await fetch(`${GEO_API_URL}${url}`);
return res.json();
} catch (error) {
toaster.danger('Erreur inattendue', {
description: error.message
})
toaster.danger("Erreur inattendue", {
description: error.message,
});
}
return null

return null;
}

private static isCodeDep(token: string) {
return ['2A', '2B'].includes(token) || token.match(/^\d{2,3}$/)
return ["2A", "2B"].includes(token) || token.match(/^\d{2,3}$/);
}

public static async searchCommunes(search: string, options = {}): Promise<CommuneApiGeoType[]> {

public static async searchCommunes(
search: string,
options = {}
): Promise<CommuneApiGeoType[]> {
const query: any = {
nom: search
}

const codeDep: string = search.split(' ').find(token => this.isCodeDep(token))
nom: search,
};

const codeDep: string = search
.split(" ")
.find((token) => this.isCodeDep(token));
if (codeDep) {
query.codeDepartement = codeDep
query.codeDepartement = codeDep;
}

const res = await this.request(`/communes?${qs.stringify({
...options,
...query
})}`)
return res || []
}

public static async getCommune(code: string, options = {}): Promise<CommuneApiGeoType> {
return this.request(`/communes/${code.toUpperCase()}?${qs.stringify(options)}`)
const res = await this.request(
`/communes?${qs.stringify({
...options,
...query,
})}`
);
return res || [];
}

}





public static async getCommune(
code: string,
options = {}
): Promise<CommuneApiGeoType> {
return this.request(
`/communes/${code.toUpperCase()}?${qs.stringify(options)}`
);
}

public static async getCommunesDeleguee(): Promise<
CommuneDelegueeApiGeoType[]
> {
return this.request(
`/communes_associees_deleguees?fields=nom,code,chefLieu,type`
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

On est obligé de récupérer toutes les communes déléguées de France et filtrer sur le chef lieu? Y'a pas moyen de passer un query param chefLieu à l'api géo?

);
}
}
7 changes: 7 additions & 0 deletions lib/geo-api/type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,10 @@ export type CommuneApiGeoType = {
siren?: string;
_score: number;
};

export type CommuneDelegueeApiGeoType = {
nom: string;
code: string;
chefLieu: string;
type: string;
};
1 change: 1 addition & 0 deletions lib/openapi/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ export { UpdateVoieDTO } from './models/UpdateVoieDTO';
export type { ValidatePinCodeDTO } from './models/ValidatePinCodeDTO';
export { Voie } from './models/Voie';

export { AdminService } from './services/AdminService';
export { BasesLocalesService } from './services/BasesLocalesService';
export { CommuneService } from './services/CommuneService';
export { ExportCsvService } from './services/ExportCsvService';
Expand Down
1 change: 1 addition & 0 deletions lib/openapi/models/CreateToponymeDTO.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import type { Position } from './Position';
export type CreateToponymeDTO = {
nom: string;
nomAlt?: Record<string, any> | null;
communeDeleguee?: string | null;
parcelles?: Array<string> | null;
positions?: Array<Position>;
};
Expand Down
1 change: 1 addition & 0 deletions lib/openapi/models/CreateVoieDTO.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import type { LineString } from './LineString';
export type CreateVoieDTO = {
nom: string;
nomAlt?: Record<string, any> | null;
communeDeleguee?: string | null;
typeNumerotation?: CreateVoieDTO.typeNumerotation;
trace?: LineString;
};
Expand Down
1 change: 1 addition & 0 deletions lib/openapi/models/ExtendedVoieDTO.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ export type ExtendedVoieDTO = {
balId: string;
nom: string;
nomAlt: Record<string, any>;
communeDeleguee: string;
typeNumerotation: ExtendedVoieDTO.typeNumerotation;
centroid: Record<string, any>;
trace: Record<string, any>;
Expand Down
1 change: 1 addition & 0 deletions lib/openapi/models/ExtentedToponymeDTO.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ export type ExtentedToponymeDTO = {
balId: string;
nom: string;
nomAlt: Record<string, any>;
communeDeleguee: string;
parcelles: Array<string>;
positions: Array<Position>;
baseLocale: BaseLocale;
Expand Down
1 change: 1 addition & 0 deletions lib/openapi/models/Toponyme.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ export type Toponyme = {
balId: string;
nom: string;
nomAlt: Record<string, any>;
communeDeleguee: string;
parcelles: Array<string>;
positions: Array<Position>;
baseLocale: BaseLocale;
Expand Down
Loading
Loading