Compare commits

..

10 Commits

65 changed files with 585 additions and 4088 deletions

239
.idea/workspace.xml generated
View File

@@ -4,10 +4,13 @@
<option name="autoReloadType" value="SELECTIVE" /> <option name="autoReloadType" value="SELECTIVE" />
</component> </component>
<component name="ChangeListManager"> <component name="ChangeListManager">
<list default="true" id="7c107abe-5995-4428-8429-b146aaca8386" name="Changes" comment="feat : front page admin bovin et changelog"> <list default="true" id="7c107abe-5995-4428-8429-b146aaca8386" name="Changes" comment="fix : correction du retour sur la liste des réceptions + suppression de la redirection après enregistrement">
<change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" /> <change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/config/reference.php" beforeDir="false" afterPath="$PROJECT_DIR$/config/reference.php" afterDir="false" /> <change beforePath="$PROJECT_DIR$/config/reference.php" beforeDir="false" afterPath="$PROJECT_DIR$/config/reference.php" afterDir="false" />
<change beforePath="$PROJECT_DIR$/frontend/components/commun/update-weight.vue" beforeDir="false" afterPath="$PROJECT_DIR$/frontend/components/commun/update-weight.vue" afterDir="false" /> <change beforePath="$PROJECT_DIR$/frontend/components/reception/update-bovin.vue" beforeDir="false" afterPath="$PROJECT_DIR$/frontend/components/reception/update-bovin.vue" afterDir="false" />
<change beforePath="$PROJECT_DIR$/frontend/components/reception/update-merchandise.vue" beforeDir="false" afterPath="$PROJECT_DIR$/frontend/components/reception/update-merchandise.vue" afterDir="false" />
<change beforePath="$PROJECT_DIR$/frontend/pages/reception/update/[[id]].vue" beforeDir="false" afterPath="$PROJECT_DIR$/frontend/pages/reception/update/[[id]].vue" afterDir="false" />
<change beforePath="$PROJECT_DIR$/frontend/services/dto/reception-data.ts" beforeDir="false" afterPath="$PROJECT_DIR$/frontend/services/dto/reception-data.ts" afterDir="false" />
</list> </list>
<option name="SHOW_DIALOG" value="false" /> <option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" /> <option name="HIGHLIGHT_CONFLICTS" value="true" />
@@ -30,16 +33,16 @@
<component name="FileTemplateManagerImpl"> <component name="FileTemplateManagerImpl">
<option name="RECENT_TEMPLATES"> <option name="RECENT_TEMPLATES">
<list> <list>
<option value="Vue Composition API Component" />
<option value="TypeScript File" /> <option value="TypeScript File" />
<option value="PHP File" /> <option value="PHP File" />
<option value="Vue Composition API Component" />
</list> </list>
</option> </option>
</component> </component>
<component name="Git.Settings"> <component name="Git.Settings">
<option name="RECENT_BRANCH_BY_REPOSITORY"> <option name="RECENT_BRANCH_BY_REPOSITORY">
<map> <map>
<entry key="$PROJECT_DIR$" value="feat/327-voir-modifier-une-expedition-terminee" /> <entry key="$PROJECT_DIR$" value="develop" />
</map> </map>
</option> </option>
<option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$" /> <option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$" />
@@ -230,8 +233,8 @@
"RunOnceActivity.TerminalTabsStorage.copyFrom.TerminalArrangementManager.252": "true", "RunOnceActivity.TerminalTabsStorage.copyFrom.TerminalArrangementManager.252": "true",
"RunOnceActivity.git.unshallow": "true", "RunOnceActivity.git.unshallow": "true",
"RunOnceActivity.typescript.service.memoryLimit.init": "true", "RunOnceActivity.typescript.service.memoryLimit.init": "true",
"git-widget-placeholder": "develop", "git-widget-placeholder": "feat/332-refonte-reception-terminee",
"last_opened_file_path": "/home/sroy/Documents/test/Ferme/frontend/components/commun", "last_opened_file_path": "//wsl.localhost/Ubuntu-24.04/home/kevin/Stage/Ferme/frontend/pages/shipment",
"node.js.detected.package.eslint": "true", "node.js.detected.package.eslint": "true",
"node.js.detected.package.tslint": "true", "node.js.detected.package.tslint": "true",
"node.js.selected.package.eslint": "(autodetect)", "node.js.selected.package.eslint": "(autodetect)",
@@ -255,8 +258,6 @@
}]]></component> }]]></component>
<component name="RecentsManager"> <component name="RecentsManager">
<key name="CopyFile.RECENT_KEYS"> <key name="CopyFile.RECENT_KEYS">
<recent name="$PROJECT_DIR$/frontend/components/commun" />
<recent name="\\wsl.localhost\Ubuntu-24.04\home\m-tristan\workspace\Ferme" />
<recent name="\\wsl.localhost\Ubuntu-24.04\home\kevin\Stage\Ferme\frontend\pages\shipment" /> <recent name="\\wsl.localhost\Ubuntu-24.04\home\kevin\Stage\Ferme\frontend\pages\shipment" />
<recent name="\\wsl.localhost\Ubuntu-24.04\home\kevin\Stage\Ferme\frontend\composables" /> <recent name="\\wsl.localhost\Ubuntu-24.04\home\kevin\Stage\Ferme\frontend\composables" />
<recent name="\\wsl.localhost\Ubuntu-24.04\home\kevin\Stage\Ferme\frontend\components\shipment" /> <recent name="\\wsl.localhost\Ubuntu-24.04\home\kevin\Stage\Ferme\frontend\components\shipment" />
@@ -311,6 +312,102 @@
<workItem from="1770966186589" duration="914000" /> <workItem from="1770966186589" duration="914000" />
<workItem from="1770967274060" duration="2388000" /> <workItem from="1770967274060" duration="2388000" />
</task> </task>
<task id="LOCAL-00008" summary="feat : ajout de la génération du bon de reception, correction de la base du formulaire multi-etape de reception et ajout d'une gestion d'erreur global">
<option name="closed" value="true" />
<created>1768498751836</created>
<option name="number" value="00008" />
<option name="presentableId" value="LOCAL-00008" />
<option name="project" value="LOCAL" />
<updated>1768498751836</updated>
</task>
<task id="LOCAL-00009" summary="feat : ajout d'une gestion d'erreur au global côté front avec la lib toaster et I18n pour centraliser les messages d'erreur">
<option name="closed" value="true" />
<created>1768555180530</created>
<option name="number" value="00009" />
<option name="presentableId" value="LOCAL-00009" />
<option name="project" value="LOCAL" />
<updated>1768555180530</updated>
</task>
<task id="LOCAL-00010" summary="feat : ajout de l'authentification avec lexik">
<option name="closed" value="true" />
<created>1768832208350</created>
<option name="number" value="00010" />
<option name="presentableId" value="LOCAL-00010" />
<option name="project" value="LOCAL" />
<updated>1768832208350</updated>
</task>
<task id="LOCAL-00011" summary="feat : update du CHANGELOG.md">
<option name="closed" value="true" />
<created>1768832516587</created>
<option name="number" value="00011" />
<option name="presentableId" value="LOCAL-00011" />
<option name="project" value="LOCAL" />
<updated>1768832516587</updated>
</task>
<task id="LOCAL-00012" summary="fix : correction de l'accès au swagger en mode dev qui n'était plus accessible">
<option name="closed" value="true" />
<created>1768940104944</created>
<option name="number" value="00012" />
<option name="presentableId" value="LOCAL-00012" />
<option name="project" value="LOCAL" />
<updated>1768940104944</updated>
</task>
<task id="LOCAL-00013" summary="feat : ajout de la conf pour le déploiement en recette">
<option name="closed" value="true" />
<created>1769005220331</created>
<option name="number" value="00013" />
<option name="presentableId" value="LOCAL-00013" />
<option name="project" value="LOCAL" />
<updated>1769005220331</updated>
</task>
<task id="LOCAL-00014" summary="fix : fix de la conf pour le déploiement en recette">
<option name="closed" value="true" />
<created>1769008700008</created>
<option name="number" value="00014" />
<option name="presentableId" value="LOCAL-00014" />
<option name="project" value="LOCAL" />
<updated>1769008700008</updated>
</task>
<task id="LOCAL-00015" summary="fix : fix de la conf pour le déploiement en recette">
<option name="closed" value="true" />
<created>1769014602062</created>
<option name="number" value="00015" />
<option name="presentableId" value="LOCAL-00015" />
<option name="project" value="LOCAL" />
<updated>1769014602062</updated>
</task>
<task id="LOCAL-00016" summary="fix : migration apache vers nginx pour un déploiement plus simple">
<option name="closed" value="true" />
<created>1769019284586</created>
<option name="number" value="00016" />
<option name="presentableId" value="LOCAL-00016" />
<option name="project" value="LOCAL" />
<updated>1769019284586</updated>
</task>
<task id="LOCAL-00017" summary="fix : dernière modification pour le déploiement en recette et le changement de conf vers nginx">
<option name="closed" value="true" />
<created>1769021756823</created>
<option name="number" value="00017" />
<option name="presentableId" value="LOCAL-00017" />
<option name="project" value="LOCAL" />
<updated>1769021756823</updated>
</task>
<task id="LOCAL-00018" summary="ci : auto tag + release artefact">
<option name="closed" value="true" />
<created>1769021818384</created>
<option name="number" value="00018" />
<option name="presentableId" value="LOCAL-00018" />
<option name="project" value="LOCAL" />
<updated>1769021818384</updated>
</task>
<task id="LOCAL-00019" summary="ci : fix release artefact">
<option name="closed" value="true" />
<created>1769022071620</created>
<option name="number" value="00019" />
<option name="presentableId" value="LOCAL-00019" />
<option name="project" value="LOCAL" />
<updated>1769022071620</updated>
</task>
<task id="LOCAL-00020" summary="ci : fix release artefact"> <task id="LOCAL-00020" summary="ci : fix release artefact">
<option name="closed" value="true" /> <option name="closed" value="true" />
<created>1769024603812</created> <created>1769024603812</created>
@@ -599,111 +696,15 @@
<option name="project" value="LOCAL" /> <option name="project" value="LOCAL" />
<updated>1770969471135</updated> <updated>1770969471135</updated>
</task> </task>
<task id="LOCAL-00056" summary="fix : corrections frontend"> <task id="LOCAL-00056" summary="fix : correction du retour sur la liste des réceptions + suppression de la redirection après enregistrement">
<option name="closed" value="true" /> <option name="closed" value="true" />
<created>1772094268366</created> <created>1772008192160</created>
<option name="number" value="00056" /> <option name="number" value="00056" />
<option name="presentableId" value="LOCAL-00056" /> <option name="presentableId" value="LOCAL-00056" />
<option name="project" value="LOCAL" /> <option name="project" value="LOCAL" />
<updated>1772094268366</updated> <updated>1772008192161</updated>
</task> </task>
<task id="LOCAL-00057" summary="feat : affichage et modification expédition et modification bouton valider"> <option name="localTasksCounter" value="57" />
<option name="closed" value="true" />
<created>1772111964268</created>
<option name="number" value="00057" />
<option name="presentableId" value="LOCAL-00057" />
<option name="project" value="LOCAL" />
<updated>1772111964268</updated>
</task>
<task id="LOCAL-00058" summary="fix : erreur customer adress et bouton valider oublie">
<option name="closed" value="true" />
<created>1772112729501</created>
<option name="number" value="00058" />
<option name="presentableId" value="LOCAL-00058" />
<option name="project" value="LOCAL" />
<updated>1772112729502</updated>
</task>
<task id="LOCAL-00059" summary="feat : changelog update">
<option name="closed" value="true" />
<created>1772112812677</created>
<option name="number" value="00059" />
<option name="presentableId" value="LOCAL-00059" />
<option name="project" value="LOCAL" />
<updated>1772112812677</updated>
</task>
<task id="LOCAL-00060" summary="feat : changelog update">
<option name="closed" value="true" />
<created>1772177400063</created>
<option name="number" value="00060" />
<option name="presentableId" value="LOCAL-00060" />
<option name="project" value="LOCAL" />
<updated>1772177400063</updated>
</task>
<task id="LOCAL-00061" summary="feat : changelog update">
<option name="closed" value="true" />
<created>1772177614438</created>
<option name="number" value="00061" />
<option name="presentableId" value="LOCAL-00061" />
<option name="project" value="LOCAL" />
<updated>1772177614438</updated>
</task>
<task id="LOCAL-00062" summary="fix : color tab">
<option name="closed" value="true" />
<created>1772178540489</created>
<option name="number" value="00062" />
<option name="presentableId" value="LOCAL-00062" />
<option name="project" value="LOCAL" />
<updated>1772178540489</updated>
</task>
<task id="LOCAL-00063" summary="feat : modification front de la page admin transporteur">
<option name="closed" value="true" />
<created>1772180053740</created>
<option name="number" value="00063" />
<option name="presentableId" value="LOCAL-00063" />
<option name="project" value="LOCAL" />
<updated>1772180053740</updated>
</task>
<task id="LOCAL-00064" summary="fix : espacement et changelog">
<option name="closed" value="true" />
<created>1772180581178</created>
<option name="number" value="00064" />
<option name="presentableId" value="LOCAL-00064" />
<option name="project" value="LOCAL" />
<updated>1772180581178</updated>
</task>
<task id="LOCAL-00065" summary="fix : espacement">
<option name="closed" value="true" />
<created>1772180684250</created>
<option name="number" value="00065" />
<option name="presentableId" value="LOCAL-00065" />
<option name="project" value="LOCAL" />
<updated>1772180684250</updated>
</task>
<task id="LOCAL-00066" summary="fix : espacement">
<option name="closed" value="true" />
<created>1772180972984</created>
<option name="number" value="00066" />
<option name="presentableId" value="LOCAL-00066" />
<option name="project" value="LOCAL" />
<updated>1772180972984</updated>
</task>
<task id="LOCAL-00067" summary="fix : text">
<option name="closed" value="true" />
<created>1772182545592</created>
<option name="number" value="00067" />
<option name="presentableId" value="LOCAL-00067" />
<option name="project" value="LOCAL" />
<updated>1772182545592</updated>
</task>
<task id="LOCAL-00068" summary="feat : front page admin bovin et changelog">
<option name="closed" value="true" />
<created>1772182707441</created>
<option name="number" value="00068" />
<option name="presentableId" value="LOCAL-00068" />
<option name="project" value="LOCAL" />
<updated>1772182707441</updated>
</task>
<option name="localTasksCounter" value="69" />
<servers /> <servers />
</component> </component>
<component name="TypeScriptGeneratedFilesManager"> <component name="TypeScriptGeneratedFilesManager">
@@ -753,6 +754,15 @@
</option> </option>
</component> </component>
<component name="VcsManagerConfiguration"> <component name="VcsManagerConfiguration">
<MESSAGE value="fix : script de déploiement" />
<MESSAGE value="feat : ajout plus d'information sur la liste des réceptions côté front sur la page d'accueil" />
<MESSAGE value="fix : redirige sur le login sur une 401 et reset du auth state + doc + timeout du toaster" />
<MESSAGE value="feat : ajout de la debug bar en mod dev" />
<MESSAGE value="feat : ajout du bundle Malio ednotif pour l'utilisation des WS" />
<MESSAGE value="fix : modification de la conf du bundle ednotif" />
<MESSAGE value="feat : update du CHANGELOG.md" />
<MESSAGE value="feat : finalisation de l'étape 1 &quot;Réception&quot; (formulaire)" />
<MESSAGE value="feat : ajout du numéro identification des receptions et ajustement du bon de reception" />
<MESSAGE value="feat : ajout de la partie reception des marchandises (étape 3) et modification du bon de réception" /> <MESSAGE value="feat : ajout de la partie reception des marchandises (étape 3) et modification du bon de réception" />
<MESSAGE value="feat : mise en place de composant UI pour les select, checkbox, date, text" /> <MESSAGE value="feat : mise en place de composant UI pour les select, checkbox, date, text" />
<MESSAGE value="feat : update CHANGELOG.md" /> <MESSAGE value="feat : update CHANGELOG.md" />
@@ -768,17 +778,8 @@
<MESSAGE value="feat : lister les expeditions terminees" /> <MESSAGE value="feat : lister les expeditions terminees" />
<MESSAGE value="fix: corrections diverses" /> <MESSAGE value="fix: corrections diverses" />
<MESSAGE value="fix : corrections diverses" /> <MESSAGE value="fix : corrections diverses" />
<MESSAGE value="fix : corrections frontend" /> <MESSAGE value="fix : correction du retour sur la liste des réceptions + suppression de la redirection après enregistrement" />
<MESSAGE value="feat : affichage et modification expédition et modification bouton valider" /> <option name="LAST_COMMIT_MESSAGE" value="fix : correction du retour sur la liste des réceptions + suppression de la redirection après enregistrement" />
<MESSAGE value="fix : erreur customer adress et bouton valider oublie" />
<MESSAGE value="feat : changelog update" />
<MESSAGE value="fix : color tab" />
<MESSAGE value="feat : modification front de la page admin transporteur" />
<MESSAGE value="fix : espacement et changelog" />
<MESSAGE value="fix : espacement" />
<MESSAGE value="fix : text" />
<MESSAGE value="feat : front page admin bovin et changelog" />
<option name="LAST_COMMIT_MESSAGE" value="feat : front page admin bovin et changelog" />
</component> </component>
<component name="XDebuggerManager"> <component name="XDebuggerManager">
<breakpoint-manager> <breakpoint-manager>

View File

@@ -8,7 +8,6 @@ Project overview
Backend conventions Backend conventions
- Use English for code identifiers/messages; keep “pont-bascule” as domain term. - Use English for code identifiers/messages; keep “pont-bascule” as domain term.
- API Platform operations are defined on Doctrine entities. - API Platform operations are defined on Doctrine entities.
- No custom repository classes are used (`src/Repository` removed); use default Doctrine repositories via `EntityManagerInterface`.
- Reception entity is in `src/Entity/Reception.php`, with custom weigh endpoint `/receptions/weigh`. - Reception entity is in `src/Entity/Reception.php`, with custom weigh endpoint `/receptions/weigh`.
- Reception fields: `date_reception`, `license_plate`, `current_step` (default 0), `is_valid` (default false). - Reception fields: `date_reception`, `license_plate`, `current_step` (default 0), `is_valid` (default false).
- Reception also has `identification_number` (auto `N-BR-####`), `merchandise_type`, `merchandise_detail`, `buildings` (M2M), and `pellet_buildings` (via `reception_pellet_building`). - Reception also has `identification_number` (auto `N-BR-####`), `merchandise_type`, `merchandise_detail`, `buildings` (M2M), and `pellet_buildings` (via `reception_pellet_building`).
@@ -18,13 +17,6 @@ Backend conventions
- Custom exception: `App\Exception\PontBasculeException` with French messages, mapped to 500 in provider. - Custom exception: `App\Exception\PontBasculeException` with French messages, mapped to 500 in provider.
- Parsing of pont-bascule payload is in `src/Service/PontBasculePayloadDecoder.php`. - Parsing of pont-bascule payload is in `src/Service/PontBasculePayloadDecoder.php`.
- `config/reference.php` is auto-generated; keep it. - `config/reference.php` is auto-generated; keep it.
- Bovine storage:
- `src/Entity/Bovine.php` with fields `nationalNumber` (unique), `receivedWeight`, `arrivalDate`, and `buildingCase` (ManyToOne).
- `src/Entity/BuildingCase.php` has `bovines` (OneToMany).
- Case PDF report:
- Endpoint: `GET /building_cases/{id}/weights-report` (provider: `App\State\BuildingCaseWeightsReportProvider`).
- Template: `templates/case_weights_report.html.twig`.
- Projection logic is done in backend from `arrivalDate`; daily gain is currently fixed at `1.3 kg/day` for all races.
Frontend conventions Frontend conventions
- Nuxt SSR disabled; Tailwind used. - Nuxt SSR disabled; Tailwind used.
@@ -44,7 +36,6 @@ Frontend conventions
- Service layer lives in `frontend/services/` with typed DTOs in `frontend/services/dto/`. - Service layer lives in `frontend/services/` with typed DTOs in `frontend/services/dto/`.
- Reception service uses `receptions`, `receptions/{id}`, `receptions/weigh` and supports success/error toast keys. - Reception service uses `receptions`, `receptions/{id}`, `receptions/weigh` and supports success/error toast keys.
- Reception receipt endpoint is `receptions/{id}/receipt` (PDF) via `frontend/composables/usePdfPrinter.ts`. - Reception receipt endpoint is `receptions/{id}/receipt` (PDF) via `frontend/composables/usePdfPrinter.ts`.
- Infrastructure case page prints the case weight report PDF from `frontend/pages/infrastructure/case.vue` using `usePdfPrinter('/building_cases/{id}/weights-report')`.
Environment & routing Environment & routing
- Frontend dev server: `npm run dev` in `frontend/`. - Frontend dev server: `npm run dev` in `frontend/`.
@@ -56,11 +47,6 @@ Environment & routing
Notes Notes
- Do not add a GET that creates resources; use POST + PATCH. - Do not add a GET that creates resources; use POST + PATCH.
- Keep endpoints in plural (API Platform convention). - Keep endpoints in plural (API Platform convention).
- Seed and fixtures conventions:
- `app:seed` now seeds infrastructure (`statut`, `building_layout`, `building_case`, `building_case_position`) and bovines.
- `app:seed` uses intermediate flushes (after buildings and after infrastructure) so find queries can resolve just-created records.
- Bovine seed rows use a legacy case token mapping to building-case code (`B{building}-C{case}`) before fallback to direct id lookup.
- Fixtures include `BuildingInfrastructureFixtures` + `BovineFixtures` (via `AppFixtures` dependencies).
- New reference data added: - New reference data added:
- Reception types (`reception_type`, fields: `label`, `code`), selectable on reception form. - Reception types (`reception_type`, fields: `label`, `code`), selectable on reception form.
- Merchandise types (`merchandise_type`, fields: `label`, `code`) and pellet types (`pellet_type`, fields: `label`, `code`). - Merchandise types (`merchandise_type`, fields: `label`, `code`) and pellet types (`pellet_type`, fields: `label`, `code`).

View File

