### Install Project Dependencies Source: https://github.com/mtes-mct/ecobalyse/blob/master/README.md Commands to install frontend and backend dependencies. Frontend uses npm, while the backend utilizes uv for environment management. ```bash npm ci --ignore-scripts uv sync ``` -------------------------------- ### Build and Run Application Source: https://github.com/mtes-mct/ecobalyse/blob/master/README.md Commands to start the development server, build the client application, or launch the production container via Docker. ```bash npm start:dev npm run build docker compose -f docker/compose.yaml up --build ``` -------------------------------- ### Configure Database URL Source: https://github.com/mtes-mct/ecobalyse/blob/master/README.md Example format for the DATABASE_URL environment variable to connect to a PostgreSQL database using asyncpg. ```text DATABASE_URL=postgresql+asyncpg://:@localhost:5432/ ``` -------------------------------- ### List Available Trims - Textile API Source: https://context7.com/mtes-mct/ecobalyse/llms.txt This example shows how to retrieve a list of available accessories (trims) such as buttons and zippers from the Ecobalyse Textile API. This list can then be used when simulating textile products that include these components. ```bash # Récupérer la liste des accessoires curl -X GET "https://ecobalyse.beta.gouv.fr/api/textile/trims" \ -H "Authorization: Bearer votre_token_api" ``` -------------------------------- ### List Available Food Ingredients - Food API Source: https://context7.com/mtes-mct/ecobalyse/llms.txt This example shows how to retrieve a list of available food ingredients from the Ecobalyse Food API. The response includes ingredient details such as ID, name, origin, category, and production scenario, which can be used for food product simulations. ```bash # Récupérer la liste des ingrédients curl -X GET "https://ecobalyse.beta.gouv.fr/api/food/ingredients" \ -H "Authorization: Bearer votre_token_api" ``` -------------------------------- ### GET /api/food/packagings Source: https://context7.com/mtes-mct/ecobalyse/llms.txt Retrieves the list of available packaging types for food products. ```APIDOC ## GET /api/food/packagings ### Description Retrieves the list of available packaging types used for conditioning food products. ### Method GET ### Endpoint https://ecobalyse.beta.gouv.fr/api/food/packagings ### Parameters #### Query Parameters - **Authorization** (string) - Required - Bearer token for authentication ### Response #### Success Response (200) - **id** (string) - Unique identifier for the packaging - **name** (string) - Human-readable name of the packaging #### Response Example [ {"id": "09bf8c91-b95e-4bd3-aaf3-4c5450f74ae7", "name": "Carton"} ] ``` -------------------------------- ### GET /api/food/ingredients Source: https://context7.com/mtes-mct/ecobalyse/llms.txt Retrieves a list of available food ingredients with their characteristics. ```APIDOC ## GET /api/food/ingredients ### Description Retrieves the list of available food ingredients with their characteristics (default origin, category, production scenario). ### Method GET ### Endpoint /api/food/ingredients ### Parameters No parameters required. ### Request Example ```bash curl -X GET "https://ecobalyse.beta.gouv.fr/api/food/ingredients" \ -H "Authorization: Bearer votre_token_api" ``` ### Response #### Success Response (200) - An array of ingredient objects, each containing details about the ingredient. #### Response Example ```json [ { "id": "uuid-ingredient-1", "name": "Pomme", "category": "Fruit", "origin": "France", "productionScenario": "conventional" }, { "id": "uuid-ingredient-2", "name": "Bœuf", "category": "Viande", "origin": "Brésil", "productionScenario": "intensive" } ] ``` ``` -------------------------------- ### GET /api/textile/trims Source: https://context7.com/mtes-mct/ecobalyse/llms.txt Retrieves a list of available trims (accessories) for textile products. ```APIDOC ## GET /api/textile/trims ### Description Retrieves the list of available trims (accessories) for garments such as buttons, zippers, rivets, etc. ### Method GET ### Endpoint /api/textile/trims ### Parameters No parameters required. ### Request Example ```bash curl -X GET "https://ecobalyse.beta.gouv.fr/api/textile/trims" \ -H "Authorization: Bearer votre_token_api" ``` ### Response #### Success Response (200) - An array of trim objects, each containing: - **id** (string) - The unique identifier for the trim. - **name** (string) - The name of the trim. #### Response Example ```json [ {"id": "uuid-bouton-metal", "name": "Bouton métal"}, {"id": "uuid-zip-metal", "name": "Fermeture éclair métal"}, {"id": "uuid-bouton-plastique", "name": "Bouton plastique"} ] ``` ``` -------------------------------- ### Support and Data Protection Source: https://github.com/mtes-mct/ecobalyse/blob/master/public/pages/api-faq.md Information on how to report bugs, get technical support, and understand data protection measures for the Ecobalyse API. ```APIDOC ## Bug Reporting and Support ### Description To report a bug or obtain technical support for the API, contact the community via [the Ecobalyse exchange platform](https://fabrique-numerique.gitbook.io/ecobalyse/communaute). ## Data Protection ### Description Ecobalyse does not store API parameters or results in any database, eliminating the risk of data leaks. Communication with the API is encrypted via HTTPS, significantly reducing the risk of traffic interception. ### Self-Hosting Option For complete control over the API server environment, the project is [open source](https://github.com/MTES-MCT/ecobalyse). Users can opt for self-hosting the service on their own infrastructure. Contact the community for guidance and support on this process. ``` -------------------------------- ### GET /api/food/transforms Source: https://context7.com/mtes-mct/ecobalyse/llms.txt Retrieves the list of available food transformation processes such as cooking, pasteurization, or fermentation. ```APIDOC ## GET /api/food/transforms ### Description Retrieves the list of available food transformation processes used in environmental impact calculations. ### Method GET ### Endpoint https://ecobalyse.beta.gouv.fr/api/food/transforms ### Parameters #### Query Parameters - **Authorization** (string) - Required - Bearer token for authentication ### Response #### Success Response (200) - **id** (string) - Unique identifier for the process - **name** (string) - Human-readable name of the process #### Response Example [ {"id": "a2836bb8-7f45-5cfa-bb00-8b38046291cf", "name": "Cuisson au four"} ] ``` -------------------------------- ### Get Detailed Lifecycle Impacts - Textile API Source: https://context7.com/mtes-mct/ecobalyse/llms.txt This snippet illustrates how to obtain detailed environmental impacts for a textile product, broken down by lifecycle stages (material, spinning, fabric, etc.). It requires product and material specifications, including optional parameters like fading and printing. The response provides a comprehensive lifecycle assessment. ```bash # Simulation détaillée avec cycle de vie complet curl -X POST "https://ecobalyse.beta.gouv.fr/api/textile/simulator/detailed" \ -H "Content-Type: application/json" \ -H "Authorization: Bearer votre_token_api" \ -d '{ "mass": 0.45, "product": "jean", "materials": [ {"id": "62a4d6fb-3276-4ba5-93a3-889ecd3bff84", "share": 0.98}, {"id": "4b6c8ebe-4d12-4cd7-8d94-6ad20d8bd471", "share": 0.02} ], "countrySpinning": "TR", "countryFabric": "TR", "countryDyeing": "TN", "countryMaking": "TN", "fabricProcess": "weaving", "fading": true, "printing": {"kind": "pigment", "ratio": 0.05} }' ``` -------------------------------- ### GET /api/textile/materials Source: https://context7.com/mtes-mct/ecobalyse/llms.txt Retrieves all available textile materials with their unique identifiers and origin types. ```APIDOC ## GET /api/textile/materials ### Description Retrieves all available textile materials including natural, synthetic, and recycled variants. ### Method GET ### Endpoint https://ecobalyse.beta.gouv.fr/api/textile/materials ### Parameters #### Query Parameters - None ### Request Example curl -X GET "https://ecobalyse.beta.gouv.fr/api/textile/materials" -H "Authorization: Bearer " ### Response #### Success Response (200) - **Array** (List) - List of material objects with uuid, name, and origin. #### Response Example [ {"uuid": "62a4d6fb-3276-4ba5-93a3-889ecd3bff84", "name": "Coton", "origin": "NaturalFromVegetal"} ] ``` -------------------------------- ### Manage Users and CLI Source: https://github.com/mtes-mct/ecobalyse/blob/master/README.md Commands to create superusers and interact with the backend CLI for help and specific command execution. ```bash uv run backend users create-user --email foo@bar.org --first-name Foo --last-name Bar --superuser uv run backend --help uv run backend users --help ``` -------------------------------- ### Manage Database and Fixtures Source: https://github.com/mtes-mct/ecobalyse/blob/master/README.md Commands to upgrade the database schema, reset the database, and load data fixtures for local development. ```bash uv run backend database upgrade --no-prompt ./bin/reset-docker-db.sh uv run backend fixtures load-processes public/data/processes_impacts.json uv run backend fixtures load-components public/data/object/components.json ``` -------------------------------- ### GET /api/textile/countries Source: https://context7.com/mtes-mct/ecobalyse/llms.txt Retrieves the list of countries available for textile simulations, including ISO codes and impact parameters. ```APIDOC ## GET /api/textile/countries ### Description Retrieves the list of countries available for textile simulations. Each entry includes the country name and ISO code used for transport and electrical mix calculations. ### Method GET ### Endpoint https://ecobalyse.beta.gouv.fr/api/textile/countries ### Parameters #### Query Parameters - None ### Request Example curl -X GET "https://ecobalyse.beta.gouv.fr/api/textile/countries" -H "Authorization: Bearer " ### Response #### Success Response (200) - **Array** (List) - List of country objects containing code and name. #### Response Example [ {"code": "FR", "name": "France"}, {"code": "CN", "name": "Chine"} ] ``` -------------------------------- ### Simulate Product with Trims - Textile API Source: https://context7.com/mtes-mct/ecobalyse/llms.txt This snippet demonstrates how to include accessories (trims) in a textile product simulation using the Ecobalyse Textile API. It shows how to specify the trim ID and quantity within the simulation request payload. ```bash # Utilisation des accessoires dans une simulation curl -X POST "https://ecobalyse.beta.gouv.fr/api/textile/simulator" \ -H "Content-Type: application/json" \ -H "Authorization: Bearer votre_token_api" \ -d '{ "mass": 0.35, "product": "chemise", "materials": [{"id": "62a4d6fb-3276-4ba5-93a3-889ecd3bff84", "share": 1}], "countryMaking": "FR", "fabricProcess": "weaving", "trims": [ {"id": "uuid-bouton-plastique", "quantity": 8} ] }' ``` -------------------------------- ### Backend API - Register New User via Magic Link Source: https://context7.com/mtes-mct/ecobalyse/llms.txt Registers a new user by collecting their email, first name, last name, and organization details. An email with a magic link will be sent for subsequent login. ```bash # Inscription d'un nouvel utilisateur curl -X POST "http://localhost:8002/api/access/register/magic-link" \ -H "Content-Type: application/json" \ -d '{ "email": "nouveau@exemple.fr", "firstName": "Jean", "lastName": "Dupont", "organization": { "name": "Ma Société", "type": "company" } }' ``` -------------------------------- ### Retrieve Textile Product Types Source: https://context7.com/mtes-mct/ecobalyse/llms.txt Lists the supported textile product categories for simulation. Each product type contains default parameters like mass and durability. ```bash curl -X GET "https://ecobalyse.beta.gouv.fr/api/textile/products" -H "Authorization: Bearer votre_token_api" ``` -------------------------------- ### CLI Backend - User Management Source: https://context7.com/mtes-mct/ecobalyse/llms.txt Command-line interface commands for administering users within the Ecobalyse application. Supports creating single users with basic details, creating super-users, and creating multiple users in a batch. ```bash # Créer un utilisateur simple uv run backend users create-user \ --email admin@exemple.fr \ --first-name Admin \ --last-name Ecobalyse \ --organization "Ecobalyse" \ --organization-type local_authority # Créer un super-utilisateur uv run backend users create-user \ --email superadmin@exemple.fr \ --first-name Super \ --last-name Admin \ --superuser # Créer plusieurs utilisateurs d'un coup uv run backend users create-users \ --users "user1@test.com/Prénom1/Nom1,user2@test.com/Prénom2/Nom2" \ --organization "MaStructure" \ --organization-type company ``` -------------------------------- ### CLI Backend - Database Management Source: https://context7.com/mtes-mct/ecobalyse/llms.txt Alembic commands integrated for schema migrations. ```APIDOC ## CLI Backend - Gestion de la Base de Données Commandes Alembic intégrées pour les migrations de schéma. ### Apply Migrations #### Description Applies all pending database schema migrations. #### Command `uv run backend database upgrade --no-prompt` #### Example ```bash uv run backend database upgrade --no-prompt ``` ### Reset Docker Database #### Description Resets the database using a Docker script. #### Command `./bin/reset-docker-db.sh` #### Example ```bash ./bin/reset-docker-db.sh ``` ### Database Connection Configuration #### Description Configures the database connection using an environment variable. #### Environment Variable - **DATABASE_URL** (string) - Specifies the database connection string. #### Format `postgresql+asyncpg://user:password@localhost:5432/ecobalyse` ``` -------------------------------- ### CLI Backend - Fixture Management Source: https://context7.com/mtes-mct/ecobalyse/llms.txt Commands for loading and exporting reference data (processes, components). ```APIDOC ## CLI Backend - Gestion des Fixtures Commandes pour charger et exporter les données de référence (processus, composants). ### Load Processes #### Description Loads processes from specified JSON files. #### Command `uv run backend fixtures load-processes` #### Arguments - `[file1]` (string) - Required - Path to the first JSON file containing process data. - `[file2]` (string) - Required - Path to the second JSON file containing process data. #### Example ```bash uv run backend fixtures load-processes \ public/data/processes_impacts.json \ public/data/processes_generic_impacts.json ``` ### Load Components #### Description Loads components from a specified JSON file. #### Command `uv run backend fixtures load-components` #### Arguments - `[file]` (string) - Required - Path to the JSON file containing component data. #### Example ```bash uv run backend fixtures load-components \ public/data/object/components.json ``` ### Export Components to JSON #### Description Exports published components to a JSON file. #### Command `uv run backend json dump-components > [output_file]` #### Arguments - `[output_file]` (string) - Required - The name of the output JSON file. #### Example ```bash uv run backend json dump-components > components_export.json ``` ### Load Test Fixtures #### Description Loads test fixtures into the database. #### Command `uv run backend fixtures load-test` #### Example ```bash uv run backend fixtures load-test ``` ``` -------------------------------- ### CLI Backend - Fixture Management Source: https://context7.com/mtes-mct/ecobalyse/llms.txt Commands for managing reference data (fixtures) such as processes and components. Includes loading data from JSON files, loading test fixtures, and exporting published components to a JSON file. ```bash # Charger les processus depuis un fichier JSON uv run backend fixtures load-processes \ public/data/processes_impacts.json \ public/data/processes_generic_impacts.json # Charger les composants uv run backend fixtures load-components \ public/data/object/components.json # Exporter les composants publiés vers JSON uv run backend json dump-components > components_export.json # Charger les fixtures de test uv run backend fixtures load-test ``` -------------------------------- ### Calculate Specific Climate Change Impact - Textile API Source: https://context7.com/mtes-mct/ecobalyse/llms.txt This example shows how to calculate a single environmental impact indicator, specifically climate change (cch), for a textile product using the Ecobalyse Textile API. It requires basic product information and material composition. The response includes the calculated impact value and a web URL for visualization. ```bash # Calculer uniquement l'impact changement climatique (cch) curl -X POST "https://ecobalyse.beta.gouv.fr/api/textile/simulator/cch" \ -H "Content-Type: application/json" \ -H "Authorization: Bearer votre_token_api" \ -d '{ "mass": 0.55, "product": "pull", "materials": [{"id": "9dba0e95-0c35-4f8b-9267-62ddf47d4984", "share": 1}] }' ``` -------------------------------- ### Simulation d'Impacts Alimentaires avec Data.Food.Recipe Source: https://context7.com/mtes-mct/ecobalyse/llms.txt Gère le calcul des impacts environnementaux des recettes alimentaires. Prend en entrée une requête de recette et retourne le résultat complet des impacts, incluant les détails par ingrédient, transformation, transport et emballage. ```Elm -- Module: Data.Food.Recipe -- Calcul des impacts d'une recette import Data.Food.Recipe as Recipe import Data.Food.Query as Query -- Structure d'une recette type alias Recipe = { ingredients : List RecipeIngredient , transform : Maybe Transform , packaging : List Packaging , distribution : Maybe Distribution , preparation : List Preparation } -- Calcul complet des impacts compute : Db -> Query -> Result String (Recipe, Results) compute db query = fromQuery db query |> Result.map computeAllImpacts -- Structure des résultats type alias Results = { total : Impacts , perKg : Impacts , recipe : { ingredientsTotal : Impacts , ingredients : List (RecipeIngredient, Impacts) , transform : Impacts , transports : Transport } , distribution : { total : Impacts, transports : Transport } , packaging : Impacts , preparation : Impacts , scoring : Scoring } -- Modes de distribution type Distribution = Ambient -- Température ambiante | Fresh -- Réfrigéré | Frozen -- Congelé -- Techniques de préparation type Preparation = Frying -- Friture | PanCooking -- Cuisson poêle | Oven -- Four | Microwave -- Micro-ondes | Refrigeration -- Réfrigération | Freezing -- Congélation ``` -------------------------------- ### Retrieve Food Transforms - API Source: https://context7.com/mtes-mct/ecobalyse/llms.txt Fetches a list of available food transformation processes such as cooking, pasteurization, and fermentation. Requires an API token for authorization. ```bash curl -X GET "https://ecobalyse.beta.gouv.fr/api/food/transforms" \ -H "Authorization: Bearer votre_token_api" ``` -------------------------------- ### Backend API - List User's API Tokens Source: https://context7.com/mtes-mct/ecobalyse/llms.txt Retrieves a list of all API tokens associated with the authenticated user. Each token entry includes its ID and creation timestamp. ```bash # Lister ses tokens curl -X GET "http://localhost:8002/api/tokens" \ -H "Authorization: Bearer votre_jwt_token" ``` -------------------------------- ### CLI Backend - Database Management Source: https://context7.com/mtes-mct/ecobalyse/llms.txt Provides commands for managing database schema migrations using Alembic. Includes applying all pending migrations and resetting the database using a Docker script. Database connection is configured via the DATABASE_URL environment variable. ```bash # Appliquer toutes les migrations uv run backend database upgrade --no-prompt # Réinitialiser la base avec Docker ./bin/reset-docker-db.sh # Configuration de la connexion # Variable d'environnement DATABASE_URL: # postgresql+asyncpg://user:password@localhost:5432/ecobalyse ``` -------------------------------- ### Configure Git Hooks and Linting Source: https://github.com/mtes-mct/ecobalyse/blob/master/README.md Commands to manage pre-commit hooks and run code linting or formatting checks using Prettier and Ruff. ```bash uv run pre-commit install npm run lint:all npm run fix:all uv run pre-commit uninstall ``` -------------------------------- ### Ecobalyse API Overview Source: https://github.com/mtes-mct/ecobalyse/blob/master/public/pages/api-faq.md This section provides an overview of the Ecobalyse API, its purpose, and how to access its documentation. ```APIDOC ## Ecobalyse API ### Description The Ecobalyse API is a communication interface that allows information systems to query the calculation engine and obtain scores. It uses the HTTP/REST protocol. ### Accessing Documentation The OpenAPI documentation is accessible in Web format on [the dedicated API page](/#/api). The JSON specification format is accessible on the API's root endpoint. ### Testing the API The [documentation is interactive](/#/api) and allows you to configure and execute requests on the API directly from the Web interface. ``` -------------------------------- ### Backend API - Component Management Source: https://context7.com/mtes-mct/ecobalyse/llms.txt Provides CRUD operations for managing reusable components like accessories and base materials. Supports listing, retrieving, creating, updating, and deleting components. Authentication may be required for certain operations (POST, PATCH, DELETE). ```bash # Lister tous les composants (public) curl -X GET "http://localhost:8002/api/components" # Récupérer un composant spécifique curl -X GET "http://localhost:8002/api/components/uuid-composant" # Créer un composant (admin uniquement) curl -X POST "http://localhost:8002/api/components" \ -H "Authorization: Bearer votre_jwt_admin" \ -H "Content-Type: application/json" \ -d '{ "name": "Nouveau composant", "scope": "object", "elements": [...], "published": false }' # Mettre à jour un composant curl -X PATCH "http://localhost:8002/api/components/uuid-composant" \ -H "Authorization: Bearer votre_jwt_admin" \ -H "Content-Type: application/json" \ -d '{"published": true}' # Supprimer un composant curl -X DELETE "http://localhost:8002/api/components/uuid-composant" \ -H "Authorization: Bearer votre_jwt_admin" ``` -------------------------------- ### Retrieve Textile Countries List Source: https://context7.com/mtes-mct/ecobalyse/llms.txt Fetches the list of available countries for textile simulations. Each entry includes an ISO code and the country name. ```bash curl -X GET "https://ecobalyse.beta.gouv.fr/api/textile/countries" -H "Authorization: Bearer votre_token_api" ``` -------------------------------- ### Backend API - Request Magic Link for Authentication Source: https://context7.com/mtes-mct/ecobalyse/llms.txt Initiates the user authentication process by sending a magic link to the provided email address. This method does not require a password. ```bash # Demander l'envoi d'un magic link curl -X POST "http://localhost:8002/api/access/login/magic-link" \ -H "Content-Type: application/json" \ -d '{ "email": "utilisateur@exemple.fr" }' ``` -------------------------------- ### Define Environment Variables for Ecobalyse Source: https://context7.com/mtes-mct/ecobalyse/llms.txt Configuration file for local development environment variables, covering database connections, email server settings, feature flags, and monitoring integrations. ```bash DATABASE_URL=postgresql+asyncpg://user:pass@localhost:5432/ecobalyse SECRET_KEY=votre_cle_secrete_32_caracteres EMAIL_FROM=noreply@ecobalyse.beta.gouv.fr EMAIL_SERVER_HOST=localhost EMAIL_SERVER_PORT=1025 EMAIL_SERVER_USE_TLS=False NODE_ENV=development ENABLE_FOOD_SECTION=True ENABLE_TEXTILE_SECTION=True ENABLE_OBJECTS_SECTION=False ENABLE_VELI_SECTION=False RATELIMIT_MAX_RPM=5000 RATELIMIT_WHITELIST=127.0.0.1 SENTRY_DSN=https://xxx@sentry.io/xxx MATOMO_HOST=stats.beta.gouv.fr MATOMO_SITE_ID=123 PLAUSIBLE_HOST=plausible.io TRANSCRYPT_KEY=cle_transcrypt ENCRYPTION_KEY=cle_pour_archives VERSION_POLL_SECONDS=300 ``` -------------------------------- ### POST /api/textile/simulator/detailed Source: https://context7.com/mtes-mct/ecobalyse/llms.txt Retrieves detailed environmental impacts across the entire lifecycle of a textile product. ```APIDOC ## POST /api/textile/simulator/detailed ### Description Retrieves detailed environmental impacts with a breakdown by lifecycle stage (material, spinning, weaving, finishing, manufacturing, distribution, use, end-of-life). ### Method POST ### Endpoint /api/textile/simulator/detailed ### Parameters #### Request Body - **mass** (number) - Required - The mass of the textile product in kilograms. - **product** (string) - Required - The type of textile product (e.g., 'jean'). - **materials** (array) - Required - An array of material objects, each with: - **id** (string) - Required - The unique identifier for the material. - **share** (number) - Required - The proportion of this material in the product (0 to 1). - **countrySpinning** (string) - Optional - The country where the material was spun. - **countryFabric** (string) - Optional - The country where the fabric was made. - **countryDyeing** (string) - Optional - The country where the fabric was dyed. - **countryMaking** (string) - Optional - The country where the product was manufactured. - **fabricProcess** (string) - Optional - The process used to create the fabric (e.g., 'weaving'). - **fading** (boolean) - Optional - Whether fading is considered. - **printing** (object) - Optional - Details about the printing process: - **kind** (string) - Required - The type of printing (e.g., 'pigment'). - **ratio** (number) - Required - The ratio of printing coverage. ### Request Example ```json { "mass": 0.45, "product": "jean", "materials": [ {"id": "62a4d6fb-3276-4ba5-93a3-889ecdbff84", "share": 0.98}, {"id": "4b6c8ebe-4d12-4cd7-8d94-6ad20d8bd471", "share": 0.02} ], "countrySpinning": "TR", "countryFabric": "TR", "countryDyeing": "TN", "countryMaking": "TN", "fabricProcess": "weaving", "fading": true, "printing": {"kind": "pigment", "ratio": 0.05} } ``` ### Response #### Success Response (200) - **impacts** (object) - Overall environmental impacts. - **impactsWithoutDurability** (object) - Impacts excluding durability factors. - **durability** (number) - A measure of the product's durability. - **daysOfWear** (number) - Estimated days of wear. - **useNbCycles** (number) - Number of use cycles. - **lifeCycle** (object) - Detailed impacts per lifecycle stage (material, spinning, fabric, ennobling, making, distribution, use, eol). - **transport** (object) - Impacts related to transportation. - **trimsImpacts** (object) - Impacts from trims (buttons, zippers, etc.). #### Response Example ```json { "impacts": {...}, "impactsWithoutDurability": {...}, "durability": 1.15, "daysOfWear": 365, "useNbCycles": 52, "lifeCycle": { "material": {"impacts": {...}, "mass": 0.52}, "spinning": {"impacts": {...}, "mass": 0.50}, "fabric": {"impacts": {...}, "mass": 0.48}, "ennobling": {"impacts": {...}}, "making": {"impacts": {...}, "mass": 0.45}, "distribution": {"impacts": {...}}, "use": {"impacts": {...}}, "eol": {"impacts": {...}} }, "transport": {...}, "trimsImpacts": {...} } ``` ``` -------------------------------- ### CLI Backend - User Management Source: https://context7.com/mtes-mct/ecobalyse/llms.txt Command-line interface commands for administering application users. ```APIDOC ## CLI Backend - Gestion des Utilisateurs Commandes en ligne pour administrer les utilisateurs de l'application. ### Create User #### Description Creates a simple user account. #### Command `uv run backend users create-user` #### Arguments - `--email` (string) - Required - The email address of the user. - `--first-name` (string) - Required - The first name of the user. - `--last-name` (string) - Required - The last name of the user. - `--organization` (string) - Required - The organization the user belongs to. - `--organization-type` (string) - Required - The type of the organization (e.g., "local_authority", "company"). #### Example ```bash uv run backend users create-user \ --email admin@exemple.fr \ --first-name Admin \ --last-name Ecobalyse \ --organization "Ecobalyse" \ --organization-type local_authority ``` ### Create Superuser #### Description Creates a superuser account. #### Command `uv run backend users create-user` #### Arguments - `--email` (string) - Required - The email address of the superuser. - `--first-name` (string) - Required - The first name of the superuser. - `--last-name` (string) - Required - The last name of the superuser. - `--superuser` (flag) - Required - Designates the user as a superuser. #### Example ```bash uv run backend users create-user \ --email superadmin@exemple.fr \ --first-name Super \ --last-name Admin \ --superuser ``` ### Create Multiple Users #### Description Creates multiple user accounts in a single command. #### Command `uv run backend users create-users` #### Arguments - `--users` (string) - Required - A comma-separated string of users in the format "email/firstName/lastName". - `--organization` (string) - Required - The organization the users belong to. - `--organization-type` (string) - Required - The type of the organization. #### Example ```bash uv run backend users create-users \ --users "user1@test.com/Prénom1/Nom1,user2@test.com/Prénom2/Nom2" \ --organization "MaStructure" \ --organization-type company ``` ``` -------------------------------- ### Backend API - Process Management Source: https://context7.com/mtes-mct/ecobalyse/llms.txt API for accessing Life Cycle Assessment (LCA) impact processes stored in the database. Allows listing all processes and retrieving specific processes with detailed impacts. Requires an authorization token for accessing detailed impacts. ```bash # Lister tous les processus curl -X GET "http://localhost:8002/api/processes" \ -H "Authorization: Bearer votre_token" # Récupérer un processus spécifique avec impacts détaillés curl -X GET "http://localhost:8002/api/processes/82aab465-3b46-52d2-9625-a68625a3f9fc" \ -H "Authorization: Bearer eco_api_xxxxx" ``` -------------------------------- ### POST /api/access/login/magic-link Source: https://context7.com/mtes-mct/ecobalyse/llms.txt Initiates user authentication via magic link sent to the provided email. ```APIDOC ## POST /api/access/login/magic-link ### Description Sends a magic link to the user's email for passwordless authentication. ### Method POST ### Endpoint http://localhost:8002/api/access/login/magic-link ### Request Body - **email** (string) - Required - User email address ### Response #### Success Response (200) - Returns 200 OK if email was sent successfully. ``` -------------------------------- ### Configure Express API Server with Elm Integration Source: https://context7.com/mtes-mct/ecobalyse/llms.txt Sets up an Express server with rate limiting and routes requests to an Elm-based engine. It handles incoming API requests by passing them to the Elm port system and returning the processed response. ```javascript const express = require("express"); const rateLimit = require("express-rate-limit"); const { Elm } = require("./server-app"); const app = express(); const api = express(); const rateLimitMaxRPM = parseInt(process.env.RATELIMIT_MAX_RPM, 10) || 5000; app.use(rateLimit({ windowMs: 60 * 1000, max: rateLimitMaxRPM, message: { error: `Rate limited to ${rateLimitMaxRPM}rpm` } })); const elmApp = Elm.Server.init(); elmApp.ports.output.subscribe(({ status, body, jsResponseHandler }) => { return jsResponseHandler({ status, body }); }); api.all(/(.*)/, bodyParser.json(), async (req, res) => { const token = extractTokenFromHeaders(req.headers); if (!token) { return res.status(401).send({ error: { authorization: "Un token est requis" } }); } const processes = await getProcesses(req.headers); elmApp.ports.input.send({ method: req.method, url: req.url, body: req.body, processes, jsResponseHandler: ({ status, body }) => { res.status(status).json(body); } }); }); app.use("/api", api); app.listen(8001, () => { console.log("Server running on port 8001"); }); ``` -------------------------------- ### Retrieve Textile Materials List Source: https://context7.com/mtes-mct/ecobalyse/llms.txt Retrieves all available textile materials with their respective UUIDs. This endpoint is essential for identifying materials used in product composition simulations. ```bash curl -X GET "https://ecobalyse.beta.gouv.fr/api/textile/materials" -H "Authorization: Bearer votre_token_api" ``` -------------------------------- ### Authentication and Usage Limits Source: https://github.com/mtes-mct/ecobalyse/blob/master/public/pages/api-faq.md Details on how to authenticate with the Ecobalyse API and information regarding usage quotas. ```APIDOC ## Authentication ### Description Authentication is required to use the Ecobalyse API. Users need to create or access their Ecobalyse account and generate an API token. To obtain detailed impact scores for simulations, users must accept the ecoinvent terms of use via their Ecobalyse account. ## Usage Quotas ### Description There is a maximum number of requests per minute per IP address, capped at 5000. This limit may be adjusted based on traffic and potential abuse to ensure optimal service quality. ``` -------------------------------- ### POST /api/textile/simulator Source: https://context7.com/mtes-mct/ecobalyse/llms.txt Simulates the environmental impact of a textile product with advanced parameters. ```APIDOC ## POST /api/textile/simulator ### Description Simulates the environmental impact of a textile product, allowing for detailed customization of materials, manufacturing processes, and logistics. ### Method POST ### Endpoint /api/textile/simulator ### Parameters #### Request Body - **mass** (number) - Required - The mass of the textile product in kilograms. - **product** (string) - Required - The type of textile product (e.g., 'tshirt', 'pull', 'jean'). - **materials** (array) - Required - An array of material objects, each with: - **id** (string) - Required - The unique identifier for the material. - **share** (number) - Required - The proportion of this material in the product (0 to 1). - **spinning** (string) - Optional - The spinning method used for the material. - **countrySpinning** (string) - Optional - The country where the material was spun. - **countryFabric** (string) - Optional - The country where the fabric was made. - **countryDyeing** (string) - Optional - The country where the fabric was dyed. - **countryMaking** (string) - Required - The country where the product was manufactured. - **fabricProcess** (string) - Optional - The process used to create the fabric (e.g., 'knitting-circular', 'weaving'). - **dyeingProcessType** (string) - Optional - The type of dyeing process. - **makingComplexity** (string) - Optional - The complexity of the manufacturing process. - **makingWaste** (number) - Optional - The waste generated during manufacturing. - **makingDeadStock** (number) - Optional - The dead stock generated during manufacturing. - **airTransportRatio** (number) - Optional - The proportion of air transport used. - **price** (number) - Optional - The price of the product. - **numberOfReferences** (number) - Optional - The number of references for the product. - **business** (string) - Optional - The business model. - **trims** (array) - Optional - An array of trim objects, each with: - **id** (string) - Required - The unique identifier for the trim. - **quantity** (number) - Required - The quantity of this trim used. ### Request Example ```json { "mass": 0.2, "product": "tshirt", "materials": [ { "id": "62a4d6fb-3276-4ba5-93a3-889ecd3bff84", "share": 0.7, "spinning": "ConventionalSpinning" }, { "id": "9dba0e95-0c35-4f8b-9267-62ddf47d4984", "share": 0.3, "spinning": "SyntheticSpinning" } ], "countrySpinning": "CN", "countryFabric": "CN", "countryDyeing": "CN", "countryMaking": "BD", "fabricProcess": "knitting-circular", "dyeingProcessType": "discontinuous", "makingComplexity": "medium", "makingWaste": 0.15, "makingDeadStock": 0.05, "airTransportRatio": 0.2, "price": 15, "numberOfReferences": 5000, "business": "large-business-without-services" } ``` ### Response #### Success Response (200) - **impacts** (object) - Contains various environmental impact metrics. - **webUrl** (string) - A URL to view the simulation results online. #### Response Example ```json { "impacts": { "cch": 10.5, "ecs": 50.2, "wtu": 25.1 }, "webUrl": "https://ecobalyse.beta.gouv.fr/#/textile/simulator?parameters..." } ``` ``` -------------------------------- ### Backend API - Component Management Source: https://context7.com/mtes-mct/ecobalyse/llms.txt CRUD API for managing reusable components (accessories, base materials) in the back office. ```APIDOC ## Backend API - Gestion des Composants API CRUD pour gérer les composants réutilisables (accessoires, matériaux de base) dans le back-office. ### GET /api/components #### Description Lists all available components. This is a public endpoint. #### Method GET #### Endpoint /api/components #### Response ##### Success Response (200) - **id** (string) - Unique identifier of the component. - **name** (string) - Name of the component. - **scope** (string) - Scope of the component (e.g., "textile"). - **published** (boolean) - Indicates if the component is published. ##### Response Example ```json [ { "id": "uuid-composant", "name": "Bouton métal 15mm", "scope": "textile", "published": true } ] ``` ### GET /api/components/{id} #### Description Retrieves a specific component by its ID. #### Method GET #### Endpoint /api/components/{id} #### Parameters ##### Path Parameters - **id** (string) - Required - The unique identifier of the component to retrieve. #### Response ##### Success Response (200) (Details similar to the list response, for a single component) ### POST /api/components #### Description Creates a new component. This endpoint is admin-only. #### Method POST #### Endpoint /api/components #### Parameters ##### Request Body - **name** (string) - Required - The name of the new component. - **scope** (string) - Required - The scope of the component. - **elements** (array) - Optional - List of elements associated with the component. - **published** (boolean) - Optional - Indicates if the component should be published. #### Request Example ```json { "name": "Nouveau composant", "scope": "object", "elements": [...], "published": false } ``` #### Response ##### Success Response (200) (Details of the created component) ### PATCH /api/components/{id} #### Description Updates an existing component. This endpoint is admin-only. #### Method PATCH #### Endpoint /api/components/{id} #### Parameters ##### Path Parameters - **id** (string) - Required - The unique identifier of the component to update. ##### Request Body - **published** (boolean) - Optional - The new publication status of the component. #### Request Example ```json {"published": true} ``` #### Response ##### Success Response (200) (Details of the updated component) ### DELETE /api/components/{id} #### Description Deletes a component. This endpoint is admin-only. #### Method DELETE #### Endpoint /api/components/{id} #### Parameters ##### Path Parameters - **id** (string) - Required - The unique identifier of the component to delete. #### Response ##### Success Response (200) (Confirmation of deletion) ``` -------------------------------- ### Simulation d'Impacts Textiles avec Data.Textile.Simulator Source: https://context7.com/mtes-mct/ecobalyse/llms.txt Implémente le calcul des impacts textiles sur l'ensemble du cycle de vie. Prend en entrée une requête textile détaillée et retourne une simulation complète incluant les impacts par étape, la durabilité et les jours d'usage. ```Elm -- Module: Data.Textile.Simulator -- Calcul des impacts d'un produit textile import Data.Textile.Simulator as Simulator import Data.Textile.Query as Query import Static.Db exposing (Db) -- Structure de la requête textile type alias TextileQuery = { mass : Float -- Masse en kg , product : String -- "tshirt", "pull", "jean" , materials : List MaterialQuery , countrySpinning : Maybe String , countryFabric : Maybe String , countryDyeing : Maybe String , countryMaking : Maybe String , fabricProcess : String , disabledStages : List Label } -- Calcul des impacts compute : Db -> Component.Config -> Query -> Result String Simulator compute db componentConfig query = -- Initialise le simulateur avec les paramètres init db componentConfig query -- Calcule les déchets à chaque étape (de la fin vers le début) |> computeMakingStageWaste |> computeFabricStageWaste |> computeSpinningStageWaste |> computeMaterialStageWaste -- Calcule les impacts par étape |> computeMaterialImpacts |> computeSpinningImpacts |> computeFabricImpacts |> computeEnnoblingImpacts |> computeMakingImpacts |> computeDistributionImpacts |> computeUseImpacts |> computeEndOfLifeImpacts -- Applique la durabilité et les compléments |> computeDurability |> computeComplements -- Résultat de simulation type alias Simulator = { impacts : Impacts -- Impacts finaux avec durabilité , lifeCycle : LifeCycle -- Détail par étape , durability : HolisticDurability , daysOfWear : Duration , transport : Transport , trimsImpacts : Impacts } ``` -------------------------------- ### Generate Backend Secret Key Source: https://github.com/mtes-mct/ecobalyse/blob/master/README.md Command to generate a secure 32-byte hexadecimal string for the backend SECRET_KEY environment variable. ```bash openssl rand -hex 32 ``` -------------------------------- ### API Versioning and Stability Source: https://github.com/mtes-mct/ecobalyse/blob/master/public/pages/api-faq.md Information regarding the versioning strategy of the Ecobalyse API and the stability of different endpoints. ```APIDOC ## API Versioning ### Description The Ecobalyse API is not versioned in the traditional sense, meaning stability is not guaranteed with each update to the environmental cost calculation method. When a method is ready for deployment or large-scale testing, it is hosted on a dedicated URL to ensure interface compatibility and stability. ### Stable API Endpoints For access to the stable and regulatory textile API, use the following URL structure: `https://ecobalyse.beta.gouv.fr/versions/v7.0.0/` While direct requests to the main Ecobalyse API are possible, the persistence of its parameters and interface is not guaranteed. ### Response Format Stability The response format of an API call to a specific version may change over time as Ecobalyse evolves its environmental cost calculation method. Parameters might be added, removed, or modified. However, methods undergoing final testing or ready for large-scale testing are hosted on subdomains with a stable API response format. ```