@@ -50,16 +50,7 @@ Ajouter dans le fichier .env du frontend
* Creation page admin listing bovins * Creation page admin listing bovins
* Creation page admin ajout/modification bovins * Creation page admin ajout/modification bovins
* [#331] Mettre à jour l'entité Shipment et bovin_shipment * [#331] Mettre à jour l'entité Shipment et bovin_shipment
* [#278] Plan du site
* [#334] Correctifs
* [#332] Refonte écran réception terminée * [#332] Refonte écran réception terminée
* [#327] afficher/modifier écran expédition terminée
* [#352] modification front admin fournisseur
* [#355] modification front admin transporteur
* [#356] front page admin bovin
* [#353] modification front admin client
* [#353] modification front admin utilisateur
### Changed ### Changed
### Fixed ### Fixed

View File

@@ -1,2 +1,2 @@
parameters: parameters:
app.version: '0.0.68' app.version: '0.0.52'

View File

@@ -1,36 +1,34 @@
<template> <template>
<form @submit.prevent="validateForm"> <form @submit.prevent="validateForm">
<div class="flex items-center mb-11 justify-between relative"> <div class="flex items-center justify-between gap-10">
<div class="flex flex-row absolute -left-[60px] "> <div>
<Icon @click="goBack" name="gg:arrow-left-o" size="40" class="cursor-pointer text-primary-500"/> <h1 class="text-3xl font-bold uppercase">
{{ props.address ? "Modification d'une adresse" : "Ajout d'une adresse" }}
</h1>
</div> </div>
<h1 class="text-3xl text-primary-500 font-bold uppercase">
{{ props.address ? "Modification d'une adresse" : "Ajout d'une adresse" }} <button
</h1> class="text-xl uppercase bg-primary-500 text-white h-[50px] w-[272px]"
type="submit"
:disabled="isLoading"
>
{{ props.address? "Sauvegarder" : "Ajouter" }}
</button>
</div> </div>
<div class="grid grid-cols-2 gap-y-16 gap-x-[200px] mb-16"> <div class="grid grid-cols-2 gap-y-16 gap-x-12 mb-16 mt-10">
<UiTextInput id="address-label" v-model="form.label" label="Libellé" /> <UiTextInput id="address-label" v-model="form.label" label="Libellé" />
<UiTextInput id="address-street" v-model="form.street" label="Rue" /> <UiTextInput id="address-street" v-model="form.street" label="Rue" />
<UiTextInput id="address-street2" v-model="form.street2" label="Complément" /> <UiTextInput id="address-street2" v-model="form.street2" label="Complément" />
<UiTextInput id="address-postalCode" v-model="form.postalCode" label="Code postal" /> <UiTextInput id="address-postalCode" v-model="form.postalCode" label="Code postal" />
<UiTextInput id="address-city" v-model="form.city" label="Ville" /> <UiTextInput id="address-city" v-model="form.city" label="Ville" />
<UiTextInput id="address-country" v-model="form.countryCode" label="Pays (code)" /> <UiTextInput id="address-country" v-model="form.countryCode" label="Pays" />
</div>
<div class="flex justify-center items-center">
<UiButton
class="inline-flex items-center justify-center text-xl text-white uppercase bg-primary-500 h-[50px] rounded hover:opacity-80 justify-self-end"
type="submit"
:disabled="isLoading"
>
Valider
</UiButton>
</div> </div>
</form> </form>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import type { AddressPayload } from "~/services/address" import { AddressPayload } from "~/services/address"
const route = useRoute() const route = useRoute()
@@ -54,20 +52,6 @@ const emptyForm = (): AddressPayload => ({
const form = reactive<AddressPayload>(emptyForm()) const form = reactive<AddressPayload>(emptyForm())
const backPath = computed(() => {
if (props.type === "customer") {
const customerId = Number(route.query.customerId)
return Number.isFinite(customerId) && customerId > 0
? `/admin/customer/${customerId}`
: "/admin/customer/customer-list"
}
const supplierId = Number(route.query.supplierId)
return Number.isFinite(supplierId) && supplierId > 0
? `/admin/supplier/${supplierId}`
: "/admin/supplier/supplier-list"
})
const hydrateForm = (address?: AddressPayload | null) => { const hydrateForm = (address?: AddressPayload | null) => {
const data = address ?? emptyForm() const data = address ?? emptyForm()
form.label = data.label ?? "" form.label = data.label ?? ""
@@ -91,10 +75,6 @@ const validateForm = () => {
emit("validate", {...form}) emit("validate", {...form})
} }
const goBack = () => {
router.push(backPath.value)
}
const emit = defineEmits<{ const emit = defineEmits<{
(event: 'validate', form: AddressPayload): void (event: 'validate', form: AddressPayload): void
}>() }>()

View File

@@ -31,14 +31,11 @@
/> />
</div> </div>
</div> </div>
<div class="flex justify-center"> <button
<UiButton class="text-xl uppercase bg-primary-500 text-white h-[50px] w-[272px]"
type="submit" @click="goNext"
class="text-xl uppercase bg-primary-500 text-white h-[50px] w-[272px] justify-self-end" >Valider
@click="goNext" </button>
>Valider
</UiButton>
</div>
</div> </div>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">

View File

@@ -64,14 +64,11 @@
</div> </div>
</div> </div>
</div> </div>
<div class="flex justify-center"> <button
<UiButton class="text-xl uppercase bg-primary-500 text-white h-[50px] w-[272px]"
type="submit" @click="goNext"
class="text-xl uppercase bg-primary-500 text-white h-[50px] w-[272px] justify-self-end" >Valider
@click="goNext" </button>
>Valider
</UiButton>
</div>
</div> </div>
</template> </template>

View File

@@ -14,7 +14,6 @@
:min="0" :min="0"
:max="10" :max="10"
wrapperClass="w-44 flex-col" wrapperClass="w-44 flex-col"
inputClass="font-medium"
/> />
</div> </div>
<UiNumberInput <UiNumberInput
@@ -22,7 +21,6 @@
v-model="localOtherQuantity" v-model="localOtherQuantity"
:disabled="!isAdmin" :disabled="!isAdmin"
wrapperClass="w-44 flex-col" wrapperClass="w-44 flex-col"
inputClass="font-medium"
/> />
</div> </div>
</form> </form>
@@ -48,38 +46,8 @@ const emit = defineEmits<{
const bovineTypes = ref<BovineTypeData[]>([]) const bovineTypes = ref<BovineTypeData[]>([])
const localQuantities = reactive<Record<string, number | null>>({}) const localQuantities = reactive<Record<string, number | null>>({})
const localOtherQuantity = ref<number | null>(props.otherQuantity ?? 0) const localOtherQuantity = ref<number | null>(props.otherQuantity ?? 0)
// Verrou pour éviter les boucles props -> local -> emit -> props.
const isSyncing = ref(false) const isSyncing = ref(false)
function entriesEqualByTypeAndQuantity(
left: ReceptionBovineTypeData[],
right: ReceptionBovineTypeData[]
): boolean {
const toMap = (entries: ReceptionBovineTypeData[]) => {
const map = new Map<number, number>()
for (const entry of entries) {
const typeId = entry.bovineType?.id ?? 0
map.set(typeId, entry.quantity ?? 0)
}
return map
}
const a = toMap(left)
const b = toMap(right)
if (a.size !== b.size) {
return false
}
for (const [typeId, quantity] of a.entries()) {
if ((b.get(typeId) ?? 0) !== quantity) {
return false
}
}
return true
}
function buildEntriesFromLocal(): ReceptionBovineTypeData[] { function buildEntriesFromLocal(): ReceptionBovineTypeData[] {
return bovineTypes.value.map((type) => { return bovineTypes.value.map((type) => {
const existing = props.modelValue.find((entry) => entry.bovineType.id === type.id) const existing = props.modelValue.find((entry) => entry.bovineType.id === type.id)
@@ -110,33 +78,20 @@ function syncLocalFromProps() {
watch( watch(
() => props.otherQuantity, () => props.otherQuantity,
(value) => { (value) => {
if (isSyncing.value) { localOtherQuantity.value = value ?? 0
return
}
const next = value ?? 0
isSyncing.value = true
localOtherQuantity.value = next
isSyncing.value = false
} }
) )
watch(localOtherQuantity, (value) => { watch(localOtherQuantity, (value) => {
if (isSyncing.value) { emit('update:otherQuantity', value ?? 0)
return
}
const next = value ?? 0
emit('update:otherQuantity', next)
}) })
watch( watch(
() => props.modelValue, () => props.modelValue,
() => { () => {
// Hydratation locale uniquement quand le parent change.
syncLocalFromProps() syncLocalFromProps()
}, },
{ immediate: true } { deep: true }
) )
watch( watch(
@@ -145,11 +100,7 @@ watch(
if (isSyncing.value) { if (isSyncing.value) {
return return
} }
// N'émet que si les quantités diffèrent réellement du parent. emit('update:modelValue', buildEntriesFromLocal())
const nextEntries = buildEntriesFromLocal()
if (!entriesEqualByTypeAndQuantity(nextEntries, props.modelValue)) {
emit('update:modelValue', nextEntries)
}
}, },
{ deep: true } { deep: true }
) )
@@ -157,5 +108,6 @@ watch(
onMounted(async () => { onMounted(async () => {
bovineTypes.value = await getBovineTypeList() bovineTypes.value = await getBovineTypeList()
syncLocalFromProps() syncLocalFromProps()
emit('update:modelValue', buildEntriesFromLocal())
}) })
</script> </script>

View File

@@ -109,8 +109,7 @@ const selectedMerchandiseTypeId = ref('')
const selectedBuildingIds = ref<string[]>([]) const selectedBuildingIds = ref<string[]>([])
const selectedPelletBuildingIds = ref<Record<string, string[]>>({}) const selectedPelletBuildingIds = ref<Record<string, string[]>>({})
const merchandiseDetail = ref('') const merchandiseDetail = ref('')
// Verrou de synchro pour empêcher les aller-retours infinis entre parent et composant. const isHydrating = ref(false)
const isSyncing = ref(false)
const isReady = ref(false) const isReady = ref(false)
const selectedMerchandiseType = computed(() => const selectedMerchandiseType = computed(() =>
@@ -131,39 +130,6 @@ function clonePelletSelections(value: Record<string, string[]>) {
return clone return clone
} }
function sorted(values: string[]): string[] {
return [...values].sort()
}
function normalizeModel(value: MerchandiseEntryData): MerchandiseEntryData {
// Normalisation stable pour comparer deux modèles sans faux positifs (ordre des tableaux).
const pellet: Record<string, string[]> = {}
const pelletKeys = Object.keys(value.selectedPelletBuildingIds ?? {}).sort()
for (const key of pelletKeys) {
pellet[key] = sorted(value.selectedPelletBuildingIds[key] ?? [])
}
return {
merchandiseTypeId: value.merchandiseTypeId ?? '',
merchandiseDetail: value.merchandiseDetail ?? '',
selectedBuildingIds: sorted(value.selectedBuildingIds ?? []),
selectedPelletBuildingIds: pellet
}
}
function buildCurrentModel(): MerchandiseEntryData {
return {
merchandiseTypeId: selectedMerchandiseTypeId.value,
merchandiseDetail: merchandiseDetail.value,
selectedBuildingIds: [...selectedBuildingIds.value],
selectedPelletBuildingIds: clonePelletSelections(selectedPelletBuildingIds.value)
}
}
function isSameModel(left: MerchandiseEntryData, right: MerchandiseEntryData): boolean {
return JSON.stringify(normalizeModel(left)) === JSON.stringify(normalizeModel(right))
}
function ensurePelletKeys() { function ensurePelletKeys() {
for (const pelletType of pelletTypes.value) { for (const pelletType of pelletTypes.value) {
const key = String(pelletType.id) const key = String(pelletType.id)
@@ -174,7 +140,7 @@ function ensurePelletKeys() {
} }
function hydrateFromModelValue(value: MerchandiseEntryData) { function hydrateFromModelValue(value: MerchandiseEntryData) {
isSyncing.value = true isHydrating.value = true
try { try {
selectedMerchandiseTypeId.value = value.merchandiseTypeId ?? '' selectedMerchandiseTypeId.value = value.merchandiseTypeId ?? ''
merchandiseDetail.value = value.merchandiseDetail ?? '' merchandiseDetail.value = value.merchandiseDetail ?? ''
@@ -184,71 +150,51 @@ function hydrateFromModelValue(value: MerchandiseEntryData) {
) )
ensurePelletKeys() ensurePelletKeys()
} finally { } finally {
isSyncing.value = false isHydrating.value = false
} }
} }
function sanitizeLocalState() { function emitModelValue() {
if (isGranule.value) { emit('update:modelValue', {
if (selectedBuildingIds.value.length > 0) { merchandiseTypeId: selectedMerchandiseTypeId.value,
selectedBuildingIds.value = [] merchandiseDetail: merchandiseDetail.value,
} selectedBuildingIds: [...selectedBuildingIds.value],
} else { selectedPelletBuildingIds: clonePelletSelections(selectedPelletBuildingIds.value)
for (const key of Object.keys(selectedPelletBuildingIds.value)) { })
if (selectedPelletBuildingIds.value[key].length > 0) {
selectedPelletBuildingIds.value[key] = []
}
}
}
if (!isAutres.value && merchandiseDetail.value !== '') {
merchandiseDetail.value = ''
}
}
function emitCurrentModel() {
const currentModel = buildCurrentModel()
// Ne pas réémettre si rien n'a changé côté métier.
if (isSameModel(currentModel, props.modelValue)) {
return
}
emit('update:modelValue', currentModel)
} }
watch( watch(
() => props.modelValue, () => props.modelValue,
(value) => { (value) => {
const currentModel = buildCurrentModel()
// Si local == parent, on ignore pour éviter la boucle de réhydratation.
if (isSameModel(currentModel, value)) {
return
}
hydrateFromModelValue(value) hydrateFromModelValue(value)
}, },
{ immediate: true } { deep: true }
) )
watch( watch(
[selectedMerchandiseTypeId, selectedBuildingIds, selectedPelletBuildingIds, merchandiseDetail], [selectedMerchandiseTypeId, selectedBuildingIds, selectedPelletBuildingIds, merchandiseDetail],
() => { () => {
if (isSyncing.value || !isReady.value) { if (isHydrating.value || !isReady.value) {
return return
} }
const beforeSanitize = buildCurrentModel() if (isGranule.value) {
isSyncing.value = true if (selectedBuildingIds.value.length > 0) {
// Applique les règles métier (granulé / autres) avant émission. selectedBuildingIds.value = []
sanitizeLocalState() }
isSyncing.value = false } else {
for (const key of Object.keys(selectedPelletBuildingIds.value)) {
const afterSanitize = buildCurrentModel() if (selectedPelletBuildingIds.value[key].length > 0) {
// Si la sanitation a modifié l'état, on laisse le watcher repasser proprement. selectedPelletBuildingIds.value[key] = []
if (!isSameModel(beforeSanitize, afterSanitize)) { }
return }
} }
emitCurrentModel() if (!isAutres.value && merchandiseDetail.value !== '') {
merchandiseDetail.value = ''
}
emitModelValue()
}, },
{ deep: true } { deep: true }
) )
@@ -265,5 +211,6 @@ onMounted(async () => {
hydrateFromModelValue(props.modelValue) hydrateFromModelValue(props.modelValue)
isReady.value = true isReady.value = true
emitModelValue()
}) })
</script> </script>

View File

@@ -8,11 +8,12 @@
v-model="localWeight.weight" v-model="localWeight.weight"
:disabled="!isAdmin" :disabled="!isAdmin"
:min="0" :min="0"
:max="48000"
wrapper-class="flex-col" wrapper-class="flex-col"
/> />
<UiDateInput <UiDateInput
label="Date de pesée" label="Date pesée"
v-model="localWeight.weighedAt" v-model="localWeight.weighedAt"
:disabled="!isAdmin" :disabled="!isAdmin"
/> />
@@ -30,7 +31,7 @@
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import type {WeightEntryData} from '~/services/dto/weight-data' import type {WeightEntryData} from '~/services/dto/reception-data'
import {reactive, watch} from "vue"; import {reactive, watch} from "vue";
const props = defineProps<{ const props = defineProps<{

View File

@@ -1,6 +1,6 @@
<template> <template>
<form @submit.prevent="validate"> <form @submit.prevent="validate">
<div class="grid grid-cols-2 h-[461px] items-start gap-y-8 gap-x-40 mb-16"> <div class="grid grid-cols-2 items-start gap-y-8 gap-x-40 mb-16">
<h1 class="font-bold text-5xl uppercase col-start-1 row-start-1 text-primary-500">Expédition</h1> <h1 class="font-bold text-5xl uppercase col-start-1 row-start-1 text-primary-500">Expédition</h1>
<!-- Nom de l'utilisateur --> <!-- Nom de l'utilisateur -->
<UiSelect <UiSelect
@@ -23,14 +23,11 @@
/> />
<!-- Type d'expédition --> <!-- Type d'expédition -->
<div class="col-start-1 row-start-4 h-[64px]"> <div class="col-start-1 row-start-4 h-[64px]">
<div class="flex w-full items-end gap-[104px]"> <div class="flex items-end gap-8 justify-between">
<UiRadioGroup <UiRadioGroup
id="shipment-type" id="shipment-type"
name="shipment-type" name="shipment-type"
label="Type d'expédition bovine" label="Type d'expédition bovine"
input-class="accent-primary-700 focus:ring-primary-700"
wrapper-class=""
group-class="flex flex-row gap-[104px] w-[160px_160px] h-[32px]"
v-model="selectedShipmentTypeId" v-model="selectedShipmentTypeId"
:options="bovineShipment.map((type) => ({ :options="bovineShipment.map((type) => ({
value: String(type.id), value: String(type.id),
@@ -39,6 +36,7 @@
/> />
<UiNumberInput <UiNumberInput
id="shipment-type-quantity" id="shipment-type-quantity"
label="Quantité"
v-model="shipmentQuantity" v-model="shipmentQuantity"
:placeholder="0" :placeholder="0"
:min="0" :min="0"
@@ -94,7 +92,7 @@
<!-- Plaque d'immatriculation (hors LIOT) --> <!-- Plaque d'immatriculation (hors LIOT) -->
<div v-if="!isLiotCarrier" class="col-start-2 row-start-4"> <div v-if="!isLiotCarrier" class="col-start-2 row-start-4">
<UiLicensePlateInput <UiLicensePlateInput
v-model="form.licensePlate" v-model="form.licencePlate"
v-model:allowAny="allowAnyLicensePlate" v-model:allowAny="allowAnyLicensePlate"
/> />
</div> </div>
@@ -129,7 +127,7 @@
<div class="flex justify-center"> <div class="flex justify-center">
<UiButton <UiButton
type="submit" type="submit"
class="text-xl mb-16 uppercase bg-primary-500 text-white h-[50px] w-[272px] justify-self-end" class="text-xl uppercase bg-primary-500 text-white h-[50px] w-[272px] justify-self-end"
>Valider >Valider
</UiButton> </UiButton>
</div> </div>
@@ -195,7 +193,7 @@ const form = reactive<ShipmentFormData>({
carrierId: '', carrierId: '',
driverId: '', driverId: '',
vehicleId: '', vehicleId: '',
licensePlate: '', licencePlate: '',
}) })
// Adresses liées au client sélectionné // Adresses liées au client sélectionné
const customerAddresses = computed<AddressData[]>(() => { const customerAddresses = computed<AddressData[]>(() => {
@@ -317,7 +315,7 @@ watch(
() => shipmentStore.current, () => shipmentStore.current,
(shipment) => { (shipment) => {
isHydrating.value = true isHydrating.value = true
form.licensePlate = shipment?.licensePlate ?? '' form.licencePlate = shipment?.licencePlate ?? ''
form.shipmentDate = shipment?.shipmentDate ?? new Date().toISOString().slice(0, 10) form.shipmentDate = shipment?.shipmentDate ?? new Date().toISOString().slice(0, 10)
form.userId = shipment?.user?.id ? String(shipment.user.id) : form.userId = shipment?.user?.id ? String(shipment.user.id) :
form.userId form.userId
@@ -443,19 +441,19 @@ watch(
(vehicle) => String(vehicle.id) === form.vehicleId (vehicle) => String(vehicle.id) === form.vehicleId
) )
if (selected) { if (selected) {
form.licensePlate = selected.plate form.licencePlate = selected.plate
allowAnyLicensePlate.value = false allowAnyLicensePlate.value = false
} }
} }
) )
watch( watch(
() => [form.licensePlate, form.carrierId, form.vehicleId, vehicles.value], () => [form.licencePlate, form.carrierId, vehicles.value],
() => { () => {
if (!isLiotCarrier.value || form.vehicleId) { if (!isLiotCarrier.value || form.vehicleId) {
return return
} }
const match = filteredVehicles.value.find( const match = filteredVehicles.value.find(
(vehicle) => vehicle.plate === form.licensePlate (vehicle) => vehicle.plate === form.licencePlate
) )
if (match) { if (match) {
form.vehicleId = String(match.id) form.vehicleId = String(match.id)
@@ -464,7 +462,7 @@ watch(
) )
const buildPayload = () => { const buildPayload = () => {
const normalizedLicensePlate = form.licensePlate.trim() const normalizedLicensePlate = form.licencePlate.trim()
const normalizedShipmentDate = form.shipmentDate.trim() const normalizedShipmentDate = form.shipmentDate.trim()
const normalizedCustomerId = form.customerId.trim() const normalizedCustomerId = form.customerId.trim()
const normalizedTruckId = form.truckId.trim() const normalizedTruckId = form.truckId.trim()
@@ -500,7 +498,7 @@ const buildPayload = () => {
Math.trunc(rawQuantity)) : 0 Math.trunc(rawQuantity)) : 0
return { return {
licensePlate: normalizedLicensePlate, licencePlate: normalizedLicensePlate,
shipmentDate: normalizedShipmentDate, shipmentDate: normalizedShipmentDate,
customer: customerIri, customer: customerIri,
truck: truckIri, truck: truckIri,

View File

@@ -75,7 +75,7 @@ const printReceipt = async () => {
await saveWeight() await saveWeight()
const shipment = shipmentStore.current const shipment = shipmentStore.current
const filename = `${shipment.identificationNumber ?? shipment.id}_${shipment.customer?.label ?? 'client'}_${shipment.licensePlate ?? 'immat'}.pdf` const filename = `${shipment.identificationNumber ?? shipment.id}_${shipment.customer?.label ?? 'client'}_${shipment.licencePlate ?? 'immat'}.pdf`
await printPdf(`/shipments/${shipment.id}/receipt`, filename) await printPdf(`/shipments/${shipment.id}/receipt`, filename)
// Laisse le temps a la boite de dialogue d'impression de s'ouvrir. // Laisse le temps a la boite de dialogue d'impression de s'ouvrir.

View File

@@ -3,7 +3,7 @@
:is="'button'" :is="'button'"
:type="type" :type="type"
:disabled="isDisabled" :disabled="isDisabled"
class="inline-flex min-w-[194px] items-center justify-center rounded-md" class="inline-flex items-center justify-center rounded-md"
:class="[ :class="[
isDisabled ? 'cursor-not-allowed opacity-60' : 'cursor-pointer', isDisabled ? 'cursor-not-allowed opacity-60' : 'cursor-pointer',
buttonClass buttonClass

View File

@@ -3,7 +3,7 @@
<label <label
v-if="label" v-if="label"
:for="id" :for="id"
class="font-bold uppercase text-xl text-primary-700" class="font-bold uppercase text-xl text-primary-500"
:class="labelClass" :class="labelClass"
> >
{{ label }} {{ label }}
@@ -16,7 +16,7 @@
:maxlength="maxlength" :maxlength="maxlength"
:disabled="disabled" :disabled="disabled"
v-bind="attrs" v-bind="attrs"
class="border-b border-black text-xl py-[6px] bg-transparent text-primary-700" class="border-b border-black text-xl py-[6px] bg-transparent text-primary-500"
:class="[ :class="[
isEmpty ? 'text-neutral-400' : 'text-black', isEmpty ? 'text-neutral-400' : 'text-black',
disabled ? 'cursor-not-allowed' : 'cursor-text', disabled ? 'cursor-not-allowed' : 'cursor-text',

View File

@@ -1,5 +1,6 @@
import type {Ref} from 'vue'
import {computed, ref} from 'vue' import {computed, ref} from 'vue'
import type {WeightEntryData} from '~/services/dto/reception-data' import type {ReceptionData, ReceptionPayload, WeightEntryData} from '~/services/dto/reception-data'
import type {WeightData} from '~/services/dto/weight-data' import type {WeightData} from '~/services/dto/weight-data'
import {getWeight} from '~/services/reception' import {getWeight} from '~/services/reception'
import {getWeightShipment} from '~/services/shipment' import {getWeightShipment} from '~/services/shipment'
@@ -61,7 +62,7 @@ export const useWeighing = ({
}) })
} else { } else {
await createWeight({ await createWeight({
reception: `/api/receptions/${reception.value.id}`, reception: `api/receptions/${reception.value.id}`,
type: mode, type: mode,
dsd: baseDsd, dsd: baseDsd,
weight: baseWeight, weight: baseWeight,
@@ -110,7 +111,7 @@ export const useWeighingShipment = ({
const displayWeight = computed(() => weightData.value?.weight ?? currentWeightEntry.value?.weight ?? null) const displayWeight = computed(() => weightData.value?.weight ?? currentWeightEntry.value?.weight ?? null)
const displayDsd = computed(() => weightData.value?.dsd ?? currentWeightEntry.value?.dsd ?? '-') const displayDsd = computed(() => weightData.value?.dsd ?? currentWeightEntry.value?.dsd ?? '-')
const title = computed(() => (modeShipment === 'gross' ? 'Pesée à vide' : 'Pesée à plein')) const title = computed(() => (modeShipment === 'gross' ? 'Pesée à plein' : 'Pesée à vide'))
const showLoadingBox = computed( const showLoadingBox = computed(
() => isFetching.value || (displayWeight.value === null && currentWeightEntry.value === null) () => isFetching.value || (displayWeight.value === null && currentWeightEntry.value === null)
) )
@@ -145,7 +146,7 @@ export const useWeighingShipment = ({
}) })
} else { } else {
await createWeight({ await createWeight({
shipment: `/api/shipments/${shipment.value.id}`, shipment: `api/shipments/${shipment.value.id}`,
type: modeShipment, type: modeShipment,
dsd: baseDsd, dsd: baseDsd,
weight: baseWeight, weight: baseWeight,

View File

@@ -82,10 +82,7 @@
"list": "Impossible de récupérer la liste des camions." "list": "Impossible de récupérer la liste des camions."
}, },
"bovin": { "bovin": {
"list": "Impossible de récupérer la liste des races de bovins.", "list": "Impossible de récupérer la liste des races de bovins."
"fetch": "Impossible de récupérer le type bovin.",
"create": "Impossible de créer le type bovin.",
"update": "Impossible de mettre à jour le type bovin."
}, },
"carrier": { "carrier": {
"list": "Impossible de récupérer la liste des transporteurs.", "list": "Impossible de récupérer la liste des transporteurs.",
@@ -136,10 +133,6 @@
"update": "Transporteur mis à jour", "update": "Transporteur mis à jour",
"create": "Transporteur créé" "create": "Transporteur créé"
}, },
"bovin": {
"update": "Type bovin mis à jour avec succès.",
"create": "Type bovin créé avec succès."
},
"weight": { "weight": {
"update": "Pesée mis à jour" "update": "Pesée mis à jour"
} }

View File

@@ -108,7 +108,7 @@
<NuxtLink <NuxtLink
v-if="auth.isAdmin" v-if="auth.isAdmin"
to="/admin/bovin/bovin-list" to="/admin/bovin/list"
custom custom
v-slot="{ href, navigate }" v-slot="{ href, navigate }"
> >
@@ -214,7 +214,7 @@
<NuxtLink v-if="auth.isAdmin" to="/admin/customer/customer-list" @click="closeMenu"> <NuxtLink v-if="auth.isAdmin" to="/admin/customer/customer-list" @click="closeMenu">
Clients Clients
</NuxtLink> </NuxtLink>
<NuxtLink v-if="auth.isAdmin" to="/admin/bovin/bovin-list" @click="closeMenu"> <NuxtLink v-if="auth.isAdmin" to="/admin/bovin/list" @click="closeMenu">
Bovins Bovins
</NuxtLink> </NuxtLink>
</nav> </nav>

View File

@@ -1,32 +1,24 @@
<template> <template>
<form @submit.prevent="validate"> <form @submit.prevent="validate">
<div class="flex items-center justify-between relative"> <div class="text-primary-500 flex items-center justify-between">
<div class="flex flex-row absolute -left-[60px]"> <h1 class="text-3xl font-bold uppercase">
<Icon {{ route.params.id ? 'Modifier bovin' : 'Ajout bovin' }}
@click="router.push('/admin/bovin/bovin-list')"
name="gg:arrow-left-o"
size="40"
class="cursor-pointer text-primary-500"
/>
</div>
<h1 class="text-3xl text-primary-500 font-bold uppercase">
{{ route.params.id ? 'Modifications du type bovin' : 'Ajout d\'un type bovin' }}
</h1> </h1>
</div>
<div class="grid grid-cols-2 items-start pt-7 mb-11 gap-x-[200px]">
<UiTextInput label="Nom du bovin" id="bovin-label" v-model="form.label" />
<UiTextInput label="Code bovin" id="code-id" v-model="form.code" />
</div>
<div class="flex justify-center items-center">
<UiButton <UiButton
type="submit" type="submit"
:disabled="isLoading || isHydrating" :disabled="isLoading || isHydrating"
class="inline-flex items-center justify-center text-xl min-w-[194px] text-white uppercase bg-primary-500 h-[50px] rounded hover:opacity-80 justify-self-end" class="text-xl uppercase bg-primary-500 text-white h-[50px] w-[272px] hover:opacity-80"
> >
Valider <Icon name="mdi:check" size="28" />
{{ isEdit ? 'Modifier' : 'Ajouter' }}
</UiButton> </UiButton>
</div> </div>
<div class="grid grid-cols-2 items-start gap-y-8 gap-x-40 py-12">
<UiTextInput label="Nom du bovin" id="bovin-label" v-model="form.label" />
<UiTextInput label="Code bovin" id="code-id" v-model="form.code" />
</div>
</form> </form>
</template> </template>
@@ -37,8 +29,6 @@ const router = useRouter()
const route = useRoute() const route = useRoute()
const isLoading = ref(false) const isLoading = ref(false)
const isHydrating = ref(false) const isHydrating = ref(false)
const idBovin = computed(() => resolveId(route.params.id))
const isEdit = computed(() => idBovin.value !== null)
function resolveId(param: unknown) { function resolveId(param: unknown) {
const idStr = Array.isArray(param) ? param[0] : param const idStr = Array.isArray(param) ? param[0] : param
@@ -47,6 +37,9 @@ function resolveId(param: unknown) {
return Number.isFinite(id) ? id : null return Number.isFinite(id) ? id : null
} }
const idBovin = computed(() => resolveId(route.params.id))
const isEdit = computed(() => idBovin.value !== null)
const form = reactive<BovinFormData>({ const form = reactive<BovinFormData>({
label: '', label: '',
code: '' code: ''
@@ -99,6 +92,7 @@ async function validate() {
} else { } else {
await createBovin(basePayload) await createBovin(basePayload)
} }
await navigate()
} finally { } finally {
isLoading.value = false isLoading.value = false
} }

View File

@@ -1,67 +0,0 @@
<template>
<div class="flex items-center justify-between ">
<h1 class="text-4xl font-bold uppercase text-primary-500">Liste des types bovins</h1>
</div>
<div class="mt-7 border border-slate-200 mb-11 ">
<div class="grid grid-cols-2 gap-4 text-primary-700 bg-slate-100 px-4 py-3 text-sm font-semibold uppercase tracking-wide">
<div>Nom</div>
<div>Code</div>
</div>
<div v-if="!auth.isAdmin" class="px-4 py-6 text-slate-400">
Accès réservé aux administrateurs.
</div>
<div v-else-if="bovinList.length === 0" class="px-4 py-6 text-slate-400">
Aucun type de bovin.
</div>
<template v-else>
<div
v-for="bovin in bovinList"
:key="bovin.id"
class="grid grid-cols-2 text-primary-700 gap-4 px-4 py-3 text-sm hover:bg-slate-50 cursor-pointer border-t border-slate-200"
role="button"
tabindex="0"
@click="goToBovin(bovin.id)"
@keydown.enter="goToBovin(bovin.id)"
>
<div>{{ bovin.label }}</div>
<div>{{ bovin.code }}</div>
</div>
</template>
</div>
<div class="flex justify-center items-center">
<NuxtLink
to="/admin/bovin"
class="inline-flex items-center justify-center text-xl text-white uppercase bg-primary-500 h-[50px] px-8 rounded hover:opacity-80 gap-2"
:class="auth.isAdmin ? '' : 'cursor-not-allowed opacity-60'"
@click="handleAddClick"
>
<Icon name="mdi:plus" size="28" />
Ajouter
</NuxtLink>
</div>
</template>
<script setup lang="ts">
import { getBovineTypeList } from "~/services/bovine-type"
import type { BovineTypeData } from "~/services/dto/bovine-type-data"
import { useAuthStore } from "~/stores/auth"
const bovinList = ref<BovineTypeData[]>([])
const router = useRouter()
const auth = useAuthStore()
const goToBovin = (id: number) => {
if (!auth.isAdmin) return
router.push(`/admin/bovin/${id}`)
}
const handleAddClick = (event: Event) => {
if (auth.isAdmin) return
event.preventDefault()
}
onMounted(async () => {
if (!auth.isAdmin) return
bovinList.value = await getBovineTypeList()
})
</script>

View File

@@ -0,0 +1,72 @@
<template>
<div class="flex items-center justify-between">
<h1 class="text-3xl font-bold text-primary-500 uppercase">Liste des types bovins</h1>
<NuxtLink
to="/admin/bovin"
class="inline-flex items-center justify-center
text-xl text-white uppercase
bg-primary-500 h-[50px] px-8 rounded
hover:opacity-80 gap-2"
@click="handleAddClick"
>
<Icon name="mdi:plus" size="28" />
Ajouter
</NuxtLink>
</div>
<div v-if="auth.isAdmin" class="mt-6 border border-slate-200 mb-16">
<div class="max-h-96 overflow-y-auto">
<div
class="sticky
grid grid-cols-2 gap-4
bg-slate-100 px-4 py-3
font-semibold uppercase
tracking-wide"
>
<div class="col-span-1">Nom</div>
<div class="col-span-1">Code</div>
</div>
<div v-if="bovinList.length === 0" class="px-4 py-6 text-slate-400">
Aucun type de bovin.
</div>
<div v-else>
<div
v-for="bovin in bovinList"
:key="bovin.id"
class="grid grid-cols-2 border-t gap-4 px-4 py-2 hover:bg-slate-50 cursor-pointer"
@click="goToBovin(bovin.id)"
>
<div class="col-span-1">{{ bovin.label }}</div>
<div class="col-span-1">{{ bovin.code }}</div>
</div>
</div>
</div>
</div>
<div v-else class="mt-6 border border-slate-200 mb-16 px-4 py-6 text-slate-400">
Accès réservé aux administrateurs.
</div>
</template>
<script setup lang="ts">
import { getBovineTypeList } from "~/services/bovine-type"
import type { BovineTypeData } from "~/services/dto/bovine-type-data"
import { useAuthStore } from "~/stores/auth"
const bovinList = ref<BovineTypeData[]>([])
const router = useRouter()
const auth = useAuthStore()
const goToBovin = (id: number) => {
if (!auth.isAdmin) return
router.push(`/admin/bovin/${id}`)
}
const handleAddClick = (event: Event) => {
if (auth.isAdmin) return
event.preventDefault()
}
onMounted(async () => {
if (!auth.isAdmin) return
bovinList.value = await getBovineTypeList()
})
</script>

View File

@@ -1,41 +1,31 @@
<template> <template>
<form @submit.prevent="validate"> <form @submit.prevent="validate">
<div class="flex items-center justify-between relative"> <div class="flex items-center justify-between">
<div class="flex flex-row absolute -left-[60px]"> <h1 class="text-3xl font-bold uppercase">
<Icon {{ route.params.id ? 'Modifier transporteur' : 'Ajout transporteur' }}
@click="router.push('/admin/carrier/carrier-list')" </h1>
name="gg:arrow-left-o"
size="40"
class="cursor-pointer text-primary-500"
/>
</div>
<h1 class="text-3xl text-primary-500 font-bold uppercase">
{{ route.params.id ? 'Modification du transporteur' : 'Ajout d\'un transporteur' }}
</h1>
</div>
<div class="grid grid-cols-2 items-start pt-7 mb-11 gap-x-[200px]"> <UiButton
<UiTextInput type="submit"
label="Nom du transporteur" class="text-xl uppercase bg-primary-500 text-white h-[50px] w-[272px] justify-self-end"
id="carrier-name" >Enregistrer
v-model="form.name" </UiButton>
/> </div>
<UiTextInput <div class="grid grid-cols-2 items-start gap-y-8 gap-x-40 py-12">
label="Code transporteur" <UiTextInput
label = "nom du fournisseur"
id="carrier-name"
v-model="form.name"
/>
<UiTextInput
label = "code fournisseur"
id="code-id" id="code-id"
v-model="form.code" v-model="form.code"
/> />
</div> </div>
<div class="flex justify-center items-center">
<UiButton
type="submit"
class="inline-flex items-center justify-center text-xl min-w-[194px] text-white uppercase bg-primary-500 h-[50px] rounded hover:opacity-80 justify-self-end"
>
Valider
</UiButton>
</div>
</form> </form>
</template> </template>
@@ -62,6 +52,10 @@ const form = reactive<CarrierFormData>({
name:'' name:''
}) })
definePageMeta({
layout: 'default'
})
const hydrateFromUser = (carrier: CarrierData | null) => { const hydrateFromUser = (carrier: CarrierData | null) => {
if (!carrier) { if (!carrier) {
return return
@@ -101,10 +95,11 @@ async function validate() {
if(idCarrier.value){ if(idCarrier.value){
await updateCarrier(idCarrier.value, basePayload) await updateCarrier(idCarrier.value, basePayload)
navigate()
return return
}else{
await createCarrier(basePayload)
} }
await createCarrier(basePayload)
navigate()
} }
function navigate(){ function navigate(){

View File

@@ -1,18 +1,25 @@
<template> <template>
<div class="flex items-center justify-between "> <div class="flex items-center justify-between ">
<h1 class="text-4xl font-bold uppercase text-primary-500">listes des transporteurs</h1> <h1 class="text-3xl font-bold uppercase text-primary-500">listes des transporteurs</h1>
<NuxtLink
to="/admin/carrier"
class="inline-flex items-center justify-center gap-2 text-xl uppercase bg-primary-500 text-white h-[50px] px-8 rounded"
>
<Icon name="mdi:plus" size="28" />
Ajouter
</NuxtLink>
</div> </div>
<div class="mt-7 border border-slate-200 mb-11 "> <div class="mt-6 border border-slate-200 mb-16 ">
<div class="grid grid-cols-2 gap-4 text-primary-700 bg-slate-100 px-4 py-3 text-sm font-semibold uppercase tracking-wide"> <div class="grid grid-cols-2 gap-4 bg-slate-100 px-4 py-3 text-sm font-semibold uppercase tracking-wide">
<div>Label</div> <div>Label</div>
<div>Code</div> <div>Code</div>
</div> </div>
<div <div
v-for="carrier in carrierList" v-for="carrier in carrierList"
:key="carrier.id" :key="carrier.id"
class="grid grid-cols-2 text-primary-700 gap-4 px-4 py-3 text-sm hover:bg-slate-50 cursor-pointer border-t border-slate-200" class="grid grid-cols-2 gap-4 px-4 py-3 text-sm hover:bg-slate-50 cursor-pointer border-t border-slate-200"
role="button" role="button"
tabindex="0" tabindex="0"
@click="goToCarrier(carrier.id)" @click="goToCarrier(carrier.id)"
@@ -22,15 +29,6 @@
<div>{{ carrier.code }}</div> <div>{{ carrier.code }}</div>
</div> </div>
</div> </div>
<div class="flex justify-center items-center">
<NuxtLink
to="/admin/carrier"
class="inline-flex items-center justify-center text-xl text-white uppercase bg-primary-500 h-[50px] px-8 rounded hover:opacity-80 gap-2"
>
<Icon name="mdi:plus" size="28" />
Ajouter
</NuxtLink>
</div>
</template> </template>
@@ -45,6 +43,10 @@ const goToCarrier = (id: number) => {
router.push(`/admin/carrier/${id}`) router.push(`/admin/carrier/${id}`)
} }
definePageMeta({
layout: 'default'
})
onMounted(async () => { onMounted(async () => {
carrierList.value = await getCarrierList(false) carrierList.value = await getCarrierList(false)
}) })

View File

@@ -1,43 +1,47 @@
<template> <template>
<form @submit.prevent="validate"> <form @submit.prevent="validate">
<div class="flex items-center relative"> <div class="flex items-center justify-between">
<div class="flex flex-row absolute -left-[60px] "> <h1 class="text-3xl font-bold uppercase">
<Icon @click="router.push('/admin/customer/customer-list')" name="gg:arrow-left-o" size="40" class="cursor-pointer text-primary-500"/> {{ customerId ? "Modifications du client" : "Ajout d'un client" }}
</div>
<h1 class="text-3xl text-primary-500 font-bold uppercase">
{{ customerId ? "Modification du client" : "Ajout d'un client" }}
</h1> </h1>
</div>
<div class="flex flex-cols-3 justify-between mb-11 pt-7">
<UiTextInput id="customer-name" v-model="form.name" label="Nom du client" :disabled="!auth.isAdmin" wrapper-class="w-[280px]"/>
<UiTextInput id="customer-phone" v-model="form.phone" label="Téléphone" :disabled="!auth.isAdmin" wrapper-class="w-[280px]"/>
<UiTextInput id="customer-email" v-model="form.email" label="Email" :disabled="!auth.isAdmin" wrapper-class="w-[280px]"/>
</div>
<div class="flex items-center justify-center">
<UiButton <UiButton
class="inline-flex mb-28 items-center justify-center text-xl min-w-[194px] text-white uppercase bg-primary-500 h-[50px] rounded hover:opacity-80 justify-self-end" class="text-xl uppercase bg-primary-500 text-white h-[50px] w-[272px]"
type="submit" type="submit"
:disabled="isLoading || !auth.isAdmin" :disabled="isLoading || !auth.isAdmin"
> >
<Icon :name="customerId ? '' : 'mdi:plus'" size="28" /> {{ customerId ? "Sauvegarder" : "Ajouter" }}
{{ customerId ? "Valider" : "Ajouter" }}
</UiButton> </UiButton>
</div> </div>
<div class="flex items-center justify-between mb-7"> <div class="grid grid-cols-2 gap-y-8 gap-x-80 mb-10 py-12">
<h2 class="text-3xl text-primary-500 font-bold uppercase">Adresses du client</h2> <UiTextInput id="customer-name" v-model="form.name" label="Nom du client" :disabled="!auth.isAdmin"/>
<UiTextInput id="customer-phone" v-model="form.phone" label="Téléphone" :disabled="!auth.isAdmin"/>
<UiTextInput id="customer-email" v-model="form.email" label="Email" :disabled="!auth.isAdmin"/>
</div> </div>
<div class="overflow-x-auto mb-11 text-primary-700">
<table class="w-full border-collapse text-primary-700"> <div class="mx-24 mb-4 py-6 border-t border-black"></div>
<div class="flex items-center justify-between mb-4">
<h2 class="text-3xl font-bold uppercase">Adresses client</h2>
<UiButton
type="button"
class="text-xl uppercase bg-primary-500 text-white h-[50px] w-[272px]"
:disabled="customerId === null || !auth.isAdmin"
@click="goToAddAddress"
>
Ajouter
</UiButton>
</div>
<div class="overflow-x-auto mb-10">
<table class="w-full border-collapse">
<thead> <thead>
<tr class="text-left border bg-slate-100 border-gray-200"> <tr class="text-left border-b border-gray-200">
<th class="py-3 px-4 text-sm uppercase">Libellé</th> <th class="py-3 pr-4 text-sm uppercase">Libellé</th>
<th class="py-3 px-4 text-sm uppercase">Rue</th> <th class="py-3 pr-4 text-sm uppercase">Rue</th>
<th class="py-3 px-4 text-sm uppercase">Complément</th> <th class="py-3 pr-4 text-sm uppercase">Complément</th>
<th class="py-3 px-4 text-sm uppercase">Code postal</th> <th class="py-3 pr-4 text-sm uppercase">Code postal</th>
<th class="py-3 px-4 text-sm uppercase">Ville</th> <th class="py-3 pr-4 text-sm uppercase">Ville</th>
<th class="py-3 px-4 text-sm uppercase">Pays</th> <th class="py-3 pr-4 text-sm uppercase">Pays</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
@@ -52,32 +56,21 @@
<tr <tr
v-for="(address, index) in form.addresses" v-for="(address, index) in form.addresses"
:key="address.id ?? index" :key="address.id ?? index"
class="border border-gray-100 hover:bg-slate-50" class="border-b border-gray-100 hover:bg-slate-50"
:class="auth.isAdmin ? 'cursor-pointer' : 'cursor-not-allowed opacity-60'" :class="auth.isAdmin ? 'cursor-pointer' : 'cursor-not-allowed opacity-60'"
@click="goToEditAddress(address.id ?? null)" @click="goToEditAddress(address.id ?? null)"
> >
<td class="py-3 px-4">{{ address.label || "—" }}</td> <td class="py-3 pr-4">{{ address.label || "—" }}</td>
<td class="py-3 px-4">{{ address.street || "—" }}</td> <td class="py-3 pr-4">{{ address.street || "—" }}</td>
<td class="py-3 px-4">{{ address.street2 || "—" }}</td> <td class="py-3 pr-4">{{ address.street2 || "—" }}</td>
<td class="py-3 px-4">{{ address.postalCode || "—" }}</td> <td class="py-3 pr-4">{{ address.postalCode || "—" }}</td>
<td class="py-3 px-4">{{ address.city || "—" }}</td> <td class="py-3 pr-4">{{ address.city || "—" }}</td>
<td class="py-3 px-4">{{ address.countryCode || "—" }}</td> <td class="py-3 pr-4">{{ address.countryCode || "—" }}</td>
</tr> </tr>
</template> </template>
</tbody> </tbody>
</table> </table>
</div> </div>
<div class="flex justify-center items-center">
<UiButton
type="button"
class="inline-flex items-center justify-center text-xl gap-2 text-white uppercase bg-primary-500 h-[50px] rounded hover:opacity-80 justify-self-end"
:disabled="customerId === null || !auth.isAdmin"
@click="goToAddAddress"
>
<Icon name="mdi:plus" size="28" />
Ajouter
</UiButton>
</div>
</form> </form>
</template> </template>
@@ -87,6 +80,8 @@ import {createCustomer, getCustomer, updateCustomer} from "~/services/customer"
import type {CustomerData, CustomerFormData, CustomerPayload} from "~/services/dto/customer-data" import type {CustomerData, CustomerFormData, CustomerPayload} from "~/services/dto/customer-data"
import {useAuthStore} from "~/stores/auth" import {useAuthStore} from "~/stores/auth"
definePageMeta({layout: "default"})
const route = useRoute() const route = useRoute()
const router = useRouter() const router = useRouter()
const auth = useAuthStore() const auth = useAuthStore()

View File

@@ -8,6 +8,8 @@ import { createAddress, getAddress, updateAddress } from "~/services/address"
import { getCustomer, updateCustomer } from "~/services/customer" import { getCustomer, updateCustomer } from "~/services/customer"
import type { CustomerData } from "~/services/dto/customer-data" import type { CustomerData } from "~/services/dto/customer-data"
definePageMeta({ layout: "default" })
const route = useRoute() const route = useRoute()
const router = useRouter() const router = useRouter()
const customerId = computed(() => Number(route.query.customerId)) const customerId = computed(() => Number(route.query.customerId))
@@ -16,10 +18,13 @@ const addressId = computed(() => (route.query.addressId !== undefined ? Number(r
const address = ref<AddressData | null>(null) const address = ref<AddressData | null>(null)
const validate = async (payload: AddressPayload) => { const validate = async (payload: AddressPayload) => {
if (addressId.value !== null) { try {
await updateAddress(addressId.value, payload) if (addressId.value !== null) {
} else { await updateAddress(addressId.value, payload)
await addAddress(payload) } else {
await addAddress(payload)
}
} finally {
await router.push("/admin/customer/" + customerId.value) await router.push("/admin/customer/" + customerId.value)
} }
} }

View File

@@ -1,12 +1,21 @@
<template> <template>
<div class="flex items-center justify-between"> <div class="flex items-center justify-between">
<h1 class="text-4xl font-bold uppercase text-primary-500">Liste des clients</h1> <h1 class="text-3xl font-bold uppercase text-primary-500">Liste des Clients</h1>
<NuxtLink
to="/admin/customer"
class="inline-flex items-center justify-center gap-2 text-xl uppercase bg-primary-500 text-white h-[50px] px-8 rounded-md"
:class="auth.isAdmin ? '' : 'cursor-not-allowed opacity-60'"
@click="handleAddClick"
>
<Icon name="mdi:plus" size="28" />
Ajouter
</NuxtLink>
</div> </div>
<div v-if="auth.isAdmin" class="mt-7 border border-slate-200 mb-11"> <div v-if="auth.isAdmin" class="mt-6 border border-slate-200 mb-16">
<div class="max-h-96 overflow-y-auto"> <div class="max-h-96 overflow-y-auto">
<div <div
class="sticky text-primary-700 top-0 z-10 grid grid-cols-8 gap-4 bg-slate-100 px-4 py-3 text-sm font-semibold uppercase tracking-wide" class="sticky top-0 z-10 grid grid-cols-8 gap-4 bg-slate-100 px-4 py-3 text-sm font-semibold uppercase tracking-wide"
> >
<div>Nom</div> <div>Nom</div>
<div>Téléphone</div> <div>Téléphone</div>
@@ -25,7 +34,7 @@
<div v-for="customer in customerList" :key="customer.id"> <div v-for="customer in customerList" :key="customer.id">
<div <div
v-if="!customer.addresses || customer.addresses.length === 0" v-if="!customer.addresses || customer.addresses.length === 0"
class="grid text-primary-700 grid-cols-8 border-t gap-4 px-4 py-2 hover:bg-slate-50 cursor-pointer" class="grid grid-cols-8 border-t gap-4 px-4 py-2 hover:bg-slate-50 cursor-pointer"
@click="goToCustomer(customer.id)" @click="goToCustomer(customer.id)"
> >
<div class="truncate">{{ customer.name || "—" }}</div> <div class="truncate">{{ customer.name || "—" }}</div>
@@ -42,7 +51,7 @@
<div <div
v-for="(address, idx) in customer.addresses" v-for="(address, idx) in customer.addresses"
:key="address.id ?? `${customer.id}-${idx}-${address.street}-${address.postalCode}`" :key="address.id ?? `${customer.id}-${idx}-${address.street}-${address.postalCode}`"
class="grid grid-cols-8 text-primary-700 hover:bg-slate-50 border-t gap-4 px-4 py-2 cursor-pointer" class="grid grid-cols-8 hover:bg-slate-50 border-t gap-4 px-4 py-2 cursor-pointer"
:class="idx > 0 ? 'pl-4 border-l-4 border-l-slate-200 bg-slate-50' : ''" :class="idx > 0 ? 'pl-4 border-l-4 border-l-slate-200 bg-slate-50' : ''"
@click="goToCustomer(customer.id)" @click="goToCustomer(customer.id)"
> >
@@ -61,7 +70,7 @@
<template v-else> <template v-else>
<div <div
class="grid grid-cols-8 text-primary-700 hover:bg-slate-50 border-t gap-4 px-4 py-2 cursor-pointer" class="grid grid-cols-8 hover:bg-slate-50 border-t gap-4 px-4 py-2 cursor-pointer"
@click="goToCustomer(customer.id)" @click="goToCustomer(customer.id)"
> >
<div class="truncate">{{ customer.name || "" }}</div> <div class="truncate">{{ customer.name || "" }}</div>
@@ -75,20 +84,9 @@
</div> </div>
</div> </div>
</div> </div>
<div v-else class="mt-7 border border-slate-200 mb-11 px-4 py-6 text-slate-400"> <div v-else class="mt-6 border border-slate-200 mb-16 px-4 py-6 text-slate-400">
Accès réservé aux administrateurs. Accès réservé aux administrateurs.
</div> </div>
<div class="flex justify-center items-center">
<NuxtLink
to="/admin/customer"
class="inline-flex items-center mb-16 justify-center text-xl text-white uppercase bg-primary-500 h-[50px] px-8 rounded hover:opacity-80 gap-2"
:class="auth.isAdmin ? '' : 'cursor-not-allowed opacity-60'"
@click="handleAddClick"
>
<Icon name="mdi:plus" size="28" />
Ajouter
</NuxtLink>
</div>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
@@ -96,6 +94,8 @@ import { getCustomerList } from "~/services/customer"
import type { CustomerData } from "~/services/dto/customer-data" import type { CustomerData } from "~/services/dto/customer-data"
import { useAuthStore } from "~/stores/auth" import { useAuthStore } from "~/stores/auth"
definePageMeta({ layout: "default" })
const customerList = ref<CustomerData[]>([]) const customerList = ref<CustomerData[]>([])
const router = useRouter() const router = useRouter()
const auth = useAuthStore() const auth = useAuthStore()

View File

@@ -0,0 +1,7 @@
<template>
</template>
<script setup lang="ts">
definePageMeta({
layout: 'default'
})
</script>

View File

@@ -1,44 +1,47 @@
<template> <template>
<form @submit.prevent="validate"> <form @submit.prevent="validate">
<div class="flex items-center justify-between">
<div class="flex items-center relative"> <h1 class="text-3xl font-bold uppercase">
<div class="flex flex-row absolute -left-[60px] "> {{ supplierId ? "Modifications du fournisseur" : "Ajout d'un fournisseur" }}
<Icon @click="router.push('/admin/supplier/supplier-list')" name="gg:arrow-left-o" size="40" class="cursor-pointer text-primary-500"/>
</div>
<h1 class="text-3xl text-primary-500 font-bold uppercase">
{{ supplierId ? "Modification du fournisseur" : "Ajout d'un fournisseur" }}
</h1> </h1>
</div>
<div class="flex flex-cols-3 justify-between mb-11 pt-7">
<UiTextInput id="supplier-name" v-model="form.name" label="Nom du fournisseur" :disabled="!auth.isAdmin" wrapper-class="w-[280px]"/>
<UiTextInput id="supplier-email" v-model="form.email" label="Email" :disabled="!auth.isAdmin" wrapper-class="w-[280px]"/>
<UiTextInput id="supplier-phone" v-model="form.phone" label="Téléphone" :disabled="!auth.isAdmin" wrapper-class="w-[280px]"/>
</div>
<div class="flex items-center justify-center">
<UiButton <UiButton
class="inline-flex mb-28 items-center justify-center text-xl min-w-[194px] text-white uppercase bg-primary-500 h-[50px] rounded hover:opacity-80 justify-self-end" class="text-xl uppercase bg-primary-500 text-white h-[50px] w-[272px]"
type="submit" type="submit"
:disabled="isLoading || !auth.isAdmin" :disabled="isLoading || !auth.isAdmin"
> >
<Icon :name="supplierId ? '' : 'mdi:plus'" size="28" /> {{ supplierId ? "Sauvegarder" : "Ajouter" }}
{{ supplierId ? "Valider" : "Ajouter" }}
</UiButton> </UiButton>
</div> </div>
<div class="flex items-center justify-between mb-7"> <div class="grid grid-cols-2 gap-y-8 gap-x-80 mb-10 py-12">
<h2 class="text-3xl text-primary-500 font-bold uppercase">Adresses du fournisseur</h2> <UiTextInput id="supplier-name" v-model="form.name" label="Nom du fournisseur" :disabled="!auth.isAdmin"/>
<UiTextInput id="supplier-email" v-model="form.email" label="Email" :disabled="!auth.isAdmin"/>
<UiTextInput id="supplier-phone" v-model="form.phone" label="Téléphone" :disabled="!auth.isAdmin"/>
</div> </div>
<div class="overflow-x-auto mb-11 text-primary-700">
<div class="mx-24 mb-4 py-6 border-t border-black"></div>
<div class="flex items-center justify-between mb-4">
<h2 class="text-3xl font-bold uppercase">Adresses fournisseur</h2>
<UiButton
type="button"
class="text-xl uppercase bg-primary-500 text-white h-[50px] w-[272px]"
:disabled="supplierId === null || !auth.isAdmin"
@click="goToAddAddress"
>
Ajouter
</UiButton>
</div>
<div class="overflow-x-auto mb-10">
<table class="w-full border-collapse"> <table class="w-full border-collapse">
<thead> <thead>
<tr class="text-left border bg-slate-100 border-gray-200"> <tr class="text-left border-b border-gray-200">
<th class="py-3 px-4 text-sm uppercase">Libellé</th> <th class="py-3 pr-4 text-sm uppercase">Libellé</th>
<th class="py-3 px-4 text-sm uppercase">Rue</th> <th class="py-3 pr-4 text-sm uppercase">Rue</th>
<th class="py-3 px-4 text-sm uppercase">Complément</th> <th class="py-3 pr-4 text-sm uppercase">Complément</th>
<th class="py-3 px-4 text-sm uppercase">Code postal</th> <th class="py-3 pr-4 text-sm uppercase">Code postal</th>
<th class="py-3 px-4 text-sm uppercase">Ville</th> <th class="py-3 pr-4 text-sm uppercase">Ville</th>
<th class="py-3 px-4 text-sm uppercase">Pays</th> <th class="py-3 pr-4 text-sm uppercase">Pays</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
@@ -53,32 +56,21 @@
<tr <tr
v-for="(address, index) in form.addresses" v-for="(address, index) in form.addresses"
:key="address.id ?? index" :key="address.id ?? index"
class="border border-gray-100 hover:bg-slate-50" class="border-b border-gray-100 hover:bg-slate-50"
:class="auth.isAdmin ? 'cursor-pointer' : 'cursor-not-allowed opacity-60'" :class="auth.isAdmin ? 'cursor-pointer' : 'cursor-not-allowed opacity-60'"
@click="goToEditAddress(address.id ?? null)" @click="goToEditAddress(address.id ?? null)"
> >
<td class="py-3 px-4">{{ address.label || "—" }}</td> <td class="py-3 pr-4">{{ address.label || "—" }}</td>
<td class="py-3 px-4">{{ address.street || "—" }}</td> <td class="py-3 pr-4">{{ address.street || "—" }}</td>
<td class="py-3 px-4">{{ address.street2 || "—" }}</td> <td class="py-3 pr-4">{{ address.street2 || "—" }}</td>
<td class="py-3 px-4">{{ address.postalCode || "—" }}</td> <td class="py-3 pr-4">{{ address.postalCode || "—" }}</td>
<td class="py-3 px-4">{{ address.city || "—" }}</td> <td class="py-3 pr-4">{{ address.city || "—" }}</td>
<td class="py-3 px-4">{{ address.countryCode || "—" }}</td> <td class="py-3 pr-4">{{ address.countryCode || "—" }}</td>
</tr> </tr>
</template> </template>
</tbody> </tbody>
</table> </table>
</div> </div>
<div class="flex justify-center items-center">
<UiButton
type="button"
class="inline-flex items-center justify-center text-xl gap-2 text-white uppercase bg-primary-500 h-[50px] rounded hover:opacity-80 justify-self-end"
:disabled="supplierId === null || !auth.isAdmin"
@click="goToAddAddress"
>
<Icon name="mdi:plus" size="28" />
Ajouter
</UiButton>
</div>
</form> </form>
</template> </template>
@@ -88,6 +80,8 @@ import {createSupplier, getSupplier, updateSupplier} from "~/services/supplier"
import type {SupplierData, SupplierFormData, SupplierPayload} from "~/services/dto/supplier-data" import type {SupplierData, SupplierFormData, SupplierPayload} from "~/services/dto/supplier-data"
import {useAuthStore} from "~/stores/auth" import {useAuthStore} from "~/stores/auth"
definePageMeta({layout: "default"})
const route = useRoute() const route = useRoute()
const router = useRouter() const router = useRouter()
const auth = useAuthStore() const auth = useAuthStore()

View File

@@ -8,6 +8,8 @@ import {createAddress, getAddress, updateAddress} from "~/services/address";
import {getSupplier, updateSupplier} from "~/services/supplier"; import {getSupplier, updateSupplier} from "~/services/supplier";
import type {SupplierData} from "~/services/dto/supplier-data"; import type {SupplierData} from "~/services/dto/supplier-data";
definePageMeta({ layout: "default" })
const route = useRoute() const route = useRoute()
const router = useRouter() const router = useRouter()
const supplierId = computed(() => { return Number(route.query.supplierId) }) const supplierId = computed(() => { return Number(route.query.supplierId) })
@@ -16,12 +18,15 @@ const addressId = computed(() => { return route.query.addressId !== undefined ?
const address = ref<AddressData|null>(null) const address = ref<AddressData|null>(null)
const validate = async (address: AddressPayload) => { const validate = async (address: AddressPayload) => {
try {
if (addressId.value !== null) { if (addressId.value !== null) {
await updateAddress(addressId.value, address) await updateAddress(addressId.value, address)
} else { } else {
await addAddress(address) await addAddress(address)
await router.push('/admin/supplier/' + supplierId.value)
} }
} finally {
await router.push('/admin/supplier/' + supplierId.value)
}
} }
const addAddress = async (address: AddressPayload) => { const addAddress = async (address: AddressPayload) => {

View File

@@ -1,12 +1,21 @@
<template> <template>
<div class="flex items-center justify-between"> <div class="flex items-center justify-between">
<h1 class="text-4xl font-bold uppercase text-primary-500">Liste des fournisseurs</h1> <h1 class="text-3xl font-bold uppercase text-primary-500">Liste des fournisseurs</h1>
<NuxtLink
to="/admin/supplier"
class="inline-flex items-center justify-center gap-2 text-xl uppercase bg-primary-500 text-white h-[50px] px-8 rounded"
:class="auth.isAdmin ? '' : 'cursor-not-allowed opacity-60'"
@click="handleAddClick"
>
<Icon name="mdi:plus" size="28" />
Ajouter
</NuxtLink>
</div> </div>
<div v-if="auth.isAdmin" class="mt-7 border border-slate-200 mb-11"> <div v-if="auth.isAdmin" class="mt-6 border border-slate-200 mb-16">
<div class="max-h-96 overflow-y-auto"> <div class="max-h-96 overflow-y-auto">
<div <div
class="sticky text-primary-700 top-0 z-10 grid grid-cols-7 gap-4 bg-slate-100 px-4 py-3 text-sm font-semibold uppercase tracking-wide" class="sticky top-0 z-10 grid grid-cols-7 gap-4 bg-slate-100 px-4 py-3 text-sm font-semibold uppercase tracking-wide"
> >
<div>Nom</div> <div>Nom</div>
<div>Mail</div> <div>Mail</div>
@@ -24,7 +33,7 @@
<div v-for="supplier in supplierList" :key="supplier.id"> <div v-for="supplier in supplierList" :key="supplier.id">
<div <div
v-if="!supplier.addresses || supplier.addresses.length === 0" v-if="!supplier.addresses || supplier.addresses.length === 0"
class="grid text-primary-700 grid-cols-7 border-t gap-4 px-4 py-2 hover:bg-slate-50 cursor-pointer" class="grid grid-cols-7 border-t gap-4 px-4 py-2 hover:bg-slate-50 cursor-pointer"
@click="goToSupplier(supplier.id)" @click="goToSupplier(supplier.id)"
> >
<div class="truncate">{{ supplier.name }}</div> <div class="truncate">{{ supplier.name }}</div>
@@ -40,7 +49,7 @@
<div <div
v-for="(address, idx) in supplier.addresses" v-for="(address, idx) in supplier.addresses"
:key="address.id ?? `${supplier.id}-${idx}-${address.street}-${address.postalCode}`" :key="address.id ?? `${supplier.id}-${idx}-${address.street}-${address.postalCode}`"
class="grid grid-cols-7 text-primary-700 hover:bg-slate-50 border-t gap-4 px-4 py-2 cursor-pointer" class="grid grid-cols-7 hover:bg-slate-50 border-t gap-4 px-4 py-2 cursor-pointer"
:class="idx > 0 ? 'pl-4 border-l-4 border-l-slate-200 bg-slate-50' : ''" :class="idx > 0 ? 'pl-4 border-l-4 border-l-slate-200 bg-slate-50' : ''"
@click="goToSupplier(supplier.id)" @click="goToSupplier(supplier.id)"
> >
@@ -58,7 +67,7 @@
<template v-else> <template v-else>
<div <div
class="grid grid-cols-7 text-primary-700 hover:bg-slate-50 border-t gap-4 px-4 py-2 cursor-pointer" class="grid grid-cols-7 hover:bg-slate-50 border-t gap-4 px-4 py-2 cursor-pointer"
@click="goToSupplier(supplier.id)" @click="goToSupplier(supplier.id)"
> >
<div class="truncate">{{ supplier.name }}</div> <div class="truncate">{{ supplier.name }}</div>
@@ -71,20 +80,9 @@
</div> </div>
</div> </div>
</div> </div>
<div v-else class="mt-7 border border-slate-200 mb-11 px-4 py-6 text-slate-400"> <div v-else class="mt-6 border border-slate-200 mb-16 px-4 py-6 text-slate-400">
Accès réservé aux administrateurs. Accès réservé aux administrateurs.
</div> </div>
<div class="flex justify-center items-center">
<NuxtLink
to="/admin/supplier"
class="inline-flex items-center mb-16 justify-center text-xl text-white uppercase bg-primary-500 h-[50px] px-8 rounded hover:opacity-80 gap-2"
:class="auth.isAdmin ? '' : 'cursor-not-allowed opacity-60'"
@click="handleAddClick"
>
<Icon name="mdi:plus" size="28" />
Ajouter
</NuxtLink>
</div>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
@@ -92,6 +90,8 @@ import { getSupplierList } from "~/services/supplier"
import type { SupplierData } from "~/services/dto/supplier-data" import type { SupplierData } from "~/services/dto/supplier-data"
import { useAuthStore } from "~/stores/auth" import { useAuthStore } from "~/stores/auth"
definePageMeta({ layout: "default" })
const supplierList = ref<SupplierData[]>([]) const supplierList = ref<SupplierData[]>([])
const router = useRouter() const router = useRouter()
const auth = useAuthStore() const auth = useAuthStore()

View File

@@ -1,70 +1,54 @@
<template> <template>
<form @submit.prevent="validate"> <form @submit.prevent="validate">
<div class="flex items-center relative"> <div
<div class="flex flex-row absolute -left-[60px]"> class="flex items-center justify-between gap-10">
<Icon <h1 class="text-3xl font-bold uppercase">
@click="router.push('/admin/user/list')" {{ userId ? "Modifications de l'utilisateur" : "Ajout d'un utilisateur" }}
name="gg:arrow-left-o"
size="40"
class="cursor-pointer text-primary-500"
/>
</div>
<h1 class="text-3xl text-primary-500 font-bold uppercase">
{{ userId ? "Modification de l'utilisateur" : "Ajout d'un utilisateur" }}
</h1> </h1>
<UiButton
class="text-xl uppercase bg-primary-500 text-white h-[50px] w-[272px]"
type="submit"
>
{{ userId ? 'Sauvegarder' : 'Ajouter' }}
</UiButton>
</div> </div>
<div class="flex flex-cols-3 justify-between mb-11 pt-7"> <div class="grid gap-y-16 gap-x-40 py-12">
<UiTextInput <UiTextInput
id="user-name" id="user-name"
v-model="form.username" v-model="form.username"
label="Nom de l'utilisateur" label="Nom de l'utilisateur"
:disabled="!auth.isAdmin"
wrapper-class="w-[280px]"
/> />
<UiSelect <UiSelect
id="user-role" id="user-role"
v-model="form.role" v-model="form.role"
label="Role de l'utilisateur" label="Rôle de l'utilisateur"
:options="ROLE" :options="ROLE"
:disabled="!auth.isAdmin"
wrapper-class="w-[280px]"
/> />
<UiTextInput <UiTextInput
id="user-password" id="user-password"
v-model="form.password" v-model="form.password"
label="Mot de passe" label="Mot de passe"
type="password" type="password"
:disabled="!auth.isAdmin"
wrapper-class="w-[280px]"
/>
</div>
<div class="flex items-center justify-center"> />
<UiButton
class="inline-flex mb-28 items-center justify-center text-xl min-w-[194px] text-white uppercase bg-primary-500 h-[50px] rounded hover:opacity-80 justify-self-end"
type="submit"
:disabled="isLoading || isHydrating || !auth.isAdmin"
>
<Icon :name="userId ? '' : 'mdi:plus'" size="28" />
{{ userId ? 'Valider' : 'Ajouter' }}
</UiButton>
</div> </div>
</form> </form>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { computed, reactive, ref, watch } from 'vue' definePageMeta({
import { ROLE } from '~/utils/constants' layout: 'default'
import { createUser, updateUser, getUser } from '~/services/auth' })
import type { UserData, UserFormData, UserPayload } from '~/services/dto/user-data'
import { useAuthStore } from '~/stores/auth' import {computed, reactive, ref, watch} from 'vue'
import {ROLE} from '~/utils/constants'
import {createUser, updateUser, getUser} from '~/services/auth'
import type {UserData, UserFormData, UserPayload} from '~/services/dto/user-data'
const route = useRoute() const route = useRoute()
const router = useRouter() const router = useRouter()
const auth = useAuthStore()
const userId = computed(() => resolveUserId(route.params.id)) const userId = computed(() => resolveUserId(route.params.id))
const isLoading = ref(false) const isLoading = ref(false)
const isHydrating = ref(false) const isHydrating = ref(false)
@@ -78,6 +62,7 @@ const resolveUserId = (param: unknown) => {
return Number.isFinite(id) ? id : null return Number.isFinite(id) ? id : null
} }
const form = reactive<UserFormData>({ const form = reactive<UserFormData>({
username: '', username: '',
password: '', password: '',
@@ -91,8 +76,8 @@ const hydrateFromUser = (user: UserData | null) => {
isHydrating.value = true isHydrating.value = true
form.username = user.username ?? '' form.username = user.username ?? ''
const roles = user.roles ?? [] const roles = user.roles ?? []
const hasAdmin = roles.includes('ROLE_ADMIN') const hasAdmin = roles.includes("ROLE_ADMIN")
form.role = hasAdmin ? 'ROLE_ADMIN' : 'ROLE_USER' form.role = hasAdmin ? "ROLE_ADMIN" : "ROLE_USER"
form.password = '' form.password = ''
isHydrating.value = false isHydrating.value = false
} }
@@ -111,11 +96,10 @@ watch(
isLoading.value = false isLoading.value = false
} }
}, },
{ immediate: true } {immediate: true}
) )
async function validate() { async function validate() {
if (!auth.isAdmin) return
const normalizedUsername = form.username.trim() const normalizedUsername = form.username.trim()
const normalizedRole = form.role.trim() const normalizedRole = form.role.trim()
@@ -131,12 +115,13 @@ async function validate() {
if (userId.value) { if (userId.value) {
await updateUser(userId.value, basePayload) await updateUser(userId.value, basePayload)
await router.push(`/admin/user/list/`)
return return
} }
const created = await createUser(basePayload) const created = await createUser(basePayload)
if (created) { if (created) {
await router.push('/admin/user/list') await router.push(`/admin/user/list/`)
} }
} }
</script> </script>

View File

@@ -1,72 +1,62 @@
<template> <template>
<div class="flex items-center justify-between"> <div class="flex items-center justify-between">
<h1 class="text-4xl font-bold uppercase text-primary-500">Liste des utilisateurs</h1> <h1 class="text-3xl font-bold uppercase text-primary-500">Liste des utilisateurs</h1>
<NuxtLink
class="inline-flex items-center justify-center gap-2 text-xl uppercase bg-primary-500 text-white h-[50px] px-8 rounded-md"
@click="router.push('/admin/user/')"
>
<Icon name="mdi:plus" size="28" />
Ajouter
</NuxtLink>
</div> </div>
<div v-if="auth.isAdmin" class="mt-7 border border-slate-200 mb-11"> <div>
<div class="grid grid-cols-2 text-primary-700 gap-4 bg-slate-100 px-4 py-3 text-sm font-semibold uppercase tracking-wide"> <div class="mt-6 border border-slate-200 mb-16 ">
<div>Utilisateur</div> <div class="grid grid-cols-3 gap-4 bg-slate-100 px-4 py-3 text-sm font-semibold uppercase tracking-wide">
<div>Role</div> <div>Username</div>
</div> <div>Role</div>
<div v-if="userList.length === 0" class="px-4 py-6 text-slate-400"> </div>
Aucun utilisateur.
</div>
<template v-else>
<div <div
v-for="user in userList" v-for="user in userList"
:key="user.id" :key="user.id"
class="grid grid-cols-2 text-primary-700 gap-4 px-4 py-3 text-sm hover:bg-slate-50 cursor-pointer border-t border-slate-200 items-center" class="grid grid-cols-3 gap-4 px-4 py-3 text-sm hover:bg-slate-50 cursor-pointer border-t items-center"
role="button" role="button"
tabindex="0" tabindex="0"
@click="goToUser(user.id)" @click="goToUser(user.id)"
@keydown.enter="goToUser(user.id)"
> >
<div>{{ user.username }}</div> <div>
<div>{{ getRoleLabels(user.roles) }}</div> {{ user.username }}
</div>
<div>
{{ getRoleLabels(user.roles) }}
</div>
</div> </div>
</template> </div>
</div>
<div v-else class="mt-7 border border-slate-200 mb-11 px-4 py-6 text-slate-400">
Acces reserve aux administrateurs.
</div>
<div class="flex justify-center items-center">
<NuxtLink
to="/admin/user"
class="inline-flex items-center mb-16 justify-center text-xl text-white uppercase bg-primary-500 h-[50px] px-8 rounded hover:opacity-80 gap-2"
:class="auth.isAdmin ? '' : 'cursor-not-allowed opacity-60'"
@click="handleAddClick"
>
<Icon name="mdi:plus" size="28" />
Ajouter
</NuxtLink>
</div> </div>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import type { UserData } from "~/services/dto/user-data" definePageMeta({
import { getAdminUsers } from "~/services/auth" layout: 'default'
import { ROLE } from "~/utils/constants" })
import { useAuthStore } from "~/stores/auth"
import type {UserData} from "~/services/dto/user-data";
import {getAdminUsers} from "~/services/auth";
import {ROLE} from "~/utils/constants";
const userList = ref<UserData[]>([]) const userList = ref<UserData[]>([])
const router = useRouter() const router = useRouter()
const auth = useAuthStore()
const roleLabelByValue = new Map(ROLE.map((role) => [role.value, role.label])) const roleLabelByValue = new Map(ROLE.map((role) => [role.value, role.label]))
const goToUser = (id: number) => { const goToUser = (id: number) => {
if (!auth.isAdmin) return
router.push(`/admin/user/${id}`) router.push(`/admin/user/${id}`)
} }
const handleAddClick = (event: Event) => {
if (auth.isAdmin) return
event.preventDefault()
}
const getRoleLabels = (roles?: string[]) => { const getRoleLabels = (roles?: string[]) => {
if (!roles || roles.length === 0) { if (!roles || roles.length === 0) {
return '---' return ' ---'
} }
return roles return roles
@@ -75,7 +65,6 @@ const getRoleLabels = (roles?: string[]) => {
} }
onMounted(async () => { onMounted(async () => {
if (!auth.isAdmin) return
userList.value = await getAdminUsers() userList.value = await getAdminUsers()
}) })
</script> </script>

View File

@@ -4,7 +4,7 @@
<div class="flex flex-wrap justify-center pb-16 gap-12"> <div class="flex flex-wrap justify-center pb-16 gap-12">
<card-link label="NOUVELLE RÉCEPTION" link="/reception" iconName="mdi:truck-outline" /> <card-link label="NOUVELLE RÉCEPTION" link="/reception" iconName="mdi:truck-outline" />
<card-link label="NOUVELLE EXPÉDITION" link="/shipment" iconName="mdi:truck-fast-outline" /> <card-link label="NOUVELLE EXPÉDITION" link="/shipment" iconName="mdi:truck-fast-outline" />
<card-link label="PLAN DE SITE" link="/infrastructure/building" iconName="material-symbols:warehouse-outline-rounded" /> <card-link label="PLAN DE SITE" link="/" iconName="material-symbols:warehouse-outline-rounded" />
<card-link link="/reception/waiting-reception" iconName="mdi:truck-remove-outline"> <card-link link="/reception/waiting-reception" iconName="mdi:truck-remove-outline">
<template #label> <template #label>
Réceptions<br>EN ATTENTE Réceptions<br>EN ATTENTE
@@ -15,7 +15,7 @@
EXPÉDITIONS<br>EN ATTENTE EXPÉDITIONS<br>EN ATTENTE
</template> </template>
</card-link> </card-link>
<card-link label="CASES" link="/infrastructure/case" iconName="material-symbols:bottom-sheets-outline" /> <card-link label="CASES" link="/" iconName="material-symbols:bottom-sheets-outline" />
<card-link label="RÉCEPTIONS FINIES" link="/reception/finish-reception" iconName="mdi:truck-check-outline" /> <card-link label="RÉCEPTIONS FINIES" link="/reception/finish-reception" iconName="mdi:truck-check-outline" />
<card-link label="EXPÉDITIONS FINIES" link="/shipment/finish-shipment" iconName="mdi:truck-delivery-outline" /> <card-link label="EXPÉDITIONS FINIES" link="/shipment/finish-shipment" iconName="mdi:truck-delivery-outline" />
<card-link link="/" iconName="mdi:cow"> <card-link link="/" iconName="mdi:cow">

View File

@@ -1,242 +0,0 @@
<template>
<div class="min-h-screen">
<!-- En-tête de page avec retour et titre -->
<div class="flex items-center justify-between mb-8">
<div class="flex items-center gap-10">
<Icon
@click="router.push('/')"
name="gg:arrow-left-o"
size="44"
class="cursor-pointer text-primary-500"
/>
<h1 class="text-3xl font-bold uppercase text-primary-500">bâtiments</h1>
</div>
</div>
<div class="px-[86px] space-y-6">
<!-- Liste des bâtiments + rendu du plan de chaque bâtiment -->
<div
v-for="entry in buildingLayouts"
:key="entry.building.id"
>
<div class="font-semibold tracking-wide text-primary-500">
{{ entry.building.label || `Bâtiment ${entry.building.id}` }}
</div>
<div class="py-4">
<!-- Aucun layout disponible pour ce bâtiment -->
<div v-if="!entry.layout" class="text-sm text-slate-400">
Aucun plan de bâtiment.
</div>
<!-- Grille CSS : les cases sont positionnées via spanStyle -->
<div v-else class="overflow-auto">
<div class="grid" :style="entry.gridStyle">
<NuxtLink
v-for="cell in entry.cells"
:key="cell.key"
class="relative text-white flex h-[50px] items-center justify-center border-y-[3px] border-y-black bg-white hover:opacity-85 focus-visible:outline-none"
:class="[cell.sideBorderClass, activeLegendStatutId !== null && cell.caseStatusId !== activeLegendStatutId ? 'opacity-35 hover:opacity-70' : '']"
:style="[cell.spanStyle, cell.sideBorderStyle]"
:to="cell.caseId ? `/infrastructure/case?id=${cell.caseId}` : '/infrastructure/case'"
:title="cell.caseStatusLabel ?? undefined"
>
<!-- Le blanc latéral est géré sur ce bloc interne (conditionnel par voisinage) -->
<div
class="flex h-full w-full items-center justify-center bg-white"
:class="cell.contentInsetClass"
:style="cell.caseStyle"
>
<!-- Numéro de case -->
{{ cell.display }}
</div>
</NuxtLink>
</div>
</div>
</div>
</div>
<!-- Légende : survol d'un statut => atténue les autres cases -->
<div class="py-4">
<!-- 3 zones fixes pour forcer gauche / centre / droite sur toute la largeur -->
<div class="grid w-full grid-cols-3 gap-3">
<div
v-for="(statut, index) in statutLegend"
:key="statut.id"
class="flex min-w-0 cursor-pointer items-center gap-2 py-1"
:class="[
index === 0 ? 'justify-self-start' : '',
index === statutLegend.length - 1 ? 'justify-self-end' : '',
index > 0 && index < statutLegend.length - 1 ? 'justify-self-center' : ''
]"
@mouseenter="activeLegendStatutId = statut.id"
@mouseleave="activeLegendStatutId = null"
>
<span
class="h-5 w-5 border border-slate-300"
:style="statut.couleur ? { backgroundColor: statut.couleur } : {}"
></span>
<span class="truncate text-sm uppercase text-slate-700">
{{ statut.label }}
</span>
</div>
</div>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import type {BuildingData} from "~/services/dto/building-data"
import type {BuildingLayoutData} from "~/services/dto/building-layout-data"
import type {BuildingCasePositionData} from "~/services/dto/building-case-position-data"
import type {BuildingCaseStatusData} from "~/services/dto/building-case-status-data"
import {getBuildingList} from "~/services/building"
import {getStatutList} from "~/services/statut"
definePageMeta({layout: "default"})
const router = useRouter()
// Données brutes chargées depuis l'API
const buildingList = ref<BuildingData[]>([])
const statutLegend = ref<BuildingCaseStatusData[]>([])
// Statut actuellement survolé dans la légende (pour filtrage visuel)
const activeLegendStatutId = ref<number | null>(null)
// Modèle de vue prêt pour le template (layout + cellules + styles de grille)
const buildingLayouts = computed(() =>
buildingList.value.map((building) => {
// On affiche uniquement le premier layout du bâtiment
const layout = building.layouts?.[0] ?? null
const view = layout ? buildLayoutView(layout) : null
return {building, layout, cells: view?.cells ?? [], gridStyle: view?.gridStyle ?? {}}
})
)
type GridCell = {
key: string
caseId: number | null
display: string
caseStatusId: number | null
caseStatusLabel: string | null
// Couleur de fond de la case (dépend du statut)
caseStyle?: Record<string, string>
// Placement dans la grille CSS (colonne/ligne de départ + span)
spanStyle: Record<string, string>
// Bordures latérales pointillées si la case touche un gap ou le bord du plan
sideBorderClass: string
// Couleur des bordures pointillées latérales (reprend la couleur de la cellule)
sideBorderStyle?: Record<string, string>
// Espace blanc interne uniquement côté(s) adjacent(s) à une autre case
contentInsetClass: string
}
// Type intermédiaire : garde des infos utiles au calcul des bordures, retirées ensuite
type GridCellDraft = Omit<GridCell, "sideBorderClass" | "sideBorderStyle" | "contentInsetClass"> & { x: number; columnSpan: number }
// Nettoie la couleur de statut pour éviter les chaînes vides / espaces
const normalizeCaseStatusColor = (value: string | null | undefined): string | null => {
const color = (value ?? "").trim()
return color.length > 0 ? color : null
}
// Styles de base communs à toutes les grilles de bâtiments
const BASE_GRID_STYLE = {gridAutoRows: "1fr", rowGap: "18px", columnGap: "0px", width: "100%"} as const
// Transforme un layout API en structure de rendu (cellules + style de grille)
const buildLayoutView = (layout: BuildingLayoutData): {
cells: GridCell[];
gridStyle: Record<string, string>
} | null => {
const rows = layout.rows ?? 0, cols = layout.columns ?? 0
if (rows <= 0 || cols <= 0) return null
// Liste des positions de cases (filtre de sécurité sur les valeurs nulles)
const positions = (layout.casePositions ?? []).filter(Boolean) as BuildingCasePositionData[]
// Colonnes occupées par au moins une case (sert à détecter les gaps)
const occupiedColumns = new Set<number>()
// Sécurité : si deux positions ont le même x/y, on garde la première
const seenCoordinates = new Set<string>()
const cellDrafts: GridCellDraft[] = []
// Tri visuel : de haut en bas, puis de gauche à droite
const positionsSorted = [...positions].sort(
(leftPosition, rightPosition) =>
(leftPosition.y ?? 1) - (rightPosition.y ?? 1) || (leftPosition.x ?? 1) - (rightPosition.x ?? 1)
)
for (const position of positionsSorted) {
const x = position.x ?? 1
const y = position.y ?? 1
const coordinateKey = `${x}-${y}`
if (seenCoordinates.has(coordinateKey)) continue
seenCoordinates.add(coordinateKey)
// w/h = nombre de colonnes / lignes occupées par la case dans la grille
const columnSpan = position.w ?? 1
const rowSpan = position.h ?? 1
// Une case peut couvrir plusieurs colonnes : on les marque toutes comme occupées
for (let column = x; column < x + columnSpan; column++) {
if (column <= cols) occupiedColumns.add(column)
}
// Métadonnées utiles au rendu / navigation / légende
const caseId = (position.buildingCase?.id ?? null) as number | null
const caseNumber = (position.buildingCase?.caseNumber ?? null) as number | null
const caseStatusId = position.buildingCase?.statut?.id ?? null
const caseStatusLabel = position.buildingCase?.statut?.label ?? null
const statusColor = normalizeCaseStatusColor(position.buildingCase?.statut?.couleur)
cellDrafts.push({
key: `case-${layout.id}-${position.id}`,
x,
columnSpan,
caseId,
display: caseNumber !== null ? String(caseNumber) : "Case",
caseStatusId,
caseStatusLabel,
caseStyle: statusColor ? {backgroundColor: statusColor} : undefined,
// Exemple : "14 / span 1" => commence en colonne 14 et occupe 1 colonne
spanStyle: {gridColumn: `${x} / span ${columnSpan}`, gridRow: `${y} / span ${rowSpan}`}
})
}
// Colonnes vides = gaps visuels (plus étroites dans la grille)
const gapColumns = Array.from({length: cols}, (_, i) => i + 1).filter((x) => !occupiedColumns.has(x))
const gapSet = new Set(gapColumns)
// Ajoute les bordures latérales pointillées pour les cases au contact d'un gap ou d'un bord
const cells: GridCell[] = cellDrafts.map(({x, columnSpan, ...cell}) => {
const touchesLeftGapOrEdge = x === 1 || gapSet.has(x - 1)
const touchesRightGapOrEdge = x + columnSpan - 1 === cols || gapSet.has(x + columnSpan)
const sideBorderClass = [
touchesLeftGapOrEdge ? "border-l-[3px] [border-left-style:dashed]" : "",
touchesRightGapOrEdge ? "border-r-[3px] [border-right-style:dashed]" : ""
].filter(Boolean).join(" ")
// Les pointillés latéraux reprennent la couleur de la cellule (si un statut en fournit une)
const sideBorderStyle = {
...(cell.caseStyle?.backgroundColor && touchesLeftGapOrEdge ? {borderLeftColor: cell.caseStyle.backgroundColor} : {}),
...(cell.caseStyle?.backgroundColor && touchesRightGapOrEdge ? {borderRightColor: cell.caseStyle.backgroundColor} : {})
}
// Le "blanc" n'est ajouté qu'entre deux cellules adjacentes (pas sur bord/gap)
const contentInsetClass = [
!touchesLeftGapOrEdge ? "ml-[4px]" : "",
!touchesRightGapOrEdge ? "mr-[4px]" : ""
].filter(Boolean).join(" ")
return {...cell, sideBorderClass, sideBorderStyle, contentInsetClass}
})
// Les colonnes de gap sont rendues en 24px, les autres occupent l'espace restant
const columnsTemplate = Array.from({length: cols}, (_, i) => (gapSet.has(i + 1) ? "24px" : "minmax(0, 1fr)")).join(" ")
return {cells, gridStyle: {gridTemplateColumns: columnsTemplate, ...BASE_GRID_STYLE}}
}
onMounted(async () => {
// Chargement initial des bâtiments et de la légende des statuts
const buildings = await getBuildingList()
const statuts = await getStatutList()
buildingList.value = buildings
// Tri alphabétique FR pour une légende stable
statutLegend.value = [...statuts].sort((a, b) =>
(a.label ?? "").localeCompare(b.label ?? "", "fr", {sensitivity: "base"})
)
})
</script>

View File

@@ -1,27 +0,0 @@
<template>
<div class="flex justify-center items-center">
<UiButton
class="text-xl uppercase bg-primary-500 text-white h-[50px] w-[272px]"
:disabled="!hasCaseId"
@click="printCaseReport"
>
Imprimer
</UiButton>
</div>
</template>
<script setup lang="ts">
const route = useRoute()
const { printPdf } = usePdfPrinter()
const caseId = computed(() => Number(route.query.id))
const hasCaseId = computed(() => Number.isFinite(caseId.value) && caseId.value > 0)
const printCaseReport = async () => {
if (!hasCaseId.value) {
return
}
const filename = `tableau_poids_case_${caseId.value}.pdf`
await printPdf(`/building_cases/${caseId.value}/weights-report`, filename)
}
</script>

View File

@@ -172,27 +172,28 @@
/> />
<update-merchandise <update-merchandise
v-if="activeTab === 'merchandise' && isMerchandise" v-show="activeTab === 'merchandise' && isMerchandise"
v-model="merchandiseForm" v-model="merchandiseForm"
:isAdmin="auth.isAdmin" :isAdmin="auth.isAdmin"
/> />
<update-bovin <update-bovin
v-if="activeTab === 'merchandise' && !isMerchandise" v-show="activeTab === 'merchandise' && !isMerchandise"
v-model="bovineEntries" v-model="bovineEntries"
v-model:otherQuantity="bovineOtherQuantity" v-model:otherQuantity="bovineOtherQuantity"
:isAdmin="auth.isAdmin" :isAdmin="auth.isAdmin"
/> />
</div> </div>
<div class="flex justify-center"> <div class="flex justify-center">
<UiButton <UiButton
v-if="auth.isAdmin" v-if="auth.isAdmin"
type="submit" type="submit"
class="inline-flex mb-16 items-center justify-center text-xl text-white uppercase bg-primary-500 h-[50px] px-8 rounded hover:opacity-80 gap-2 justify-self-end" class="text-xl uppercase bg-primary-500 text-white h-[50px] w-[272px] mb-16"
>
Valider >
</UiButton> Enregistrer
</div> </UiButton>
</div>
</div> </div>
</form> </form>
</template> </template>
@@ -202,7 +203,7 @@ import { usePdfPrinter } from '#imports'
import { computed } from 'vue' import { computed } from 'vue'
import UpdateBovin from '~/components/reception/update-bovin.vue' import UpdateBovin from '~/components/reception/update-bovin.vue'
import UpdateMerchandise from '~/components/reception/update-merchandise.vue' import UpdateMerchandise from '~/components/reception/update-merchandise.vue'
import UpdateWeight from '~/components/commun/update-weight.vue' import UpdateWeight from '~/components/reception/update-weight.vue'
import { getUsers } from '~/services/auth' import { getUsers } from '~/services/auth'
import { getCarrierList } from '~/services/carrier' import { getCarrierList } from '~/services/carrier'
import type { CarrierData } from '~/services/dto/carrier-data' import type { CarrierData } from '~/services/dto/carrier-data'
@@ -212,8 +213,8 @@ import type {
MerchandiseEntryData, MerchandiseEntryData,
ReceptionData, ReceptionData,
ReceptionFormData, ReceptionFormData,
WeightEntryData
} from '~/services/dto/reception-data' } from '~/services/dto/reception-data'
import type { WeightEntryData } from '~/services/dto/weight-data'
import type { ReceptionTypeData } from '~/services/dto/reception-type-data' import type { ReceptionTypeData } from '~/services/dto/reception-type-data'
import type { SupplierData } from '~/services/dto/supplier-data' import type { SupplierData } from '~/services/dto/supplier-data'
import type { TruckData } from '~/services/dto/truck-data' import type { TruckData } from '~/services/dto/truck-data'
@@ -278,25 +279,9 @@ const isLoadingVehicles = ref(false)
const formIsLoading = ref(false) const formIsLoading = ref(false)
const isMerchandise = ref(false) const isMerchandise = ref(false)
const isHydrating = ref(false) const isHydrating = ref(false)
const vehicleSyncLock = ref(false)
const idReception = Number(route.params.id) const idReception = Number(route.params.id)
function runWithVehicleSyncLock(mutator: () => void) {
if (vehicleSyncLock.value) {
return
}
vehicleSyncLock.value = true
try {
mutator()
} finally {
queueMicrotask(() => {
vehicleSyncLock.value = false
})
}
}
const form = reactive<ReceptionFormData>({ const form = reactive<ReceptionFormData>({
identificationNumber: null, identificationNumber: null,
licensePlate: '', licensePlate: '',
@@ -342,7 +327,7 @@ const filteredVehicles = computed<VehicleData[]>(() => {
watch( watch(
() => idReception, () => idReception,
async (id) => { async (id) => {
if (!Number.isFinite(id) || id <= 0) { if (id === null) {
return return
} }
isLoading.value = true isLoading.value = true
@@ -515,7 +500,7 @@ async function loadTypes() {
try { try {
receptionTypes.value = await getReceptionTypeList() receptionTypes.value = await getReceptionTypeList()
} finally { } finally {
isLoadingTypes.value = false isLoadingSuppliers.value = false
} }
} }
@@ -596,16 +581,8 @@ async function saveWeightEntry(entry: WeightEntryData) {
return return
} }
// Fallback: if id is missing in local state, reuse existing weight by type.
const reception = await getReception(idReception)
const existingEntry = reception?.weights?.find((weight) => weight.type === entry.type) ?? null
if (existingEntry?.id) {
await updateWeight(existingEntry.id, payload)
return
}
await createWeight({ await createWeight({
reception: `/api/receptions/${idReception}`, reception: `api/receptions/${idReception}`,
...payload ...payload
}) })
} }
@@ -808,11 +785,8 @@ async function validate() {
}) })
} }
// Évite une réhydratation complète après save (source de cascades de watchers). const refreshedReception = await getReception(idReception)
// On recharge uniquement les bovins quand on est en mode bovins. hydrateFromReception(refreshedReception)
if (!isMerchandise.value) {
await loadBovineEntries(idReception)
}
return return
} }
@@ -835,20 +809,12 @@ onMounted(async () => {
watch( watch(
() => [form.supplierId, form.addressId, suppliers.value], () => [form.supplierId, form.addressId, suppliers.value],
() => { () => {
if (isHydrating.value) {
return
}
if (!form.supplierId) { if (!form.supplierId) {
if (form.addressId !== '') { form.addressId = ''
form.addressId = ''
}
return return
} }
if (!form.addressId && supplierAddresses.value.length === 1) { if (!form.addressId && supplierAddresses.value.length === 1) {
const nextAddressId = String(supplierAddresses.value[0].id) form.addressId = String(supplierAddresses.value[0].id)
if (form.addressId !== nextAddressId) {
form.addressId = nextAddressId
}
return return
} }
if (!form.addressId) { if (!form.addressId) {
@@ -859,14 +825,9 @@ watch(
) )
if (!matches) { if (!matches) {
if (supplierAddresses.value.length === 1) { if (supplierAddresses.value.length === 1) {
const nextAddressId = String(supplierAddresses.value[0].id) form.addressId = String(supplierAddresses.value[0].id)
if (form.addressId !== nextAddressId) {
form.addressId = nextAddressId
}
} else { } else {
if (form.addressId !== '') { form.addressId = ''
form.addressId = ''
}
} }
} }
}, },
@@ -876,36 +837,24 @@ watch(
watch( watch(
() => form.carrierId, () => form.carrierId,
() => { () => {
if (isHydrating.value || vehicleSyncLock.value) { if (isHydrating.value) {
return return
} }
if (!form.carrierId && idReception == null) { if (!form.carrierId && idReception == null) {
runWithVehicleSyncLock(() => { form.driverId = ''
form.driverId = '' form.vehicleId = ''
form.vehicleId = ''
})
return return
} }
if (!isLiotCarrier.value && idReception == null) { if (!isLiotCarrier.value && idReception == null) {
runWithVehicleSyncLock(() => { form.driverId = ''
form.driverId = '' form.vehicleId = ''
form.vehicleId = ''
})
return return
} }
if (filteredDrivers.value.length === 1) { if (filteredDrivers.value.length === 1) {
const nextDriverId = String(filteredDrivers.value[0].id) form.driverId = String(filteredDrivers.value[0].id)
if (form.driverId !== nextDriverId) {
form.driverId = nextDriverId
}
} }
if (filteredVehicles.value.length === 1) { if (filteredVehicles.value.length === 1) {
const nextVehicleId = String(filteredVehicles.value[0].id) form.vehicleId = String(filteredVehicles.value[0].id)
if (form.vehicleId !== nextVehicleId) {
runWithVehicleSyncLock(() => {
form.vehicleId = nextVehicleId
})
}
} }
}, },
{ immediate: true } { immediate: true }
@@ -914,19 +863,11 @@ watch(
watch( watch(
() => [form.truckId, form.carrierId, vehicles.value], () => [form.truckId, form.carrierId, vehicles.value],
() => { () => {
if (isHydrating.value || vehicleSyncLock.value) {
return
}
if (!isLiotCarrier.value) { if (!isLiotCarrier.value) {
return return
} }
if (filteredVehicles.value.length === 1) { if (filteredVehicles.value.length === 1) {
const nextVehicleId = String(filteredVehicles.value[0].id) form.vehicleId = String(filteredVehicles.value[0].id)
if (form.vehicleId !== nextVehicleId) {
runWithVehicleSyncLock(() => {
form.vehicleId = nextVehicleId
})
}
return return
} }
if (!form.vehicleId) { if (!form.vehicleId) {
@@ -936,11 +877,7 @@ watch(
(vehicle) => String(vehicle.id) === form.vehicleId (vehicle) => String(vehicle.id) === form.vehicleId
) )
if (!matches) { if (!matches) {
if (form.vehicleId !== '') { form.vehicleId = ''
runWithVehicleSyncLock(() => {
form.vehicleId = ''
})
}
} }
}, },
{ immediate: true } { immediate: true }
@@ -949,9 +886,6 @@ watch(
watch( watch(
() => [form.vehicleId, form.carrierId, vehicles.value], () => [form.vehicleId, form.carrierId, vehicles.value],
() => { () => {
if (vehicleSyncLock.value) {
return
}
if (!isLiotCarrier.value) { if (!isLiotCarrier.value) {
return return
} }
@@ -961,11 +895,9 @@ watch(
const selected = filteredVehicles.value.find( const selected = filteredVehicles.value.find(
(vehicle) => String(vehicle.id) === form.vehicleId (vehicle) => String(vehicle.id) === form.vehicleId
) )
if (selected && form.licensePlate !== selected.plate) { if (selected) {
runWithVehicleSyncLock(() => { form.licensePlate = selected.plate
form.licensePlate = selected.plate allowAnyLicensePlate.value = false
allowAnyLicensePlate.value = false
})
} }
} }
) )
@@ -973,12 +905,6 @@ watch(
watch( watch(
() => [form.licensePlate, form.carrierId, vehicles.value], () => [form.licensePlate, form.carrierId, vehicles.value],
() => { () => {
if (vehicleSyncLock.value) {
return
}
if (isHydrating.value) {
return
}
if (!isLiotCarrier.value || form.vehicleId) { if (!isLiotCarrier.value || form.vehicleId) {
return return
} }
@@ -986,12 +912,7 @@ watch(
(vehicle) => vehicle.plate === form.licensePlate (vehicle) => vehicle.plate === form.licensePlate
) )
if (match) { if (match) {
const nextVehicleId = String(match.id) form.vehicleId = String(match.id)
if (form.vehicleId !== nextVehicleId) {
runWithVehicleSyncLock(() => {
form.vehicleId = nextVehicleId
})
}
} }
} }
) )

View File

@@ -1,639 +0,0 @@
<template>
<form @submit.prevent="validate">
<div class="grid grid-cols-2 h-[461px] items-start gap-y-8 gap-x-40 mb-16">
<div class="flex items-center justify-between gap-10 relative col-start-1 row-start-1">
<div class="flex flex-row absolute -left-[60px] justify-between">
<Icon @click="router.push('/shipment/finish-shipment')" name="gg:arrow-left-o" size="44" class="cursor-pointer text-primary-500"/>
</div>
<h1 class="font-bold text-4xl col-start-1 row-start-1 text-primary-500 uppercase">Expédition {{ form.identificationNumber }}</h1>
<Icon @click="printReceipt" name="mdi:printer-outline" size="44" class="cursor-pointer text-primary-500"/>
</div>
<UiSelect
id="shipment-user"
v-model="form.userId"
label="Nom de l'utilisateur"
:options="users.map((user) => ({
value: String(user.id),
label: user.username
}))"
:loading="isLoadingUsers"
wrapper-class="col-start-1 row-start-2"
/>
<UiDateInput
id="shipment-date"
v-model="form.shipmentDate"
label="Date d'expédition"
wrapper-class="col-start-1 row-start-3"
/>
<div class="col-start-1 row-start-4 h-[64px]">
<div class="flex w-full items-end gap-[104px]">
<UiRadioGroup
id="shipment-type"
name="shipment-type"
label="Type d'expédition bovine"
input-class="accent-primary-700 focus:ring-primary-700"
group-class="flex flex-row gap-[104px] w-[160px_160px] h-[32px]"
v-model="selectedShipmentTypeId"
:options="bovineShipment.map((type) => ({
value: String(type.id),
label: type.label
}))"
/>
<UiNumberInput
id="shipment-type-quantity"
v-model="shipmentQuantity"
:placeholder="0"
:min="0"
:max="1200"
:disabled="!selectedShipmentTypeId"
/>
</div>
</div>
<UiSelect
id="shipment-customer"
v-model="form.customerId"
label="Client"
:options="customers.map((customer) => ({
value: String(customer.id),
label: customer.name || `Client #${customer.id}`
}))"
:loading="isLoadingCustomers"
wrapper-class="col-start-1 row-start-5"
/>
<UiSelect
id="shipment-address"
v-model="form.addressId"
:options="customerAddressOptions"
:disabled="isLoadingCustomers || customerAddresses.length === 0"
label="Adresse"
wrapper-class="col-start-2 row-start-1"
/>
<UiSelect
id="shipment-truck"
v-model="form.truckId"
label="Camion"
:options="trucks.map((truck) => ({
value: String(truck.id),
label: truck.name
}))"
:loading="isLoadingTrucks"
wrapper-class="col-start-2 row-start-2"
/>
<UiSelect
id="shipment-carrier"
v-model="form.carrierId"
label="Transporteur"
:options="carriers.map((carrier) => ({
value: String(carrier.id),
label: carrier.name
}))"
wrapper-class="col-start-2 row-start-3"
/>
<div v-if="!isLiotCarrier" class="col-start-2 row-start-4">
<UiLicensePlateInput
v-model="form.licensePlate"
v-model:allowAny="allowAnyLicensePlate"
/>
</div>
<UiSelect
v-if="isLiotCarrier"
id="shipment-vehicle"
v-model="form.vehicleId"
label="Immatriculation"
:options="filteredVehicles.map((vehicle) => ({
value: String(vehicle.id),
label: vehicle.plate
}))"
:loading="isLoadingVehicles"
:disabled="isLoadingVehicles || filteredVehicles.length === 0"
wrapper-class="col-start-2 row-start-4"
/>
<div class="col-start-2 row-start-5 min-h-[72px]">
<UiSelect
v-if="isLiotCarrier"
id="shipment-driver"
v-model="form.driverId"
label="Nom du chauffeur si LIOT"
:options="filteredDrivers.map((driver) => ({
value: String(driver.id),
label: driver.name
}))"
:loading="isLoadingDrivers"
/>
</div>
</div>
<div v-if="formIsLoading">
<div class="flex justify-evenly gap-y-8 gap-x-41 mb-10 border-b border-primary-500/60">
<h1
class="font-bold text-3xl uppercase px-12 col-start-1 row-start-1 cursor-pointer"
:class="activeTab === 'weights' ? 'border-b-[6px] border-primary-500 text-primary-500' : 'text-primary-500/50'"
@click="activeTab = 'weights'"
>
pesée à plein
</h1>
<h1
class="font-bold text-3xl uppercase col-start-1 row-start-1 px-12 cursor-pointer"
:class="activeTab === 'weightsEmpty' ? 'border-b-[6px] border-primary-500 text-primary-500' : 'text-primary-500/50'"
@click="activeTab = 'weightsEmpty'"
>
pesée à vide
</h1>
</div>
<div class="mb-12">
<update-weight
v-show="activeTab === 'weights'"
v-model="grossWeight"
v-if="grossWeight"
:isAdmin="authStore.isAdmin"
/>
<update-weight
v-show="activeTab === 'weightsEmpty'"
v-model="tareWeight"
v-if="tareWeight"
:isAdmin="authStore.isAdmin"
/>
</div>
</div>
<div class="flex justify-center">
<UiButton
type="submit"
class="text-xl mb-16 uppercase bg-primary-500 text-white h-[50px] w-[272px] justify-self-end"
>
Valider
</UiButton>
</div>
</form>
</template>
<script setup lang="ts">
import { usePdfPrinter } from '#imports'
import { computed, onMounted, reactive, ref, watch } from 'vue'
import UpdateWeight from '~/components/commun/update-weight.vue'
import { getUsers } from '~/services/auth'
import { getCarrierList } from '~/services/carrier'
import { getCustomerList } from '~/services/customer'
import type { AddressData } from '~/services/dto/address-data'
import type { CarrierData } from '~/services/dto/carrier-data'
import type { CustomerData } from '~/services/dto/customer-data'
import type { DriverData } from '~/services/dto/driver-data'
import type { ShipmentData, ShipmentFormData } from '~/services/dto/shipment-data'
import type { ShipmentTypeData } from '~/services/dto/shipment-type-data'
import type { TruckData } from '~/services/dto/truck-data'
import type { UserData } from '~/services/dto/user-data'
import type { VehicleData } from '~/services/dto/vehicle-data'
import type { WeightEntryData } from '~/services/dto/weight-data'
import { getDriverList } from '~/services/driver'
import { getShipment, updateShipment } from '~/services/shipment'
import { getShipmentTypeList } from '~/services/shipment-type'
import { getTruckList } from '~/services/truck'
import { getVehicleList } from '~/services/vehicle'
import { createWeight, updateWeight } from '~/services/weight'
import { useAuthStore } from '~/stores/auth'
import { SUPPLIER_CODE } from '~/utils/constants'
const router = useRouter()
const route = useRoute()
const authStore = useAuthStore()
const { printPdf } = usePdfPrinter()
const users = ref<UserData[]>([])
const customers = ref<CustomerData[]>([])
const trucks = ref<TruckData[]>([])
const carriers = ref<CarrierData[]>([])
const drivers = ref<DriverData[]>([])
const vehicles = ref<VehicleData[]>([])
const bovineShipment = ref<ShipmentTypeData[]>([])
const currentShipment = ref<ShipmentData | null>(null)
const selectedShipmentTypeId = ref('')
const shipmentQuantity = ref<number | null>(0)
const allowAnyLicensePlate = ref(false)
const activeTab = ref<'weightsEmpty' | 'weights'>('weights')
const grossWeight = ref<WeightEntryData>(createEmptyWeightEntry('gross'))
const tareWeight = ref<WeightEntryData>(createEmptyWeightEntry('tare'))
const formIsLoading = ref(false)
const isLoadingUsers = ref(false)
const isLoadingShipmentTypes = ref(false)
const isLoadingCustomers = ref(false)
const isLoadingTrucks = ref(false)
const isLoadingCarriers = ref(false)
const isLoadingVehicles = ref(false)
const isLoadingDrivers = ref(false)
const isHydrating = ref(false)
const form = reactive<ShipmentFormData & { identificationNumber: string | null }>({
identificationNumber: null,
userId: '',
shipmentDate: new Date().toISOString().slice(0, 10),
customerId: '',
addressId: '',
truckId: '',
carrierId: '',
driverId: '',
vehicleId: '',
licensePlate: ''
})
const shipmentId = computed(() => {
const id = Number(route.params.id)
return Number.isFinite(id) ? id : null
})
const selectedCarrier = computed(() =>
carriers.value.find((carrier) => String(carrier.id) === form.carrierId) ?? null
)
const isLiotCarrier = computed(() => selectedCarrier.value?.code === SUPPLIER_CODE.LIOT)
const isAddressData = (value: unknown): value is AddressData =>
typeof value === 'object' &&
value !== null &&
'id' in value &&
'fullAddress' in value
const customerAddresses = computed<AddressData[]>(() => {
if (!form.customerId) return []
const customerId = Number(form.customerId)
if (!Number.isFinite(customerId) || customerId <= 0) return []
const addresses = customers.value.find((c) => c.id === customerId)?.addresses ?? []
return addresses.filter(isAddressData)
})
const customerAddressOptions = computed(() =>
customerAddresses.value.map((address) => ({
value: String(address.id),
label: address.fullAddress
}))
)
const filteredDrivers = computed<DriverData[]>(() => {
if (!form.carrierId) {
return []
}
return drivers.value.filter((driver) => String(driver.carrier?.id) === form.carrierId)
})
const filteredVehicles = computed<VehicleData[]>(() => {
if (!form.carrierId) {
return []
}
return vehicles.value.filter(
(vehicle) =>
String(vehicle.carrier?.id) === form.carrierId &&
(!form.truckId || String(vehicle.truck?.id) === form.truckId)
)
})
const loadUsers = async () => {
isLoadingUsers.value = true
try {
users.value = await getUsers()
} finally {
isLoadingUsers.value = false
}
}
const loadShipmentType = async () => {
isLoadingShipmentTypes.value = true
try {
bovineShipment.value = await getShipmentTypeList()
} finally {
isLoadingShipmentTypes.value = false
}
}
const loadCustomers = async () => {
isLoadingCustomers.value = true
try {
customers.value = await getCustomerList()
} finally {
isLoadingCustomers.value = false
}
}
const loadTrucks = async () => {
isLoadingTrucks.value = true
try {
trucks.value = await getTruckList()
} finally {
isLoadingTrucks.value = false
}
}
const loadCarriers = async () => {
isLoadingCarriers.value = true
try {
carriers.value = await getCarrierList()
} finally {
isLoadingCarriers.value = false
}
}
const loadVehicles = async () => {
isLoadingVehicles.value = true
try {
vehicles.value = await getVehicleList()
} finally {
isLoadingVehicles.value = false
}
}
const loadDrivers = async () => {
isLoadingDrivers.value = true
try {
drivers.value = await getDriverList()
} finally {
isLoadingDrivers.value = false
}
}
function setDefaultUser() {
if (form.userId) {
return
}
if (authStore.user?.id) {
form.userId = String(authStore.user.id)
}
}
function hydrateFromShipment(shipment: ShipmentData | null) {
if (!shipment) {
return
}
isHydrating.value = true
form.identificationNumber = shipment.identificationNumber ?? null
form.licensePlate = shipment.licensePlate ?? ''
form.shipmentDate = shipment.shipmentDate ?? new Date().toISOString().slice(0, 10)
form.userId = shipment.user?.id ? String(shipment.user.id) : form.userId
form.customerId = shipment.customer?.id ? String(shipment.customer.id) : ''
form.addressId = shipment.address?.id ? String(shipment.address.id) : ''
form.truckId = shipment.truck?.id ? String(shipment.truck.id) : ''
form.carrierId = shipment.carrier?.id ? String(shipment.carrier.id) : ''
form.driverId = shipment.driver?.id ? String(shipment.driver.id) : ''
form.vehicleId = shipment.vehicle?.id ? String(shipment.vehicle.id) : ''
selectedShipmentTypeId.value = shipment.shipmentType?.id ? String(shipment.shipmentType.id) : ''
shipmentQuantity.value = shipment.nbBovinSend ?? 0
const gross = shipment.weights?.find((weight) => weight.type === 'gross') ?? null
const tare = shipment.weights?.find((weight) => weight.type === 'tare') ?? null
grossWeight.value = gross ? { ...gross } : createEmptyWeightEntry('gross')
tareWeight.value = tare ? { ...tare } : createEmptyWeightEntry('tare')
isHydrating.value = false
}
async function printReceipt() {
if (!import.meta.client || shipmentId.value === null || shipmentId.value <= 0) {
return
}
const customerName =
customers.value.find((customer) => String(customer.id) === form.customerId)?.name ??
'client'
const filename = `${form.identificationNumber || shipmentId.value}_${customerName}_${form.licensePlate || 'immat'}.pdf`
await printPdf(`/shipments/${shipmentId.value}/receipt`, filename)
await new Promise((resolve) => setTimeout(resolve, 600))
}
async function loadShipmentForUpdate() {
if (shipmentId.value === null) {
return
}
const shipment = await getShipment(shipmentId.value)
currentShipment.value = shipment
hydrateFromShipment(shipment)
}
watch(
() => [form.customerId, form.addressId, customers.value],
() => {
if (!form.customerId) {
form.addressId = ''
return
}
if (!form.addressId && customerAddresses.value.length === 1) {
form.addressId = String(customerAddresses.value[0].id)
return
}
if (!form.addressId) {
return
}
const matches = customerAddresses.value.some(
(address) => String(address.id) === form.addressId
)
if (!matches) {
if (customerAddresses.value.length === 1) {
form.addressId = String(customerAddresses.value[0].id)
} else {
form.addressId = ''
}
}
},
{ immediate: true }
)
function applyLiotDefaults() {
if (isHydrating.value) {
return
}
if (!form.carrierId) {
form.driverId = ''
form.vehicleId = ''
return
}
if (!isLiotCarrier.value) {
form.driverId = ''
form.vehicleId = ''
return
}
if (filteredDrivers.value.length === 1) {
form.driverId = String(filteredDrivers.value[0].id)
}
if (filteredVehicles.value.length === 1) {
form.vehicleId = String(filteredVehicles.value[0].id)
}
}
watch(
() => form.carrierId,
() => {
applyLiotDefaults()
},
{ immediate: true }
)
watch(
() => isHydrating.value,
(value) => {
if (!value) {
applyLiotDefaults()
}
}
)
watch(
() => [form.truckId, form.carrierId, vehicles.value],
() => {
if (!isLiotCarrier.value) {
return
}
if (filteredVehicles.value.length === 1) {
form.vehicleId = String(filteredVehicles.value[0].id)
return
}
if (!form.vehicleId) {
return
}
const matches = filteredVehicles.value.some(
(vehicle) => String(vehicle.id) === form.vehicleId
)
if (!matches) {
form.vehicleId = ''
}
},
{ immediate: true }
)
watch(
() => [form.vehicleId, form.carrierId, vehicles.value],
() => {
if (!isLiotCarrier.value || isHydrating.value) {
return
}
const selected = filteredVehicles.value.find(
(vehicle) => String(vehicle.id) === form.vehicleId
)
if (selected) {
form.licensePlate = selected.plate
allowAnyLicensePlate.value = false
}
}
)
watch(
() => [form.licensePlate, form.carrierId, form.vehicleId, vehicles.value],
() => {
if (!isLiotCarrier.value || form.vehicleId) {
return
}
const match = filteredVehicles.value.find(
(vehicle) => vehicle.plate === form.licensePlate
)
if (match) {
form.vehicleId = String(match.id)
}
}
)
function buildPayload() {
const normalizedLicensePlate = form.licensePlate.trim()
const normalizedShipmentDate = form.shipmentDate.trim()
const normalizedCustomerId = form.customerId.trim()
const normalizedTruckId = form.truckId.trim()
const normalizedCarrierId = form.carrierId.trim()
const normalizedDriverId = form.driverId.trim()
const normalizedUserId = form.userId.trim()
const normalizedAddressId = form.addressId.trim()
const normalizedShipmentTypeId = selectedShipmentTypeId.value.trim()
const customerIri = normalizedCustomerId ? `/api/customers/${normalizedCustomerId}` : null
const truckIri = normalizedTruckId ? `/api/trucks/${normalizedTruckId}` : null
const carrierIri = normalizedCarrierId ? `/api/carriers/${normalizedCarrierId}` : null
const userIri = normalizedUserId ? `/api/users/${normalizedUserId}` : null
const driverIri = normalizedDriverId ? `/api/drivers/${normalizedDriverId}` : null
const addressIri = normalizedAddressId ? `/api/addresses/${normalizedAddressId}` : null
const shipmentTypeIri = normalizedShipmentTypeId
? `/api/shipment_types/${normalizedShipmentTypeId}`
: null
const rawQuantity = Number(shipmentQuantity.value ?? 0)
const normalizedQuantity = Number.isFinite(rawQuantity)
? Math.max(0, Math.trunc(rawQuantity))
: 0
return {
licensePlate: normalizedLicensePlate,
shipmentDate: normalizedShipmentDate,
customer: customerIri,
truck: truckIri,
carrier: carrierIri,
driver: driverIri,
user: userIri,
address: addressIri,
shipmentType: shipmentTypeIri,
nbBovinSend: normalizedQuantity
}
}
function createEmptyWeightEntry(type: 'gross' | 'tare'): WeightEntryData {
return {
type,
dsd: null,
weight: null,
weighedAt: null
}
}
async function saveWeightEntry(entry: WeightEntryData) {
if (!shipmentId.value || entry.weight === null) {
return
}
const payload = {
type: entry.type,
dsd: entry.dsd ?? null,
weight: entry.weight,
weighedAt: entry.weighedAt ?? null
}
if (entry.id) {
await updateWeight(entry.id, payload)
return
}
await createWeight({
shipment: `api/shipments/${shipmentId.value}`,
...payload
})
}
async function validate() {
if (shipmentId.value === null) {
return
}
await updateShipment(shipmentId.value, {
currentStep: currentShipment.value?.currentStep ?? 0,
...buildPayload()
})
await saveWeightEntry(grossWeight.value)
await saveWeightEntry(tareWeight.value)
await loadShipmentForUpdate()
}
onMounted(async () => {
await loadShipmentType()
await loadUsers()
await loadCustomers()
await loadTrucks()
await loadCarriers()
await loadVehicles()
await loadDrivers()
await authStore.ensureSession()
formIsLoading.value = true
setDefaultUser()
await loadShipmentForUpdate()
})
</script>

View File

@@ -38,7 +38,7 @@
</template> </template>
</div> </div>
<div>{{ shipment.carrier?.name }}</div> <div>{{ shipment.carrier?.name }}</div>
<div>{{ shipment.licensePlate }}</div> <div>{{ shipment.licencePlate }}</div>
</div> </div>
</div> </div>
</div> </div>

View File

@@ -24,27 +24,19 @@ export async function getBovineTypeList(): Promise<BovineTypeData[]> {
export async function getBovin(id: number): Promise<BovineTypeData> { export async function getBovin(id: number): Promise<BovineTypeData> {
const api = useApi() const api = useApi()
const response = await api.get<BovineTypeData>(`bovine_types/${id}`, {}, { const response = await api.get<BovineTypeData>(`bovine_types/${id}`)
toastErrorKey: 'errors.bovin.fetch'
})
return mapToBovineTypeData(response) return mapToBovineTypeData(response)
} }
export async function createBovin(payload: BovinPayload = {}): Promise<BovineTypeData> { export async function createBovin(payload: BovinPayload = {}): Promise<BovineTypeData> {
const api = useApi() const api = useApi()
const response = await api.post<BovineTypeData>('bovine_types', toBovineTypePayload(payload), { const response = await api.post<BovineTypeData>('bovine_types', toBovineTypePayload(payload))
toastErrorKey: 'errors.bovin.create',
toastSuccessKey: 'success.bovin.create'
})
return mapToBovineTypeData(response) return mapToBovineTypeData(response)
} }
export async function updateBovin(id: number, payload: BovinPayload = {}): Promise<BovineTypeData> { export async function updateBovin(id: number, payload: BovinPayload = {}): Promise<BovineTypeData> {
const api = useApi() const api = useApi()
const response = await api.patch<BovineTypeData>(`bovine_types/${id}`, toBovineTypePayload(payload), { const response = await api.patch<BovineTypeData>(`bovine_types/${id}`, toBovineTypePayload(payload))
toastErrorKey: 'errors.bovin.update',
toastSuccessKey: 'success.bovin.update'
})
return mapToBovineTypeData(response) return mapToBovineTypeData(response)
} }

View File

@@ -1,9 +0,0 @@
import type { BuildingCaseStatusData } from '~/services/dto/building-case-status-data'
export interface BuildingCaseData {
id: number
caseNumber: number | null
code: string | null
capacity: number | null
statut?: BuildingCaseStatusData | null
}

View File

@@ -1,11 +0,0 @@
import type { BuildingCaseData } from '~/services/dto/building-case-data'
export interface BuildingCasePositionData {
id: number
x: number | null
y: number | null
w: number | null
h: number | null
renderOrder: string | null
buildingCase: BuildingCaseData | null
}

View File

@@ -1,6 +0,0 @@
export interface BuildingCaseStatusData {
id: number
label: string | null
code: string | null
couleur: string | null
}

View File

@@ -1,8 +1,5 @@
import type { BuildingLayoutData } from '~/services/dto/building-layout-data'
export interface BuildingData { export interface BuildingData {
id: number id: number
label: string label: string
code: string code: string
layouts?: BuildingLayoutData[] | null
} }

View File

@@ -1,9 +0,0 @@
import type { BuildingCasePositionData } from '~/services/dto/building-case-position-data'
export interface BuildingLayoutData {
id: number
name: string | null
columns: number | null
rows: number | null
casePositions?: BuildingCasePositionData[] | null
}

View File

@@ -2,9 +2,6 @@ import type {CarrierData} from '~/services/dto/carrier-data'
import type {TruckData} from '~/services/dto/truck-data' import type {TruckData} from '~/services/dto/truck-data'
import type {CustomerData} from '~/services/dto/customer-data' import type {CustomerData} from '~/services/dto/customer-data'
import type {AddressData} from "~/services/dto/address-data"; import type {AddressData} from "~/services/dto/address-data";
import type {UserData} from '~/services/dto/user-data'
import type {DriverData} from '~/services/dto/driver-data'
import type {VehicleData} from '~/services/dto/vehicle-data'
export interface ShipmentTypeData { export interface ShipmentTypeData {
id: number id: number
@@ -15,7 +12,7 @@ export interface ShipmentTypeData {
export type ShipmentData = { export type ShipmentData = {
id: number id: number
identificationNumber?: string | null identificationNumber?: string | null
licensePlate: string | null licencePlate: string | null
shipmentDate: string shipmentDate: string
currentStep: number currentStep: number
isValid: boolean isValid: boolean
@@ -23,9 +20,6 @@ export type ShipmentData = {
carrier?: CarrierData | null carrier?: CarrierData | null
truck?: TruckData | null truck?: TruckData | null
customer?: CustomerData | null customer?: CustomerData | null
user?: UserData | null
driver?: DriverData | null
vehicle?: VehicleData | null
shipmentType?: ShipmentTypeData | null shipmentType?: ShipmentTypeData | null
nbBovinSend?: number | null nbBovinSend?: number | null
weights?: WeightShipmentEntryData[] | null weights?: WeightShipmentEntryData[] | null
@@ -49,11 +43,11 @@ export type ShipmentFormData = {
carrierId: string, carrierId: string,
driverId: string, driverId: string,
vehicleId: string, vehicleId: string,
licensePlate: string, licencePlate: string,
} }
export type ShipmentPayload = { export type ShipmentPayload = {
licensePlate?: string | null licencePlate?: string | null
shipmentDate?: string shipmentDate?: string
currentStep?: number currentStep?: number
isValid?: boolean isValid?: boolean

View File

@@ -4,11 +4,3 @@ export interface WeightData {
weighedAt: string | null weighedAt: string | null
type : string | null type : string | null
} }
export interface WeightEntryData {
id?: number
type: 'gross' | 'tare'
dsd: number | null
weight: number | null
weighedAt: string | null
}

View File

@@ -1,23 +0,0 @@
import { useApi } from '~/composables/useApi'
import type { BuildingCaseStatusData } from '~/services/dto/building-case-status-data'
export type StatutListResponse =
| BuildingCaseStatusData[]
| { 'hydra:member'?: BuildingCaseStatusData[] }
export async function getStatutList(): Promise<BuildingCaseStatusData[]> {
const api = useApi()
const response = await api.get<StatutListResponse>('statuts', {}, {
toastErrorKey: 'errors.http.get'
})
if (Array.isArray(response)) {
return response
}
if (response && typeof response === 'object' && Array.isArray(response['hydra:member'])) {
return response['hydra:member']
}
return []
}

View File

@@ -1,47 +0,0 @@
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Auto-generated Migration: Please modify to your needs!
*/
final class Version20260219100826 extends AbstractMigration
{
public function getDescription(): string
{
return '';
}
public function up(Schema $schema): void
{
// this up() migration is auto-generated, please modify it to your needs
$this->addSql('CREATE TABLE building_case (id INT GENERATED BY DEFAULT AS IDENTITY NOT NULL, case_number INT NOT NULL, code VARCHAR(255) NOT NULL, capacity INT NOT NULL, id_building_id INT DEFAULT NULL, PRIMARY KEY (id))');
$this->addSql('CREATE INDEX IDX_DE2CEE505538B3E5 ON building_case (id_building_id)');
$this->addSql('CREATE TABLE building_case_position (id INT GENERATED BY DEFAULT AS IDENTITY NOT NULL, x INT NOT NULL, y INT NOT NULL, w INT NOT NULL, h INT NOT NULL, render_order VARCHAR(255) NOT NULL, building_layout_id INT NOT NULL, building_case_id INT NOT NULL, PRIMARY KEY (id))');
$this->addSql('CREATE INDEX IDX_ACCDF9077040AE67 ON building_case_position (building_layout_id)');
$this->addSql('CREATE INDEX IDX_ACCDF907F8D859DF ON building_case_position (building_case_id)');
$this->addSql('CREATE TABLE building_layout (id INT GENERATED BY DEFAULT AS IDENTITY NOT NULL, name VARCHAR(255) NOT NULL, columns INT NOT NULL, rows INT NOT NULL, id_building_id INT NOT NULL, PRIMARY KEY (id))');
$this->addSql('CREATE INDEX IDX_2A8CB1095538B3E5 ON building_layout (id_building_id)');
$this->addSql('ALTER TABLE building_case ADD CONSTRAINT FK_DE2CEE505538B3E5 FOREIGN KEY (id_building_id) REFERENCES building (id)');
$this->addSql('ALTER TABLE building_case_position ADD CONSTRAINT FK_ACCDF9077040AE67 FOREIGN KEY (building_layout_id) REFERENCES building_layout (id) NOT DEFERRABLE');
$this->addSql('ALTER TABLE building_case_position ADD CONSTRAINT FK_ACCDF907F8D859DF FOREIGN KEY (building_case_id) REFERENCES building_case (id) NOT DEFERRABLE');
$this->addSql('ALTER TABLE building_layout ADD CONSTRAINT FK_2A8CB1095538B3E5 FOREIGN KEY (id_building_id) REFERENCES building (id) NOT DEFERRABLE');
}
public function down(Schema $schema): void
{
// this down() migration is auto-generated, please modify it to your needs
$this->addSql('ALTER TABLE building_case DROP CONSTRAINT FK_DE2CEE505538B3E5');
$this->addSql('ALTER TABLE building_case_position DROP CONSTRAINT FK_ACCDF9077040AE67');
$this->addSql('ALTER TABLE building_case_position DROP CONSTRAINT FK_ACCDF907F8D859DF');
$this->addSql('ALTER TABLE building_layout DROP CONSTRAINT FK_2A8CB1095538B3E5');
$this->addSql('DROP TABLE building_case');
$this->addSql('DROP TABLE building_case_position');
$this->addSql('DROP TABLE building_layout');
}
}

View File

@@ -1,37 +0,0 @@
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Auto-generated Migration: Please modify to your needs!
*/
final class Version20260220101607 extends AbstractMigration
{
public function getDescription(): string
{
return '';
}
public function up(Schema $schema): void
{
// this up() migration is auto-generated, please modify it to your needs
$this->addSql('CREATE TABLE statut (id INT GENERATED BY DEFAULT AS IDENTITY NOT NULL, label VARCHAR(255) NOT NULL, code VARCHAR(255) NOT NULL, color VARCHAR(255) NOT NULL, PRIMARY KEY (id))');
$this->addSql('ALTER TABLE building_case ADD statut_id INT DEFAULT NULL');
$this->addSql('ALTER TABLE building_case ADD CONSTRAINT FK_DE2CEE50F6203804 FOREIGN KEY (statut_id) REFERENCES statut (id)');
$this->addSql('CREATE INDEX IDX_DE2CEE50F6203804 ON building_case (statut_id)');
}
public function down(Schema $schema): void
{
// this down() migration is auto-generated, please modify it to your needs
$this->addSql('DROP TABLE statut');
$this->addSql('ALTER TABLE building_case DROP CONSTRAINT FK_DE2CEE50F6203804');
$this->addSql('DROP INDEX IDX_DE2CEE50F6203804');
$this->addSql('ALTER TABLE building_case DROP statut_id');
}
}

View File

@@ -1,26 +0,0 @@
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
final class Version20260225110000 extends AbstractMigration
{
public function getDescription(): string
{
return 'Rename shipment.licence_plate to license_plate';
}
public function up(Schema $schema): void
{
$this->addSql('ALTER TABLE shipment RENAME COLUMN licence_plate TO license_plate');
}
public function down(Schema $schema): void
{
$this->addSql('ALTER TABLE shipment RENAME COLUMN license_plate TO licence_plate');
}
}

View File

@@ -1,30 +0,0 @@
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
final class Version20260225123000 extends AbstractMigration
{
public function getDescription(): string
{
return 'Create bovine table and relation to building_case.';
}
public function up(Schema $schema): void
{
$this->addSql('CREATE TABLE bovine (id INT GENERATED BY DEFAULT AS IDENTITY NOT NULL, building_case_id INT DEFAULT NULL, national_number VARCHAR(50) NOT NULL, received_weight INT DEFAULT NULL, PRIMARY KEY(id))');
$this->addSql('CREATE INDEX IDX_EA9E2A42F8D859DF ON bovine (building_case_id)');
$this->addSql('CREATE UNIQUE INDEX uniq_bovine_national_number ON bovine (national_number)');
$this->addSql('ALTER TABLE bovine ADD CONSTRAINT FK_EA9E2A42F8D859DF FOREIGN KEY (building_case_id) REFERENCES building_case (id) NOT DEFERRABLE');
}
public function down(Schema $schema): void
{
$this->addSql('ALTER TABLE bovine DROP CONSTRAINT FK_EA9E2A42F8D859DF');
$this->addSql('DROP TABLE bovine');
}
}

View File

@@ -1,26 +0,0 @@
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
final class Version20260225131500 extends AbstractMigration
{
public function getDescription(): string
{
return 'Add arrival_date column to bovine table.';
}
public function up(Schema $schema): void
{
$this->addSql('ALTER TABLE bovine ADD arrival_date DATE DEFAULT NULL');
}
public function down(Schema $schema): void
{
$this->addSql('ALTER TABLE bovine DROP arrival_date');
}
}

View File

@@ -5,12 +5,8 @@ declare(strict_types=1);
namespace App\Command; namespace App\Command;
use App\Entity\Address; use App\Entity\Address;
use App\Entity\Bovine;
use App\Entity\BovineType; use App\Entity\BovineType;
use App\Entity\Building; use App\Entity\Building;
use App\Entity\BuildingCase;
use App\Entity\BuildingCasePosition;
use App\Entity\BuildingLayout;
use App\Entity\Carrier; use App\Entity\Carrier;
use App\Entity\Customer; use App\Entity\Customer;
use App\Entity\Driver; use App\Entity\Driver;
@@ -18,11 +14,9 @@ use App\Entity\MerchandiseType;
use App\Entity\PelletType; use App\Entity\PelletType;
use App\Entity\ReceptionType; use App\Entity\ReceptionType;
use App\Entity\ShipmentType; use App\Entity\ShipmentType;
use App\Entity\Statut;
use App\Entity\Supplier; use App\Entity\Supplier;
use App\Entity\Truck; use App\Entity\Truck;
use App\Entity\Vehicle; use App\Entity\Vehicle;
use DateTimeImmutable;
use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Command\Command;
@@ -58,12 +52,6 @@ class SeedCommand extends Command
$this->seedMerchandiseTypes(); $this->seedMerchandiseTypes();
$this->seedPelletTypes(); $this->seedPelletTypes();
$this->seedBuildings(); $this->seedBuildings();
$this->entityManager->flush();
$this->seedBuildingInfrastructure();
$this->entityManager->flush();
$this->seedBovines($io);
$this->seedReceptionTypes(); $this->seedReceptionTypes();
$this->seedBovineTypes(); $this->seedBovineTypes();
$this->seedShipmentTypes(); $this->seedShipmentTypes();
@@ -227,137 +215,6 @@ class SeedCommand extends Command
} }
} }
private function seedBuildingInfrastructure(): void
{
$statusByCode = [];
$statusRows = [
['label' => 'Libre', 'code' => 'LB', 'color' => '#A3B18A'],
['label' => 'Occupé', 'code' => 'OC', 'color' => '#3A506B'],
['label' => 'Malade', 'code' => 'ML', 'color' => '#E07A5F'],
];
foreach ($statusRows as $statusRow) {
/** @var Statut $status */
$status = $this->upsertByCode(Statut::class, $statusRow['code'], static function (Statut $entity) use ($statusRow) {
$entity
->setLabel($statusRow['label'])
->setCode($statusRow['code'])
->setColor($statusRow['color'])
;
});
$statusByCode[$statusRow['code']] = $status;
}
$buildingRepo = $this->entityManager->getRepository(Building::class);
$layoutByBuildingCode = [];
$layoutRows = [
['buildingCode' => 'B1', 'name' => 'plan1', 'columns' => 23, 'rows' => 2],
['buildingCode' => 'B2', 'name' => 'plan2', 'columns' => 23, 'rows' => 2],
['buildingCode' => 'B3', 'name' => 'plan3', 'columns' => 23, 'rows' => 2],
];
foreach ($layoutRows as $layoutRow) {
$building = $buildingRepo->findOneBy(['code' => $layoutRow['buildingCode']]);
if (!$building instanceof Building) {
continue;
}
/** @var BuildingLayout $layout */
$layout = $this->upsertByName(BuildingLayout::class, $layoutRow['name'], static function (BuildingLayout $entity) use ($layoutRow, $building) {
$entity
->setName($layoutRow['name'])
->setColumns($layoutRow['columns'])
->setRows($layoutRow['rows'])
->setIdBuilding($building)
;
});
$layoutByBuildingCode[$layoutRow['buildingCode']] = $layout;
}
$caseRows = [
['buildingCode' => 'B1', 'from' => 1, 'to' => 12, 'status' => 'LB'],
['buildingCode' => 'B1', 'from' => 13, 'to' => 24, 'status' => 'OC'],
['buildingCode' => 'B1', 'from' => 25, 'to' => 32, 'status' => 'ML'],
['buildingCode' => 'B1', 'from' => 33, 'to' => 44, 'status' => 'LB'],
['buildingCode' => 'B2', 'from' => 1, 'to' => 10, 'status' => 'OC'],
['buildingCode' => 'B2', 'from' => 11, 'to' => 22, 'status' => 'LB'],
['buildingCode' => 'B2', 'from' => 23, 'to' => 30, 'status' => 'ML'],
['buildingCode' => 'B2', 'from' => 31, 'to' => 44, 'status' => 'OC'],
['buildingCode' => 'B3', 'from' => 1, 'to' => 8, 'status' => 'ML'],
['buildingCode' => 'B3', 'from' => 9, 'to' => 20, 'status' => 'LB'],
['buildingCode' => 'B3', 'from' => 21, 'to' => 34, 'status' => 'OC'],
['buildingCode' => 'B3', 'from' => 35, 'to' => 44, 'status' => 'ML'],
];
$caseByCode = [];
foreach ($caseRows as $caseRow) {
$building = $buildingRepo->findOneBy(['code' => $caseRow['buildingCode']]);
$status = $statusByCode[$caseRow['status']] ?? null;
if (!$building instanceof Building || !$status instanceof Statut) {
continue;
}
for ($caseNumber = $caseRow['from']; $caseNumber <= $caseRow['to']; ++$caseNumber) {
$code = sprintf('%s-C%d', $caseRow['buildingCode'], $caseNumber);
/** @var BuildingCase $buildingCase */
$buildingCase = $this->upsertByCode(BuildingCase::class, $code, static function (BuildingCase $entity) use ($code, $caseNumber, $building, $status) {
$entity
->setCode($code)
->setCaseNumber($caseNumber)
->setCapacity(15)
->setIdBuilding($building)
->setStatut($status)
;
});
$caseByCode[$code] = $buildingCase;
}
}
$slots = $this->buildSlotMap();
$positionRepo = $this->entityManager->getRepository(BuildingCasePosition::class);
foreach (['B1' => 'plan1', 'B2' => 'plan2', 'B3' => 'plan3'] as $buildingCode => $layoutName) {
$layout = $layoutByBuildingCode[$buildingCode] ?? null;
if (!$layout instanceof BuildingLayout || $layout->getName() !== $layoutName) {
continue;
}
foreach ($slots as $slot) {
$caseCode = sprintf('%s-C%d', $buildingCode, $slot['caseNumber']);
$buildingCase = $caseByCode[$caseCode] ?? null;
if (!$buildingCase instanceof BuildingCase) {
continue;
}
$position = $positionRepo->findOneBy([
'buildingLayout' => $layout,
'buildingCase' => $buildingCase,
'x' => $slot['x'],
'y' => $slot['y'],
]);
if ($position instanceof BuildingCasePosition) {
++$this->updated;
continue;
}
$position = new BuildingCasePosition();
$position
->setX($slot['x'])
->setY($slot['y'])
->setW($slot['w'])
->setH($slot['h'])
->setRenderOrder((string) $slot['renderOrder'])
->setBuildingLayout($layout)
->setBuildingCase($buildingCase)
;
++$this->created;
$this->entityManager->persist($position);
}
}
}
private function seedReceptionTypes(): void private function seedReceptionTypes(): void
{ {
$receptionTypes = [ $receptionTypes = [
@@ -374,134 +231,6 @@ class SeedCommand extends Command
} }
} }
private function seedBovines(SymfonyStyle $io): void
{
$rows = [
[1, 15, '7979580026', 390, '2026-02-25'],
[5, 113, '4405604924', 397, '2025-05-22'],
[4, 113, '4405604944', 375, '2025-05-22'],
[2, 113, '4963291114', 319, '2025-05-22'],
[3, 113, '4405604922', 386, '2025-05-22'],
[6, 126, '4415811026', 367, '2025-07-02'],
[7, 126, '4950971149', 398, '2025-07-02'],
[8, 126, '4950971170', 386, '2025-07-02'],
[9, 126, '4489751630', 408, '2025-07-02'],
[10, 126, '8551323003', 478, '2025-07-02'],
[11, 126, '8503833703', 378, '2025-07-02'],
[12, 126, '4402104572', 379, '2025-07-02'],
[13, 126, '4402104580', 465, '2025-07-02'],
[14, 126, '4402104607', 381, '2025-07-02'],
[15, 126, '8504059581', 446, '2025-07-02'],
[16, 124, '4950971161', 382, '2025-07-02'],
[17, 124, '5652911499', 376, '2025-07-02'],
[18, 124, '8551323029', 414, '2025-07-02'],
[19, 124, '4402104590', 474, '2025-07-02'],
[20, 124, '4402104594', 408, '2025-07-02'],
[21, 124, '4402104595', 399, '2025-07-02'],
[22, 124, '4402104604', 374, '2025-07-02'],
[23, 124, '8504059579', 403, '2025-07-02'],
[24, 124, '8504059590', 398, '2025-07-02'],
[25, 123, '8551782070', 395, '2025-07-02'],
[26, 123, '8551782080', 443, '2025-07-02'],
[27, 123, '8551782084', 394, '2025-07-02'],
[28, 123, '8551782090', 378, '2025-07-02'],
[29, 123, '8551782092', 424, '2025-07-02'],
[30, 123, '8551782094', 389, '2025-07-02'],
[31, 123, '8551782099', 411, '2025-07-02'],
[32, 123, '8551323020', 392, '2025-07-02'],
[33, 123, '8551323051', 371, '2025-07-02'],
[34, 123, '7947673148', 378, '2025-07-02'],
[39, 114, '1731177447', 395, '2025-06-19'],
[42, 114, '1726167608', 299, '2025-06-19'],
[38, 114, '1731177442', 343, '2025-06-19'],
[40, 114, '1731177448', 362, '2025-06-19'],
[41, 114, '1731177458', 359, '2025-06-19'],
[35, 114, '7946282100', 291, '2025-06-19'],
[43, 114, '1726167613', 339, '2025-06-19'],
[37, 114, '1731177427', 375, '2025-06-19'],
[36, 114, '7946282103', 354, '2025-06-19'],
];
$bovineRepo = $this->entityManager->getRepository(Bovine::class);
$caseRepo = $this->entityManager->getRepository(BuildingCase::class);
foreach ($rows as [, $legacyCaseId, $nationalNumber, $receivedWeight, $arrivalDate]) {
$buildingCase = $this->resolveBuildingCaseByLegacyId((int) $legacyCaseId);
if (!$buildingCase instanceof BuildingCase) {
$buildingCase = $caseRepo->find((int) $legacyCaseId);
}
if (!$buildingCase instanceof BuildingCase) {
$io->warning(sprintf(
'Bovine %s skipped: building_case token %d not found.',
$nationalNumber,
$legacyCaseId
));
continue;
}
$bovine = $bovineRepo->findOneBy(['nationalNumber' => $nationalNumber]);
if (!$bovine instanceof Bovine) {
$bovine = new Bovine();
++$this->created;
} else {
++$this->updated;
}
$bovine
->setNationalNumber((string) $nationalNumber)
->setBuildingCase($buildingCase)
->setReceivedWeight((int) $receivedWeight)
->setArrivalDate(new DateTimeImmutable((string) $arrivalDate))
;
$this->entityManager->persist($bovine);
}
}
/**
* @return array<int, array{x:int,y:int,w:int,h:int,renderOrder:int,caseNumber:int}>
*/
private function buildSlotMap(): array
{
$slots = [];
for ($column = 1; $column <= 12; ++$column) {
$slots[] = ['x' => $column, 'y' => 1, 'w' => 1, 'h' => 1, 'renderOrder' => $column, 'caseNumber' => $column + 12];
}
for ($column = 14; $column <= 23; ++$column) {
$slots[] = ['x' => $column, 'y' => 1, 'w' => 1, 'h' => 1, 'renderOrder' => $column - 1, 'caseNumber' => $column + 11];
}
for ($column = 1; $column <= 12; ++$column) {
$slots[] = ['x' => $column, 'y' => 2, 'w' => 1, 'h' => 1, 'renderOrder' => 22 + $column, 'caseNumber' => 13 - $column];
}
for ($column = 14; $column <= 23; ++$column) {
$slots[] = ['x' => $column, 'y' => 2, 'w' => 1, 'h' => 1, 'renderOrder' => 21 + $column, 'caseNumber' => 58 - $column];
}
return $slots;
}
private function resolveBuildingCaseByLegacyId(int $legacyCaseId): ?BuildingCase
{
if ($legacyCaseId < 1) {
return null;
}
$buildingNumber = intdiv($legacyCaseId - 1, 44) + 1;
$caseNumber = (($legacyCaseId - 1) % 44) + 1;
if ($buildingNumber < 1 || $buildingNumber > 3) {
return null;
}
$code = sprintf('B%d-C%d', $buildingNumber, $caseNumber);
$buildingCase = $this->entityManager->getRepository(BuildingCase::class)->findOneBy(['code' => $code]);
return $buildingCase instanceof BuildingCase ? $buildingCase : null;
}
private function seedBovineTypes(): void private function seedBovineTypes(): void
{ {
$bovineTypes = [ $bovineTypes = [

View File

@@ -20,8 +20,6 @@ class AppFixtures extends Fixture implements DependentFixtureInterface
return [ return [
TransportFixtures::class, TransportFixtures::class,
ReferenceFixtures::class, ReferenceFixtures::class,
BuildingInfrastructureFixtures::class,
BovineFixtures::class,
UserFixtures::class, UserFixtures::class,
]; ];
} }

View File

@@ -1,120 +0,0 @@
<?php
declare(strict_types=1);
namespace App\DataFixtures;
use App\Entity\Bovine;
use App\Entity\BuildingCase;
use DateTimeImmutable;
use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Common\DataFixtures\DependentFixtureInterface;
use Doctrine\Persistence\ObjectManager;
class BovineFixtures extends Fixture implements DependentFixtureInterface
{
public function load(ObjectManager $manager): void
{
$rows = [
[1, 15, '7979580026', 390, '2026-02-25'],
[5, 113, '4405604924', 397, '2025-05-22'],
[4, 113, '4405604944', 375, '2025-05-22'],
[2, 113, '4963291114', 319, '2025-05-22'],
[3, 113, '4405604922', 386, '2025-05-22'],
[6, 126, '4415811026', 367, '2025-07-02'],
[7, 126, '4950971149', 398, '2025-07-02'],
[8, 126, '4950971170', 386, '2025-07-02'],
[9, 126, '4489751630', 408, '2025-07-02'],
[10, 126, '8551323003', 478, '2025-07-02'],
[11, 126, '8503833703', 378, '2025-07-02'],
[12, 126, '4402104572', 379, '2025-07-02'],
[13, 126, '4402104580', 465, '2025-07-02'],
[14, 126, '4402104607', 381, '2025-07-02'],
[15, 126, '8504059581', 446, '2025-07-02'],
[16, 124, '4950971161', 382, '2025-07-02'],
[17, 124, '5652911499', 376, '2025-07-02'],
[18, 124, '8551323029', 414, '2025-07-02'],
[19, 124, '4402104590', 474, '2025-07-02'],
[20, 124, '4402104594', 408, '2025-07-02'],
[21, 124, '4402104595', 399, '2025-07-02'],
[22, 124, '4402104604', 374, '2025-07-02'],
[23, 124, '8504059579', 403, '2025-07-02'],
[24, 124, '8504059590', 398, '2025-07-02'],
[25, 123, '8551782070', 395, '2025-07-02'],
[26, 123, '8551782080', 443, '2025-07-02'],
[27, 123, '8551782084', 394, '2025-07-02'],
[28, 123, '8551782090', 378, '2025-07-02'],
[29, 123, '8551782092', 424, '2025-07-02'],
[30, 123, '8551782094', 389, '2025-07-02'],
[31, 123, '8551782099', 411, '2025-07-02'],
[32, 123, '8551323020', 392, '2025-07-02'],
[33, 123, '8551323051', 371, '2025-07-02'],
[34, 123, '7947673148', 378, '2025-07-02'],
[39, 114, '1731177447', 395, '2025-06-19'],
[42, 114, '1726167608', 299, '2025-06-19'],
[38, 114, '1731177442', 343, '2025-06-19'],
[40, 114, '1731177448', 362, '2025-06-19'],
[41, 114, '1731177458', 359, '2025-06-19'],
[35, 114, '7946282100', 291, '2025-06-19'],
[43, 114, '1726167613', 339, '2025-06-19'],
[37, 114, '1731177427', 375, '2025-06-19'],
[36, 114, '7946282103', 354, '2025-06-19'],
];
$bovineRepository = $manager->getRepository(Bovine::class);
$caseRepository = $manager->getRepository(BuildingCase::class);
foreach ($rows as [, $legacyCaseId, $nationalNumber, $receivedWeight, $arrivalDate]) {
$buildingCase = $this->resolveBuildingCaseByLegacyId($manager, (int) $legacyCaseId);
if (!$buildingCase instanceof BuildingCase) {
$buildingCase = $caseRepository->find((int) $legacyCaseId);
}
if (!$buildingCase instanceof BuildingCase) {
continue;
}
/** @var null|Bovine $bovine */
$bovine = $bovineRepository->findOneBy(['nationalNumber' => (string) $nationalNumber]);
if (!$bovine instanceof Bovine) {
$bovine = new Bovine();
}
$bovine
->setNationalNumber((string) $nationalNumber)
->setBuildingCase($buildingCase)
->setReceivedWeight((int) $receivedWeight)
->setArrivalDate(new DateTimeImmutable((string) $arrivalDate))
;
$manager->persist($bovine);
}
$manager->flush();
}
public function getDependencies(): array
{
return [
BuildingInfrastructureFixtures::class,
];
}
private function resolveBuildingCaseByLegacyId(ObjectManager $manager, int $legacyCaseId): ?BuildingCase
{
if ($legacyCaseId < 1) {
return null;
}
$buildingNumber = intdiv($legacyCaseId - 1, 44) + 1;
$caseNumber = (($legacyCaseId - 1) % 44) + 1;
if ($buildingNumber < 1 || $buildingNumber > 3) {
return null;
}
$code = sprintf('B%d-C%d', $buildingNumber, $caseNumber);
$buildingCase = $manager->getRepository(BuildingCase::class)->findOneBy(['code' => $code]);
return $buildingCase instanceof BuildingCase ? $buildingCase : null;
}
}

View File

@@ -1,299 +0,0 @@
<?php
declare(strict_types=1);
namespace App\DataFixtures;
use App\Entity\Building;
use App\Entity\BuildingCase;
use App\Entity\BuildingCasePosition;
use App\Entity\BuildingLayout;
use App\Entity\Statut;
use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Common\DataFixtures\DependentFixtureInterface;
use Doctrine\Persistence\ObjectManager;
use RuntimeException;
class BuildingInfrastructureFixtures extends Fixture implements DependentFixtureInterface
{
public function load(ObjectManager $manager): void
{
$statuts = $this->loadStatuts($manager);
$buildings = $this->getBuildingsByCode($manager, ['B1', 'B2', 'B3']);
$layouts = $this->loadLayouts($manager, $buildings);
$cases = $this->loadBuildingCases($manager, $buildings, $statuts);
$this->loadCasePositions($manager, $layouts, $cases);
$manager->flush();
}
public function getDependencies(): array
{
return [
ReferenceFixtures::class,
];
}
/**
* @return array<string, Statut>
*/
private function loadStatuts(ObjectManager $manager): array
{
$repo = $manager->getRepository(Statut::class);
$data = [
['label' => 'Libre', 'code' => 'LB', 'color' => '#A3B18A'],
['label' => 'Occupé', 'code' => 'OC', 'color' => '#3A506B'],
['label' => 'Malade', 'code' => 'ML', 'color' => '#E07A5F'],
];
$result = [];
foreach ($data as $row) {
/** @var null|Statut $statut */
$statut = $repo->findOneBy(['code' => $row['code']]);
if (!$statut instanceof Statut) {
$statut = new Statut()
->setLabel($row['label'])
->setCode($row['code'])
->setColor($row['color'])
;
$manager->persist($statut);
}
$result[$row['code']] = $statut;
}
return $result;
}
/**
* @param list<string> $codes
*
* @return array<string, Building>
*/
private function getBuildingsByCode(ObjectManager $manager, array $codes): array
{
$repo = $manager->getRepository(Building::class);
$result = [];
foreach ($codes as $code) {
/** @var null|Building $building */
$building = $repo->findOneBy(['code' => $code]);
if (!$building instanceof Building) {
throw new RuntimeException(sprintf('Building "%s" not found. Load ReferenceFixtures first.', $code));
}
$result[$code] = $building;
}
return $result;
}
/**
* @param array<string, Building> $buildings
*
* @return array<string, BuildingLayout>
*/
private function loadLayouts(ObjectManager $manager, array $buildings): array
{
$repo = $manager->getRepository(BuildingLayout::class);
$data = [
['name' => 'plan1', 'columns' => 23, 'rows' => 2, 'buildingCode' => 'B1'],
['name' => 'plan2', 'columns' => 23, 'rows' => 2, 'buildingCode' => 'B2'],
['name' => 'plan3', 'columns' => 23, 'rows' => 2, 'buildingCode' => 'B3'],
];
$result = [];
foreach ($data as $row) {
/** @var null|BuildingLayout $layout */
$layout = $repo->findOneBy(['name' => $row['name']]);
if (!$layout instanceof BuildingLayout) {
$layout = new BuildingLayout()
->setName($row['name'])
->setColumns($row['columns'])
->setRows($row['rows'])
->setIdBuilding($buildings[$row['buildingCode']])
;
$manager->persist($layout);
}
$result[$row['buildingCode']] = $layout;
}
return $result;
}
/**
* @param array<string, Building> $buildings
* @param array<string, Statut> $statuts
*
* @return array<string, BuildingCase>
*/
private function loadBuildingCases(ObjectManager $manager, array $buildings, array $statuts): array
{
$repo = $manager->getRepository(BuildingCase::class);
$statusRanges = [
// B1
['buildingCode' => 'B1', 'from' => 1, 'to' => 12, 'statut' => 'LB'],
['buildingCode' => 'B1', 'from' => 13, 'to' => 24, 'statut' => 'OC'],
['buildingCode' => 'B1', 'from' => 25, 'to' => 32, 'statut' => 'ML'],
['buildingCode' => 'B1', 'from' => 33, 'to' => 44, 'statut' => 'LB'],
// B2
['buildingCode' => 'B2', 'from' => 1, 'to' => 10, 'statut' => 'OC'],
['buildingCode' => 'B2', 'from' => 11, 'to' => 22, 'statut' => 'LB'],
['buildingCode' => 'B2', 'from' => 23, 'to' => 30, 'statut' => 'ML'],
['buildingCode' => 'B2', 'from' => 31, 'to' => 44, 'statut' => 'OC'],
// B3
['buildingCode' => 'B3', 'from' => 1, 'to' => 8, 'statut' => 'ML'],
['buildingCode' => 'B3', 'from' => 9, 'to' => 20, 'statut' => 'LB'],
['buildingCode' => 'B3', 'from' => 21, 'to' => 34, 'statut' => 'OC'],
['buildingCode' => 'B3', 'from' => 35, 'to' => 44, 'statut' => 'ML'],
];
$result = [];
foreach ($statusRanges as $range) {
for ($caseNumber = $range['from']; $caseNumber <= $range['to']; ++$caseNumber) {
$code = sprintf('%s-C%d', $range['buildingCode'], $caseNumber);
if (isset($result[$code])) {
continue;
}
/** @var null|BuildingCase $buildingCase */
$buildingCase = $repo->findOneBy(['code' => $code]);
if (!$buildingCase instanceof BuildingCase) {
$buildingCase = new BuildingCase()
->setCaseNumber($caseNumber)
->setCode($code)
->setCapacity(15)
->setIdBuilding($buildings[$range['buildingCode']])
->setStatut($statuts[$range['statut']])
;
$manager->persist($buildingCase);
}
$result[$code] = $buildingCase;
}
}
return $result;
}
/**
* @param array<string, BuildingLayout> $layouts
* @param array<string, BuildingCase> $casesByCode
*/
private function loadCasePositions(ObjectManager $manager, array $layouts, array $casesByCode): void
{
$repo = $manager->getRepository(BuildingCasePosition::class);
$layoutMap = [
'B1' => 'plan1',
'B2' => 'plan2',
'B3' => 'plan3',
];
$slots = $this->buildSlotMap();
foreach ($layoutMap as $buildingCode => $layoutName) {
$layout = $layouts[$buildingCode] ?? null;
if (!$layout instanceof BuildingLayout || $layout->getName() !== $layoutName) {
throw new RuntimeException(sprintf('Layout "%s" for building "%s" not found.', $layoutName, $buildingCode));
}
foreach ($slots as $slot) {
$caseCode = sprintf('%s-C%d', $buildingCode, $slot['caseNumber']);
$buildingCase = $casesByCode[$caseCode] ?? null;
if (!$buildingCase instanceof BuildingCase) {
throw new RuntimeException(sprintf('Building case "%s" not found.', $caseCode));
}
/** @var null|BuildingCasePosition $position */
$position = $repo->findOneBy([
'buildingLayout' => $layout,
'buildingCase' => $buildingCase,
'x' => $slot['x'],
'y' => $slot['y'],
]);
if ($position instanceof BuildingCasePosition) {
continue;
}
$position = new BuildingCasePosition()
->setX($slot['x'])
->setY($slot['y'])
->setW($slot['w'])
->setH($slot['h'])
->setRenderOrder((string) $slot['renderOrder'])
->setBuildingLayout($layout)
->setBuildingCase($buildingCase)
;
$manager->persist($position);
}
}
}
/**
* Reproduit le slot_map SQL (44 emplacements sur 2 lignes avec un gap en colonne 13).
*
* @return list<array{x:int,y:int,w:int,h:int,renderOrder:int,caseNumber:int}>
*/
private function buildSlotMap(): array
{
$slots = [];
// Ligne 1, colonnes 1..12 => cases 13..24
for ($c = 1; $c <= 12; ++$c) {
$slots[] = [
'x' => $c,
'y' => 1,
'w' => 1,
'h' => 1,
'renderOrder' => $c,
'caseNumber' => $c + 12,
];
}
// Ligne 1, colonnes 14..23 => cases 25..34
for ($c = 14; $c <= 23; ++$c) {
$slots[] = [
'x' => $c,
'y' => 1,
'w' => 1,
'h' => 1,
'renderOrder' => $c - 1,
'caseNumber' => $c + 11,
];
}
// Ligne 2, colonnes 1..12 => cases 12..1
for ($c = 1; $c <= 12; ++$c) {
$slots[] = [
'x' => $c,
'y' => 2,
'w' => 1,
'h' => 1,
'renderOrder' => 22 + $c,
'caseNumber' => 13 - $c,
];
}
// Ligne 2, colonnes 14..23 => cases 44..35
for ($c = 14; $c <= 23; ++$c) {
$slots[] = [
'x' => $c,
'y' => 2,
'w' => 1,
'h' => 1,
'renderOrder' => 21 + $c,
'caseNumber' => 58 - $c,
];
}
return $slots;
}
}

View File

@@ -1,121 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Entity;
use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\Get;
use ApiPlatform\Metadata\GetCollection;
use ApiPlatform\Metadata\Patch;
use ApiPlatform\Metadata\Post;
use DateTimeImmutable;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Attribute\Context;
use Symfony\Component\Serializer\Attribute\Groups;
use Symfony\Component\Serializer\Normalizer\DateTimeNormalizer;
#[ORM\Entity]
#[ORM\Table(name: 'bovine')]
#[ORM\UniqueConstraint(name: 'uniq_bovine_national_number', columns: ['national_number'])]
#[ApiResource(
operations: [
new Get(
requirements: ['id' => '\d+'],
normalizationContext: ['groups' => ['bovine:read']],
),
new GetCollection(
normalizationContext: ['groups' => ['bovine:read']],
),
new Post(
normalizationContext: ['groups' => ['bovine:read']],
denormalizationContext: ['groups' => ['bovine:write']],
security: "is_granted('ROLE_ADMIN')",
),
new Patch(
requirements: ['id' => '\d+'],
normalizationContext: ['groups' => ['bovine:read']],
denormalizationContext: ['groups' => ['bovine:write']],
security: "is_granted('ROLE_ADMIN')",
),
],
security: "is_granted('ROLE_USER')",
)]
class Bovine
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
#[Groups(['bovine:read'])]
private ?int $id = null;
#[ORM\Column(length: 50)]
#[Groups(['bovine:read', 'bovine:write'])]
private string $nationalNumber = '';
#[ORM\Column(nullable: true)]
#[Groups(['bovine:read', 'bovine:write'])]
private ?int $receivedWeight = null;
#[ORM\Column(type: 'date_immutable', nullable: true)]
#[Groups(['bovine:read', 'bovine:write'])]
#[Context([DateTimeNormalizer::FORMAT_KEY => 'Y-m-d'])]
private ?DateTimeImmutable $arrivalDate = null;
#[ORM\ManyToOne(inversedBy: 'bovines')]
#[Groups(['bovine:read', 'bovine:write'])]
private ?BuildingCase $buildingCase = null;
public function getId(): ?int
{
return $this->id;
}
public function getNationalNumber(): string
{
return $this->nationalNumber;
}
public function setNationalNumber(string $nationalNumber): static
{
$this->nationalNumber = $nationalNumber;
return $this;
}
public function getReceivedWeight(): ?int
{
return $this->receivedWeight;
}
public function setReceivedWeight(?int $receivedWeight): static
{
$this->receivedWeight = $receivedWeight;
return $this;
}
public function getArrivalDate(): ?DateTimeImmutable
{
return $this->arrivalDate;
}
public function setArrivalDate(?DateTimeImmutable $arrivalDate): static
{
$this->arrivalDate = $arrivalDate;
return $this;
}
public function getBuildingCase(): ?BuildingCase
{
return $this->buildingCase;
}
public function setBuildingCase(?BuildingCase $buildingCase): static
{
$this->buildingCase = $buildingCase;
return $this;
}
}

View File

@@ -11,7 +11,6 @@ use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection; use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM; use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Attribute\Groups; use Symfony\Component\Serializer\Attribute\Groups;
use Symfony\Component\Serializer\Attribute\SerializedName;
#[ORM\Entity] #[ORM\Entity]
#[ORM\Table(name: 'building')] #[ORM\Table(name: 'building')]
@@ -49,25 +48,9 @@ class Building
#[ORM\ManyToMany(targetEntity: Reception::class, mappedBy: 'buildings')] #[ORM\ManyToMany(targetEntity: Reception::class, mappedBy: 'buildings')]
private Collection $receptions; private Collection $receptions;
/**
* @var Collection<int, BuildingCase>
*/
#[ORM\OneToMany(targetEntity: BuildingCase::class, mappedBy: 'id_building')]
private Collection $buildingCases;
/**
* @var Collection<int, BuildingLayout>
*/
#[ORM\OneToMany(targetEntity: BuildingLayout::class, mappedBy: 'id_building')]
#[Groups(['building:read'])]
#[SerializedName('layouts')]
private Collection $buildingLayout;
public function __construct() public function __construct()
{ {
$this->receptions = new ArrayCollection(); $this->receptions = new ArrayCollection();
$this->buildingCases = new ArrayCollection();
$this->buildingLayout = new ArrayCollection();
} }
public function getId(): ?int public function getId(): ?int
@@ -106,41 +89,4 @@ class Building
{ {
return $this->receptions; return $this->receptions;
} }
/**
* @return Collection<int, BuildingCase>
*/
public function getBuildingCases(): Collection
{
return $this->buildingCases;
}
public function addBuildingCase(BuildingCase $buildingCase): static
{
if (!$this->buildingCases->contains($buildingCase)) {
$this->buildingCases->add($buildingCase);
$buildingCase->setIdBuilding($this);
}
return $this;
}
public function removeBuildingCase(BuildingCase $buildingCase): static
{
if ($this->buildingCases->removeElement($buildingCase)) {
if ($buildingCase->getIdBuilding() === $this) {
$buildingCase->setIdBuilding(null);
}
}
return $this;
}
/**
* @return Collection<int, BuildingLayout>
*/
public function getBuildingLayout(): Collection
{
return $this->buildingLayout;
}
} }

View File

@@ -1,209 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Entity;
use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\Get;
use ApiPlatform\OpenApi\Model\Operation as OpenApiOperation;
use App\State\BuildingCaseWeightsReportProvider;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Attribute\Groups;
use Symfony\Component\Serializer\Attribute\SerializedName;
#[ORM\Entity]
#[ApiResource(
operations: [
new Get(
uriTemplate: '/building_cases/{id}/weights-report',
requirements: ['id' => '\d+'],
openapi: new OpenApiOperation(
summary: 'Render case weights report',
description: 'Returns a PDF report of bovines stored in the selected case.',
),
output: false,
provider: BuildingCaseWeightsReportProvider::class,
),
],
security: "is_granted('ROLE_USER')",
)]
class BuildingCase
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
#[Groups(['building:read'])]
private ?int $id = null;
#[ORM\Column]
#[Groups(['building:read'])]
#[SerializedName('caseNumber')]
private ?int $case_number = null;
#[ORM\Column(length: 255)]
#[Groups(['building:read'])]
private ?string $code = null;
#[ORM\Column]
#[Groups(['building:read'])]
private ?int $capacity = null;
/**
* @var Collection<int, BuildingCasePosition>
*/
#[ORM\OneToMany(targetEntity: BuildingCasePosition::class, mappedBy: 'buildingCase')]
private Collection $id_case_position;
#[ORM\ManyToOne(inversedBy: 'buildingCases')]
private ?Building $id_building = null;
#[ORM\ManyToOne(inversedBy: 'id_case')]
#[Groups(['building:read'])]
private ?Statut $statut = null;
/**
* @var Collection<int, Bovine>
*/
#[ORM\OneToMany(targetEntity: Bovine::class, mappedBy: 'buildingCase')]
private Collection $bovines;
public function __construct()
{
$this->id_case_position = new ArrayCollection();
$this->bovines = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function setId(int $id): static
{
$this->id = $id;
return $this;
}
public function getCaseNumber(): ?int
{
return $this->case_number;
}
public function setCaseNumber(int $case_number): static
{
$this->case_number = $case_number;
return $this;
}
public function getCode(): ?string
{
return $this->code;
}
public function setCode(string $code): static
{
$this->code = $code;
return $this;
}
public function getCapacity(): ?int
{
return $this->capacity;
}
public function setCapacity(int $capacity): static
{
$this->capacity = $capacity;
return $this;
}
/**
* @return Collection<int, BuildingCasePosition>
*/
public function getIdCasePosition(): Collection
{
return $this->id_case_position;
}
public function addIdCasePosition(BuildingCasePosition $idCasePosition): static
{
if (!$this->id_case_position->contains($idCasePosition)) {
$this->id_case_position->add($idCasePosition);
$idCasePosition->setBuildingCase($this);
}
return $this;
}
public function removeIdCasePosition(BuildingCasePosition $idCasePosition): static
{
if ($this->id_case_position->removeElement($idCasePosition)) {
// set the owning side to null (unless already changed)
if ($idCasePosition->getBuildingCase() === $this) {
$idCasePosition->setBuildingCase(null);
}
}
return $this;
}
public function getIdBuilding(): ?Building
{
return $this->id_building;
}
public function setIdBuilding(?Building $id_building): static
{
$this->id_building = $id_building;
return $this;
}
public function getStatut(): ?Statut
{
return $this->statut;
}
public function setStatut(?Statut $statut): static
{
$this->statut = $statut;
return $this;
}
/**
* @return Collection<int, Bovine>
*/
public function getBovines(): Collection
{
return $this->bovines;
}
public function addBovine(Bovine $bovine): static
{
if (!$this->bovines->contains($bovine)) {
$this->bovines->add($bovine);
$bovine->setBuildingCase($this);
}
return $this;
}
public function removeBovine(Bovine $bovine): static
{
if ($this->bovines->removeElement($bovine)) {
if ($bovine->getBuildingCase() === $this) {
$bovine->setBuildingCase(null);
}
}
return $this;
}
}

View File

@@ -1,145 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Attribute\Groups;
use Symfony\Component\Serializer\Attribute\SerializedName;
#[ORM\Entity]
class BuildingCasePosition
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
#[Groups(['building:read'])]
private ?int $id = null;
#[ORM\Column]
#[Groups(['building:read'])]
private ?int $x = null;
#[ORM\Column]
#[Groups(['building:read'])]
private ?int $y = null;
#[ORM\Column]
#[Groups(['building:read'])]
private ?int $w = null;
#[ORM\Column]
#[Groups(['building:read'])]
private ?int $h = null;
#[ORM\Column(length: 255)]
#[Groups(['building:read'])]
#[SerializedName('renderOrder')]
private ?string $render_order = null;
#[ORM\ManyToOne(inversedBy: 'id_case_position')]
#[ORM\JoinColumn(nullable: false)]
private ?BuildingLayout $buildingLayout = null;
#[ORM\ManyToOne(inversedBy: 'id_case_position')]
#[ORM\JoinColumn(nullable: false)]
#[Groups(['building:read'])]
private ?BuildingCase $buildingCase = null;
public function getId(): ?int
{
return $this->id;
}
public function setId(int $id): static
{
$this->id = $id;
return $this;
}
public function getX(): ?int
{
return $this->x;
}
public function setX(int $x): static
{
$this->x = $x;
return $this;
}
public function getY(): ?int
{
return $this->y;
}
public function setY(int $y): static
{
$this->y = $y;
return $this;
}
public function getW(): ?int
{
return $this->w;
}
public function setW(int $w): static
{
$this->w = $w;
return $this;
}
public function getH(): ?int
{
return $this->h;
}
public function setH(int $h): static
{
$this->h = $h;
return $this;
}
public function getRenderOrder(): ?string
{
return $this->render_order;
}
public function setRenderOrder(string $render_order): static
{
$this->render_order = $render_order;
return $this;
}
public function getBuildingLayout(): ?BuildingLayout
{
return $this->buildingLayout;
}
public function setBuildingLayout(?BuildingLayout $buildingLayout): static
{
$this->buildingLayout = $buildingLayout;
return $this;
}
public function getBuildingCase(): ?BuildingCase
{
return $this->buildingCase;
}
public function setBuildingCase(?BuildingCase $buildingCase): static
{
$this->buildingCase = $buildingCase;
return $this;
}
}

View File

@@ -1,140 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Attribute\Groups;
use Symfony\Component\Serializer\Attribute\SerializedName;
#[ORM\Entity]
class BuildingLayout
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
#[Groups(['building:read'])]
private ?int $id = null;
#[ORM\Column(length: 255)]
#[Groups(['building:read'])]
private ?string $name = null;
#[ORM\Column]
#[Groups(['building:read'])]
private ?int $columns = null;
#[ORM\Column]
#[Groups(['building:read'])]
private ?int $rows = null;
#[ORM\ManyToOne(inversedBy: 'buildingLayout')]
#[ORM\JoinColumn(nullable: false)]
private ?Building $id_building = null;
/**
* @var Collection<int, BuildingCasePosition>
*/
#[ORM\OneToMany(targetEntity: BuildingCasePosition::class, mappedBy: 'buildingLayout')]
#[Groups(['building:read'])]
#[SerializedName('casePositions')]
private Collection $id_case_position;
public function __construct()
{
$this->id_case_position = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function setId(int $id): static
{
$this->id = $id;
return $this;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): static
{
$this->name = $name;
return $this;
}
public function getColumns(): ?int
{
return $this->columns;
}
public function setColumns(int $columns): static
{
$this->columns = $columns;
return $this;
}
public function getRows(): ?int
{
return $this->rows;
}
public function setRows(int $rows): static
{
$this->rows = $rows;
return $this;
}
public function getIdBuilding(): ?Building
{
return $this->id_building;
}
public function setIdBuilding(?Building $id_building): static
{
$this->id_building = $id_building;
return $this;
}
/**
* @return Collection<int, BuildingCasePosition>
*/
public function getIdCasePosition(): Collection
{
return $this->id_case_position;
}
public function addIdCasePosition(BuildingCasePosition $idCasePosition): static
{
if (!$this->id_case_position->contains($idCasePosition)) {
$this->id_case_position->add($idCasePosition);
$idCasePosition->setBuildingLayout($this);
}
return $this;
}
public function removeIdCasePosition(BuildingCasePosition $idCasePosition): static
{
if ($this->id_case_position->removeElement($idCasePosition)) {
// set the owning side to null (unless already changed)
if ($idCasePosition->getBuildingLayout() === $this) {
$idCasePosition->setBuildingLayout(null);
}
}
return $this;
}
}

View File

@@ -80,7 +80,7 @@ class Shipment
#[ORM\Column(length: 255)] #[ORM\Column(length: 255)]
#[Groups(['shipment:read', 'shipment:write'])] #[Groups(['shipment:read', 'shipment:write'])]
private ?string $licensePlate = null; private ?string $licencePlate = null;
#[ORM\Column(length: 20, unique: true, nullable: true)] #[ORM\Column(length: 20, unique: true, nullable: true)]
#[Groups(['shipment:read'])] #[Groups(['shipment:read'])]
@@ -162,14 +162,14 @@ class Shipment
return $this->id; return $this->id;
} }
public function getLicensePlate(): ?string public function getLicencePlate(): ?string
{ {
return $this->licensePlate; return $this->licencePlate;
} }
public function setLicensePlate(?string $licensePlate): void public function setLicencePlate(?string $licencePlate): void
{ {
$this->licensePlate = $licensePlate; $this->licencePlate = $licencePlate;
} }
public function getIdentificationNumber(): ?string public function getIdentificationNumber(): ?string

View File

@@ -1,138 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Entity;
use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\Get;
use ApiPlatform\Metadata\GetCollection;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Attribute\Groups;
use Symfony\Component\Serializer\Attribute\SerializedName;
#[ORM\Entity]
#[ApiResource(
operations: [
new Get(
requirements: ['id' => '\d+'],
normalizationContext: ['groups' => ['building:read']],
),
new GetCollection(
normalizationContext: ['groups' => ['building:read']],
),
],
security: "is_granted('ROLE_USER')",
)]
class Statut
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
#[Groups(['building:read'])]
private ?int $id = null;
#[ORM\Column(length: 255)]
#[Groups(['building:read'])]
private ?string $label = null;
#[ORM\Column(length: 255)]
#[Groups(['building:read'])]
private ?string $code = null;
#[ORM\Column(length: 255)]
#[Groups(['building:read'])]
#[SerializedName('couleur')]
private ?string $color = null;
/**
* @var Collection<int, BuildingCase>
*/
#[ORM\OneToMany(targetEntity: BuildingCase::class, mappedBy: 'statut')]
private Collection $id_case;
public function __construct()
{
$this->id_case = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function setId(int $id): static
{
$this->id = $id;
return $this;
}
public function getLabel(): ?string
{
return $this->label;
}
public function setLabel(string $label): static
{
$this->label = $label;
return $this;
}
public function getCode(): ?string
{
return $this->code;
}
public function setCode(string $code): static
{
$this->code = $code;
return $this;
}
public function getColor(): ?string
{
return $this->color;
}
public function setColor(string $color): static
{
$this->color = $color;
return $this;
}
/**
* @return Collection<int, BuildingCase>
*/
public function getIdCase(): Collection
{
return $this->id_case;
}
public function addIdCase(BuildingCase $idCase): static
{
if (!$this->id_case->contains($idCase)) {
$this->id_case->add($idCase);
$idCase->setStatut($this);
}
return $this;
}
public function removeIdCase(BuildingCase $idCase): static
{
if ($this->id_case->removeElement($idCase)) {
// set the owning side to null (unless already changed)
if ($idCase->getStatut() === $this) {
$idCase->setStatut(null);
}
}
return $this;
}
}

View File

@@ -1,210 +0,0 @@
<?php
declare(strict_types=1);
namespace App\State;
use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use App\Entity\Bovine;
use App\Entity\BuildingCase;
use DateTimeImmutable;
use Doctrine\ORM\EntityManagerInterface;
use Dompdf\Dompdf;
use Malio\EdnotifBundle\Bovin\Api\BovinApiInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Throwable;
use Twig\Environment;
use Twig\Error\LoaderError;
use Twig\Error\RuntimeError;
use Twig\Error\SyntaxError;
final readonly class BuildingCaseWeightsReportProvider implements ProviderInterface
{
private const FRENCH_MONTHS = [
1 => 'Janvier',
2 => 'Février',
3 => 'Mars',
4 => 'Avril',
5 => 'Mai',
6 => 'Juin',
7 => 'Juillet',
8 => 'Août',
9 => 'Septembre',
10 => 'Octobre',
11 => 'Novembre',
12 => 'Décembre',
];
public function __construct(
private Environment $twig,
private EntityManagerInterface $entityManager,
private BovinApiInterface $bovinApi,
) {}
/**
* @throws RuntimeError
* @throws SyntaxError
* @throws LoaderError
*/
public function provide(Operation $operation, array $uriVariables = [], array $context = []): Response
{
$id = $uriVariables['id'] ?? null;
if (null === $id) {
throw new NotFoundHttpException('Case not found.');
}
$buildingCase = $this->entityManager->getRepository(BuildingCase::class)->find($id);
if (!$buildingCase instanceof BuildingCase) {
throw new NotFoundHttpException('Case not found.');
}
$rows = [];
$firstArrivalDate = null;
$headerBreedCode = null;
foreach ($buildingCase->getBovines() as $bovine) {
if (!$bovine instanceof Bovine) {
continue;
}
$workNumber = null;
$birthDate = null;
$breedCode = null;
try {
$animalFileDto = $this->bovinApi->getAnimalFile(
nationalNumber: $bovine->getNationalNumber(),
countryCode: 'FR',
);
$workNumber = $animalFileDto->identification?->workNumber;
$birthDate = $animalFileDto->identification?->birthDate?->date?->format('d/m/y');
$breedCode = $this->normalizeBreedCode($animalFileDto->identification?->breedType);
if (null === $headerBreedCode && null !== $breedCode) {
$headerBreedCode = $breedCode;
}
} catch (Throwable) {
// Keep row data even if external identification service is unavailable.
}
$arrivalDate = $bovine->getArrivalDate();
if ($arrivalDate instanceof DateTimeImmutable && null === $firstArrivalDate) {
$firstArrivalDate = $arrivalDate;
}
$projectedWeights = $this->buildProjectedWeights(
$bovine->getReceivedWeight(),
$arrivalDate,
$breedCode,
);
$rows[] = [
'nationalNumber' => $bovine->getNationalNumber(),
'workNumber' => $workNumber,
'birthDate' => $birthDate,
'receivedWeight' => $bovine->getReceivedWeight(),
'arrivalDate' => $bovine->getArrivalDate()?->format('d/m/Y'),
'projectedWeights' => $projectedWeights,
];
}
$monthHeaders = $this->buildMonthHeaders($firstArrivalDate, $headerBreedCode);
$dompdf = new Dompdf();
$html = $this->twig->render('case_weights_report.html.twig', [
'buildingCase' => $buildingCase,
'rows' => $rows,
'monthHeaders' => $monthHeaders,
'printedAt' => new DateTimeImmutable(),
]);
$dompdf->loadHtml($html);
$dompdf->setPaper('A4', 'landscape');
$dompdf->render();
$filename = sprintf('tableau-poids-case-%d.pdf', $buildingCase->getId());
return new Response($dompdf->output(), Response::HTTP_OK, [
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'inline; filename="'.$filename.'"',
]);
}
private function normalizeBreedCode(mixed $breedType): ?string
{
if (null === $breedType) {
return null;
}
if (is_numeric($breedType)) {
return (string) $breedType;
}
if (is_string($breedType) && preg_match('/\d+/', $breedType, $matches)) {
return $matches[0];
}
return null;
}
private function resolveDailyGainKg(?string $breedCode): float
{
return 1.3;
}
/**
* @return array<int, null|float>
*/
private function buildProjectedWeights(?int $receivedWeight, ?DateTimeImmutable $arrivalDate, ?string $breedCode): array
{
$result = array_fill(0, 12, null);
if (null === $receivedWeight || !$arrivalDate instanceof DateTimeImmutable) {
return $result;
}
$currentWeight = (float) $receivedWeight;
$dailyGainKg = $this->resolveDailyGainKg($breedCode);
for ($i = 0; $i < 12; ++$i) {
$monthDate = $arrivalDate->modify('first day of this month')->modify(sprintf('+%d month', $i));
$daysInMonth = (int) $monthDate->format('t');
$daysToApply = 0 === $i
? max($daysInMonth - (int) $arrivalDate->format('j'), 0)
: $daysInMonth;
$currentWeight += $daysToApply * $dailyGainKg;
$result[$i] = $currentWeight;
}
return $result;
}
/**
* @return array<int, array{name:string,days:string,base:string}>
*/
private function buildMonthHeaders(?DateTimeImmutable $arrivalDate, ?string $breedCode): array
{
$referenceDate = $arrivalDate ?? new DateTimeImmutable('first day of january this year');
$dailyGainKg = $this->resolveDailyGainKg($breedCode);
$headers = [];
for ($i = 0; $i < 12; ++$i) {
$monthDate = $referenceDate->modify('first day of this month')->modify(sprintf('+%d month', $i));
$monthIndex = (int) $monthDate->format('n');
$daysInMonth = (int) $monthDate->format('t');
$daysToApply = 0 === $i
? max($daysInMonth - (int) $referenceDate->format('j'), 0)
: $daysInMonth;
$headers[] = [
'name' => self::FRENCH_MONTHS[$monthIndex],
'days' => sprintf('%d jours', $daysToApply),
'baseValue' => $daysToApply * $dailyGainKg,
];
}
return $headers;
}
}

View File

@@ -1,378 +0,0 @@
<!doctype html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<style>
/* =========================
DOMPDF FRIENDLY SETTINGS
========================= */
@page { size: A4 landscape; }
html, body {
margin: 0;
padding: 6mm;
font-family: Helvetica, sans-serif;
font-size: 8px;
}
body {
/* DejaVu Sans est très bien géré par dompdf (accents, stabilité) */
font-family: Helvetica, sans-serif;
font-size: 10px;
color: #111;
}
.sheet { width: auto; }
h1 {
margin: 8px 0 16px 0;
padding: 0;
line-height: 1;
text-transform: uppercase;
}
table {
width: 100%;
border-collapse: collapse;
table-layout: fixed;
}
th, td {
border: 2px solid #2b2b2b;
padding: 2px 3px;
text-align: center;
vertical-align: middle;
line-height: 1.1;
white-space: nowrap; /* important pour dompdf */
overflow: hidden; /* évite les débordements */
text-overflow: clip;
}
/* =========================
HEADER (mise en page)
========================= */
.header-layout,
.header-layout td {
border: 0;
padding: 0;
}
.header-left td,
.header-right td {
border: 2px solid #2b2b2b;
font-weight: 700;
padding: 0;
}
/* Bloc CASE */
.header-left td {
height: 34px;
font-size: 10px;
}
.header-left .case-label {
width: 34%;
letter-spacing: 0.2px;
}
.header-left .case-number {
width: 66%;
font-size: 18px; /* volontairement compact pour dompdf */
line-height: 1;
}
/* Bloc PROVENANCE / RACE */
.header-right .label {
font-size: 11px;
height: 18px;
letter-spacing: 0;
}
.header-right .mini {
height: 18px;
font-size: 10px;
}
.header-right .mini-empty {
height: 18px;
font-size: 9px;
}
.header-right .race {
height: 24px;
font-size: 11px;
letter-spacing: 0;
}
.header-right .breed {
font-size: 9px;
font-weight: 700;
padding: 0 2px;
}
/* =========================
TABLEAU PRINCIPAL
========================= */
.main {
margin-top: 2px;
}
.main th {
background: #ffffff;
font-weight: 700;
padding: 2px 1px;
}
.main .head-big {
font-size: 14px;
font-weight: 700;
white-space: normal; /* permet les <br> */
line-height: 1.15;
}
.main .month {
font-size: 12px;
}
.main .days {
font-size: 12px;
}
.main .sub-title {
font-size: 16px;
font-weight: 700;
letter-spacing: 0;
padding: 8px;
}
.main .base {
font-size: 12px;
}
/* Hauteurs de lignes d'en-tête (stables en dompdf) */
.main thead tr:nth-child(1) th { height: 24px; }
.main thead tr:nth-child(2) th { height: 18px; }
.main thead tr:nth-child(3) th { height: 18px; }
.main thead tr:nth-child(4) th { height: 18px; }
/* Lignes data */
.data-row td {
height: 18px;
font-size: 14px;
}
.row-work {
text-align: center;
font-size: 18px !important;
font-weight: 700;
line-height: 1;
}
.row-weight,
.row-birth,
.row-month {
font-size: 9px;
line-height: 1;
}
/* =========================
FOOTER VACCINS / NOTES
========================= */
.footer {
font-size: 12px;
}
/* Header droit sans bordures par défaut */
.header-right-free,
.header-right-free td {
padding: 0;
width: 6.25%;
}
</style>
</head>
<body>
{% set firstArrivalDate = rows is not empty ? rows[0].arrivalDate : null %}
{% set monthCount = ((monthHeaders|default([]))|length) > 0 ? ((monthHeaders|default([]))|length) : 12 %}
<div class="sheet">
<!-- =========================
EN-TÊTE (CASE / PROVENANCE / RACE)
========================= -->
<h1 style="color: red; text-align: center; width: 100%; font-size: 36px">
Arrivage du {{ firstArrivalDate ?? '-' }}
</h1>
<table style="width:100%; border-collapse:collapse; table-layout:fixed; margin-bottom: 16px">
<tr>
<td style="width:40%; vertical-align:top; padding-right:2mm; border:0;">
<table style="width:100%; border-collapse:collapse; table-layout:fixed;">
<tr>
<td style="border: 0; height: 20px"></td>
</tr>
<tr>
<td style="font-weight:700; text-align: left; border: none; font-size: 24px">CASE N° {{ buildingCase.caseNumber ?? '' }}</td>
</tr>
</table>
</td>
<td style="width:60%; vertical-align:top; padding-left:2mm; border:0;">
<table class="header-right-free" style="width:100%; border-collapse:collapse; table-layout:fixed;">
<tr>
<td style="border:0; text-align:center; font-weight:700; height: 20px;" colspan="5"></td>
<td style="border:0;" colspan="2"></td>
<td style="border:1px solid #2b2b2b; text-align:center; font-weight:700; height: 20px;">1</td>
<td style="border:0; height: 20px;"></td>
<td style="border:1px solid #2b2b2b; text-align:center; font-weight:700; height: 20px;">2</td>
<td style="border:0; height: 20px;"></td>
<td style="border:1px solid #2b2b2b; text-align:center; font-weight:700; height: 20px;">3</td>
<td style="border:0; height: 20px;"></td>
<td style="border:1px solid #2b2b2b; text-align:center; font-weight:700; height: 20px;">4</td>
<td style="border:0;" colspan="2"></td>
</tr>
<tr>
<td style="border:0; text-align:left; font-weight:700; font-size: 24px; width:40%; height: 20px;" colspan="5">PROVENANCE</td>
<td style="border:0;" colspan="2"></td>
<td style="border:1px solid #2b2b2b;"></td>
<td style="border:0;"></td>
<td style="border:1px solid #2b2b2b;"></td>
<td style="border:0;"></td>
<td style="border:1px solid #2b2b2b;"></td>
<td style="border:0;"></td>
<td style="border:1px solid #2b2b2b;"></td>
<td style="border: 0; width: 20%;" colspan="2"></td>
</tr>
<tr>
<td style="border: 0; height: 20px" colspan="16"></td>
</tr>
<tr>
<td style="border: 0; text-align:left; font-weight:700; font-size: 24px" colspan="3">RACE</td>
<td style="border:1px solid #2b2b2b; text-align:center; font-weight:700;" colspan="3">LIMOUSIN</td>
<td style="border:1px solid #2b2b2b; text-align:center; font-weight:700;" colspan="1"></td>
<td style="border: 0; text-align:center; font-weight:700;" colspan="1"></td>
<td style="border:1px solid #2b2b2b; text-align:center; font-weight:700;" colspan="3">CHAROLAIS</td>
<td style="border:1px solid #2b2b2b; text-align:center; font-weight:700;" colspan="1"></td>
<td style="border: 0; text-align:center; font-weight:700;" colspan="1"></td>
<td style="border:1px solid #2b2b2b; text-align:center; font-weight:700;" colspan="2">Autre</td>
<td style="border:1px solid #2b2b2b; text-align:center; font-weight:700;" colspan="1"></td>
</tr>
</table>
</td>
</tr>
</table>
<!-- =========================
TABLEAU PRINCIPAL
========================= -->
<table class="main">
<colgroup>
<col style="width:8%">
<col style="width:4%">
<col style="width:7%">
{% for month in monthHeaders %}
<col style="width:6.75%">
{% endfor %}
</colgroup>
<thead>
<tr>
<th rowspan="4" class="head-big">N° de<br>travail</th>
<th rowspan="4" class="head-big head-big-weight">Poids<br>(kg)</th>
<th rowspan="4" class="head-big">Date de<br>naissance</th>
{% for month in monthHeaders|default([]) %}
<th class="month">{{ month.name }}</th>
{% endfor %}
</tr>
<tr>
{% for month in monthHeaders|default([]) %}
<th class="days">{{ month.days }}</th>
{% endfor %}
</tr>
<tr>
<th colspan="{{ monthHeaders|length }}" class="sub-title">POIDS PAR MOIS</th>
</tr>
<tr>
{% for month in monthHeaders|default([]) %}
<th class="base">
{% if month.baseValue is defined %}
{{ month.baseValue|round(0, 'common') }} kg
{% elseif month.base is defined %}
{{ month.base }}
{% endif %}
</th>
{% endfor %}
</tr>
</thead>
<tbody>
{# 11 lignes comme dans ton code (0..10) #}
{% for i in 0..12 %}
{% set row = rows[i] ?? null %}
{% set baseWeight = row ? (row.receivedWeight ?? null) : null %}
<tr class="data-row">
<td class="row-work">{{ row ? (row.workNumber ?? '') : '' }}</td>
<td class="row-weight">{{ baseWeight ?? '' }}</td>
<td class="row-birth">
{% if row and row.birthDate %}
{% set birthParts = row.birthDate|split('/') %}
{{ birthParts|length == 3 ? birthParts[1] ~ '/' ~ birthParts[2] : row.birthDate }}
{% endif %}
</td>
{% for idx in 0..(monthCount > 0 ? monthCount - 1 : 0) %}
{% set projectedWeight = row and row.projectedWeights is defined ? (row.projectedWeights[idx] ?? null) : null %}
<td class="row-month"{% if loop.index0 < 4 %} style="background:#e0e0e0;"{% endif %}>
{{ projectedWeight is not null ? projectedWeight|round(0, 'common') : '' }}
</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
<!-- =========================
FOOTER (traitements / vaccins)
========================= -->
<table class="footer" style="border-collapse:collapse; margin-top: 32px">
<tr>
<td style="height: 20px; border: 0" colspan="4"></td>
<td style="font-weight: 700" colspan="2">Grippe</td>
<td style="font-weight: 700" colspan="2">Protivity</td>
</tr>
<tr>
<td style="height: 20px">Date</td>
<td>Antibiotique</td>
<td>Date</td>
<td>Antero</td>
<td>Date</td>
<td>Intranasale</td>
<td>Date</td>
<td>Rappel 30 jours</td>
</tr>
<tr>
<td style="height: 20px"></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td style="height: 20px"></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</table>
</div>
</body>
</html>

View File

@@ -275,7 +275,7 @@
<div class="meta"> <div class="meta">
<p>Transporteur : {{ shipment.carrier ? shipment.carrier.name : '-' }}</p> <p>Transporteur : {{ shipment.carrier ? shipment.carrier.name : '-' }}</p>
<p>Mode d'expédition : {{ shipment.truck ? shipment.truck.name : '-' }}</p> <p>Mode d'expédition : {{ shipment.truck ? shipment.truck.name : '-' }}</p>
<p>Immatriculation : {{ shipment.licensePlate ?? '-' }}</p> <p>Immatriculation : {{ shipment.licencePlate ?? '-' }}</p>
</div> </div>
</td> </td>