Compare commits
56 Commits
fb8e3c8ef6
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| fcf938ee6f | |||
| 6e4f19a965 | |||
| 3755f4c414 | |||
| e7a18cd339 | |||
| f9b83a166d | |||
| 09e6d07c2d | |||
| f9e370afe2 | |||
| 58c78bbbbd | |||
| dc35995e64 | |||
| 3d9b807261 | |||
| f1d60e2109 | |||
| f7226604e2 | |||
| 4c1dd72659 | |||
| 532dcb83c1 | |||
| e43e9c40ad | |||
| 60e2f95637 | |||
| 8adc817428 | |||
| 5fb6f3303b | |||
| 6dbf5a00c4 | |||
| 775b09ebeb | |||
| 49b1a3b363 | |||
| 571019d34b | |||
| 3c0335ae7c | |||
| fdac954cea | |||
| e315160975 | |||
| 91f67f7dfc | |||
| d03dc94ad1 | |||
| 7c59944646 | |||
| 3367129d37 | |||
| 217e0b8dc0 | |||
| dbc8c2a2a2 | |||
| 93f52f1ae1 | |||
| b9919828e4 | |||
| ce76a29038 | |||
| eb0f921464 | |||
| cbabe13162 | |||
| 538ec2419d | |||
| 19fda276b0 | |||
| 1df2d8276c | |||
| 2fd101565e | |||
| 021730b90b | |||
| 2f9b12250f | |||
| 89d6651af2 | |||
| 118e6431da | |||
| 477fcb69c4 | |||
| 40de46588e | |||
| 2deafd219b | |||
| c41cdad90d | |||
| e01afb9a10 | |||
| 5fd349dee2 | |||
| 490be6a89b | |||
| ff237332e1 | |||
| c7362a553b | |||
| eb699666d9 | |||
| 1a8e37bd36 | |||
| 8ebb4d06e5 |
8
.dockerignore
Normal file
8
.dockerignore
Normal file
@@ -0,0 +1,8 @@
|
||||
.git
|
||||
.gitignore
|
||||
.DS_Store
|
||||
.vscode
|
||||
|
||||
backend/target
|
||||
frontend/dist
|
||||
frontend/node_modules
|
||||
1
.gitignore
vendored
1
.gitignore
vendored
@@ -2,3 +2,4 @@ backend/target/
|
||||
frontend/node_modules/
|
||||
frontend/dist/
|
||||
.DS_Store
|
||||
.env
|
||||
|
||||
38
Dockerfile
Normal file
38
Dockerfile
Normal file
@@ -0,0 +1,38 @@
|
||||
FROM node:20-alpine AS frontend-build
|
||||
WORKDIR /build/frontend
|
||||
|
||||
ARG VITE_API_URL=/api
|
||||
ENV VITE_API_URL=${VITE_API_URL}
|
||||
|
||||
COPY backend/pom.xml /build/backend/pom.xml
|
||||
COPY frontend/package*.json ./
|
||||
RUN npm ci
|
||||
|
||||
COPY frontend/ ./
|
||||
RUN npm run build
|
||||
|
||||
|
||||
FROM maven:3.9.11-eclipse-temurin-21 AS backend-build
|
||||
WORKDIR /build/backend
|
||||
|
||||
COPY backend/pom.xml ./
|
||||
RUN mvn -B -q -DskipTests dependency:go-offline
|
||||
|
||||
COPY backend/ ./
|
||||
COPY --from=frontend-build /build/frontend/dist ./src/main/resources/static
|
||||
RUN mvn -B -q -DskipTests package \
|
||||
&& cp "$(find target -maxdepth 1 -type f -name '*.jar' ! -name '*.original' | head -n 1)" /build/backend/app.jar
|
||||
|
||||
|
||||
FROM eclipse-temurin:21-jre-alpine AS runtime
|
||||
WORKDIR /app
|
||||
|
||||
RUN addgroup -S spring && adduser -S spring -G spring
|
||||
|
||||
COPY --from=backend-build /build/backend/app.jar /app/app.jar
|
||||
|
||||
USER spring:spring
|
||||
|
||||
EXPOSE 8090
|
||||
|
||||
ENTRYPOINT ["java", "-jar", "/app/app.jar"]
|
||||
47
README.md
47
README.md
@@ -10,18 +10,26 @@ Therapieempfehlungen sowie Verwaltungs- und Portalaufgaben.
|
||||
|
||||
## Konfiguration
|
||||
|
||||
MongoDB ist bereits im Backend vorkonfiguriert:
|
||||
Die Anwendung liest Konfigurationswerte aus einer `.env` im Projektverzeichnis
|
||||
oder aus Umgebungsvariablen.
|
||||
|
||||
- `mongodb://192.168.180.25:27017/muh`
|
||||
Die lokale `.env` ist in `.gitignore` eingetragen und sollte nicht mit echten Zugangsdaten committed werden.
|
||||
|
||||
MongoDB:
|
||||
|
||||
- `MUH_MONGODB_URL`
|
||||
- `MUH_MONGODB_USERNAME`
|
||||
- `MUH_MONGODB_PASSWORD`
|
||||
|
||||
Optional fuer echten Mailversand im Portal:
|
||||
|
||||
- `MUH_MAIL_ENABLED=true`
|
||||
- `MUH_MAIL_FROM=...`
|
||||
- `MUH_MAIL_HOST=...`
|
||||
- `MUH_MAIL_PORT=587`
|
||||
- `MUH_MAIL_USERNAME=...`
|
||||
- `MUH_MAIL_PASSWORD=...`
|
||||
- `MUH_MAIL_FROM=...`
|
||||
- `MUH_MAIL_PROTOCOL=smtp`
|
||||
- `MUH_MAIL_AUTH=true`
|
||||
- `MUH_MAIL_STARTTLS=true`
|
||||
|
||||
@@ -52,13 +60,34 @@ Frontend-URL:
|
||||
|
||||
Optional kann die API-URL im Frontend ueber `VITE_API_URL` gesetzt werden.
|
||||
|
||||
## Docker Deployment
|
||||
|
||||
Produktions-Image bauen:
|
||||
|
||||
```bash
|
||||
docker build -t muh-app .
|
||||
```
|
||||
|
||||
Container starten:
|
||||
|
||||
```bash
|
||||
docker run --rm --env-file .env -p 8090:8090 muh-app
|
||||
```
|
||||
|
||||
Die Anwendung ist danach unter `http://localhost:8090` erreichbar.
|
||||
|
||||
Hinweis:
|
||||
|
||||
- Das Dockerfile baut das React-Frontend und das Spring-Boot-Backend in einem Image.
|
||||
- Das Frontend wird im Container direkt ueber Spring Boot ausgeliefert.
|
||||
- API-Aufrufe laufen in Produktion relativ ueber `/api`.
|
||||
|
||||
## Anmeldung
|
||||
|
||||
Es gibt jetzt drei Varianten:
|
||||
Es gibt jetzt zwei Varianten:
|
||||
|
||||
- Schnelllogin ueber Benutzerkuerzel
|
||||
- Login ueber E-Mail oder Benutzername plus Passwort
|
||||
- Registrierung eines neuen Kundenkontos ueber Firmenname, Adresse, E-Mail und Passwort
|
||||
- Registrierung eines neuen Kundenkontos ueber Firmenname, Strasse, Hausnummer, PLZ, Ort, E-Mail und Passwort
|
||||
|
||||
Vordefinierter Admin:
|
||||
|
||||
@@ -76,3 +105,9 @@ Kundenregistrierung:
|
||||
|
||||
- `cd backend && mvn test`
|
||||
- `cd frontend && npm run build`
|
||||
|
||||
## Docker
|
||||
docker build -t muh:0.9.1 .
|
||||
docker buildx build --platform linux/amd64 -t gitea.appcreation.de/sven/muh:0.8.0 --push .
|
||||
|
||||
docker run -d --name muh --network br0 --ip 192.168.180.26 --restart unless-stopped -e MUH_MONGODB_URL=mongodb://192.168.180.25:27017/muh -e MUH_TOKEN_SECRET=local-dev-muh-token-secret-2026-03-13 -e MUH_TOKEN_VALIDITY_HOURS=12 -e MUH_ALLOWED_ORIGINS=https://muh.appcreation.de gitea.appcreation.de/sven/muh:0.8.0
|
||||
@@ -12,12 +12,12 @@
|
||||
|
||||
<groupId>de.svencarstensen</groupId>
|
||||
<artifactId>muh-backend</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<version>0.9.4</version>
|
||||
<name>muh-backend</name>
|
||||
<description>MUH application backend</description>
|
||||
|
||||
<properties>
|
||||
<java.version>17</java.version>
|
||||
<java.version>21</java.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
@@ -37,6 +37,10 @@
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-mail</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-security</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.security</groupId>
|
||||
<artifactId>spring-security-crypto</artifactId>
|
||||
|
||||
@@ -18,7 +18,8 @@ public class CorsConfig {
|
||||
configuration.setAllowedOrigins(allowedOrigins);
|
||||
configuration.setAllowedHeaders(List.of("*"));
|
||||
configuration.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"));
|
||||
configuration.setAllowCredentials(false);
|
||||
configuration.setAllowCredentials(true);
|
||||
configuration.setExposedHeaders(List.of("Authorization"));
|
||||
|
||||
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
|
||||
source.registerCorsConfiguration("/api/**", configuration);
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
package de.svencarstensen.muh.config;
|
||||
|
||||
import com.mongodb.ConnectionString;
|
||||
import com.mongodb.MongoClientSettings;
|
||||
import com.mongodb.MongoCredential;
|
||||
import com.mongodb.client.MongoClient;
|
||||
import com.mongodb.client.MongoClients;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
@Configuration
|
||||
public class MongoConfig {
|
||||
|
||||
@Bean
|
||||
MongoClient mongoClient(
|
||||
@Value("${muh.mongodb.url}") String mongoUrl,
|
||||
@Value("${muh.mongodb.username:}") String username,
|
||||
@Value("${muh.mongodb.password:}") String password
|
||||
) {
|
||||
ConnectionString connectionString = new ConnectionString(mongoUrl);
|
||||
MongoClientSettings.Builder builder = MongoClientSettings.builder()
|
||||
.applyConnectionString(connectionString);
|
||||
|
||||
if (StringUtils.hasText(username)) {
|
||||
String authDatabase = connectionString.getDatabase() == null ? "admin" : connectionString.getDatabase();
|
||||
builder.credential(MongoCredential.createCredential(
|
||||
username.trim(),
|
||||
authDatabase,
|
||||
password == null ? new char[0] : password.toCharArray()
|
||||
));
|
||||
}
|
||||
|
||||
return MongoClients.create(builder.build());
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import java.time.LocalDateTime;
|
||||
@Document("antibiotics")
|
||||
public record AntibioticCatalogItem(
|
||||
@Id String id,
|
||||
String accountId,
|
||||
String businessKey,
|
||||
String code,
|
||||
String name,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package de.svencarstensen.muh.domain;
|
||||
|
||||
import org.springframework.data.annotation.Id;
|
||||
import org.springframework.data.mongodb.core.index.Indexed;
|
||||
import org.springframework.data.mongodb.core.mapping.Document;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
@@ -8,16 +9,32 @@ import java.time.LocalDateTime;
|
||||
@Document("users")
|
||||
public record AppUser(
|
||||
@Id String id,
|
||||
String code,
|
||||
String accountId,
|
||||
Boolean primaryUser,
|
||||
String displayName,
|
||||
String companyName,
|
||||
String address,
|
||||
String street,
|
||||
String houseNumber,
|
||||
String postalCode,
|
||||
String city,
|
||||
String email,
|
||||
String portalLogin,
|
||||
String phoneNumber,
|
||||
String accountHolder,
|
||||
String bankName,
|
||||
String iban,
|
||||
String bic,
|
||||
String passwordHash,
|
||||
boolean active,
|
||||
UserRole role,
|
||||
Long nextSampleNumber,
|
||||
@Indexed(unique = true) String customerNumber,
|
||||
LocalDateTime createdAt,
|
||||
LocalDateTime updatedAt
|
||||
) {
|
||||
public AppUser {
|
||||
if (nextSampleNumber == null) {
|
||||
nextSampleNumber = 100000L;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,9 +8,17 @@ import java.time.LocalDateTime;
|
||||
@Document("farmers")
|
||||
public record Farmer(
|
||||
@Id String id,
|
||||
String accountId,
|
||||
String businessKey,
|
||||
String name,
|
||||
String customerNumber,
|
||||
String companyName,
|
||||
String contactPerson,
|
||||
String street,
|
||||
String houseNumber,
|
||||
String postalCode,
|
||||
String city,
|
||||
String email,
|
||||
String phoneNumber,
|
||||
boolean active,
|
||||
String supersedesId,
|
||||
LocalDateTime createdAt,
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
package de.svencarstensen.muh.domain;
|
||||
|
||||
import org.springframework.data.annotation.Id;
|
||||
import org.springframework.data.mongodb.core.mapping.Document;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
@Document("invoiceTemplates")
|
||||
public record InvoiceTemplate(
|
||||
@Id String userId,
|
||||
List<InvoiceTemplateElement> elements,
|
||||
LocalDateTime createdAt,
|
||||
LocalDateTime updatedAt
|
||||
) {
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package de.svencarstensen.muh.domain;
|
||||
|
||||
public record InvoiceTemplateElement(
|
||||
String id,
|
||||
String paletteId,
|
||||
String kind,
|
||||
String label,
|
||||
String content,
|
||||
Integer x,
|
||||
Integer y,
|
||||
Integer width,
|
||||
Integer height,
|
||||
Integer fontSize,
|
||||
Integer fontWeight,
|
||||
String textAlign,
|
||||
String lineOrientation,
|
||||
String imageSrc,
|
||||
Integer imageNaturalWidth,
|
||||
Integer imageNaturalHeight
|
||||
) {
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import java.time.LocalDateTime;
|
||||
@Document("medications")
|
||||
public record MedicationCatalogItem(
|
||||
@Id String id,
|
||||
String accountId,
|
||||
String businessKey,
|
||||
String name,
|
||||
MedicationCategory category,
|
||||
|
||||
@@ -8,6 +8,7 @@ import java.time.LocalDateTime;
|
||||
@Document("pathogens")
|
||||
public record PathogenCatalogItem(
|
||||
@Id String id,
|
||||
String accountId,
|
||||
String businessKey,
|
||||
String code,
|
||||
String name,
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
package de.svencarstensen.muh.domain;
|
||||
|
||||
public record Pretreatment(
|
||||
String inUdderInjector,
|
||||
String systemicAntibiotics,
|
||||
String painMedication,
|
||||
String dryOffTreatment
|
||||
) {
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package de.svencarstensen.muh.domain;
|
||||
|
||||
import org.springframework.data.annotation.Id;
|
||||
import org.springframework.data.mongodb.core.mapping.Document;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
@Document("reportTemplates")
|
||||
public record ReportTemplate(
|
||||
@Id String userId,
|
||||
List<InvoiceTemplateElement> elements,
|
||||
LocalDateTime createdAt,
|
||||
LocalDateTime updatedAt
|
||||
) {
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package de.svencarstensen.muh.domain;
|
||||
import org.springframework.data.annotation.Id;
|
||||
import org.springframework.data.mongodb.core.mapping.Document;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
@@ -27,7 +28,12 @@ public record Sample(
|
||||
LocalDateTime createdAt,
|
||||
LocalDateTime updatedAt,
|
||||
LocalDateTime completedAt,
|
||||
String ownerAccountId,
|
||||
String createdByUserCode,
|
||||
String createdByDisplayName
|
||||
String createdByDisplayName,
|
||||
// Additional fields from Lua version
|
||||
Pretreatment pretreatment,
|
||||
LocalDate clinicalExamDate,
|
||||
String internalNote
|
||||
) {
|
||||
}
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
package de.svencarstensen.muh.domain;
|
||||
|
||||
import org.springframework.data.annotation.Id;
|
||||
import org.springframework.data.mongodb.core.mapping.Document;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Document("systemPricing")
|
||||
public record SystemPricing(
|
||||
@Id String id,
|
||||
Double monthlyPrice,
|
||||
LocalDateTime createdAt,
|
||||
LocalDateTime updatedAt
|
||||
) {
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package de.svencarstensen.muh.domain;
|
||||
|
||||
import org.springframework.data.annotation.Id;
|
||||
import org.springframework.data.mongodb.core.index.CompoundIndex;
|
||||
import org.springframework.data.mongodb.core.mapping.Document;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
@Document("templates")
|
||||
@CompoundIndex(name = "user_template_type_unique", def = "{'userId': 1, 'type': 1}", unique = true)
|
||||
public record Template(
|
||||
@Id String id,
|
||||
String userId,
|
||||
TemplateType type,
|
||||
List<InvoiceTemplateElement> elements,
|
||||
LocalDateTime createdAt,
|
||||
LocalDateTime updatedAt
|
||||
) {
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package de.svencarstensen.muh.domain;
|
||||
|
||||
public enum TemplateType {
|
||||
INVOICE,
|
||||
REPORT
|
||||
}
|
||||
@@ -16,6 +16,15 @@ public record TherapyRecommendation(
|
||||
List<String> dryAntibioticKeys,
|
||||
List<String> dryAntibioticNames,
|
||||
String farmerNote,
|
||||
String internalNote
|
||||
String internalNote,
|
||||
// Additional fields from Lua version
|
||||
String inUdderCount,
|
||||
String inUdderDuration,
|
||||
String systemicCount,
|
||||
String systemicDuration,
|
||||
String systemicDosage,
|
||||
String systemicLocation,
|
||||
Boolean startvacVaccination,
|
||||
Boolean noAntibioticTreatment
|
||||
) {
|
||||
}
|
||||
|
||||
@@ -7,4 +7,8 @@ import java.util.List;
|
||||
|
||||
public interface AntibioticCatalogRepository extends MongoRepository<AntibioticCatalogItem, String> {
|
||||
List<AntibioticCatalogItem> findByActiveTrueOrderByNameAsc();
|
||||
|
||||
List<AntibioticCatalogItem> findByAccountIdOrderByNameAsc(String accountId);
|
||||
|
||||
List<AntibioticCatalogItem> findByAccountIdAndActiveTrueOrderByNameAsc(String accountId);
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package de.svencarstensen.muh.repository;
|
||||
|
||||
import de.svencarstensen.muh.domain.AppUser;
|
||||
import org.springframework.data.mongodb.repository.MongoRepository;
|
||||
import org.springframework.data.mongodb.repository.Query;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
@@ -9,9 +10,12 @@ import java.util.Optional;
|
||||
public interface AppUserRepository extends MongoRepository<AppUser, String> {
|
||||
List<AppUser> findByActiveTrueOrderByDisplayNameAsc();
|
||||
|
||||
Optional<AppUser> findByCodeIgnoreCase(String code);
|
||||
List<AppUser> findByAccountIdOrderByDisplayNameAsc(String accountId);
|
||||
|
||||
Optional<AppUser> findByEmailIgnoreCase(String email);
|
||||
|
||||
Optional<AppUser> findByPortalLoginIgnoreCase(String portalLogin);
|
||||
Optional<AppUser> findByCustomerNumber(String customerNumber);
|
||||
|
||||
@Query(value = "{ 'customerNumber': { $exists: true, $ne: null } }", sort = "{ 'customerNumber': -1 }")
|
||||
List<AppUser> findTopByCustomerNumberExistsOrderByCustomerNumberDesc();
|
||||
}
|
||||
|
||||
@@ -6,7 +6,11 @@ import org.springframework.data.mongodb.repository.MongoRepository;
|
||||
import java.util.List;
|
||||
|
||||
public interface FarmerRepository extends MongoRepository<Farmer, String> {
|
||||
List<Farmer> findByActiveTrueOrderByNameAsc();
|
||||
List<Farmer> findByActiveTrueOrderByCompanyNameAsc();
|
||||
|
||||
List<Farmer> findByNameContainingIgnoreCaseOrderByNameAsc(String name);
|
||||
List<Farmer> findByAccountIdOrderByCompanyNameAsc(String accountId);
|
||||
|
||||
List<Farmer> findByAccountIdAndActiveTrueOrderByCompanyNameAsc(String accountId);
|
||||
|
||||
List<Farmer> findByCompanyNameContainingIgnoreCaseOrderByCompanyNameAsc(String companyName);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
package de.svencarstensen.muh.repository;
|
||||
|
||||
import de.svencarstensen.muh.domain.InvoiceTemplate;
|
||||
import org.springframework.data.mongodb.repository.MongoRepository;
|
||||
|
||||
public interface InvoiceTemplateRepository extends MongoRepository<InvoiceTemplate, String> {
|
||||
}
|
||||
@@ -7,4 +7,8 @@ import java.util.List;
|
||||
|
||||
public interface MedicationCatalogRepository extends MongoRepository<MedicationCatalogItem, String> {
|
||||
List<MedicationCatalogItem> findByActiveTrueOrderByNameAsc();
|
||||
|
||||
List<MedicationCatalogItem> findByAccountIdOrderByNameAsc(String accountId);
|
||||
|
||||
List<MedicationCatalogItem> findByAccountIdAndActiveTrueOrderByNameAsc(String accountId);
|
||||
}
|
||||
|
||||
@@ -7,4 +7,8 @@ import java.util.List;
|
||||
|
||||
public interface PathogenCatalogRepository extends MongoRepository<PathogenCatalogItem, String> {
|
||||
List<PathogenCatalogItem> findByActiveTrueOrderByNameAsc();
|
||||
|
||||
List<PathogenCatalogItem> findByAccountIdOrderByNameAsc(String accountId);
|
||||
|
||||
List<PathogenCatalogItem> findByAccountIdAndActiveTrueOrderByNameAsc(String accountId);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
package de.svencarstensen.muh.repository;
|
||||
|
||||
import de.svencarstensen.muh.domain.ReportTemplate;
|
||||
import org.springframework.data.mongodb.repository.MongoRepository;
|
||||
|
||||
public interface ReportTemplateRepository extends MongoRepository<ReportTemplate, String> {
|
||||
}
|
||||
@@ -12,10 +12,14 @@ public interface SampleRepository extends MongoRepository<Sample, String> {
|
||||
|
||||
Optional<Sample> findTopByOrderBySampleNumberDesc();
|
||||
|
||||
Optional<Sample> findTopByOwnerAccountIdOrderBySampleNumberDesc(String ownerAccountId);
|
||||
|
||||
List<Sample> findTop12ByOrderByUpdatedAtDesc();
|
||||
|
||||
List<Sample> findByFarmerBusinessKeyOrderByCreatedAtDesc(String farmerBusinessKey);
|
||||
|
||||
List<Sample> findByCreatedAtBetweenOrderByCreatedAtDesc(LocalDateTime start, LocalDateTime end);
|
||||
|
||||
List<Sample> findByCompletedAtBetweenOrderByCompletedAtDesc(LocalDateTime start, LocalDateTime end);
|
||||
|
||||
List<Sample> findByCompletedAtNotNullOrderByCompletedAtDesc();
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
package de.svencarstensen.muh.repository;
|
||||
|
||||
import de.svencarstensen.muh.domain.SystemPricing;
|
||||
import org.springframework.data.mongodb.repository.MongoRepository;
|
||||
|
||||
public interface SystemPricingRepository extends MongoRepository<SystemPricing, String> {
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package de.svencarstensen.muh.repository;
|
||||
|
||||
import de.svencarstensen.muh.domain.Template;
|
||||
import de.svencarstensen.muh.domain.TemplateType;
|
||||
import org.springframework.data.mongodb.repository.MongoRepository;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
public interface TemplateRepository extends MongoRepository<Template, String> {
|
||||
|
||||
Optional<Template> findByUserIdAndType(String userId, TemplateType type);
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package de.svencarstensen.muh.security;
|
||||
|
||||
import de.svencarstensen.muh.domain.AppUser;
|
||||
import de.svencarstensen.muh.domain.UserRole;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.GeneralSecurityException;
|
||||
import java.time.Instant;
|
||||
import java.util.Base64;
|
||||
|
||||
@Service
|
||||
public class AuthTokenService {
|
||||
|
||||
private final byte[] secret;
|
||||
private final long validitySeconds;
|
||||
|
||||
public AuthTokenService(
|
||||
@Value("${muh.security.token-secret}") String secret,
|
||||
@Value("${muh.security.token-validity-hours:12}") long validityHours
|
||||
) {
|
||||
if (secret == null || secret.isBlank()) {
|
||||
throw new IllegalStateException("MUH_TOKEN_SECRET muss gesetzt sein");
|
||||
}
|
||||
this.secret = secret.getBytes(StandardCharsets.UTF_8);
|
||||
this.validitySeconds = Math.max(1, validityHours) * 3600L;
|
||||
}
|
||||
|
||||
public String createToken(AppUser user) {
|
||||
long expiresAt = Instant.now().plusSeconds(validitySeconds).getEpochSecond();
|
||||
String payload = user.id() + "|" + user.role().name() + "|" + expiresAt;
|
||||
return encode(payload) + "." + sign(payload);
|
||||
}
|
||||
|
||||
public AuthenticatedUser parseToken(String token) {
|
||||
String[] parts = token.split("\\.");
|
||||
if (parts.length != 2) {
|
||||
throw new IllegalArgumentException("Token-Format ungueltig");
|
||||
}
|
||||
|
||||
String payload = decode(parts[0]);
|
||||
String expectedSignature = sign(payload);
|
||||
if (!expectedSignature.equals(parts[1])) {
|
||||
throw new IllegalArgumentException("Token-Signatur ungueltig");
|
||||
}
|
||||
|
||||
String[] payloadParts = payload.split("\\|");
|
||||
if (payloadParts.length != 3) {
|
||||
throw new IllegalArgumentException("Token-Inhalt ungueltig");
|
||||
}
|
||||
|
||||
long expiresAt = Long.parseLong(payloadParts[2]);
|
||||
if (Instant.now().getEpochSecond() > expiresAt) {
|
||||
throw new IllegalArgumentException("Token abgelaufen");
|
||||
}
|
||||
|
||||
return new AuthenticatedUser(payloadParts[0], "", UserRole.valueOf(payloadParts[1]));
|
||||
}
|
||||
|
||||
private String sign(String payload) {
|
||||
try {
|
||||
Mac mac = Mac.getInstance("HmacSHA256");
|
||||
mac.init(new SecretKeySpec(secret, "HmacSHA256"));
|
||||
return encode(mac.doFinal(payload.getBytes(StandardCharsets.UTF_8)));
|
||||
} catch (GeneralSecurityException exception) {
|
||||
throw new IllegalStateException("Token-Signatur konnte nicht erzeugt werden", exception);
|
||||
}
|
||||
}
|
||||
|
||||
private String encode(byte[] value) {
|
||||
return Base64.getUrlEncoder().withoutPadding().encodeToString(value);
|
||||
}
|
||||
|
||||
private String encode(String value) {
|
||||
return encode(value.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
private String decode(String value) {
|
||||
return new String(Base64.getUrlDecoder().decode(value), StandardCharsets.UTF_8);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package de.svencarstensen.muh.security;
|
||||
|
||||
import de.svencarstensen.muh.domain.UserRole;
|
||||
|
||||
public record AuthenticatedUser(String id, String displayName, UserRole role) {
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package de.svencarstensen.muh.security;
|
||||
|
||||
import de.svencarstensen.muh.domain.AppUser;
|
||||
import de.svencarstensen.muh.domain.UserRole;
|
||||
import de.svencarstensen.muh.repository.AppUserRepository;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.lang.NonNull;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
@Service
|
||||
public class AuthorizationService {
|
||||
|
||||
private final AppUserRepository appUserRepository;
|
||||
|
||||
public AuthorizationService(AppUserRepository appUserRepository) {
|
||||
this.appUserRepository = appUserRepository;
|
||||
}
|
||||
|
||||
public AppUser requireActiveUser(String actorId, String message) {
|
||||
return appUserRepository.findById(requireText(actorId, message))
|
||||
.filter(AppUser::active)
|
||||
.orElseThrow(() -> new ResponseStatusException(HttpStatus.FORBIDDEN, message));
|
||||
}
|
||||
|
||||
public void requireAdmin(String actorId, String message) {
|
||||
AppUser actor = requireActiveUser(actorId, message);
|
||||
if (!isAdmin(actor)) {
|
||||
throw new ResponseStatusException(HttpStatus.FORBIDDEN, message);
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isAdmin(AppUser user) {
|
||||
return user.role() == UserRole.ADMIN;
|
||||
}
|
||||
|
||||
public String accountId(AppUser user) {
|
||||
if (user.accountId() == null || user.accountId().isBlank()) {
|
||||
if (user.id() == null || user.id().isBlank()) {
|
||||
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "Benutzerkonto ungueltig");
|
||||
}
|
||||
return user.id().trim();
|
||||
}
|
||||
return user.accountId().trim();
|
||||
}
|
||||
|
||||
private @NonNull String requireText(String value, String message) {
|
||||
if (value == null || value.isBlank()) {
|
||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, message);
|
||||
}
|
||||
String sanitized = Objects.requireNonNull(value).trim();
|
||||
return Objects.requireNonNull(sanitized);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package de.svencarstensen.muh.security;
|
||||
|
||||
import de.svencarstensen.muh.domain.AppUser;
|
||||
import de.svencarstensen.muh.repository.AppUserRepository;
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.lang.NonNull;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
@Component
|
||||
public class BearerTokenAuthenticationFilter extends OncePerRequestFilter {
|
||||
|
||||
private final AuthTokenService authTokenService;
|
||||
private final AppUserRepository appUserRepository;
|
||||
|
||||
public BearerTokenAuthenticationFilter(AuthTokenService authTokenService, AppUserRepository appUserRepository) {
|
||||
this.authTokenService = authTokenService;
|
||||
this.appUserRepository = appUserRepository;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(
|
||||
@NonNull HttpServletRequest request,
|
||||
@NonNull HttpServletResponse response,
|
||||
@NonNull FilterChain filterChain
|
||||
)
|
||||
throws ServletException, IOException {
|
||||
String authorization = request.getHeader(HttpHeaders.AUTHORIZATION);
|
||||
if (authorization == null || !authorization.startsWith("Bearer ")) {
|
||||
filterChain.doFilter(request, response);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
AuthenticatedUser tokenUser = authTokenService.parseToken(authorization.substring(7));
|
||||
AppUser user = appUserRepository.findById(Objects.requireNonNull(tokenUser.id()))
|
||||
.filter(AppUser::active)
|
||||
.orElseThrow(() -> new IllegalArgumentException("Benutzer ungueltig"));
|
||||
|
||||
AuthenticatedUser principal = new AuthenticatedUser(user.id(), user.displayName(), user.role());
|
||||
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
|
||||
principal,
|
||||
null,
|
||||
List.of(new SimpleGrantedAuthority("ROLE_" + user.role().name()))
|
||||
);
|
||||
SecurityContextHolder.getContext().setAuthentication(authentication);
|
||||
} catch (RuntimeException exception) {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
|
||||
filterChain.doFilter(request, response);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package de.svencarstensen.muh.security;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.security.config.Customizer;
|
||||
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
|
||||
import org.springframework.security.config.http.SessionCreationPolicy;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
|
||||
|
||||
@Configuration
|
||||
@EnableMethodSecurity
|
||||
public class SecurityConfig {
|
||||
|
||||
@Bean
|
||||
SecurityFilterChain securityFilterChain(HttpSecurity http, BearerTokenAuthenticationFilter bearerTokenAuthenticationFilter)
|
||||
throws Exception {
|
||||
http
|
||||
.csrf(AbstractHttpConfigurer::disable)
|
||||
.httpBasic(AbstractHttpConfigurer::disable)
|
||||
.formLogin(AbstractHttpConfigurer::disable)
|
||||
.sessionManagement(configurer -> configurer.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||
.authorizeHttpRequests(authorize -> authorize
|
||||
.requestMatchers(HttpMethod.POST, "/api/session/password-login", "/api/session/register").permitAll()
|
||||
.requestMatchers("/api/catalog/**").hasRole("CUSTOMER")
|
||||
.requestMatchers("/api/admin/**").hasRole("ADMIN")
|
||||
.requestMatchers("/api/**").authenticated()
|
||||
.anyRequest().permitAll()
|
||||
)
|
||||
.addFilterBefore(bearerTokenAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
|
||||
.cors(Customizer.withDefaults());
|
||||
|
||||
return http.build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package de.svencarstensen.muh.security;
|
||||
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class SecuritySupport {
|
||||
|
||||
public AuthenticatedUser currentUser() {
|
||||
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||
if (authentication == null || !(authentication.getPrincipal() instanceof AuthenticatedUser principal)) {
|
||||
throw new IllegalStateException("Kein authentifizierter Benutzer vorhanden");
|
||||
}
|
||||
return principal;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package de.svencarstensen.muh.service;
|
||||
|
||||
import de.svencarstensen.muh.domain.AppUser;
|
||||
import de.svencarstensen.muh.domain.Sample;
|
||||
import de.svencarstensen.muh.domain.UserRole;
|
||||
import de.svencarstensen.muh.repository.AppUserRepository;
|
||||
import de.svencarstensen.muh.repository.SampleRepository;
|
||||
import de.svencarstensen.muh.web.dto.AdminStatistics;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
public class AdminStatisticsService {
|
||||
|
||||
private final AppUserRepository appUserRepository;
|
||||
private final SampleRepository sampleRepository;
|
||||
|
||||
public AdminStatisticsService(AppUserRepository appUserRepository, SampleRepository sampleRepository) {
|
||||
this.appUserRepository = appUserRepository;
|
||||
this.sampleRepository = sampleRepository;
|
||||
}
|
||||
|
||||
public AdminStatistics getStatistics() {
|
||||
// Alle Hauptnutzer (Tierärzte) laden - primaryUser=true und role=CUSTOMER
|
||||
List<AppUser> vets = appUserRepository.findAll().stream()
|
||||
.filter(u -> Boolean.TRUE.equals(u.primaryUser()))
|
||||
.filter(u -> u.role() == UserRole.CUSTOMER)
|
||||
.toList();
|
||||
|
||||
// Alle Proben laden
|
||||
List<Sample> allSamples = sampleRepository.findAll();
|
||||
|
||||
// Proben pro Tierarzt zählen (basierend auf ownerAccountId oder createdByUserCode)
|
||||
List<AdminStatistics.VetSampleStats> samplesPerVet = vets.stream()
|
||||
.map(vet -> {
|
||||
String vetId = vet.id();
|
||||
String accountId = vet.accountId();
|
||||
|
||||
long sampleCount = allSamples.stream()
|
||||
.filter(s -> {
|
||||
// Prüfe sowohl ownerAccountId als auch createdByUserCode
|
||||
String ownerId = s.ownerAccountId();
|
||||
String creatorId = s.createdByUserCode();
|
||||
|
||||
// Vergleiche mit vet.id() oder vet.accountId()
|
||||
return vetId.equals(ownerId) ||
|
||||
vetId.equals(creatorId) ||
|
||||
accountId != null && accountId.equals(ownerId) ||
|
||||
accountId != null && accountId.equals(creatorId);
|
||||
})
|
||||
.count();
|
||||
return new AdminStatistics.VetSampleStats(
|
||||
vet.id(),
|
||||
vet.displayName(),
|
||||
vet.companyName(),
|
||||
sampleCount
|
||||
);
|
||||
})
|
||||
.filter(s -> s.sampleCount() > 0)
|
||||
.sorted((a, b) -> Long.compare(b.sampleCount(), a.sampleCount()))
|
||||
.toList();
|
||||
|
||||
return new AdminStatistics(
|
||||
vets.size(),
|
||||
allSamples.size(),
|
||||
samplesPerVet
|
||||
);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,20 @@
|
||||
package de.svencarstensen.muh.service;
|
||||
|
||||
import org.springframework.boot.ApplicationArguments;
|
||||
import org.springframework.boot.ApplicationRunner;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class DefaultUserInitializer implements ApplicationRunner {
|
||||
|
||||
private final CatalogService catalogService;
|
||||
|
||||
public DefaultUserInitializer(CatalogService catalogService) {
|
||||
this.catalogService = catalogService;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run(ApplicationArguments args) {
|
||||
catalogService.ensureDefaultUsers();
|
||||
}
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
package de.svencarstensen.muh.service;
|
||||
|
||||
import de.svencarstensen.muh.domain.AntibioticCatalogItem;
|
||||
import de.svencarstensen.muh.domain.Farmer;
|
||||
import de.svencarstensen.muh.domain.MedicationCatalogItem;
|
||||
import de.svencarstensen.muh.domain.MedicationCategory;
|
||||
import de.svencarstensen.muh.domain.PathogenCatalogItem;
|
||||
import de.svencarstensen.muh.domain.PathogenKind;
|
||||
import de.svencarstensen.muh.repository.AntibioticCatalogRepository;
|
||||
import de.svencarstensen.muh.repository.FarmerRepository;
|
||||
import de.svencarstensen.muh.repository.MedicationCatalogRepository;
|
||||
import de.svencarstensen.muh.repository.PathogenCatalogRepository;
|
||||
import org.springframework.boot.ApplicationArguments;
|
||||
import org.springframework.boot.ApplicationRunner;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.UUID;
|
||||
|
||||
@Component
|
||||
public class DemoDataInitializer implements ApplicationRunner {
|
||||
|
||||
private final FarmerRepository farmerRepository;
|
||||
private final MedicationCatalogRepository medicationRepository;
|
||||
private final PathogenCatalogRepository pathogenRepository;
|
||||
private final AntibioticCatalogRepository antibioticRepository;
|
||||
private final CatalogService catalogService;
|
||||
|
||||
public DemoDataInitializer(
|
||||
FarmerRepository farmerRepository,
|
||||
MedicationCatalogRepository medicationRepository,
|
||||
PathogenCatalogRepository pathogenRepository,
|
||||
AntibioticCatalogRepository antibioticRepository,
|
||||
CatalogService catalogService
|
||||
) {
|
||||
this.farmerRepository = farmerRepository;
|
||||
this.medicationRepository = medicationRepository;
|
||||
this.pathogenRepository = pathogenRepository;
|
||||
this.antibioticRepository = antibioticRepository;
|
||||
this.catalogService = catalogService;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run(ApplicationArguments args) {
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
|
||||
if (farmerRepository.count() == 0) {
|
||||
farmerRepository.save(new Farmer(null, UUID.randomUUID().toString(), "Hof Hansen", "hansen@example.com", true, null, now, now));
|
||||
farmerRepository.save(new Farmer(null, UUID.randomUUID().toString(), "Agrar Lindenblick", "lindenblick@example.com", true, null, now, now));
|
||||
farmerRepository.save(new Farmer(null, UUID.randomUUID().toString(), "Gut Westerkamp", "westerkamp@example.com", true, null, now, now));
|
||||
}
|
||||
|
||||
if (medicationRepository.count() == 0) {
|
||||
medicationRepository.save(new MedicationCatalogItem(null, UUID.randomUUID().toString(), "Mastijet", MedicationCategory.IN_UDDER, true, null, now, now));
|
||||
medicationRepository.save(new MedicationCatalogItem(null, UUID.randomUUID().toString(), "Metacam", MedicationCategory.SYSTEMIC_PAIN, true, null, now, now));
|
||||
medicationRepository.save(new MedicationCatalogItem(null, UUID.randomUUID().toString(), "Cobactan", MedicationCategory.SYSTEMIC_ANTIBIOTIC, true, null, now, now));
|
||||
medicationRepository.save(new MedicationCatalogItem(null, UUID.randomUUID().toString(), "Orbeseal", MedicationCategory.DRY_SEALER, true, null, now, now));
|
||||
medicationRepository.save(new MedicationCatalogItem(null, UUID.randomUUID().toString(), "Nafpenzal", MedicationCategory.DRY_ANTIBIOTIC, true, null, now, now));
|
||||
}
|
||||
|
||||
if (pathogenRepository.count() == 0) {
|
||||
pathogenRepository.save(new PathogenCatalogItem(null, UUID.randomUUID().toString(), "SAU", "Staph. aureus", PathogenKind.BACTERIAL, true, null, now, now));
|
||||
pathogenRepository.save(new PathogenCatalogItem(null, UUID.randomUUID().toString(), "ECO", "E. coli", PathogenKind.BACTERIAL, true, null, now, now));
|
||||
pathogenRepository.save(new PathogenCatalogItem(null, UUID.randomUUID().toString(), "NG", "Kein Wachstum", PathogenKind.NO_GROWTH, true, null, now, now));
|
||||
pathogenRepository.save(new PathogenCatalogItem(null, UUID.randomUUID().toString(), "VER", "Verunreinigt", PathogenKind.CONTAMINATED, true, null, now, now));
|
||||
}
|
||||
|
||||
if (antibioticRepository.count() == 0) {
|
||||
antibioticRepository.save(new AntibioticCatalogItem(null, UUID.randomUUID().toString(), "PEN", "Penicillin", true, null, now, now));
|
||||
antibioticRepository.save(new AntibioticCatalogItem(null, UUID.randomUUID().toString(), "CEF", "Cefalexin", true, null, now, now));
|
||||
antibioticRepository.save(new AntibioticCatalogItem(null, UUID.randomUUID().toString(), "ENR", "Enrofloxacin", true, null, now, now));
|
||||
}
|
||||
|
||||
catalogService.ensureDefaultUsers();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
package de.svencarstensen.muh.service;
|
||||
|
||||
import de.svencarstensen.muh.domain.AppUser;
|
||||
import de.svencarstensen.muh.domain.InvoiceTemplate;
|
||||
import de.svencarstensen.muh.domain.InvoiceTemplateElement;
|
||||
import de.svencarstensen.muh.domain.SystemPricing;
|
||||
import de.svencarstensen.muh.domain.Template;
|
||||
import de.svencarstensen.muh.domain.TemplateType;
|
||||
import de.svencarstensen.muh.repository.AppUserRepository;
|
||||
import de.svencarstensen.muh.repository.InvoiceTemplateRepository;
|
||||
import de.svencarstensen.muh.repository.TemplateRepository;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@Service
|
||||
public class InvoiceService {
|
||||
|
||||
private final AppUserRepository appUserRepository;
|
||||
private final TemplateRepository templateRepository;
|
||||
private final InvoiceTemplateRepository invoiceTemplateRepository;
|
||||
private final SystemPricingService pricingService;
|
||||
|
||||
public InvoiceService(
|
||||
AppUserRepository appUserRepository,
|
||||
TemplateRepository templateRepository,
|
||||
InvoiceTemplateRepository invoiceTemplateRepository,
|
||||
SystemPricingService pricingService
|
||||
) {
|
||||
this.appUserRepository = appUserRepository;
|
||||
this.templateRepository = templateRepository;
|
||||
this.invoiceTemplateRepository = invoiceTemplateRepository;
|
||||
this.pricingService = pricingService;
|
||||
}
|
||||
|
||||
public List<CustomerDto> listPrimaryCustomers() {
|
||||
return appUserRepository.findAll().stream()
|
||||
.filter(user -> Boolean.TRUE.equals(user.primaryUser()))
|
||||
.filter(user -> user.role() != de.svencarstensen.muh.domain.UserRole.ADMIN)
|
||||
.map(this::toCustomerDto)
|
||||
.sorted((a, b) -> a.displayName().compareToIgnoreCase(b.displayName()))
|
||||
.toList();
|
||||
}
|
||||
|
||||
public InvoiceData getInvoiceData(String actorId, String customerId) {
|
||||
AppUser customer = appUserRepository.findById(customerId != null ? customerId : "")
|
||||
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Kunde nicht gefunden"));
|
||||
|
||||
if (!Boolean.TRUE.equals(customer.primaryUser())) {
|
||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Nur Hauptbenutzer können Rechnungen erhalten");
|
||||
}
|
||||
|
||||
// Use the issuing admin's template for invoice generation
|
||||
List<TemplateElementDto> templateElements = getTemplateElements(actorId);
|
||||
|
||||
// Generate invoice number: R-YYYY-NNNN
|
||||
String invoiceNumber = generateInvoiceNumber();
|
||||
|
||||
// Calculate dates
|
||||
LocalDate invoiceDate = LocalDate.now();
|
||||
LocalDate dueDate = invoiceDate.plusDays(14);
|
||||
|
||||
// Get pricing
|
||||
double monthlyPrice = getMonthlyPrice();
|
||||
double vatRate = 0.19;
|
||||
double netAmount = monthlyPrice;
|
||||
double vatAmount = netAmount * vatRate;
|
||||
double grossAmount = netAmount + vatAmount;
|
||||
|
||||
return new InvoiceData(
|
||||
invoiceNumber,
|
||||
invoiceDate.format(DateTimeFormatter.ofPattern("dd.MM.yyyy")),
|
||||
dueDate.format(DateTimeFormatter.ofPattern("dd.MM.yyyy")),
|
||||
toCustomerDto(customer),
|
||||
templateElements,
|
||||
netAmount,
|
||||
vatAmount,
|
||||
grossAmount,
|
||||
monthlyPrice
|
||||
);
|
||||
}
|
||||
|
||||
private String generateInvoiceNumber() {
|
||||
// Format: R-YYYY-NNNN (starting from 1000)
|
||||
String year = String.valueOf(LocalDate.now().getYear());
|
||||
// For now, use a simple counter based on current time
|
||||
// In production, this should query the database for the last invoice number
|
||||
int sequence = (int) (System.currentTimeMillis() % 9000) + 1000;
|
||||
return "R-" + year + "-" + sequence;
|
||||
}
|
||||
|
||||
private double getMonthlyPrice() {
|
||||
try {
|
||||
var pricing = pricingService.getCurrentPricing();
|
||||
return pricing.map(SystemPricing::monthlyPrice).orElse(49.00);
|
||||
} catch (Exception e) {
|
||||
return 49.00; // Default price
|
||||
}
|
||||
}
|
||||
|
||||
private List<TemplateElementDto> getTemplateElements(String userId) {
|
||||
// Try to get user's template first
|
||||
Optional<Template> userTemplate = templateRepository.findByUserIdAndType(userId, TemplateType.INVOICE);
|
||||
if (userTemplate.isPresent()) {
|
||||
return mapTemplateElements(userTemplate.get().elements());
|
||||
}
|
||||
|
||||
// Fall back to legacy template
|
||||
Optional<InvoiceTemplate> legacyTemplate = invoiceTemplateRepository.findById(userId != null ? userId : "");
|
||||
if (legacyTemplate.isPresent()) {
|
||||
return mapTemplateElements(legacyTemplate.get().elements());
|
||||
}
|
||||
|
||||
// Return empty list - frontend will use default layout
|
||||
return List.of();
|
||||
}
|
||||
|
||||
private List<TemplateElementDto> mapTemplateElements(List<?> elements) {
|
||||
if (elements == null) {
|
||||
return List.of();
|
||||
}
|
||||
return elements.stream()
|
||||
.filter(InvoiceTemplateElement.class::isInstance)
|
||||
.map(InvoiceTemplateElement.class::cast)
|
||||
.map(element -> new TemplateElementDto(
|
||||
element.id(),
|
||||
element.paletteId(),
|
||||
element.kind(),
|
||||
element.label(),
|
||||
element.content(),
|
||||
element.x(),
|
||||
element.y(),
|
||||
element.width(),
|
||||
element.height(),
|
||||
element.fontSize(),
|
||||
element.fontWeight(),
|
||||
element.textAlign(),
|
||||
element.lineOrientation(),
|
||||
element.imageSrc(),
|
||||
element.imageNaturalWidth(),
|
||||
element.imageNaturalHeight()
|
||||
))
|
||||
.toList();
|
||||
}
|
||||
|
||||
private CustomerDto toCustomerDto(AppUser user) {
|
||||
return new CustomerDto(
|
||||
user.id(),
|
||||
user.displayName(),
|
||||
user.companyName(),
|
||||
user.street(),
|
||||
user.houseNumber(),
|
||||
user.postalCode(),
|
||||
user.city(),
|
||||
user.email(),
|
||||
user.phoneNumber(),
|
||||
user.accountHolder(),
|
||||
user.bankName(),
|
||||
user.iban(),
|
||||
user.bic(),
|
||||
user.customerNumber()
|
||||
);
|
||||
}
|
||||
|
||||
public record CustomerDto(
|
||||
String id,
|
||||
String displayName,
|
||||
String companyName,
|
||||
String street,
|
||||
String houseNumber,
|
||||
String postalCode,
|
||||
String city,
|
||||
String email,
|
||||
String phoneNumber,
|
||||
String accountHolder,
|
||||
String bankName,
|
||||
String iban,
|
||||
String bic,
|
||||
String customerNumber
|
||||
) {
|
||||
}
|
||||
|
||||
public record InvoiceData(
|
||||
String invoiceNumber,
|
||||
String invoiceDate,
|
||||
String dueDate,
|
||||
CustomerDto customer,
|
||||
List<TemplateElementDto> templateElements,
|
||||
double netAmount,
|
||||
double vatAmount,
|
||||
double grossAmount,
|
||||
double monthlyPrice
|
||||
) {
|
||||
}
|
||||
|
||||
public record TemplateElementDto(
|
||||
String id,
|
||||
String paletteId,
|
||||
String kind,
|
||||
String label,
|
||||
String content,
|
||||
Integer x,
|
||||
Integer y,
|
||||
Integer width,
|
||||
Integer height,
|
||||
Integer fontSize,
|
||||
Integer fontWeight,
|
||||
String textAlign,
|
||||
String lineOrientation,
|
||||
String imageSrc,
|
||||
Integer imageNaturalWidth,
|
||||
Integer imageNaturalHeight
|
||||
) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
package de.svencarstensen.muh.service;
|
||||
|
||||
import de.svencarstensen.muh.domain.AppUser;
|
||||
import de.svencarstensen.muh.domain.InvoiceTemplate;
|
||||
import de.svencarstensen.muh.domain.InvoiceTemplateElement;
|
||||
import de.svencarstensen.muh.domain.Template;
|
||||
import de.svencarstensen.muh.domain.TemplateType;
|
||||
import de.svencarstensen.muh.repository.AppUserRepository;
|
||||
import de.svencarstensen.muh.repository.InvoiceTemplateRepository;
|
||||
import de.svencarstensen.muh.repository.TemplateRepository;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.lang.NonNull;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Objects;
|
||||
|
||||
@Service
|
||||
public class InvoiceTemplateService {
|
||||
|
||||
private static final TemplateType TEMPLATE_TYPE = TemplateType.INVOICE;
|
||||
|
||||
private final AppUserRepository appUserRepository;
|
||||
private final TemplateRepository templateRepository;
|
||||
private final InvoiceTemplateRepository invoiceTemplateRepository;
|
||||
|
||||
public InvoiceTemplateService(
|
||||
AppUserRepository appUserRepository,
|
||||
TemplateRepository templateRepository,
|
||||
InvoiceTemplateRepository invoiceTemplateRepository
|
||||
) {
|
||||
this.appUserRepository = appUserRepository;
|
||||
this.templateRepository = templateRepository;
|
||||
this.invoiceTemplateRepository = invoiceTemplateRepository;
|
||||
}
|
||||
|
||||
public InvoiceTemplateResponse currentTemplate(String actorId) {
|
||||
String userId = requireActorId(actorId);
|
||||
requireActiveUser(userId);
|
||||
return templateRepository.findByUserIdAndType(userId, TEMPLATE_TYPE)
|
||||
.map(this::toResponse)
|
||||
.or(() -> invoiceTemplateRepository.findById(userId).map(this::toLegacyResponse))
|
||||
.orElseGet(() -> new InvoiceTemplateResponse(false, List.of(), null));
|
||||
}
|
||||
|
||||
public InvoiceTemplateResponse saveTemplate(String actorId, List<InvoiceTemplateElementPayload> payloadElements) {
|
||||
String userId = requireActorId(actorId);
|
||||
requireActiveUser(userId);
|
||||
Template existing = templateRepository.findByUserIdAndType(userId, TEMPLATE_TYPE).orElse(null);
|
||||
InvoiceTemplate legacyTemplate = existing == null
|
||||
? invoiceTemplateRepository.findById(userId).orElse(null)
|
||||
: null;
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
|
||||
Template saved = templateRepository.save(new Template(
|
||||
existing != null ? existing.id() : templateId(userId),
|
||||
userId,
|
||||
TEMPLATE_TYPE,
|
||||
sanitizeElements(payloadElements),
|
||||
existing != null ? existing.createdAt() : legacyTemplate != null ? legacyTemplate.createdAt() : now,
|
||||
now
|
||||
));
|
||||
return toResponse(saved);
|
||||
}
|
||||
|
||||
private AppUser requireActiveUser(@NonNull String actorId) {
|
||||
return appUserRepository.findById(actorId)
|
||||
.filter(AppUser::active)
|
||||
.orElseThrow(() -> new ResponseStatusException(HttpStatus.FORBIDDEN, "Nicht berechtigt"));
|
||||
}
|
||||
|
||||
private @NonNull String requireActorId(String actorId) {
|
||||
if (isBlank(actorId)) {
|
||||
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "Nicht berechtigt");
|
||||
}
|
||||
String sanitized = Objects.requireNonNull(actorId).trim();
|
||||
return Objects.requireNonNull(sanitized);
|
||||
}
|
||||
|
||||
private List<InvoiceTemplateElement> sanitizeElements(List<InvoiceTemplateElementPayload> payloadElements) {
|
||||
if (payloadElements == null || payloadElements.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
return payloadElements.stream()
|
||||
.map(this::sanitizeElement)
|
||||
.filter(Objects::nonNull)
|
||||
.toList();
|
||||
}
|
||||
|
||||
private InvoiceTemplateElement sanitizeElement(InvoiceTemplateElementPayload payload) {
|
||||
if (payload == null
|
||||
|| isBlank(payload.id())
|
||||
|| isBlank(payload.paletteId())
|
||||
|| isBlank(payload.kind())
|
||||
|| payload.x() == null
|
||||
|| payload.y() == null
|
||||
|| payload.width() == null
|
||||
|| payload.fontSize() == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return new InvoiceTemplateElement(
|
||||
payload.id().trim(),
|
||||
payload.paletteId().trim(),
|
||||
payload.kind().trim(),
|
||||
trimOrEmpty(payload.label()),
|
||||
nullToEmpty(payload.content()),
|
||||
payload.x(),
|
||||
payload.y(),
|
||||
payload.width(),
|
||||
payload.height(),
|
||||
payload.fontSize(),
|
||||
payload.fontWeight(),
|
||||
blankToNull(payload.textAlign()),
|
||||
blankToNull(payload.lineOrientation()),
|
||||
blankToNull(payload.imageSrc()),
|
||||
payload.imageNaturalWidth(),
|
||||
payload.imageNaturalHeight()
|
||||
);
|
||||
}
|
||||
|
||||
private InvoiceTemplateResponse toResponse(Template template) {
|
||||
return toResponse(template.elements(), template.updatedAt());
|
||||
}
|
||||
|
||||
private InvoiceTemplateResponse toLegacyResponse(InvoiceTemplate template) {
|
||||
return toResponse(template.elements(), template.updatedAt());
|
||||
}
|
||||
|
||||
private InvoiceTemplateElementPayload toPayload(InvoiceTemplateElement element) {
|
||||
return new InvoiceTemplateElementPayload(
|
||||
element.id(),
|
||||
element.paletteId(),
|
||||
element.kind(),
|
||||
element.label(),
|
||||
element.content(),
|
||||
element.x(),
|
||||
element.y(),
|
||||
element.width(),
|
||||
element.height(),
|
||||
element.fontSize(),
|
||||
element.fontWeight(),
|
||||
element.textAlign(),
|
||||
element.lineOrientation(),
|
||||
element.imageSrc(),
|
||||
element.imageNaturalWidth(),
|
||||
element.imageNaturalHeight()
|
||||
);
|
||||
}
|
||||
|
||||
private boolean isBlank(String value) {
|
||||
return value == null || value.isBlank();
|
||||
}
|
||||
|
||||
private String blankToNull(String value) {
|
||||
return isBlank(value) ? null : value.trim();
|
||||
}
|
||||
|
||||
private String trimOrEmpty(String value) {
|
||||
return value == null ? "" : value.trim();
|
||||
}
|
||||
|
||||
private String nullToEmpty(String value) {
|
||||
return value == null ? "" : value;
|
||||
}
|
||||
|
||||
private InvoiceTemplateResponse toResponse(List<InvoiceTemplateElement> elements, LocalDateTime updatedAt) {
|
||||
List<InvoiceTemplateElementPayload> payloads = elements == null
|
||||
? List.of()
|
||||
: elements.stream().map(this::toPayload).toList();
|
||||
return new InvoiceTemplateResponse(true, payloads, updatedAt);
|
||||
}
|
||||
|
||||
private String templateId(String userId) {
|
||||
return userId + ":" + TEMPLATE_TYPE.name().toLowerCase(Locale.ROOT);
|
||||
}
|
||||
|
||||
public record InvoiceTemplateElementPayload(
|
||||
String id,
|
||||
String paletteId,
|
||||
String kind,
|
||||
String label,
|
||||
String content,
|
||||
Integer x,
|
||||
Integer y,
|
||||
Integer width,
|
||||
Integer height,
|
||||
Integer fontSize,
|
||||
Integer fontWeight,
|
||||
String textAlign,
|
||||
String lineOrientation,
|
||||
String imageSrc,
|
||||
Integer imageNaturalWidth,
|
||||
Integer imageNaturalHeight
|
||||
) {
|
||||
}
|
||||
|
||||
public record InvoiceTemplateResponse(
|
||||
boolean stored,
|
||||
List<InvoiceTemplateElementPayload> elements,
|
||||
LocalDateTime updatedAt
|
||||
) {
|
||||
}
|
||||
}
|
||||
@@ -21,27 +21,35 @@ public class PortalService {
|
||||
this.catalogService = catalogService;
|
||||
}
|
||||
|
||||
public PortalSnapshot snapshot(String farmerBusinessKey, String farmerQuery, String cowQuery, Long sampleNumber, LocalDate date) {
|
||||
List<CatalogService.FarmerOption> matchingFarmers = catalogService.activeCatalogSummary().farmers().stream()
|
||||
.filter(farmer -> farmerQuery == null || farmerQuery.isBlank() || farmer.name().toLowerCase(Locale.ROOT).contains(farmerQuery.toLowerCase(Locale.ROOT)))
|
||||
public PortalSnapshot snapshot(
|
||||
boolean includeUsers,
|
||||
String actorId,
|
||||
String farmerBusinessKey,
|
||||
String farmerQuery,
|
||||
String cowQuery,
|
||||
Long sampleNumber,
|
||||
LocalDate date
|
||||
) {
|
||||
List<CatalogService.FarmerOption> matchingFarmers = catalogService.activeCatalogSummary(actorId).farmers().stream()
|
||||
.filter(farmer -> farmerQuery == null || farmerQuery.isBlank() || farmer.companyName().toLowerCase(Locale.ROOT).contains(farmerQuery.toLowerCase(Locale.ROOT)))
|
||||
.toList();
|
||||
|
||||
List<PortalSampleRow> sampleRows;
|
||||
if (sampleNumber != null) {
|
||||
sampleRows = List.of(toPortalRow(sampleService.getSampleByNumber(sampleNumber)));
|
||||
sampleRows = List.of(toPortalRow(sampleService.getSampleByNumber(actorId, sampleNumber)));
|
||||
} else if (farmerBusinessKey != null && !farmerBusinessKey.isBlank()) {
|
||||
sampleRows = sampleService.samplesByFarmerBusinessKey(farmerBusinessKey).stream()
|
||||
sampleRows = sampleService.samplesByFarmerBusinessKey(actorId, farmerBusinessKey).stream()
|
||||
.filter(sample -> cowQuery == null || cowQuery.isBlank() || cowMatches(sample, cowQuery))
|
||||
.map(this::toPortalRow)
|
||||
.sorted(Comparator.comparing(PortalSampleRow::createdAt).reversed())
|
||||
.toList();
|
||||
} else if (date != null) {
|
||||
sampleRows = sampleService.samplesByDate(date).stream()
|
||||
sampleRows = sampleService.samplesByDate(actorId, date).stream()
|
||||
.map(this::toPortalRow)
|
||||
.sorted(Comparator.comparing(PortalSampleRow::completedAt, Comparator.nullsLast(Comparator.reverseOrder())))
|
||||
.toList();
|
||||
} else {
|
||||
sampleRows = sampleService.completedSamples().stream()
|
||||
sampleRows = sampleService.completedSamples(actorId).stream()
|
||||
.limit(25)
|
||||
.map(this::toPortalRow)
|
||||
.toList();
|
||||
@@ -50,11 +58,18 @@ public class PortalService {
|
||||
return new PortalSnapshot(
|
||||
matchingFarmers,
|
||||
sampleRows,
|
||||
reportService.reportCandidates(),
|
||||
catalogService.listUsers()
|
||||
reportService.reportCandidates(actorId),
|
||||
includeUsers ? catalogService.listUsers(actorId) : List.of()
|
||||
);
|
||||
}
|
||||
|
||||
public List<PortalSampleRow> searchSamplesByCreatedDate(String actorId, LocalDate date) {
|
||||
return sampleService.samplesByCreatedDate(actorId, date).stream()
|
||||
.map(this::toPortalRow)
|
||||
.sorted(Comparator.comparing(PortalSampleRow::createdAt).reversed())
|
||||
.toList();
|
||||
}
|
||||
|
||||
private boolean cowMatches(Sample sample, String cowQuery) {
|
||||
String query = cowQuery.toLowerCase(Locale.ROOT);
|
||||
return (sample.cowNumber() != null && sample.cowNumber().toLowerCase(Locale.ROOT).contains(query))
|
||||
|
||||
@@ -1,57 +1,72 @@
|
||||
package de.svencarstensen.muh.service;
|
||||
|
||||
import de.svencarstensen.muh.domain.Sample;
|
||||
import de.svencarstensen.muh.domain.AppUser;
|
||||
import de.svencarstensen.muh.repository.AppUserRepository;
|
||||
import org.springframework.beans.factory.ObjectProvider;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.core.io.ByteArrayResource;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.lang.NonNull;
|
||||
import org.springframework.mail.javamail.JavaMailSender;
|
||||
import org.springframework.mail.javamail.MimeMessageHelper;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.FileCopyUtils;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import jakarta.mail.internet.MimeMessage;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
@Service
|
||||
public class ReportService {
|
||||
|
||||
private final SampleService sampleService;
|
||||
private final AppUserRepository appUserRepository;
|
||||
private final ObjectProvider<JavaMailSender> mailSenderProvider;
|
||||
private final boolean mailEnabled;
|
||||
private final String mailFrom;
|
||||
private final String reportMailTemplate;
|
||||
|
||||
public ReportService(
|
||||
SampleService sampleService,
|
||||
AppUserRepository appUserRepository,
|
||||
ObjectProvider<JavaMailSender> mailSenderProvider,
|
||||
@Value("classpath:mail/report-mail-template.txt") Resource reportMailTemplateResource,
|
||||
@Value("${muh.mail.enabled:false}") boolean mailEnabled,
|
||||
@Value("${muh.mail.from:no-reply@muh.local}") String mailFrom
|
||||
) {
|
||||
this.sampleService = sampleService;
|
||||
this.appUserRepository = appUserRepository;
|
||||
this.mailSenderProvider = mailSenderProvider;
|
||||
this.mailEnabled = mailEnabled;
|
||||
this.mailFrom = mailFrom;
|
||||
this.reportMailTemplate = loadTemplate(reportMailTemplateResource);
|
||||
}
|
||||
|
||||
public List<ReportCandidate> reportCandidates() {
|
||||
return sampleService.completedSamples().stream()
|
||||
public List<ReportCandidate> reportCandidates(String actorId) {
|
||||
return sampleService.completedSamples(actorId).stream()
|
||||
.filter(sample -> sample.farmerEmail() != null && !sample.farmerEmail().isBlank())
|
||||
.map(this::toCandidate)
|
||||
.toList();
|
||||
}
|
||||
|
||||
public DispatchResult sendReports(List<String> sampleIds) {
|
||||
public DispatchResult sendReports(String actorId, List<String> sampleIds) {
|
||||
String customerSignature = buildCustomerSignature(actorId);
|
||||
List<ReportCandidate> sent = new ArrayList<>();
|
||||
List<ReportCandidate> skipped = new ArrayList<>();
|
||||
|
||||
for (String sampleId : sampleIds) {
|
||||
Sample sample = sampleService.loadSampleEntity(sampleId);
|
||||
Sample sample = sampleService.loadSampleEntity(actorId, sampleId);
|
||||
if (sample.farmerEmail() == null || sample.farmerEmail().isBlank() || sample.reportBlocked()) {
|
||||
skipped.add(toCandidate(sample));
|
||||
continue;
|
||||
@@ -59,7 +74,7 @@ public class ReportService {
|
||||
|
||||
byte[] pdf = buildPdf(sample);
|
||||
if (mailEnabled && mailSenderProvider.getIfAvailable() != null) {
|
||||
sendMail(sample, pdf);
|
||||
sendMail(sample, pdf, customerSignature);
|
||||
}
|
||||
Sample updated = sampleService.markReportSent(sample.id(), LocalDateTime.now());
|
||||
sent.add(toCandidate(updated));
|
||||
@@ -67,15 +82,16 @@ public class ReportService {
|
||||
return new DispatchResult(sent, skipped, mailEnabled && mailSenderProvider.getIfAvailable() != null);
|
||||
}
|
||||
|
||||
public byte[] reportPdf(String sampleId) {
|
||||
return buildPdf(sampleService.loadSampleEntity(sampleId));
|
||||
public byte[] reportPdf(String actorId, String sampleId) {
|
||||
return buildPdf(sampleService.loadSampleEntity(actorId, sampleId));
|
||||
}
|
||||
|
||||
public SampleService.SampleDetail toggleReportBlocked(String sampleId, boolean blocked) {
|
||||
return sampleService.getSample(sampleService.toggleReportBlocked(sampleId, blocked).id());
|
||||
public SampleService.SampleDetail toggleReportBlocked(String actorId, String sampleId, boolean blocked) {
|
||||
Sample sample = sampleService.loadSampleEntity(actorId, sampleId);
|
||||
return sampleService.getSample(actorId, sampleService.toggleReportBlocked(sample.id(), blocked).id());
|
||||
}
|
||||
|
||||
private void sendMail(Sample sample, byte[] pdf) {
|
||||
private void sendMail(Sample sample, byte[] pdf, String customerSignature) {
|
||||
try {
|
||||
JavaMailSender sender = mailSenderProvider.getIfAvailable();
|
||||
if (sender == null) {
|
||||
@@ -86,7 +102,7 @@ public class ReportService {
|
||||
helper.setFrom(requireText(mailFrom, "Absender fehlt"));
|
||||
helper.setTo(requireText(sample.farmerEmail(), "Empfänger fehlt"));
|
||||
helper.setSubject("MUH-Bericht Probe " + sample.sampleNumber());
|
||||
helper.setText("Im Anhang befindet sich der Bericht zur Probe " + sample.sampleNumber() + ".", false);
|
||||
helper.setText(Objects.requireNonNull(buildMailBody(sample, customerSignature)), false);
|
||||
helper.addAttachment("MUH-Bericht-" + sample.sampleNumber() + ".pdf", new ByteArrayResource(Objects.requireNonNull(pdf)));
|
||||
sender.send(message);
|
||||
} catch (Exception exception) {
|
||||
@@ -136,6 +152,79 @@ public class ReportService {
|
||||
return value == null || value.isBlank() ? "-" : value;
|
||||
}
|
||||
|
||||
private String buildMailBody(Sample sample, String customerSignature) {
|
||||
return reportMailTemplate
|
||||
.replace("{{sampleNumber}}", String.valueOf(sample.sampleNumber()))
|
||||
.replace("{{cowLabel}}", resolveCowLabel(sample))
|
||||
.replace("{{customerSignature}}", customerSignature);
|
||||
}
|
||||
|
||||
private String resolveCowLabel(Sample sample) {
|
||||
if (sample.cowName() == null || sample.cowName().isBlank()) {
|
||||
return sample.cowNumber();
|
||||
}
|
||||
return sample.cowNumber() + " / " + sample.cowName();
|
||||
}
|
||||
|
||||
private String buildCustomerSignature(String actorId) {
|
||||
if (actorId == null || actorId.isBlank()) {
|
||||
return defaultCustomerSignature();
|
||||
}
|
||||
|
||||
String normalizedActorId = Objects.requireNonNull(actorId).trim();
|
||||
AppUser actor = appUserRepository.findById(Objects.requireNonNull(normalizedActorId)).orElse(null);
|
||||
if (actor == null) {
|
||||
return defaultCustomerSignature();
|
||||
}
|
||||
|
||||
String primaryName = firstNonBlank(actor.companyName(), actor.displayName(), "MUH App");
|
||||
String secondaryName = actor.companyName() != null
|
||||
&& actor.displayName() != null
|
||||
&& !actor.companyName().equalsIgnoreCase(actor.displayName())
|
||||
? actor.displayName()
|
||||
: null;
|
||||
String streetLine = joinParts(" ", actor.street(), actor.houseNumber());
|
||||
String cityLine = joinParts(" ", actor.postalCode(), actor.city());
|
||||
|
||||
return Stream.of(
|
||||
primaryName,
|
||||
secondaryName,
|
||||
streetLine,
|
||||
cityLine,
|
||||
actor.email(),
|
||||
actor.phoneNumber()
|
||||
)
|
||||
.filter(part -> part != null && !part.isBlank())
|
||||
.collect(Collectors.joining(System.lineSeparator()));
|
||||
}
|
||||
|
||||
private String defaultCustomerSignature() {
|
||||
return firstNonBlank(mailFrom, "MUH App");
|
||||
}
|
||||
|
||||
private String joinParts(String separator, String... values) {
|
||||
return Stream.of(values)
|
||||
.filter(value -> value != null && !value.isBlank())
|
||||
.map(String::trim)
|
||||
.collect(Collectors.joining(separator));
|
||||
}
|
||||
|
||||
private String firstNonBlank(String... values) {
|
||||
return Stream.of(values)
|
||||
.filter(value -> value != null && !value.isBlank())
|
||||
.map(String::trim)
|
||||
.findFirst()
|
||||
.orElse("");
|
||||
}
|
||||
|
||||
private String loadTemplate(Resource resource) {
|
||||
try (InputStreamReader reader = new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8)) {
|
||||
return FileCopyUtils.copyToString(reader);
|
||||
} catch (IOException exception) {
|
||||
throw new IllegalStateException("Mail-Template konnte nicht geladen werden", exception);
|
||||
}
|
||||
}
|
||||
|
||||
private @NonNull String requireText(String value, String message) {
|
||||
if (value == null || value.isBlank()) {
|
||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, message);
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
package de.svencarstensen.muh.service;
|
||||
|
||||
import de.svencarstensen.muh.domain.AppUser;
|
||||
import de.svencarstensen.muh.domain.InvoiceTemplateElement;
|
||||
import de.svencarstensen.muh.domain.ReportTemplate;
|
||||
import de.svencarstensen.muh.domain.Template;
|
||||
import de.svencarstensen.muh.domain.TemplateType;
|
||||
import de.svencarstensen.muh.repository.AppUserRepository;
|
||||
import de.svencarstensen.muh.repository.ReportTemplateRepository;
|
||||
import de.svencarstensen.muh.repository.TemplateRepository;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.lang.NonNull;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Objects;
|
||||
|
||||
@Service
|
||||
public class ReportTemplateService {
|
||||
|
||||
private static final TemplateType TEMPLATE_TYPE = TemplateType.REPORT;
|
||||
|
||||
private final AppUserRepository appUserRepository;
|
||||
private final TemplateRepository templateRepository;
|
||||
private final ReportTemplateRepository reportTemplateRepository;
|
||||
|
||||
public ReportTemplateService(
|
||||
AppUserRepository appUserRepository,
|
||||
TemplateRepository templateRepository,
|
||||
ReportTemplateRepository reportTemplateRepository
|
||||
) {
|
||||
this.appUserRepository = appUserRepository;
|
||||
this.templateRepository = templateRepository;
|
||||
this.reportTemplateRepository = reportTemplateRepository;
|
||||
}
|
||||
|
||||
public InvoiceTemplateService.InvoiceTemplateResponse currentTemplate(String actorId) {
|
||||
String userId = requireActorId(actorId);
|
||||
requireActiveUser(userId);
|
||||
return templateRepository.findByUserIdAndType(userId, TEMPLATE_TYPE)
|
||||
.map(this::toResponse)
|
||||
.or(() -> reportTemplateRepository.findById(userId).map(this::toLegacyResponse))
|
||||
.orElseGet(() -> new InvoiceTemplateService.InvoiceTemplateResponse(false, List.of(), null));
|
||||
}
|
||||
|
||||
public InvoiceTemplateService.InvoiceTemplateResponse saveTemplate(
|
||||
String actorId,
|
||||
List<InvoiceTemplateService.InvoiceTemplateElementPayload> payloadElements
|
||||
) {
|
||||
String userId = requireActorId(actorId);
|
||||
requireActiveUser(userId);
|
||||
Template existing = templateRepository.findByUserIdAndType(userId, TEMPLATE_TYPE).orElse(null);
|
||||
ReportTemplate legacyTemplate = existing == null
|
||||
? reportTemplateRepository.findById(userId).orElse(null)
|
||||
: null;
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
|
||||
Template saved = templateRepository.save(new Template(
|
||||
existing != null ? existing.id() : templateId(userId),
|
||||
userId,
|
||||
TEMPLATE_TYPE,
|
||||
sanitizeElements(payloadElements),
|
||||
existing != null ? existing.createdAt() : legacyTemplate != null ? legacyTemplate.createdAt() : now,
|
||||
now
|
||||
));
|
||||
return toResponse(saved);
|
||||
}
|
||||
|
||||
private AppUser requireActiveUser(@NonNull String actorId) {
|
||||
return appUserRepository.findById(actorId)
|
||||
.filter(AppUser::active)
|
||||
.orElseThrow(() -> new ResponseStatusException(HttpStatus.FORBIDDEN, "Nicht berechtigt"));
|
||||
}
|
||||
|
||||
private @NonNull String requireActorId(String actorId) {
|
||||
if (isBlank(actorId)) {
|
||||
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "Nicht berechtigt");
|
||||
}
|
||||
String sanitized = Objects.requireNonNull(actorId).trim();
|
||||
return Objects.requireNonNull(sanitized);
|
||||
}
|
||||
|
||||
private List<InvoiceTemplateElement> sanitizeElements(
|
||||
List<InvoiceTemplateService.InvoiceTemplateElementPayload> payloadElements
|
||||
) {
|
||||
if (payloadElements == null || payloadElements.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
return payloadElements.stream()
|
||||
.map(this::sanitizeElement)
|
||||
.filter(Objects::nonNull)
|
||||
.toList();
|
||||
}
|
||||
|
||||
private InvoiceTemplateElement sanitizeElement(InvoiceTemplateService.InvoiceTemplateElementPayload payload) {
|
||||
if (payload == null
|
||||
|| isBlank(payload.id())
|
||||
|| isBlank(payload.paletteId())
|
||||
|| isBlank(payload.kind())
|
||||
|| payload.x() == null
|
||||
|| payload.y() == null
|
||||
|| payload.width() == null
|
||||
|| payload.fontSize() == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return new InvoiceTemplateElement(
|
||||
payload.id().trim(),
|
||||
payload.paletteId().trim(),
|
||||
payload.kind().trim(),
|
||||
trimOrEmpty(payload.label()),
|
||||
nullToEmpty(payload.content()),
|
||||
payload.x(),
|
||||
payload.y(),
|
||||
payload.width(),
|
||||
payload.height(),
|
||||
payload.fontSize(),
|
||||
payload.fontWeight(),
|
||||
blankToNull(payload.textAlign()),
|
||||
blankToNull(payload.lineOrientation()),
|
||||
blankToNull(payload.imageSrc()),
|
||||
payload.imageNaturalWidth(),
|
||||
payload.imageNaturalHeight()
|
||||
);
|
||||
}
|
||||
|
||||
private InvoiceTemplateService.InvoiceTemplateResponse toResponse(Template template) {
|
||||
return toResponse(template.elements(), template.updatedAt());
|
||||
}
|
||||
|
||||
private InvoiceTemplateService.InvoiceTemplateResponse toLegacyResponse(ReportTemplate template) {
|
||||
return toResponse(template.elements(), template.updatedAt());
|
||||
}
|
||||
|
||||
private InvoiceTemplateService.InvoiceTemplateElementPayload toPayload(InvoiceTemplateElement element) {
|
||||
return new InvoiceTemplateService.InvoiceTemplateElementPayload(
|
||||
element.id(),
|
||||
element.paletteId(),
|
||||
element.kind(),
|
||||
element.label(),
|
||||
element.content(),
|
||||
element.x(),
|
||||
element.y(),
|
||||
element.width(),
|
||||
element.height(),
|
||||
element.fontSize(),
|
||||
element.fontWeight(),
|
||||
element.textAlign(),
|
||||
element.lineOrientation(),
|
||||
element.imageSrc(),
|
||||
element.imageNaturalWidth(),
|
||||
element.imageNaturalHeight()
|
||||
);
|
||||
}
|
||||
|
||||
private boolean isBlank(String value) {
|
||||
return value == null || value.isBlank();
|
||||
}
|
||||
|
||||
private String blankToNull(String value) {
|
||||
return isBlank(value) ? null : value.trim();
|
||||
}
|
||||
|
||||
private String trimOrEmpty(String value) {
|
||||
return value == null ? "" : value.trim();
|
||||
}
|
||||
|
||||
private String nullToEmpty(String value) {
|
||||
return value == null ? "" : value;
|
||||
}
|
||||
|
||||
private InvoiceTemplateService.InvoiceTemplateResponse toResponse(
|
||||
List<InvoiceTemplateElement> elements,
|
||||
LocalDateTime updatedAt
|
||||
) {
|
||||
List<InvoiceTemplateService.InvoiceTemplateElementPayload> payloads = elements == null
|
||||
? List.of()
|
||||
: elements.stream().map(this::toPayload).toList();
|
||||
return new InvoiceTemplateService.InvoiceTemplateResponse(true, payloads, updatedAt);
|
||||
}
|
||||
|
||||
private String templateId(String userId) {
|
||||
return userId + ":" + TEMPLATE_TYPE.name().toLowerCase(Locale.ROOT);
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,10 @@
|
||||
package de.svencarstensen.muh.service;
|
||||
|
||||
import de.svencarstensen.muh.domain.AntibiogramEntry;
|
||||
import de.svencarstensen.muh.domain.AppUser;
|
||||
import de.svencarstensen.muh.domain.PathogenCatalogItem;
|
||||
import de.svencarstensen.muh.domain.PathogenKind;
|
||||
import de.svencarstensen.muh.domain.Pretreatment;
|
||||
import de.svencarstensen.muh.domain.QuarterAntibiogram;
|
||||
import de.svencarstensen.muh.domain.QuarterFinding;
|
||||
import de.svencarstensen.muh.domain.QuarterKey;
|
||||
@@ -13,45 +15,68 @@ import de.svencarstensen.muh.domain.SamplingMode;
|
||||
import de.svencarstensen.muh.domain.SensitivityResult;
|
||||
import de.svencarstensen.muh.domain.TherapyRecommendation;
|
||||
import de.svencarstensen.muh.repository.SampleRepository;
|
||||
import de.svencarstensen.muh.repository.AppUserRepository;
|
||||
import de.svencarstensen.muh.security.AuthorizationService;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.time.format.DateTimeParseException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Service
|
||||
public class SampleService {
|
||||
|
||||
private final SampleRepository sampleRepository;
|
||||
private final CatalogService catalogService;
|
||||
private final AppUserRepository appUserRepository;
|
||||
private final AuthorizationService authorizationService;
|
||||
|
||||
public SampleService(SampleRepository sampleRepository, CatalogService catalogService) {
|
||||
public SampleService(
|
||||
SampleRepository sampleRepository,
|
||||
CatalogService catalogService,
|
||||
AppUserRepository appUserRepository,
|
||||
AuthorizationService authorizationService
|
||||
) {
|
||||
this.sampleRepository = sampleRepository;
|
||||
this.catalogService = catalogService;
|
||||
this.appUserRepository = appUserRepository;
|
||||
this.authorizationService = authorizationService;
|
||||
}
|
||||
|
||||
public DashboardOverview dashboardOverview() {
|
||||
List<SampleSummary> recent = sampleRepository.findTop12ByOrderByUpdatedAtDesc().stream()
|
||||
public DashboardOverview dashboardOverview(String actorId) {
|
||||
AppUser actor = requireActor(actorId);
|
||||
List<Sample> accessibleSamples = accessibleSamples(actor);
|
||||
List<SampleSummary> recent = accessibleSamples.stream()
|
||||
.sorted(Comparator.comparing(Sample::updatedAt).reversed())
|
||||
.limit(12)
|
||||
.map(this::toSummary)
|
||||
.toList();
|
||||
long openCount = sampleRepository.findAll().stream().filter(sample -> sample.currentStep() != SampleWorkflowStep.COMPLETED).count();
|
||||
long openCount = accessibleSamples.stream()
|
||||
.filter(sample -> sample.currentStep() != SampleWorkflowStep.COMPLETED)
|
||||
.count();
|
||||
LocalDate today = LocalDate.now();
|
||||
long completedToday = sampleRepository.findByCompletedAtBetweenOrderByCompletedAtDesc(
|
||||
today.atStartOfDay(),
|
||||
today.plusDays(1).atStartOfDay()
|
||||
).size();
|
||||
return new DashboardOverview(nextSampleNumber(), openCount, completedToday, recent);
|
||||
long completedToday = accessibleSamples.stream()
|
||||
.filter(sample -> sample.completedAt() != null)
|
||||
.filter(sample -> !sample.completedAt().isBefore(today.atStartOfDay()))
|
||||
.filter(sample -> sample.completedAt().isBefore(today.plusDays(1).atStartOfDay()))
|
||||
.count();
|
||||
return new DashboardOverview(nextSampleNumber(actorId), openCount, completedToday, recent);
|
||||
}
|
||||
|
||||
public LookupResult lookup(long sampleNumber) {
|
||||
public LookupResult lookup(String actorId, long sampleNumber) {
|
||||
AppUser actor = requireActor(actorId);
|
||||
return sampleRepository.findBySampleNumber(sampleNumber)
|
||||
.filter(sample -> canAccess(actor, sample))
|
||||
.map(sample -> new LookupResult(
|
||||
true,
|
||||
"Probe gefunden",
|
||||
@@ -62,28 +87,44 @@ public class SampleService {
|
||||
.orElseGet(() -> new LookupResult(false, "Proben-Nummer unbekannt", null, null, null));
|
||||
}
|
||||
|
||||
public SampleDetail getSample(String id) {
|
||||
return toDetail(loadSample(id));
|
||||
public SampleDetail getSample(String actorId, String id) {
|
||||
return toDetail(loadAccessibleSample(actorId, id));
|
||||
}
|
||||
|
||||
public SampleDetail getSampleByNumber(long sampleNumber) {
|
||||
public SampleDetail getSampleByNumber(String actorId, long sampleNumber) {
|
||||
AppUser actor = requireActor(actorId);
|
||||
return sampleRepository.findBySampleNumber(sampleNumber)
|
||||
.filter(sample -> canAccess(actor, sample))
|
||||
.map(this::toDetail)
|
||||
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Probe nicht gefunden"));
|
||||
}
|
||||
|
||||
public SampleDetail createSample(RegistrationRequest request) {
|
||||
public SampleDetail createSample(String actorId, RegistrationRequest request) {
|
||||
AppUser actor = requireActor(actorId);
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
CatalogService.FarmerOption farmer = catalogService.activeCatalogSummary().farmers().stream()
|
||||
CatalogService.FarmerOption farmer = catalogService.activeCatalogSummary(actorId).farmers().stream()
|
||||
.filter(candidate -> candidate.businessKey().equals(request.farmerBusinessKey()))
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new ResponseStatusException(HttpStatus.BAD_REQUEST, "Landwirt nicht gefunden"));
|
||||
|
||||
long sampleNumber = reserveNextSampleNumber(actorId);
|
||||
Pretreatment pretreatment = request.pretreatmentInUdderInjector() == null &&
|
||||
request.pretreatmentSystemicAntibiotics() == null &&
|
||||
request.pretreatmentPainMedication() == null &&
|
||||
request.pretreatmentDryOffTreatment() == null
|
||||
? null
|
||||
: new Pretreatment(
|
||||
blankToNull(request.pretreatmentInUdderInjector()),
|
||||
blankToNull(request.pretreatmentSystemicAntibiotics()),
|
||||
blankToNull(request.pretreatmentPainMedication()),
|
||||
blankToNull(request.pretreatmentDryOffTreatment())
|
||||
);
|
||||
|
||||
Sample sample = new Sample(
|
||||
null,
|
||||
nextSampleNumber(),
|
||||
sampleNumber,
|
||||
farmer.businessKey(),
|
||||
farmer.name(),
|
||||
farmer.companyName(),
|
||||
farmer.email(),
|
||||
request.cowNumber().trim(),
|
||||
blankToNull(request.cowName()),
|
||||
@@ -99,29 +140,45 @@ public class SampleService {
|
||||
now,
|
||||
now,
|
||||
null,
|
||||
authorizationService.accountId(actor),
|
||||
request.userCode(),
|
||||
request.userDisplayName()
|
||||
request.userDisplayName(),
|
||||
pretreatment,
|
||||
parseClinicalExamDate(request.clinicalExamDate()),
|
||||
blankToNull(request.internalNote())
|
||||
);
|
||||
|
||||
return toDetail(sampleRepository.save(sample));
|
||||
}
|
||||
|
||||
public SampleDetail saveRegistration(String id, RegistrationRequest request) {
|
||||
Sample existing = loadSample(id);
|
||||
public SampleDetail saveRegistration(String actorId, String id, RegistrationRequest request) {
|
||||
Sample existing = loadAccessibleSample(actorId, id);
|
||||
if (!SampleWorkflowRules.canEditRegistration(existing)) {
|
||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Stammdaten können nicht mehr geändert werden");
|
||||
}
|
||||
|
||||
CatalogService.FarmerOption farmer = catalogService.activeCatalogSummary().farmers().stream()
|
||||
CatalogService.FarmerOption farmer = catalogService.activeCatalogSummary(actorId).farmers().stream()
|
||||
.filter(candidate -> candidate.businessKey().equals(request.farmerBusinessKey()))
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new ResponseStatusException(HttpStatus.BAD_REQUEST, "Landwirt nicht gefunden"));
|
||||
|
||||
Pretreatment pretreatment = request.pretreatmentInUdderInjector() == null &&
|
||||
request.pretreatmentSystemicAntibiotics() == null &&
|
||||
request.pretreatmentPainMedication() == null &&
|
||||
request.pretreatmentDryOffTreatment() == null
|
||||
? existing.pretreatment()
|
||||
: new Pretreatment(
|
||||
blankToNull(request.pretreatmentInUdderInjector()),
|
||||
blankToNull(request.pretreatmentSystemicAntibiotics()),
|
||||
blankToNull(request.pretreatmentPainMedication()),
|
||||
blankToNull(request.pretreatmentDryOffTreatment())
|
||||
);
|
||||
|
||||
Sample saved = sampleRepository.save(new Sample(
|
||||
existing.id(),
|
||||
existing.sampleNumber(),
|
||||
farmer.businessKey(),
|
||||
farmer.name(),
|
||||
farmer.companyName(),
|
||||
farmer.email(),
|
||||
request.cowNumber().trim(),
|
||||
blankToNull(request.cowName()),
|
||||
@@ -137,15 +194,23 @@ public class SampleService {
|
||||
existing.createdAt(),
|
||||
LocalDateTime.now(),
|
||||
existing.completedAt(),
|
||||
existing.ownerAccountId(),
|
||||
existing.createdByUserCode(),
|
||||
existing.createdByDisplayName()
|
||||
existing.createdByDisplayName(),
|
||||
pretreatment,
|
||||
parseClinicalExamDate(request.clinicalExamDate()) != null
|
||||
? parseClinicalExamDate(request.clinicalExamDate())
|
||||
: existing.clinicalExamDate(),
|
||||
request.internalNote() != null
|
||||
? blankToNull(request.internalNote())
|
||||
: existing.internalNote()
|
||||
));
|
||||
|
||||
return toDetail(saved);
|
||||
}
|
||||
|
||||
public SampleDetail saveAnamnesis(String id, AnamnesisRequest request) {
|
||||
Sample existing = loadSample(id);
|
||||
public SampleDetail saveAnamnesis(String actorId, String id, AnamnesisRequest request) {
|
||||
Sample existing = loadAccessibleSample(actorId, id);
|
||||
if (!SampleWorkflowRules.canEditAnamnesis(existing)) {
|
||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Anamnese kann an dieser Stelle nicht geändert werden");
|
||||
}
|
||||
@@ -155,7 +220,7 @@ public class SampleService {
|
||||
current.put(quarter.quarterKey(), quarter);
|
||||
}
|
||||
|
||||
Map<String, PathogenCatalogItem> pathogens = catalogService.activePathogensByBusinessKey();
|
||||
Map<String, PathogenCatalogItem> pathogens = catalogService.activePathogensByBusinessKey(actorId);
|
||||
List<QuarterFinding> updatedQuarters = new ArrayList<>();
|
||||
for (AnamnesisQuarterRequest quarterRequest : request.quarters()) {
|
||||
QuarterFinding base = current.get(quarterRequest.quarterKey());
|
||||
@@ -203,19 +268,23 @@ public class SampleService {
|
||||
existing.createdAt(),
|
||||
LocalDateTime.now(),
|
||||
existing.completedAt(),
|
||||
existing.ownerAccountId(),
|
||||
existing.createdByUserCode(),
|
||||
existing.createdByDisplayName()
|
||||
existing.createdByDisplayName(),
|
||||
existing.pretreatment(),
|
||||
existing.clinicalExamDate(),
|
||||
existing.internalNote()
|
||||
));
|
||||
return toDetail(saved);
|
||||
}
|
||||
|
||||
public SampleDetail saveAntibiogram(String id, AntibiogramRequest request) {
|
||||
Sample existing = loadSample(id);
|
||||
public SampleDetail saveAntibiogram(String actorId, String id, AntibiogramRequest request) {
|
||||
Sample existing = loadAccessibleSample(actorId, id);
|
||||
if (!SampleWorkflowRules.canEditAntibiogram(existing)) {
|
||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Antibiogramm kann nicht mehr geändert werden");
|
||||
}
|
||||
|
||||
Map<String, de.svencarstensen.muh.domain.AntibioticCatalogItem> antibiotics = catalogService.activeAntibioticsByBusinessKey();
|
||||
Map<String, de.svencarstensen.muh.domain.AntibioticCatalogItem> antibiotics = catalogService.activeAntibioticsByBusinessKey(actorId);
|
||||
Map<QuarterKey, QuarterAntibiogram> groups = new HashMap<>();
|
||||
Map<QuarterKey, QuarterFinding> quartersByKey = existing.quarters().stream()
|
||||
.collect(java.util.stream.Collectors.toMap(QuarterFinding::quarterKey, quarter -> quarter));
|
||||
@@ -293,18 +362,22 @@ public class SampleService {
|
||||
existing.createdAt(),
|
||||
LocalDateTime.now(),
|
||||
existing.completedAt(),
|
||||
existing.ownerAccountId(),
|
||||
existing.createdByUserCode(),
|
||||
existing.createdByDisplayName()
|
||||
existing.createdByDisplayName(),
|
||||
existing.pretreatment(),
|
||||
existing.clinicalExamDate(),
|
||||
existing.internalNote()
|
||||
));
|
||||
return toDetail(saved);
|
||||
}
|
||||
|
||||
public SampleDetail saveTherapy(String id, TherapyRequest request) {
|
||||
Sample existing = loadSample(id);
|
||||
public SampleDetail saveTherapy(String actorId, String id, TherapyRequest request) {
|
||||
Sample existing = loadAccessibleSample(actorId, id);
|
||||
if (existing.currentStep() == SampleWorkflowStep.COMPLETED) {
|
||||
TherapyRecommendation previous = existing.therapyRecommendation();
|
||||
TherapyRecommendation updated = previous == null
|
||||
? new TherapyRecommendation(false, false, List.of(), List.of(), null, List.of(), List.of(), null, List.of(), List.of(), List.of(), List.of(), null, blankToNull(request.internalNote()))
|
||||
? new TherapyRecommendation(false, false, List.of(), List.of(), null, List.of(), List.of(), null, List.of(), List.of(), List.of(), List.of(), null, blankToNull(request.internalNote()), null, null, null, null, null, null, Boolean.FALSE, Boolean.FALSE)
|
||||
: new TherapyRecommendation(
|
||||
previous.continueStarted(),
|
||||
previous.switchTherapy(),
|
||||
@@ -319,7 +392,15 @@ public class SampleService {
|
||||
previous.dryAntibioticKeys(),
|
||||
previous.dryAntibioticNames(),
|
||||
previous.farmerNote(),
|
||||
blankToNull(request.internalNote())
|
||||
blankToNull(request.internalNote()),
|
||||
previous.inUdderCount(),
|
||||
previous.inUdderDuration(),
|
||||
previous.systemicCount(),
|
||||
previous.systemicDuration(),
|
||||
previous.systemicDosage(),
|
||||
previous.systemicLocation(),
|
||||
previous.startvacVaccination() != null ? previous.startvacVaccination() : Boolean.FALSE,
|
||||
previous.noAntibioticTreatment() != null ? previous.noAntibioticTreatment() : Boolean.FALSE
|
||||
);
|
||||
return toDetail(sampleRepository.save(new Sample(
|
||||
existing.id(),
|
||||
@@ -341,8 +422,12 @@ public class SampleService {
|
||||
existing.createdAt(),
|
||||
LocalDateTime.now(),
|
||||
existing.completedAt(),
|
||||
existing.ownerAccountId(),
|
||||
existing.createdByUserCode(),
|
||||
existing.createdByDisplayName()
|
||||
existing.createdByDisplayName(),
|
||||
existing.pretreatment(),
|
||||
existing.clinicalExamDate(),
|
||||
existing.internalNote()
|
||||
)));
|
||||
}
|
||||
|
||||
@@ -350,7 +435,7 @@ public class SampleService {
|
||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Therapie kann nicht bearbeitet werden");
|
||||
}
|
||||
|
||||
Map<String, de.svencarstensen.muh.domain.MedicationCatalogItem> medications = catalogService.activeMedicationsByBusinessKey();
|
||||
Map<String, de.svencarstensen.muh.domain.MedicationCatalogItem> medications = catalogService.activeMedicationsByBusinessKey(actorId);
|
||||
TherapyRecommendation therapy = new TherapyRecommendation(
|
||||
request.continueStarted(),
|
||||
request.switchTherapy(),
|
||||
@@ -365,7 +450,15 @@ public class SampleService {
|
||||
request.dryAntibioticKeys(),
|
||||
resolveMedicationNames(request.dryAntibioticKeys(), medications),
|
||||
blankToNull(request.farmerNote()),
|
||||
blankToNull(request.internalNote())
|
||||
blankToNull(request.internalNote()),
|
||||
blankToNull(request.inUdderCount()),
|
||||
blankToNull(request.inUdderDuration()),
|
||||
blankToNull(request.systemicCount()),
|
||||
blankToNull(request.systemicDuration()),
|
||||
blankToNull(request.systemicDosage()),
|
||||
blankToNull(request.systemicLocation()),
|
||||
request.startvacVaccination(),
|
||||
request.noAntibioticTreatment()
|
||||
);
|
||||
|
||||
Sample saved = sampleRepository.save(new Sample(
|
||||
@@ -388,8 +481,12 @@ public class SampleService {
|
||||
existing.createdAt(),
|
||||
LocalDateTime.now(),
|
||||
LocalDateTime.now(),
|
||||
existing.ownerAccountId(),
|
||||
existing.createdByUserCode(),
|
||||
existing.createdByDisplayName()
|
||||
existing.createdByDisplayName(),
|
||||
existing.pretreatment(),
|
||||
existing.clinicalExamDate(),
|
||||
existing.internalNote()
|
||||
));
|
||||
return toDetail(saved);
|
||||
}
|
||||
@@ -416,8 +513,12 @@ public class SampleService {
|
||||
existing.createdAt(),
|
||||
LocalDateTime.now(),
|
||||
existing.completedAt(),
|
||||
existing.ownerAccountId(),
|
||||
existing.createdByUserCode(),
|
||||
existing.createdByDisplayName()
|
||||
existing.createdByDisplayName(),
|
||||
existing.pretreatment(),
|
||||
existing.clinicalExamDate(),
|
||||
existing.internalNote()
|
||||
));
|
||||
}
|
||||
|
||||
@@ -443,38 +544,208 @@ public class SampleService {
|
||||
existing.createdAt(),
|
||||
LocalDateTime.now(),
|
||||
existing.completedAt(),
|
||||
existing.ownerAccountId(),
|
||||
existing.createdByUserCode(),
|
||||
existing.createdByDisplayName()
|
||||
existing.createdByDisplayName(),
|
||||
existing.pretreatment(),
|
||||
existing.clinicalExamDate(),
|
||||
existing.internalNote()
|
||||
));
|
||||
}
|
||||
|
||||
public List<Sample> completedSamples() {
|
||||
return sampleRepository.findByCompletedAtNotNullOrderByCompletedAtDesc();
|
||||
public List<Sample> completedSamples(String actorId) {
|
||||
return accessibleSamples(requireActor(actorId)).stream()
|
||||
.filter(sample -> sample.completedAt() != null)
|
||||
.sorted(Comparator.comparing(Sample::completedAt).reversed())
|
||||
.toList();
|
||||
}
|
||||
|
||||
public List<Sample> samplesByFarmerBusinessKey(String businessKey) {
|
||||
return sampleRepository.findByFarmerBusinessKeyOrderByCreatedAtDesc(businessKey);
|
||||
public List<Sample> samplesByFarmerBusinessKey(String actorId, String businessKey) {
|
||||
return accessibleSamples(requireActor(actorId)).stream()
|
||||
.filter(sample -> Objects.equals(sample.farmerBusinessKey(), businessKey))
|
||||
.sorted(Comparator.comparing(Sample::createdAt).reversed())
|
||||
.toList();
|
||||
}
|
||||
|
||||
public List<Sample> samplesByDate(LocalDate date) {
|
||||
return sampleRepository.findByCompletedAtBetweenOrderByCompletedAtDesc(date.atStartOfDay(), date.plusDays(1).atStartOfDay());
|
||||
public List<Sample> samplesByCreatedDate(String actorId, LocalDate date) {
|
||||
return accessibleSamples(requireActor(actorId)).stream()
|
||||
.filter(sample -> !sample.createdAt().isBefore(date.atStartOfDay()))
|
||||
.filter(sample -> sample.createdAt().isBefore(date.plusDays(1).atStartOfDay()))
|
||||
.sorted(Comparator.comparing(Sample::createdAt).reversed())
|
||||
.toList();
|
||||
}
|
||||
|
||||
public List<Sample> samplesByDate(String actorId, LocalDate date) {
|
||||
return accessibleSamples(requireActor(actorId)).stream()
|
||||
.filter(sample -> sample.completedAt() != null)
|
||||
.filter(sample -> !sample.completedAt().isBefore(date.atStartOfDay()))
|
||||
.filter(sample -> sample.completedAt().isBefore(date.plusDays(1).atStartOfDay()))
|
||||
.sorted(Comparator.comparing(Sample::completedAt).reversed())
|
||||
.toList();
|
||||
}
|
||||
|
||||
public long nextSampleNumber() {
|
||||
return sampleRepository.findTopByOrderBySampleNumberDesc()
|
||||
.map(sample -> sample.sampleNumber() + 1)
|
||||
.orElse(100001L);
|
||||
return nextSampleNumber(null);
|
||||
}
|
||||
|
||||
public Sample loadSampleEntity(String id) {
|
||||
return loadSample(id);
|
||||
public long nextSampleNumber(String actorId) {
|
||||
if (actorId == null) {
|
||||
return 100000L;
|
||||
}
|
||||
AppUser actor = requireActor(actorId);
|
||||
return actor.nextSampleNumber() != null ? actor.nextSampleNumber() : 100000L;
|
||||
}
|
||||
|
||||
public long reserveNextSampleNumber(String actorId) {
|
||||
AppUser actor = requireActor(actorId);
|
||||
long sampleNumber = actor.nextSampleNumber() != null ? actor.nextSampleNumber() : 100000L;
|
||||
|
||||
// Update user with next sample number
|
||||
appUserRepository.save(new AppUser(
|
||||
actor.id(),
|
||||
actor.accountId(),
|
||||
actor.primaryUser(),
|
||||
actor.displayName(),
|
||||
actor.companyName(),
|
||||
actor.address(),
|
||||
actor.street(),
|
||||
actor.houseNumber(),
|
||||
actor.postalCode(),
|
||||
actor.city(),
|
||||
actor.email(),
|
||||
actor.phoneNumber(),
|
||||
actor.accountHolder(),
|
||||
actor.bankName(),
|
||||
actor.iban(),
|
||||
actor.bic(),
|
||||
actor.passwordHash(),
|
||||
actor.active(),
|
||||
actor.role(),
|
||||
sampleNumber + 1,
|
||||
actor.customerNumber(),
|
||||
actor.createdAt(),
|
||||
LocalDateTime.now()
|
||||
));
|
||||
|
||||
return sampleNumber;
|
||||
}
|
||||
|
||||
public Sample loadSampleEntity(String actorId, String id) {
|
||||
return loadAccessibleSample(actorId, id);
|
||||
}
|
||||
|
||||
private AppUser requireActor(String actorId) {
|
||||
ensureSampleOwnershipMigration();
|
||||
return authorizationService.requireActiveUser(actorId, "Nicht berechtigt");
|
||||
}
|
||||
|
||||
private List<Sample> accessibleSamples(AppUser actor) {
|
||||
List<Sample> samples = sampleRepository.findAll();
|
||||
if (authorizationService.isAdmin(actor)) {
|
||||
return samples;
|
||||
}
|
||||
String accountId = authorizationService.accountId(actor);
|
||||
return samples.stream()
|
||||
.filter(sample -> Objects.equals(sample.ownerAccountId(), accountId))
|
||||
.toList();
|
||||
}
|
||||
|
||||
private boolean canAccess(AppUser actor, Sample sample) {
|
||||
return authorizationService.isAdmin(actor)
|
||||
|| Objects.equals(sample.ownerAccountId(), authorizationService.accountId(actor));
|
||||
}
|
||||
|
||||
private Sample loadAccessibleSample(String actorId, String id) {
|
||||
AppUser actor = requireActor(actorId);
|
||||
Sample sample = loadSample(id);
|
||||
if (!canAccess(actor, sample)) {
|
||||
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Probe nicht gefunden");
|
||||
}
|
||||
return sample;
|
||||
}
|
||||
|
||||
private Sample loadSample(String id) {
|
||||
ensureSampleOwnershipMigration();
|
||||
return sampleRepository.findById(Objects.requireNonNull(id))
|
||||
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "Probe nicht gefunden"));
|
||||
}
|
||||
|
||||
private void ensureSampleOwnershipMigration() {
|
||||
List<Sample> samples = sampleRepository.findAll().stream()
|
||||
.filter(sample -> sample.ownerAccountId() == null || sample.ownerAccountId().isBlank())
|
||||
.toList();
|
||||
if (samples.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
List<AppUser> users = appUserRepository.findAll().stream()
|
||||
.filter(AppUser::active)
|
||||
.toList();
|
||||
Map<String, List<AppUser>> usersByDisplayName = users.stream()
|
||||
.filter(user -> user.displayName() != null && !user.displayName().isBlank())
|
||||
.collect(Collectors.groupingBy(user -> user.displayName().trim().toLowerCase()));
|
||||
List<String> primaryCustomerAccounts = users.stream()
|
||||
.filter(user -> user.role() != de.svencarstensen.muh.domain.UserRole.ADMIN)
|
||||
.filter(user -> Boolean.TRUE.equals(user.primaryUser()))
|
||||
.map(authorizationService::accountId)
|
||||
.distinct()
|
||||
.toList();
|
||||
String fallbackAccountId = primaryCustomerAccounts.size() == 1 ? primaryCustomerAccounts.get(0) : null;
|
||||
|
||||
for (Sample sample : samples) {
|
||||
String resolvedAccountId = resolveSampleOwnerAccountId(sample, usersByDisplayName, fallbackAccountId);
|
||||
if (resolvedAccountId == null) {
|
||||
continue;
|
||||
}
|
||||
sampleRepository.save(new Sample(
|
||||
sample.id(),
|
||||
sample.sampleNumber(),
|
||||
sample.farmerBusinessKey(),
|
||||
sample.farmerName(),
|
||||
sample.farmerEmail(),
|
||||
sample.cowNumber(),
|
||||
sample.cowName(),
|
||||
sample.sampleKind(),
|
||||
sample.samplingMode(),
|
||||
sample.currentStep(),
|
||||
sample.quarters(),
|
||||
sample.antibiograms(),
|
||||
sample.therapyRecommendation(),
|
||||
sample.reportSent(),
|
||||
sample.reportBlocked(),
|
||||
sample.reportSentAt(),
|
||||
sample.createdAt(),
|
||||
sample.updatedAt(),
|
||||
sample.completedAt(),
|
||||
resolvedAccountId,
|
||||
sample.createdByUserCode(),
|
||||
sample.createdByDisplayName(),
|
||||
sample.pretreatment(),
|
||||
sample.clinicalExamDate(),
|
||||
sample.internalNote()
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
private String resolveSampleOwnerAccountId(
|
||||
Sample sample,
|
||||
Map<String, List<AppUser>> usersByDisplayName,
|
||||
String fallbackAccountId
|
||||
) {
|
||||
if (sample.createdByDisplayName() != null && !sample.createdByDisplayName().isBlank()) {
|
||||
List<String> matchingAccounts = usersByDisplayName
|
||||
.getOrDefault(sample.createdByDisplayName().trim().toLowerCase(), List.of())
|
||||
.stream()
|
||||
.map(authorizationService::accountId)
|
||||
.distinct()
|
||||
.toList();
|
||||
if (matchingAccounts.size() == 1) {
|
||||
return matchingAccounts.get(0);
|
||||
}
|
||||
}
|
||||
return fallbackAccountId;
|
||||
}
|
||||
|
||||
private SampleSummary toSummary(Sample sample) {
|
||||
return new SampleSummary(
|
||||
sample.id(),
|
||||
@@ -545,7 +816,10 @@ public class SampleService {
|
||||
SampleWorkflowRules.canEditAnamnesis(sample),
|
||||
SampleWorkflowRules.canEditAntibiogram(sample),
|
||||
SampleWorkflowRules.canEditTherapy(sample),
|
||||
sample.currentStep() == SampleWorkflowStep.COMPLETED
|
||||
sample.currentStep() == SampleWorkflowStep.COMPLETED,
|
||||
sample.pretreatment(),
|
||||
sample.clinicalExamDate(),
|
||||
sample.internalNote()
|
||||
);
|
||||
}
|
||||
|
||||
@@ -567,7 +841,15 @@ public class SampleService {
|
||||
therapy.dryAntibioticKeys(),
|
||||
therapy.dryAntibioticNames(),
|
||||
therapy.farmerNote(),
|
||||
therapy.internalNote()
|
||||
therapy.internalNote(),
|
||||
therapy.inUdderCount(),
|
||||
therapy.inUdderDuration(),
|
||||
therapy.systemicCount(),
|
||||
therapy.systemicDuration(),
|
||||
therapy.systemicDosage(),
|
||||
therapy.systemicLocation(),
|
||||
therapy.startvacVaccination() != null ? therapy.startvacVaccination() : Boolean.FALSE,
|
||||
therapy.noAntibioticTreatment() != null ? therapy.noAntibioticTreatment() : Boolean.FALSE
|
||||
);
|
||||
}
|
||||
|
||||
@@ -685,7 +967,15 @@ public class SampleService {
|
||||
List<String> dryAntibioticKeys,
|
||||
List<String> dryAntibioticNames,
|
||||
String farmerNote,
|
||||
String internalNote
|
||||
String internalNote,
|
||||
String inUdderCount,
|
||||
String inUdderDuration,
|
||||
String systemicCount,
|
||||
String systemicDuration,
|
||||
String systemicDosage,
|
||||
String systemicLocation,
|
||||
Boolean startvacVaccination,
|
||||
Boolean noAntibioticTreatment
|
||||
) {
|
||||
}
|
||||
|
||||
@@ -717,7 +1007,10 @@ public class SampleService {
|
||||
boolean anamnesisEditable,
|
||||
boolean antibiogramEditable,
|
||||
boolean therapyEditable,
|
||||
boolean completed
|
||||
boolean completed,
|
||||
Pretreatment pretreatment,
|
||||
LocalDate clinicalExamDate,
|
||||
String internalNote
|
||||
) {
|
||||
}
|
||||
|
||||
@@ -729,7 +1022,13 @@ public class SampleService {
|
||||
SamplingMode samplingMode,
|
||||
List<QuarterKey> flaggedQuarters,
|
||||
String userCode,
|
||||
String userDisplayName
|
||||
String userDisplayName,
|
||||
String pretreatmentInUdderInjector,
|
||||
String pretreatmentSystemicAntibiotics,
|
||||
String pretreatmentPainMedication,
|
||||
String pretreatmentDryOffTreatment,
|
||||
String clinicalExamDate,
|
||||
String internalNote
|
||||
) {
|
||||
}
|
||||
|
||||
@@ -763,7 +1062,33 @@ public class SampleService {
|
||||
List<String> drySealerKeys,
|
||||
List<String> dryAntibioticKeys,
|
||||
String farmerNote,
|
||||
String internalNote
|
||||
String internalNote,
|
||||
String inUdderCount,
|
||||
String inUdderDuration,
|
||||
String systemicCount,
|
||||
String systemicDuration,
|
||||
String systemicDosage,
|
||||
String systemicLocation,
|
||||
Boolean startvacVaccination,
|
||||
Boolean noAntibioticTreatment
|
||||
) {
|
||||
}
|
||||
|
||||
private LocalDate parseClinicalExamDate(String dateStr) {
|
||||
if (dateStr == null || dateStr.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
// Try ISO format first (YYYY-MM-DD)
|
||||
return LocalDate.parse(dateStr);
|
||||
} catch (DateTimeParseException e) {
|
||||
try {
|
||||
// Try German format (DD.MM.YYYY)
|
||||
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy");
|
||||
return LocalDate.parse(dateStr, formatter);
|
||||
} catch (DateTimeParseException e2) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
package de.svencarstensen.muh.service;
|
||||
|
||||
import de.svencarstensen.muh.domain.SystemPricing;
|
||||
import de.svencarstensen.muh.repository.SystemPricingRepository;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Optional;
|
||||
|
||||
@Service
|
||||
public class SystemPricingService {
|
||||
|
||||
private static final String PRICING_ID = "default";
|
||||
|
||||
private final SystemPricingRepository systemPricingRepository;
|
||||
|
||||
public SystemPricingService(SystemPricingRepository systemPricingRepository) {
|
||||
this.systemPricingRepository = systemPricingRepository;
|
||||
}
|
||||
|
||||
public Optional<SystemPricing> getCurrentPricing() {
|
||||
return systemPricingRepository.findById(PRICING_ID);
|
||||
}
|
||||
|
||||
public SystemPricing savePricing(Double monthlyPrice) {
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
Optional<SystemPricing> existing = systemPricingRepository.findById(PRICING_ID);
|
||||
|
||||
SystemPricing pricing = new SystemPricing(
|
||||
PRICING_ID,
|
||||
monthlyPrice,
|
||||
existing.map(SystemPricing::createdAt).orElse(now),
|
||||
now
|
||||
);
|
||||
|
||||
return systemPricingRepository.save(pricing);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package de.svencarstensen.muh.web;
|
||||
|
||||
import de.svencarstensen.muh.service.AdminStatisticsService;
|
||||
import de.svencarstensen.muh.web.dto.AdminStatistics;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/admin")
|
||||
@PreAuthorize("hasRole('ADMIN')")
|
||||
public class AdminController {
|
||||
|
||||
private final AdminStatisticsService adminStatisticsService;
|
||||
|
||||
public AdminController(AdminStatisticsService adminStatisticsService) {
|
||||
this.adminStatisticsService = adminStatisticsService;
|
||||
}
|
||||
|
||||
@GetMapping("/statistics")
|
||||
public AdminStatistics getStatistics() {
|
||||
return adminStatisticsService.getStatistics();
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package de.svencarstensen.muh.web;
|
||||
|
||||
import de.svencarstensen.muh.service.CatalogService;
|
||||
import de.svencarstensen.muh.security.SecuritySupport;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
@@ -16,59 +17,88 @@ import java.util.List;
|
||||
public class CatalogController {
|
||||
|
||||
private final CatalogService catalogService;
|
||||
private final SecuritySupport securitySupport;
|
||||
|
||||
public CatalogController(CatalogService catalogService) {
|
||||
public CatalogController(CatalogService catalogService, SecuritySupport securitySupport) {
|
||||
this.catalogService = catalogService;
|
||||
this.securitySupport = securitySupport;
|
||||
}
|
||||
|
||||
@GetMapping("/catalogs/summary")
|
||||
public CatalogService.ActiveCatalogSummary catalogSummary() {
|
||||
return catalogService.activeCatalogSummary();
|
||||
return catalogService.activeCatalogSummary(securitySupport.currentUser().id());
|
||||
}
|
||||
|
||||
// Legacy admin endpoints - ADMIN only
|
||||
@GetMapping("/admin")
|
||||
public CatalogService.AdministrationOverview administrationOverview() {
|
||||
return catalogService.administrationOverview();
|
||||
return catalogService.administrationOverview(securitySupport.currentUser().id());
|
||||
}
|
||||
|
||||
@PostMapping("/admin/farmers")
|
||||
public List<CatalogService.FarmerRow> saveFarmers(@RequestBody List<CatalogService.FarmerMutation> mutations) {
|
||||
return catalogService.saveFarmers(mutations);
|
||||
public List<CatalogService.FarmerRow> saveFarmersAdmin(@RequestBody List<CatalogService.FarmerMutation> mutations) {
|
||||
return catalogService.saveFarmers(securitySupport.currentUser().id(), mutations);
|
||||
}
|
||||
|
||||
@PostMapping("/admin/medications")
|
||||
public List<CatalogService.MedicationRow> saveMedications(@RequestBody List<CatalogService.MedicationMutation> mutations) {
|
||||
return catalogService.saveMedications(mutations);
|
||||
public List<CatalogService.MedicationRow> saveMedicationsAdmin(@RequestBody List<CatalogService.MedicationMutation> mutations) {
|
||||
return catalogService.saveMedications(securitySupport.currentUser().id(), mutations);
|
||||
}
|
||||
|
||||
@PostMapping("/admin/pathogens")
|
||||
public List<CatalogService.PathogenRow> savePathogens(@RequestBody List<CatalogService.PathogenMutation> mutations) {
|
||||
return catalogService.savePathogens(mutations);
|
||||
public List<CatalogService.PathogenRow> savePathogensAdmin(@RequestBody List<CatalogService.PathogenMutation> mutations) {
|
||||
return catalogService.savePathogens(securitySupport.currentUser().id(), mutations);
|
||||
}
|
||||
|
||||
@PostMapping("/admin/antibiotics")
|
||||
public List<CatalogService.AntibioticRow> saveAntibioticsAdmin(@RequestBody List<CatalogService.AntibioticMutation> mutations) {
|
||||
return catalogService.saveAntibiotics(securitySupport.currentUser().id(), mutations);
|
||||
}
|
||||
|
||||
// New catalog endpoints - ADMIN and CUSTOMER
|
||||
@GetMapping("/catalog/overview")
|
||||
public CatalogService.AdministrationOverview catalogOverview() {
|
||||
return catalogService.administrationOverview(securitySupport.currentUser().id());
|
||||
}
|
||||
|
||||
@PostMapping("/catalog/farmers")
|
||||
public List<CatalogService.FarmerRow> saveFarmers(@RequestBody List<CatalogService.FarmerMutation> mutations) {
|
||||
return catalogService.saveFarmers(securitySupport.currentUser().id(), mutations);
|
||||
}
|
||||
|
||||
@PostMapping("/catalog/medications")
|
||||
public List<CatalogService.MedicationRow> saveMedications(@RequestBody List<CatalogService.MedicationMutation> mutations) {
|
||||
return catalogService.saveMedications(securitySupport.currentUser().id(), mutations);
|
||||
}
|
||||
|
||||
@PostMapping("/catalog/pathogens")
|
||||
public List<CatalogService.PathogenRow> savePathogens(@RequestBody List<CatalogService.PathogenMutation> mutations) {
|
||||
return catalogService.savePathogens(securitySupport.currentUser().id(), mutations);
|
||||
}
|
||||
|
||||
@PostMapping("/catalog/antibiotics")
|
||||
public List<CatalogService.AntibioticRow> saveAntibiotics(@RequestBody List<CatalogService.AntibioticMutation> mutations) {
|
||||
return catalogService.saveAntibiotics(mutations);
|
||||
return catalogService.saveAntibiotics(securitySupport.currentUser().id(), mutations);
|
||||
}
|
||||
|
||||
@GetMapping("/portal/users")
|
||||
public List<CatalogService.UserRow> users() {
|
||||
return catalogService.listUsers();
|
||||
return catalogService.listUsers(securitySupport.currentUser().id());
|
||||
}
|
||||
|
||||
@PostMapping("/portal/users")
|
||||
public CatalogService.UserRow saveUser(@RequestBody CatalogService.UserMutation mutation) {
|
||||
return catalogService.createOrUpdateUser(mutation);
|
||||
return catalogService.createOrUpdateUser(securitySupport.currentUser().id(), mutation);
|
||||
}
|
||||
|
||||
@DeleteMapping("/portal/users/{id}")
|
||||
public void deleteUser(@PathVariable String id) {
|
||||
catalogService.deleteUser(id);
|
||||
catalogService.deleteUser(securitySupport.currentUser().id(), id);
|
||||
}
|
||||
|
||||
@PostMapping("/portal/users/{id}/password")
|
||||
public void changePassword(@PathVariable String id, @RequestBody PasswordChangeRequest request) {
|
||||
catalogService.changePassword(id, request.password());
|
||||
catalogService.changePassword(securitySupport.currentUser().id(), id, request.password());
|
||||
}
|
||||
|
||||
public record PasswordChangeRequest(String password) {
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
package de.svencarstensen.muh.web;
|
||||
|
||||
import de.svencarstensen.muh.service.InvoiceService;
|
||||
import de.svencarstensen.muh.security.SecuritySupport;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/admin")
|
||||
public class InvoiceController {
|
||||
|
||||
private final InvoiceService invoiceService;
|
||||
private final SecuritySupport securitySupport;
|
||||
|
||||
public InvoiceController(InvoiceService invoiceService, SecuritySupport securitySupport) {
|
||||
this.invoiceService = invoiceService;
|
||||
this.securitySupport = securitySupport;
|
||||
}
|
||||
|
||||
@GetMapping("/customers/primary")
|
||||
public List<InvoiceService.CustomerDto> listPrimaryCustomers() {
|
||||
return invoiceService.listPrimaryCustomers();
|
||||
}
|
||||
|
||||
@GetMapping("/customers/{customerId}/invoice-data")
|
||||
public ResponseEntity<?> getInvoiceData(@PathVariable String customerId) {
|
||||
try {
|
||||
InvoiceService.InvoiceData data = invoiceService.getInvoiceData(
|
||||
securitySupport.currentUser().id(),
|
||||
customerId
|
||||
);
|
||||
return ResponseEntity.ok(data);
|
||||
} catch (ResponseStatusException e) {
|
||||
return ResponseEntity.status(e.getStatusCode()).body(Map.of("message", e.getReason()));
|
||||
} catch (Exception e) {
|
||||
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
.body(Map.of("message", "Fehler beim Erstellen der Rechnung: " + e.getMessage()));
|
||||
}
|
||||
}
|
||||
|
||||
@GetMapping("/invoices")
|
||||
public InvoiceOverview getInvoices() {
|
||||
// Mock implementation - returns empty list for now
|
||||
return new InvoiceOverview(List.of());
|
||||
}
|
||||
|
||||
public record InvoiceOverview(List<InvoiceSummary> invoices) {
|
||||
}
|
||||
|
||||
public record InvoiceSummary(
|
||||
String id,
|
||||
String invoiceNumber,
|
||||
String customerName,
|
||||
String invoiceDate,
|
||||
String dueDate,
|
||||
double totalAmount,
|
||||
String status
|
||||
) {
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package de.svencarstensen.muh.web;
|
||||
import de.svencarstensen.muh.service.PortalService;
|
||||
import de.svencarstensen.muh.service.ReportService;
|
||||
import de.svencarstensen.muh.service.SampleService;
|
||||
import de.svencarstensen.muh.security.SecuritySupport;
|
||||
import org.springframework.http.ContentDisposition;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
@@ -26,10 +27,12 @@ public class PortalController {
|
||||
|
||||
private final PortalService portalService;
|
||||
private final ReportService reportService;
|
||||
private final SecuritySupport securitySupport;
|
||||
|
||||
public PortalController(PortalService portalService, ReportService reportService) {
|
||||
public PortalController(PortalService portalService, ReportService reportService, SecuritySupport securitySupport) {
|
||||
this.portalService = portalService;
|
||||
this.reportService = reportService;
|
||||
this.securitySupport = securitySupport;
|
||||
}
|
||||
|
||||
@GetMapping("/snapshot")
|
||||
@@ -40,27 +43,41 @@ public class PortalController {
|
||||
@RequestParam(required = false) Long sampleNumber,
|
||||
@RequestParam(required = false) LocalDate date
|
||||
) {
|
||||
return portalService.snapshot(farmerBusinessKey, farmerQuery, cowQuery, sampleNumber, date);
|
||||
var currentUser = securitySupport.currentUser();
|
||||
return portalService.snapshot(
|
||||
currentUser.role() == de.svencarstensen.muh.domain.UserRole.ADMIN,
|
||||
currentUser.id(),
|
||||
farmerBusinessKey,
|
||||
farmerQuery,
|
||||
cowQuery,
|
||||
sampleNumber,
|
||||
date
|
||||
);
|
||||
}
|
||||
|
||||
@GetMapping("/reports")
|
||||
public List<ReportService.ReportCandidate> reports() {
|
||||
return reportService.reportCandidates();
|
||||
return reportService.reportCandidates(securitySupport.currentUser().id());
|
||||
}
|
||||
|
||||
@GetMapping("/search/by-date")
|
||||
public List<PortalService.PortalSampleRow> searchByDate(@RequestParam LocalDate date) {
|
||||
return portalService.searchSamplesByCreatedDate(securitySupport.currentUser().id(), date);
|
||||
}
|
||||
|
||||
@PostMapping("/reports/send")
|
||||
public ReportService.DispatchResult send(@RequestBody ReportDispatchRequest request) {
|
||||
return reportService.sendReports(request.sampleIds());
|
||||
return reportService.sendReports(securitySupport.currentUser().id(), request.sampleIds());
|
||||
}
|
||||
|
||||
@PatchMapping("/reports/{sampleId}/block")
|
||||
public SampleService.SampleDetail block(@PathVariable String sampleId, @RequestBody BlockRequest request) {
|
||||
return reportService.toggleReportBlocked(sampleId, request.blocked());
|
||||
return reportService.toggleReportBlocked(securitySupport.currentUser().id(), sampleId, request.blocked());
|
||||
}
|
||||
|
||||
@GetMapping("/reports/{sampleId}/pdf")
|
||||
public ResponseEntity<byte[]> pdf(@PathVariable String sampleId) {
|
||||
byte[] pdf = reportService.reportPdf(sampleId);
|
||||
byte[] pdf = reportService.reportPdf(securitySupport.currentUser().id(), sampleId);
|
||||
return ResponseEntity.ok()
|
||||
.contentType(Objects.requireNonNull(MediaType.APPLICATION_PDF))
|
||||
.header(HttpHeaders.CONTENT_DISPOSITION, ContentDisposition.inline()
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
package de.svencarstensen.muh.web;
|
||||
|
||||
import de.svencarstensen.muh.security.AuthenticatedUser;
|
||||
import de.svencarstensen.muh.security.SecuritySupport;
|
||||
import de.svencarstensen.muh.service.SampleService;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
@@ -14,53 +16,82 @@ import org.springframework.web.bind.annotation.RestController;
|
||||
public class SampleController {
|
||||
|
||||
private final SampleService sampleService;
|
||||
private final SecuritySupport securitySupport;
|
||||
|
||||
public SampleController(SampleService sampleService) {
|
||||
public SampleController(SampleService sampleService, SecuritySupport securitySupport) {
|
||||
this.sampleService = sampleService;
|
||||
this.securitySupport = securitySupport;
|
||||
}
|
||||
|
||||
@GetMapping("/dashboard")
|
||||
public SampleService.DashboardOverview dashboardOverview() {
|
||||
return sampleService.dashboardOverview();
|
||||
return sampleService.dashboardOverview(securitySupport.currentUser().id());
|
||||
}
|
||||
|
||||
@GetMapping("/dashboard/lookup/{sampleNumber}")
|
||||
public SampleService.LookupResult lookup(@PathVariable long sampleNumber) {
|
||||
return sampleService.lookup(sampleNumber);
|
||||
return sampleService.lookup(securitySupport.currentUser().id(), sampleNumber);
|
||||
}
|
||||
|
||||
@GetMapping("/samples/{id}")
|
||||
public SampleService.SampleDetail sample(@PathVariable String id) {
|
||||
return sampleService.getSample(id);
|
||||
return sampleService.getSample(securitySupport.currentUser().id(), id);
|
||||
}
|
||||
|
||||
@GetMapping("/samples/by-number/{sampleNumber}")
|
||||
public SampleService.SampleDetail sampleByNumber(@PathVariable long sampleNumber) {
|
||||
return sampleService.getSampleByNumber(sampleNumber);
|
||||
return sampleService.getSampleByNumber(securitySupport.currentUser().id(), sampleNumber);
|
||||
}
|
||||
|
||||
@PostMapping("/samples")
|
||||
public SampleService.SampleDetail create(@RequestBody SampleService.RegistrationRequest request) {
|
||||
return sampleService.createSample(request);
|
||||
AuthenticatedUser user = securitySupport.currentUser();
|
||||
return sampleService.createSample(user.id(), new SampleService.RegistrationRequest(
|
||||
request.farmerBusinessKey(),
|
||||
request.cowNumber(),
|
||||
request.cowName(),
|
||||
request.sampleKind(),
|
||||
request.samplingMode(),
|
||||
request.flaggedQuarters(),
|
||||
deriveUserLabel(user.displayName()),
|
||||
user.displayName(),
|
||||
request.pretreatmentInUdderInjector(),
|
||||
request.pretreatmentSystemicAntibiotics(),
|
||||
request.pretreatmentPainMedication(),
|
||||
request.pretreatmentDryOffTreatment(),
|
||||
request.clinicalExamDate(),
|
||||
request.internalNote()
|
||||
));
|
||||
}
|
||||
|
||||
@PutMapping("/samples/{id}/registration")
|
||||
public SampleService.SampleDetail saveRegistration(@PathVariable String id, @RequestBody SampleService.RegistrationRequest request) {
|
||||
return sampleService.saveRegistration(id, request);
|
||||
return sampleService.saveRegistration(securitySupport.currentUser().id(), id, request);
|
||||
}
|
||||
|
||||
@PutMapping("/samples/{id}/anamnesis")
|
||||
public SampleService.SampleDetail saveAnamnesis(@PathVariable String id, @RequestBody SampleService.AnamnesisRequest request) {
|
||||
return sampleService.saveAnamnesis(id, request);
|
||||
return sampleService.saveAnamnesis(securitySupport.currentUser().id(), id, request);
|
||||
}
|
||||
|
||||
@PutMapping("/samples/{id}/antibiogram")
|
||||
public SampleService.SampleDetail saveAntibiogram(@PathVariable String id, @RequestBody SampleService.AntibiogramRequest request) {
|
||||
return sampleService.saveAntibiogram(id, request);
|
||||
return sampleService.saveAntibiogram(securitySupport.currentUser().id(), id, request);
|
||||
}
|
||||
|
||||
@PutMapping("/samples/{id}/therapy")
|
||||
public SampleService.SampleDetail saveTherapy(@PathVariable String id, @RequestBody SampleService.TherapyRequest request) {
|
||||
return sampleService.saveTherapy(id, request);
|
||||
return sampleService.saveTherapy(securitySupport.currentUser().id(), id, request);
|
||||
}
|
||||
|
||||
private String deriveUserLabel(String displayName) {
|
||||
if (displayName == null || displayName.isBlank()) {
|
||||
return "USR";
|
||||
}
|
||||
String compact = displayName.replaceAll("[^A-Za-z0-9]", "").toUpperCase();
|
||||
if (compact.isBlank()) {
|
||||
return "USR";
|
||||
}
|
||||
return compact.substring(0, Math.min(4, compact.length()));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
package de.svencarstensen.muh.web;
|
||||
|
||||
import de.svencarstensen.muh.service.CatalogService;
|
||||
import de.svencarstensen.muh.service.InvoiceTemplateService;
|
||||
import de.svencarstensen.muh.service.ReportTemplateService;
|
||||
import de.svencarstensen.muh.security.SecuritySupport;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
@@ -15,47 +19,93 @@ import java.util.List;
|
||||
public class SessionController {
|
||||
|
||||
private final CatalogService catalogService;
|
||||
private final InvoiceTemplateService invoiceTemplateService;
|
||||
private final ReportTemplateService reportTemplateService;
|
||||
private final SecuritySupport securitySupport;
|
||||
|
||||
public SessionController(CatalogService catalogService) {
|
||||
public SessionController(
|
||||
CatalogService catalogService,
|
||||
InvoiceTemplateService invoiceTemplateService,
|
||||
ReportTemplateService reportTemplateService,
|
||||
SecuritySupport securitySupport
|
||||
) {
|
||||
this.catalogService = catalogService;
|
||||
this.invoiceTemplateService = invoiceTemplateService;
|
||||
this.reportTemplateService = reportTemplateService;
|
||||
this.securitySupport = securitySupport;
|
||||
}
|
||||
|
||||
@GetMapping("/users")
|
||||
public List<CatalogService.UserOption> activeUsers() {
|
||||
return catalogService.activeCatalogSummary().users();
|
||||
@GetMapping("/me")
|
||||
public CatalogService.UserOption currentUser() {
|
||||
return catalogService.currentUser(securitySupport.currentUser().id());
|
||||
}
|
||||
|
||||
@PostMapping("/login")
|
||||
public CatalogService.UserOption login(@RequestBody LoginRequest request) {
|
||||
return catalogService.loginByCode(request.code());
|
||||
@GetMapping("/invoice-template")
|
||||
public InvoiceTemplateService.InvoiceTemplateResponse currentInvoiceTemplate() {
|
||||
return invoiceTemplateService.currentTemplate(securitySupport.currentUser().id());
|
||||
}
|
||||
|
||||
@GetMapping("/report-template")
|
||||
public InvoiceTemplateService.InvoiceTemplateResponse currentReportTemplate() {
|
||||
return reportTemplateService.currentTemplate(securitySupport.currentUser().id());
|
||||
}
|
||||
|
||||
@PostMapping("/password-login")
|
||||
public CatalogService.UserOption passwordLogin(@RequestBody PasswordLoginRequest request) {
|
||||
return catalogService.loginWithPassword(request.identifier(), request.password());
|
||||
public CatalogService.SessionResponse passwordLogin(@RequestBody PasswordLoginRequest request) {
|
||||
return catalogService.loginWithPassword(request.email(), request.password());
|
||||
}
|
||||
|
||||
@PostMapping("/register")
|
||||
public CatalogService.UserOption register(@RequestBody RegistrationRequest request) {
|
||||
public CatalogService.RegistrationResponse register(@RequestBody RegistrationRequest request) {
|
||||
return catalogService.registerCustomer(new CatalogService.RegistrationMutation(
|
||||
request.companyName(),
|
||||
request.address(),
|
||||
request.street(),
|
||||
request.houseNumber(),
|
||||
request.postalCode(),
|
||||
request.city(),
|
||||
request.email(),
|
||||
request.phoneNumber(),
|
||||
request.password()
|
||||
));
|
||||
}
|
||||
|
||||
public record LoginRequest(@NotBlank String code) {
|
||||
@PutMapping("/invoice-template")
|
||||
public InvoiceTemplateService.InvoiceTemplateResponse saveInvoiceTemplate(
|
||||
@RequestBody TemplateRequest request
|
||||
) {
|
||||
return invoiceTemplateService.saveTemplate(
|
||||
securitySupport.currentUser().id(),
|
||||
request.elements()
|
||||
);
|
||||
}
|
||||
|
||||
public record PasswordLoginRequest(@NotBlank String identifier, @NotBlank String password) {
|
||||
@PutMapping("/report-template")
|
||||
public InvoiceTemplateService.InvoiceTemplateResponse saveReportTemplate(
|
||||
@RequestBody TemplateRequest request
|
||||
) {
|
||||
return reportTemplateService.saveTemplate(
|
||||
securitySupport.currentUser().id(),
|
||||
request.elements()
|
||||
);
|
||||
}
|
||||
|
||||
public record PasswordLoginRequest(@NotBlank String email, @NotBlank String password) {
|
||||
}
|
||||
|
||||
public record RegistrationRequest(
|
||||
@NotBlank String companyName,
|
||||
@NotBlank String address,
|
||||
@NotBlank String street,
|
||||
@NotBlank String houseNumber,
|
||||
@NotBlank String postalCode,
|
||||
@NotBlank String city,
|
||||
@NotBlank String email,
|
||||
@NotBlank String phoneNumber,
|
||||
@NotBlank String password
|
||||
) {
|
||||
}
|
||||
|
||||
public record TemplateRequest(
|
||||
List<InvoiceTemplateService.InvoiceTemplateElementPayload> elements
|
||||
) {
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
package de.svencarstensen.muh.web;
|
||||
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
|
||||
@Controller
|
||||
public class SpaForwardController {
|
||||
|
||||
@GetMapping({
|
||||
"/",
|
||||
"/{path:^(?!api$)[^.]+}",
|
||||
"/{path:^(?!api$)[^.]+}/{segment:[^.]+}",
|
||||
"/{path:^(?!api$)[^.]+}/{segment:[^.]+}/{leaf:[^.]+}"
|
||||
})
|
||||
public String forward() {
|
||||
return "forward:/index.html";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package de.svencarstensen.muh.web;
|
||||
|
||||
import de.svencarstensen.muh.domain.SystemPricing;
|
||||
import de.svencarstensen.muh.service.SystemPricingService;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/admin/pricing")
|
||||
public class SystemPricingController {
|
||||
|
||||
private final SystemPricingService systemPricingService;
|
||||
|
||||
public SystemPricingController(SystemPricingService systemPricingService) {
|
||||
this.systemPricingService = systemPricingService;
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
@PreAuthorize("hasRole('ADMIN')")
|
||||
public PricingResponse getPricing() {
|
||||
Optional<SystemPricing> pricing = systemPricingService.getCurrentPricing();
|
||||
return pricing.map(p -> new PricingResponse(p.monthlyPrice(), p.updatedAt().toString()))
|
||||
.orElseGet(() -> new PricingResponse(null, null));
|
||||
}
|
||||
|
||||
@GetMapping("/current")
|
||||
@PreAuthorize("isAuthenticated()")
|
||||
public PricingResponse getCurrentPricing() {
|
||||
Optional<SystemPricing> pricing = systemPricingService.getCurrentPricing();
|
||||
return pricing.map(p -> new PricingResponse(p.monthlyPrice(), p.updatedAt().toString()))
|
||||
.orElseGet(() -> new PricingResponse(null, null));
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
@PreAuthorize("hasRole('ADMIN')")
|
||||
public PricingResponse savePricing(@RequestBody PricingRequest request) {
|
||||
SystemPricing saved = systemPricingService.savePricing(request.monthlyPrice());
|
||||
return new PricingResponse(saved.monthlyPrice(), saved.updatedAt().toString());
|
||||
}
|
||||
|
||||
public record PricingRequest(Double monthlyPrice) {
|
||||
}
|
||||
|
||||
public record PricingResponse(Double monthlyPrice, String updatedAt) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package de.svencarstensen.muh.web.dto;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public record AdminStatistics(
|
||||
long totalVets,
|
||||
long totalSamples,
|
||||
List<VetSampleStats> samplesPerVet
|
||||
) {
|
||||
public record VetSampleStats(
|
||||
String userId,
|
||||
String displayName,
|
||||
String companyName,
|
||||
long sampleCount
|
||||
) {
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,18 @@
|
||||
server:
|
||||
port: 8090
|
||||
error:
|
||||
include-message: always
|
||||
|
||||
spring:
|
||||
config:
|
||||
import:
|
||||
- optional:file:./.env[.properties]
|
||||
- optional:file:../.env[.properties]
|
||||
application:
|
||||
name: muh-backend
|
||||
data:
|
||||
mongodb:
|
||||
uri: mongodb://192.168.180.25:27017/muh
|
||||
uri: ${MUH_MONGODB_URL:mongodb://192.168.180.25:27017/muh}
|
||||
jackson:
|
||||
time-zone: Europe/Berlin
|
||||
mail:
|
||||
@@ -14,16 +20,28 @@ spring:
|
||||
port: ${MUH_MAIL_PORT:587}
|
||||
username: ${MUH_MAIL_USERNAME:}
|
||||
password: ${MUH_MAIL_PASSWORD:}
|
||||
protocol: ${MUH_MAIL_PROTOCOL:smtp}
|
||||
properties:
|
||||
mail:
|
||||
transport:
|
||||
protocol: ${MUH_MAIL_PROTOCOL:smtp}
|
||||
smtp:
|
||||
auth: ${MUH_MAIL_AUTH:false}
|
||||
starttls:
|
||||
enable: ${MUH_MAIL_STARTTLS:false}
|
||||
|
||||
muh:
|
||||
app:
|
||||
version: '@project.version@'
|
||||
cors:
|
||||
allowed-origins: ${MUH_ALLOWED_ORIGINS:http://localhost:5173,http://localhost:3000}
|
||||
security:
|
||||
token-secret: ${MUH_TOKEN_SECRET:}
|
||||
token-validity-hours: ${MUH_TOKEN_VALIDITY_HOURS:12}
|
||||
mongodb:
|
||||
url: ${MUH_MONGODB_URL:mongodb://192.168.180.25:27017/muh}
|
||||
username: ${MUH_MONGODB_USERNAME:}
|
||||
password: ${MUH_MONGODB_PASSWORD:}
|
||||
mail:
|
||||
enabled: ${MUH_MAIL_ENABLED:false}
|
||||
from: ${MUH_MAIL_FROM:no-reply@muh.local}
|
||||
|
||||
39
backend/src/main/resources/mail/report-mail-template.txt
Normal file
39
backend/src/main/resources/mail/report-mail-template.txt
Normal file
@@ -0,0 +1,39 @@
|
||||
Anbei finden Sie die Milchprobenauswertung Nr. {{sampleNumber}} fuer Ihre Kuh {{cowLabel}}.
|
||||
|
||||
Dies ist eine automatisch generierte E-Mail von einer System-E-Mail-Adresse, bitte nicht antworten.
|
||||
|
||||
Mit freundlichen Gruessen
|
||||
|
||||
{{customerSignature}}
|
||||
|
||||
|
||||
Liste der Handelsnamen und Wirkstoffe
|
||||
|
||||
|
||||
Laktation
|
||||
|
||||
Penicillin: Mastinject, Revozyn RTU, Penicillin Injektoren, Ingel Mamyzin
|
||||
Amoxicillin Clavulansaeure: Synulox RTU/LC, Noroclav
|
||||
Sulfadoxin Trimetoprim: Diatrim, Sulphix
|
||||
Lincomycin Neomycin: Albiotic
|
||||
Tylosin: Pharmasin
|
||||
Cefquinom: Cobactan
|
||||
Cefoperacon: Peracef
|
||||
Enrofloxacin: Powerflox
|
||||
Cefalexin/Kanamycin: Ubrolexin
|
||||
Ampicillin/Cloxacillin: Gelstamp
|
||||
|
||||
|
||||
Trockensteher
|
||||
|
||||
Framycetin: Benestermycin
|
||||
Cefalonium: Cepravin
|
||||
Penicillin: Mastinject, Revozyn RTU, Penicillin Injektoren, Naphpenzal T
|
||||
Cloxacillin: Orbenin und Cloxacillin
|
||||
Amoxicillin Clavulansaeure: Synulox RTU/LC
|
||||
Sulfadoxin Trimetoprim: Diatrim
|
||||
Lincomycin Neomycin: Albiotic
|
||||
Tylosin: Pharmasin
|
||||
Cefquinom: Cobactan
|
||||
Cefoperacon: Peracef
|
||||
Enrofloxacin: Powerflox
|
||||
73
docker_push.sh
Executable file
73
docker_push.sh
Executable file
@@ -0,0 +1,73 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
readonly SCRIPT_DIR="$(CDPATH= cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
|
||||
readonly REGISTRY_IMAGE="registry.assecutor.org/muh"
|
||||
readonly POM_FILE="${SCRIPT_DIR}/backend/pom.xml"
|
||||
|
||||
usage() {
|
||||
cat <<'EOF'
|
||||
Verwendung:
|
||||
./docker_push.sh [x.y.z]
|
||||
|
||||
Beispiel:
|
||||
./docker_push.sh 0.9.13
|
||||
./docker_push.sh
|
||||
|
||||
Voraussetzungen:
|
||||
- Docker Buildx ist installiert
|
||||
- Login zur Registry wurde bereits ausgeführt:
|
||||
docker login registry.assecutor.org
|
||||
|
||||
Ohne Versionsargument wird automatisch die Version aus backend/pom.xml verwendet.
|
||||
Optional kann VITE_API_URL als Umgebungsvariable gesetzt werden.
|
||||
EOF
|
||||
}
|
||||
|
||||
fail() {
|
||||
echo "Fehler: $*" >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
require_command() {
|
||||
command -v "$1" >/dev/null 2>&1 || fail "'$1' wurde nicht gefunden."
|
||||
}
|
||||
|
||||
resolve_app_version() {
|
||||
[[ -f "${POM_FILE}" ]] || fail "'${POM_FILE}' wurde nicht gefunden."
|
||||
|
||||
local version
|
||||
version="$(sed -n '/<parent>/,/<\/parent>/!{ s/.*<version>\(.*\)<\/version>.*/\1/p; }' "${POM_FILE}" | head -1)"
|
||||
|
||||
[[ -n "${version}" ]] || fail "Version konnte nicht aus ${POM_FILE} ermittelt werden."
|
||||
[[ "${version}" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] || fail "Version in ${POM_FILE} muss das Format x.y.z haben."
|
||||
echo "${version}"
|
||||
}
|
||||
|
||||
VERSION="${1:-$(resolve_app_version)}"
|
||||
|
||||
if [[ "${VERSION}" == "-h" || "${VERSION}" == "--help" ]]; then
|
||||
usage
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if [[ ! "${VERSION}" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
|
||||
fail "Versionsnummer muss das Format x.y.z haben."
|
||||
fi
|
||||
|
||||
require_command docker
|
||||
docker buildx version >/dev/null 2>&1 || fail "Docker Buildx ist nicht verfügbar."
|
||||
|
||||
cd "${SCRIPT_DIR}"
|
||||
|
||||
echo "Verwende Release-Version ${VERSION}."
|
||||
echo "Pushe Image ${REGISTRY_IMAGE}:${VERSION} ..."
|
||||
docker buildx build \
|
||||
--platform linux/amd64 \
|
||||
--build-arg "VITE_API_URL=${VITE_API_URL:-/api}" \
|
||||
-t "${REGISTRY_IMAGE}:${VERSION}" \
|
||||
--push \
|
||||
.
|
||||
|
||||
echo "Fertig: ${REGISTRY_IMAGE}:${VERSION}"
|
||||
30
frontend/package-lock.json
generated
30
frontend/package-lock.json
generated
@@ -8,7 +8,9 @@
|
||||
"name": "muh-frontend",
|
||||
"version": "0.0.1",
|
||||
"dependencies": {
|
||||
"chart.js": "^4.5.1",
|
||||
"react": "18.2.0",
|
||||
"react-chartjs-2": "^5.3.1",
|
||||
"react-dom": "18.2.0",
|
||||
"react-router-dom": "6.23.1"
|
||||
},
|
||||
@@ -745,6 +747,12 @@
|
||||
"@jridgewell/sourcemap-codec": "^1.4.14"
|
||||
}
|
||||
},
|
||||
"node_modules/@kurkle/color": {
|
||||
"version": "0.3.4",
|
||||
"resolved": "https://registry.npmjs.org/@kurkle/color/-/color-0.3.4.tgz",
|
||||
"integrity": "sha512-M5UknZPHRu3DEDWoipU6sE8PdkZ6Z/S+v4dD+Ke8IaNlpdSQah50lz1KtcFBa2vsdOnwbbnxJwVM4wty6udA5w==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@remix-run/router": {
|
||||
"version": "1.16.1",
|
||||
"resolved": "https://registry.npmjs.org/@remix-run/router/-/router-1.16.1.tgz",
|
||||
@@ -1290,6 +1298,18 @@
|
||||
],
|
||||
"license": "CC-BY-4.0"
|
||||
},
|
||||
"node_modules/chart.js": {
|
||||
"version": "4.5.1",
|
||||
"resolved": "https://registry.npmjs.org/chart.js/-/chart.js-4.5.1.tgz",
|
||||
"integrity": "sha512-GIjfiT9dbmHRiYi6Nl2yFCq7kkwdkp1W/lp2J99rX0yo9tgJGn3lKQATztIjb5tVtevcBtIdICNWqlq5+E8/Pw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@kurkle/color": "^0.3.0"
|
||||
},
|
||||
"engines": {
|
||||
"pnpm": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/convert-source-map": {
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz",
|
||||
@@ -1538,6 +1558,16 @@
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/react-chartjs-2": {
|
||||
"version": "5.3.1",
|
||||
"resolved": "https://registry.npmjs.org/react-chartjs-2/-/react-chartjs-2-5.3.1.tgz",
|
||||
"integrity": "sha512-h5IPXKg9EXpjoBzUfyWJvllMjG2mQ4EiuHQFhms/AjUm0XSZHhyRy2xVmLXHKrtcdrPO4mnGqRtYoD0vp95A0A==",
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"chart.js": "^4.1.1",
|
||||
"react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/react-dom": {
|
||||
"version": "18.2.0",
|
||||
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.2.0.tgz",
|
||||
|
||||
@@ -9,7 +9,9 @@
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"chart.js": "^4.5.1",
|
||||
"react": "18.2.0",
|
||||
"react-chartjs-2": "^5.3.1",
|
||||
"react-dom": "18.2.0",
|
||||
"react-router-dom": "6.23.1"
|
||||
},
|
||||
|
||||
@@ -2,6 +2,7 @@ import { Navigate, Route, Routes } from "react-router-dom";
|
||||
import { SessionProvider, useSession } from "./lib/session";
|
||||
import AppShell from "./layout/AppShell";
|
||||
import HomePage from "./pages/HomePage";
|
||||
import AdminDashboardPage from "./pages/AdminDashboardPage";
|
||||
import LoginPage from "./pages/LoginPage";
|
||||
import SampleRegistrationPage from "./pages/SampleRegistrationPage";
|
||||
import AnamnesisPage from "./pages/AnamnesisPage";
|
||||
@@ -9,9 +10,23 @@ import AntibiogramPage from "./pages/AntibiogramPage";
|
||||
import TherapyPage from "./pages/TherapyPage";
|
||||
import AdministrationPage from "./pages/AdministrationPage";
|
||||
import PortalPage from "./pages/PortalPage";
|
||||
import SearchPage from "./pages/SearchPage";
|
||||
import SearchFarmerPage from "./pages/SearchFarmerPage";
|
||||
import SearchCalendarPage from "./pages/SearchCalendarPage";
|
||||
import UserManagementPage from "./pages/UserManagementPage";
|
||||
import ReportTemplatePage from "./pages/ReportTemplatePage";
|
||||
import InvoiceTemplatePage from "./pages/InvoiceTemplatePage";
|
||||
import InvoiceManagementPage from "./pages/InvoiceManagementPage";
|
||||
import PricingPage from "./pages/PricingPage";
|
||||
import AdminProfilePage from "./pages/AdminProfilePage";
|
||||
|
||||
function ProtectedRoutes() {
|
||||
const { user } = useSession();
|
||||
const { user, ready } = useSession();
|
||||
const isAdmin = user?.role === "ADMIN";
|
||||
|
||||
if (!ready) {
|
||||
return <div className="empty-state">Sitzung wird geladen ...</div>;
|
||||
}
|
||||
|
||||
if (!user) {
|
||||
return <Navigate to="/" replace />;
|
||||
@@ -20,13 +35,28 @@ function ProtectedRoutes() {
|
||||
return (
|
||||
<Routes>
|
||||
<Route element={<AppShell />}>
|
||||
<Route path="/home" element={<HomePage />} />
|
||||
<Route path="/home" element={isAdmin ? <AdminDashboardPage /> : <HomePage />} />
|
||||
<Route path="/admin/dashboard" element={<AdminDashboardPage />} />
|
||||
<Route path="/samples/new" element={<SampleRegistrationPage />} />
|
||||
<Route path="/samples/:sampleId/registration" element={<SampleRegistrationPage />} />
|
||||
<Route path="/samples/:sampleId/anamnesis" element={<AnamnesisPage />} />
|
||||
<Route path="/samples/:sampleId/antibiogram" element={<AntibiogramPage />} />
|
||||
<Route path="/samples/:sampleId/therapy" element={<TherapyPage />} />
|
||||
<Route path="/admin" element={<AdministrationPage />} />
|
||||
<Route path="/report-template" element={<ReportTemplatePage />} />
|
||||
<Route path="/admin" element={<Navigate to={isAdmin ? "/admin/landwirte" : "/admin/benutzer"} replace />} />
|
||||
<Route path="/admin/benutzer" element={<UserManagementPage />} />
|
||||
<Route path="/admin/landwirte" element={<AdministrationPage />} />
|
||||
<Route path="/admin/medikamente" element={<AdministrationPage />} />
|
||||
<Route path="/admin/erreger" element={<AdministrationPage />} />
|
||||
<Route path="/admin/antibiogramm" element={<AdministrationPage />} />
|
||||
<Route path="/admin/stammdaten" element={<AdminProfilePage />} />
|
||||
<Route path="/admin/preistabelle" element={<PricingPage />} />
|
||||
<Route path="/admin/rechnung/verwalten" element={<InvoiceManagementPage />} />
|
||||
<Route path="/admin/rechnung/template" element={<InvoiceTemplatePage />} />
|
||||
<Route path="/search" element={<Navigate to="/search/probe" replace />} />
|
||||
<Route path="/search/probe" element={<SearchPage />} />
|
||||
<Route path="/search/landwirt" element={<SearchFarmerPage />} />
|
||||
<Route path="/search/kalendar" element={<SearchCalendarPage />} />
|
||||
<Route path="/portal" element={<PortalPage />} />
|
||||
</Route>
|
||||
<Route path="*" element={<Navigate to="/home" replace />} />
|
||||
@@ -35,7 +65,10 @@ function ProtectedRoutes() {
|
||||
}
|
||||
|
||||
function ApplicationRouter() {
|
||||
const { user } = useSession();
|
||||
const { user, ready } = useSession();
|
||||
if (!ready) {
|
||||
return <div className="empty-state">Sitzung wird geladen ...</div>;
|
||||
}
|
||||
if (!user) {
|
||||
return (
|
||||
<Routes>
|
||||
|
||||
79
frontend/src/components/SampleSearchResultsSection.tsx
Normal file
79
frontend/src/components/SampleSearchResultsSection.tsx
Normal file
@@ -0,0 +1,79 @@
|
||||
import type { PortalSampleRow } from "../lib/types";
|
||||
|
||||
function formatDate(value: string | null) {
|
||||
if (!value) {
|
||||
return "-";
|
||||
}
|
||||
return new Intl.DateTimeFormat("de-DE", {
|
||||
dateStyle: "medium",
|
||||
timeStyle: "short",
|
||||
}).format(new Date(value));
|
||||
}
|
||||
|
||||
type SampleSearchResultsSectionProps = {
|
||||
eyebrow: string;
|
||||
title: string;
|
||||
emptyText: string;
|
||||
samples: PortalSampleRow[];
|
||||
onOpen: (sampleNumber: number) => void;
|
||||
};
|
||||
|
||||
export default function SampleSearchResultsSection({
|
||||
eyebrow,
|
||||
title,
|
||||
emptyText,
|
||||
samples,
|
||||
onOpen,
|
||||
}: SampleSearchResultsSectionProps) {
|
||||
return (
|
||||
<section className="section-card">
|
||||
<div className="section-card__header">
|
||||
<div>
|
||||
<p className="eyebrow">{eyebrow}</p>
|
||||
<h3>{title}</h3>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{!samples.length ? (
|
||||
<div className="empty-state">{emptyText}</div>
|
||||
) : (
|
||||
<div className="table-shell">
|
||||
<table className="data-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Probe</th>
|
||||
<th>Erfasst</th>
|
||||
<th>Landwirt</th>
|
||||
<th>Kuh</th>
|
||||
<th>Typ</th>
|
||||
<th>Interne Bemerkung</th>
|
||||
<th />
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{samples.map((sample) => (
|
||||
<tr key={sample.sampleId}>
|
||||
<td>{sample.sampleNumber}</td>
|
||||
<td>{formatDate(sample.createdAt)}</td>
|
||||
<td>{sample.farmerName}</td>
|
||||
<td>{sample.cowNumber}{sample.cowName ? ` / ${sample.cowName}` : ""}</td>
|
||||
<td>{sample.sampleKindLabel === "DRY_OFF" ? "Trockensteller" : "Milchprobe"}</td>
|
||||
<td>{sample.internalNote ?? "-"}</td>
|
||||
<td>
|
||||
<button
|
||||
type="button"
|
||||
className="table-link"
|
||||
onClick={() => onOpen(sample.sampleNumber)}
|
||||
>
|
||||
Oeffnen
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
2
frontend/src/globals.d.ts
vendored
2
frontend/src/globals.d.ts
vendored
@@ -1 +1,3 @@
|
||||
declare const __APP_VERSION__: string;
|
||||
|
||||
interface Worker {}
|
||||
|
||||
@@ -1,21 +1,19 @@
|
||||
import { NavLink, Outlet, useLocation, useNavigate } from "react-router-dom";
|
||||
import { useSession } from "../lib/session";
|
||||
|
||||
const NAV_ITEMS = [
|
||||
{ to: "/home", label: "Start" },
|
||||
{ to: "/samples/new", label: "Neue Probe" },
|
||||
{ to: "/admin", label: "Verwaltung" },
|
||||
{ to: "/portal", label: "Portal" },
|
||||
];
|
||||
|
||||
const PAGE_TITLES: Record<string, string> = {
|
||||
"/home": "Startseite",
|
||||
"/admin/dashboard": "Admin Dashboard",
|
||||
"/samples/new": "Neuanlage einer Probe",
|
||||
"/admin": "Verwaltung",
|
||||
"/portal": "MUH-Portal",
|
||||
"/report-template": "Bericht",
|
||||
"/admin/stammdaten": "Meine Stammdaten",
|
||||
"/admin/preistabelle": "Preistabelle",
|
||||
"/admin/rechnung/verwalten": "Rechnungsverwaltung",
|
||||
"/admin/rechnung/template": "Rechnungsvorlage",
|
||||
};
|
||||
|
||||
function resolvePageTitle(pathname: string) {
|
||||
function resolvePageTitle(pathname: string, isAdmin: boolean) {
|
||||
if (pathname.includes("/anamnesis")) {
|
||||
return "Anamnese";
|
||||
}
|
||||
@@ -28,11 +26,14 @@ function resolvePageTitle(pathname: string) {
|
||||
if (pathname.includes("/registration")) {
|
||||
return "Probe bearbeiten";
|
||||
}
|
||||
if (pathname.startsWith("/admin/benutzer")) {
|
||||
return isAdmin ? "Benutzerfreigabe" : "Verwaltung | Benutzer";
|
||||
}
|
||||
return PAGE_TITLES[pathname] ?? "MUH App";
|
||||
}
|
||||
|
||||
export default function AppShell() {
|
||||
const { user, setUser } = useSession();
|
||||
const { user, setSession } = useSession();
|
||||
const location = useLocation();
|
||||
const navigate = useNavigate();
|
||||
|
||||
@@ -40,31 +41,126 @@ export default function AppShell() {
|
||||
<div className="app-shell">
|
||||
<aside className="sidebar">
|
||||
<div className="sidebar__brand">
|
||||
<div className="sidebar__logo">MUH</div>
|
||||
<div className="sidebar__logo">
|
||||
MUH <span className="sidebar__version">({__APP_VERSION__})</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<nav className="sidebar__nav">
|
||||
{NAV_ITEMS.map((item) => (
|
||||
<NavLink
|
||||
key={item.to}
|
||||
to={item.to}
|
||||
className={({ isActive }) => `nav-link ${isActive ? "is-active" : ""}`}
|
||||
>
|
||||
{item.label}
|
||||
</NavLink>
|
||||
))}
|
||||
{user?.role === "ADMIN" ? (
|
||||
<>
|
||||
<NavLink
|
||||
to="/admin/dashboard"
|
||||
className={({ isActive }) => `nav-link ${isActive ? "is-active" : ""}`}
|
||||
>
|
||||
Dashboard
|
||||
</NavLink>
|
||||
|
||||
<div className="nav-group">
|
||||
<div className="nav-group__label">Benutzerverwaltung</div>
|
||||
<div className="nav-subnav">
|
||||
<NavLink to="/admin/benutzer" className={({ isActive }) => `nav-sublink ${isActive ? "is-active" : ""}`}>
|
||||
Freigabe / Sperre
|
||||
</NavLink>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<NavLink
|
||||
to="/admin/stammdaten"
|
||||
className={({ isActive }) => `nav-link ${isActive ? "is-active" : ""}`}
|
||||
>
|
||||
Stammdaten
|
||||
</NavLink>
|
||||
|
||||
<NavLink
|
||||
to="/admin/preistabelle"
|
||||
className={({ isActive }) => `nav-link ${isActive ? "is-active" : ""}`}
|
||||
>
|
||||
Preistabelle
|
||||
</NavLink>
|
||||
|
||||
<div className="nav-group">
|
||||
<div className="nav-group__label">Rechnung</div>
|
||||
<div className="nav-subnav">
|
||||
<NavLink to="/admin/rechnung/verwalten" className={({ isActive }) => `nav-sublink ${isActive ? "is-active" : ""}`}>
|
||||
Verwalten
|
||||
</NavLink>
|
||||
<NavLink to="/admin/rechnung/template" className={({ isActive }) => `nav-sublink ${isActive ? "is-active" : ""}`}>
|
||||
Template
|
||||
</NavLink>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<NavLink to="/home" className={({ isActive }) => `nav-link ${isActive ? "is-active" : ""}`}>
|
||||
Start
|
||||
</NavLink>
|
||||
<NavLink to="/samples/new" className={({ isActive }) => `nav-link ${isActive ? "is-active" : ""}`}>
|
||||
Neue Probe
|
||||
</NavLink>
|
||||
|
||||
<div className="nav-group">
|
||||
<div className="nav-group__label">Verwaltung</div>
|
||||
<div className="nav-subnav">
|
||||
<div className="nav-subgroup">
|
||||
<div className="nav-subgroup__label">Vorlagen</div>
|
||||
<div className="nav-subnav nav-subnav--nested">
|
||||
<NavLink to="/report-template" className={({ isActive }) => `nav-sublink ${isActive ? "is-active" : ""}`}>
|
||||
Bericht
|
||||
</NavLink>
|
||||
</div>
|
||||
</div>
|
||||
<NavLink to="/admin/landwirte" className={({ isActive }) => `nav-sublink ${isActive ? "is-active" : ""}`}>
|
||||
Landwirte
|
||||
</NavLink>
|
||||
<NavLink to="/admin/medikamente" className={({ isActive }) => `nav-sublink ${isActive ? "is-active" : ""}`}>
|
||||
Medikamente
|
||||
</NavLink>
|
||||
<NavLink to="/admin/erreger" className={({ isActive }) => `nav-sublink ${isActive ? "is-active" : ""}`}>
|
||||
Erreger
|
||||
</NavLink>
|
||||
<NavLink to="/admin/antibiogramm" className={({ isActive }) => `nav-sublink ${isActive ? "is-active" : ""}`}>
|
||||
Antibiogramm
|
||||
</NavLink>
|
||||
<NavLink to="/admin/benutzer" className={({ isActive }) => `nav-sublink ${isActive ? "is-active" : ""}`}>
|
||||
Benutzer
|
||||
</NavLink>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="nav-group">
|
||||
<div className="nav-group__label">Suche</div>
|
||||
<div className="nav-subnav">
|
||||
<NavLink to="/search/landwirt" className={({ isActive }) => `nav-sublink ${isActive ? "is-active" : ""}`}>
|
||||
Landwirt
|
||||
</NavLink>
|
||||
<NavLink to="/search/probe" className={({ isActive }) => `nav-sublink ${isActive ? "is-active" : ""}`}>
|
||||
Probe
|
||||
</NavLink>
|
||||
<NavLink to="/search/kalendar" className={({ isActive }) => `nav-sublink ${isActive ? "is-active" : ""}`}>
|
||||
Kalendar
|
||||
</NavLink>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<NavLink to="/portal" className={({ isActive }) => `nav-link ${isActive ? "is-active" : ""}`}>
|
||||
Portal
|
||||
</NavLink>
|
||||
</>
|
||||
)}
|
||||
</nav>
|
||||
|
||||
<div className="sidebar__footer">
|
||||
<div className="user-chip user-chip--stacked">
|
||||
<span>{user?.displayName}</span>
|
||||
<small>{user?.code}</small>
|
||||
<small>{user?.email ?? user?.role}</small>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className="ghost-button"
|
||||
onClick={() => {
|
||||
setUser(null);
|
||||
setSession(null);
|
||||
navigate("/");
|
||||
}}
|
||||
>
|
||||
@@ -76,13 +172,7 @@ export default function AppShell() {
|
||||
<div className="shell-main">
|
||||
<header className="topbar">
|
||||
<div className="topbar__headline">
|
||||
<h2>{resolvePageTitle(location.pathname)}</h2>
|
||||
</div>
|
||||
|
||||
<div className="topbar__actions">
|
||||
<button type="button" className="accent-button" onClick={() => navigate("/samples/new")}>
|
||||
Neuanlage
|
||||
</button>
|
||||
<h2>{resolvePageTitle(location.pathname, user?.role === "ADMIN")}</h2>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
|
||||
@@ -1,25 +1,87 @@
|
||||
const API_ROOT = import.meta.env.VITE_API_URL ?? "http://localhost:8090/api";
|
||||
import { AUTH_TOKEN_STORAGE_KEY } from "./storage";
|
||||
|
||||
const API_ROOT = import.meta.env.VITE_API_URL ?? (import.meta.env.DEV ? "http://localhost:8090/api" : "/api");
|
||||
|
||||
export class ApiError extends Error {
|
||||
status: number;
|
||||
|
||||
constructor(message: string, status: number) {
|
||||
super(message);
|
||||
this.name = "ApiError";
|
||||
this.status = status;
|
||||
}
|
||||
}
|
||||
|
||||
type ApiErrorPayload = {
|
||||
message?: string;
|
||||
error?: string;
|
||||
detail?: string;
|
||||
};
|
||||
|
||||
async function readErrorMessage(response: Response): Promise<string> {
|
||||
const contentType = response.headers.get("content-type") ?? "";
|
||||
|
||||
if (contentType.includes("application/json")) {
|
||||
const payload = (await response.json()) as ApiErrorPayload;
|
||||
const message = payload.message?.trim() || payload.detail?.trim();
|
||||
if (message) {
|
||||
return message;
|
||||
}
|
||||
if (payload.error?.trim()) {
|
||||
return `Anfrage fehlgeschlagen: ${payload.error.trim()}`;
|
||||
}
|
||||
}
|
||||
|
||||
const text = (await response.text()).trim();
|
||||
if (text) {
|
||||
return text;
|
||||
}
|
||||
|
||||
return `Anfrage fehlgeschlagen (${response.status})`;
|
||||
}
|
||||
|
||||
function authHeaders(): Record<string, string> {
|
||||
if (typeof window === "undefined") {
|
||||
return {};
|
||||
}
|
||||
|
||||
const token = window.localStorage.getItem(AUTH_TOKEN_STORAGE_KEY);
|
||||
if (!token) {
|
||||
return {};
|
||||
}
|
||||
return { Authorization: `Bearer ${token}` };
|
||||
}
|
||||
|
||||
async function handleResponse<T>(response: Response): Promise<T> {
|
||||
if (!response.ok) {
|
||||
const text = await response.text();
|
||||
throw new Error(text || "Unbekannter API-Fehler");
|
||||
throw new ApiError(await readErrorMessage(response), response.status);
|
||||
}
|
||||
if (response.status === 204) {
|
||||
return undefined as T;
|
||||
}
|
||||
return (await response.json()) as T;
|
||||
const text = await response.text();
|
||||
if (!text.trim()) {
|
||||
return undefined as T;
|
||||
}
|
||||
return JSON.parse(text) as T;
|
||||
}
|
||||
|
||||
export async function apiGet<T>(path: string): Promise<T> {
|
||||
return handleResponse<T>(await fetch(`${API_ROOT}${path}`));
|
||||
return handleResponse<T>(
|
||||
await fetch(`${API_ROOT}${path}`, {
|
||||
headers: authHeaders(),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export async function apiPost<T>(path: string, body: unknown): Promise<T> {
|
||||
return handleResponse<T>(
|
||||
await fetch(`${API_ROOT}${path}`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
...authHeaders(),
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
}),
|
||||
);
|
||||
@@ -29,7 +91,10 @@ export async function apiPut<T>(path: string, body: unknown): Promise<T> {
|
||||
return handleResponse<T>(
|
||||
await fetch(`${API_ROOT}${path}`, {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
...authHeaders(),
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
}),
|
||||
);
|
||||
@@ -39,7 +104,10 @@ export async function apiPatch<T>(path: string, body: unknown): Promise<T> {
|
||||
return handleResponse<T>(
|
||||
await fetch(`${API_ROOT}${path}`, {
|
||||
method: "PATCH",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
...authHeaders(),
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
}),
|
||||
);
|
||||
@@ -49,6 +117,7 @@ export async function apiDelete(path: string): Promise<void> {
|
||||
await handleResponse<void>(
|
||||
await fetch(`${API_ROOT}${path}`, {
|
||||
method: "DELETE",
|
||||
headers: authHeaders(),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -6,17 +6,22 @@ import {
|
||||
useState,
|
||||
type PropsWithChildren,
|
||||
} from "react";
|
||||
import { USER_STORAGE_KEY } from "./storage";
|
||||
import type { UserOption } from "./types";
|
||||
import { apiGet } from "./api";
|
||||
import { AUTH_TOKEN_STORAGE_KEY, USER_STORAGE_KEY } from "./storage";
|
||||
import type { SessionResponse, UserOption } from "./types";
|
||||
|
||||
interface SessionContextValue {
|
||||
user: UserOption | null;
|
||||
setUser: (user: UserOption | null) => void;
|
||||
ready: boolean;
|
||||
setSession: (session: SessionResponse | null) => void;
|
||||
updateUser: (user: UserOption) => void;
|
||||
}
|
||||
|
||||
const SessionContext = createContext<SessionContextValue>({
|
||||
user: null,
|
||||
setUser: () => undefined,
|
||||
ready: false,
|
||||
setSession: () => undefined,
|
||||
updateUser: () => undefined,
|
||||
});
|
||||
|
||||
function loadStoredUser(): UserOption | null {
|
||||
@@ -33,6 +38,39 @@ function loadStoredUser(): UserOption | null {
|
||||
|
||||
export function SessionProvider({ children }: PropsWithChildren) {
|
||||
const [user, setUserState] = useState<UserOption | null>(() => loadStoredUser());
|
||||
const [ready, setReady] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
const token = window.localStorage.getItem(AUTH_TOKEN_STORAGE_KEY);
|
||||
if (!token) {
|
||||
setReady(true);
|
||||
return;
|
||||
}
|
||||
|
||||
let cancelled = false;
|
||||
void apiGet<UserOption>("/session/me")
|
||||
.then((currentUser) => {
|
||||
if (!cancelled) {
|
||||
setUserState(currentUser);
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
if (!cancelled) {
|
||||
window.localStorage.removeItem(AUTH_TOKEN_STORAGE_KEY);
|
||||
window.localStorage.removeItem(USER_STORAGE_KEY);
|
||||
setUserState(null);
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
if (!cancelled) {
|
||||
setReady(true);
|
||||
}
|
||||
});
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (user) {
|
||||
@@ -42,12 +80,31 @@ export function SessionProvider({ children }: PropsWithChildren) {
|
||||
window.localStorage.removeItem(USER_STORAGE_KEY);
|
||||
}, [user]);
|
||||
|
||||
function setSession(session: SessionResponse | null) {
|
||||
if (session) {
|
||||
window.localStorage.setItem(AUTH_TOKEN_STORAGE_KEY, session.token);
|
||||
setUserState(session.user);
|
||||
setReady(true);
|
||||
return;
|
||||
}
|
||||
window.localStorage.removeItem(AUTH_TOKEN_STORAGE_KEY);
|
||||
window.localStorage.removeItem(USER_STORAGE_KEY);
|
||||
setUserState(null);
|
||||
setReady(true);
|
||||
}
|
||||
|
||||
function updateUser(updatedUser: UserOption) {
|
||||
setUserState(updatedUser);
|
||||
}
|
||||
|
||||
const value = useMemo(
|
||||
() => ({
|
||||
user,
|
||||
setUser: setUserState,
|
||||
ready,
|
||||
setSession,
|
||||
updateUser,
|
||||
}),
|
||||
[user],
|
||||
[ready, user],
|
||||
);
|
||||
|
||||
return <SessionContext.Provider value={value}>{children}</SessionContext.Provider>;
|
||||
|
||||
@@ -1 +1,2 @@
|
||||
export const USER_STORAGE_KEY = "muh.current-user";
|
||||
export const AUTH_TOKEN_STORAGE_KEY = "muh.auth-token";
|
||||
|
||||
@@ -9,6 +9,13 @@ export type QuarterKey =
|
||||
| "LEFT_REAR"
|
||||
| "RIGHT_REAR";
|
||||
export type PathogenKind = "BACTERIAL" | "NO_GROWTH" | "CONTAMINATED" | "OTHER";
|
||||
|
||||
export interface Pretreatment {
|
||||
inUdderInjector: string | null;
|
||||
systemicAntibiotics: string | null;
|
||||
painMedication: string | null;
|
||||
dryOffTreatment: string | null;
|
||||
}
|
||||
export type SensitivityResult = "SENSITIVE" | "INTERMEDIATE" | "RESISTANT";
|
||||
export type MedicationCategory =
|
||||
| "IN_UDDER"
|
||||
@@ -16,11 +23,12 @@ export type MedicationCategory =
|
||||
| "SYSTEMIC_PAIN"
|
||||
| "DRY_SEALER"
|
||||
| "DRY_ANTIBIOTIC";
|
||||
export type UserRole = "APP" | "ADMIN" | "CUSTOMER";
|
||||
export type UserRole = "ADMIN" | "CUSTOMER";
|
||||
|
||||
export interface FarmerOption {
|
||||
businessKey: string;
|
||||
name: string;
|
||||
companyName: string;
|
||||
contactPerson: string | null;
|
||||
email: string | null;
|
||||
}
|
||||
|
||||
@@ -45,13 +53,27 @@ export interface AntibioticOption {
|
||||
|
||||
export interface UserOption {
|
||||
id: string;
|
||||
code: string;
|
||||
primaryUser: boolean;
|
||||
displayName: string;
|
||||
companyName: string | null;
|
||||
address: string | null;
|
||||
street: string | null;
|
||||
houseNumber: string | null;
|
||||
postalCode: string | null;
|
||||
city: string | null;
|
||||
email: string | null;
|
||||
portalLogin: string | null;
|
||||
phoneNumber: string | null;
|
||||
accountHolder: string | null;
|
||||
bankName: string | null;
|
||||
iban: string | null;
|
||||
bic: string | null;
|
||||
role: UserRole;
|
||||
customerNumber: string | null;
|
||||
}
|
||||
|
||||
export interface SessionResponse {
|
||||
token: string;
|
||||
user: UserOption;
|
||||
}
|
||||
|
||||
export interface UserRow extends UserOption {
|
||||
@@ -136,6 +158,14 @@ export interface TherapyView {
|
||||
dryAntibioticNames: string[];
|
||||
farmerNote: string | null;
|
||||
internalNote: string | null;
|
||||
inUdderCount: string | null;
|
||||
inUdderDuration: string | null;
|
||||
systemicCount: string | null;
|
||||
systemicDuration: string | null;
|
||||
systemicDosage: string | null;
|
||||
systemicLocation: string | null;
|
||||
startvacVaccination: boolean | null;
|
||||
noAntibioticTreatment: boolean | null;
|
||||
}
|
||||
|
||||
export interface SampleDetail {
|
||||
@@ -167,13 +197,23 @@ export interface SampleDetail {
|
||||
antibiogramEditable: boolean;
|
||||
therapyEditable: boolean;
|
||||
completed: boolean;
|
||||
pretreatment: Pretreatment | null;
|
||||
clinicalExamDate: string | null;
|
||||
internalNote: string | null;
|
||||
}
|
||||
|
||||
export interface FarmerRow {
|
||||
id: string;
|
||||
businessKey: string;
|
||||
name: string;
|
||||
customerNumber: string | null;
|
||||
companyName: string;
|
||||
contactPerson: string | null;
|
||||
street: string | null;
|
||||
houseNumber: string | null;
|
||||
postalCode: string | null;
|
||||
city: string | null;
|
||||
email: string | null;
|
||||
phoneNumber: string | null;
|
||||
active: boolean;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
201
frontend/src/pages/AdminDashboardPage.tsx
Normal file
201
frontend/src/pages/AdminDashboardPage.tsx
Normal file
@@ -0,0 +1,201 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import {
|
||||
Chart as ChartJS,
|
||||
CategoryScale,
|
||||
LinearScale,
|
||||
BarElement,
|
||||
Title,
|
||||
Tooltip,
|
||||
Legend,
|
||||
type TooltipItem,
|
||||
} from "chart.js";
|
||||
import { Bar } from "react-chartjs-2";
|
||||
import { apiGet } from "../lib/api";
|
||||
|
||||
// Chart.js Komponenten registrieren
|
||||
ChartJS.register(
|
||||
CategoryScale,
|
||||
LinearScale,
|
||||
BarElement,
|
||||
Title,
|
||||
Tooltip,
|
||||
Legend
|
||||
);
|
||||
|
||||
interface VetSampleStats {
|
||||
userId: string;
|
||||
displayName: string;
|
||||
companyName: string | null;
|
||||
sampleCount: number;
|
||||
}
|
||||
|
||||
interface AdminStatistics {
|
||||
totalVets: number;
|
||||
totalSamples: number;
|
||||
samplesPerVet: VetSampleStats[];
|
||||
}
|
||||
|
||||
export default function AdminDashboardPage() {
|
||||
const [stats, setStats] = useState<AdminStatistics | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
async function loadStats() {
|
||||
try {
|
||||
const response = await apiGet<AdminStatistics>("/admin/statistics");
|
||||
setStats(response);
|
||||
} catch (err) {
|
||||
setError((err as Error).message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
void loadStats();
|
||||
}, []);
|
||||
|
||||
// Chart Daten vorbereiten
|
||||
const chartData = {
|
||||
labels: stats?.samplesPerVet.map((vet) => vet.displayName) || [],
|
||||
datasets: [
|
||||
{
|
||||
label: "Anzahl Proben",
|
||||
data: stats?.samplesPerVet.map((vet) => vet.sampleCount) || [],
|
||||
backgroundColor: "rgba(90, 123, 168, 0.8)",
|
||||
borderColor: "rgba(90, 123, 168, 1)",
|
||||
borderWidth: 1,
|
||||
borderRadius: 8,
|
||||
borderSkipped: false,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const chartOptions = {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
plugins: {
|
||||
legend: {
|
||||
display: false,
|
||||
},
|
||||
title: {
|
||||
display: true,
|
||||
text: "Proben pro Tierarzt",
|
||||
font: {
|
||||
size: 16,
|
||||
weight: "bold" as const,
|
||||
},
|
||||
padding: {
|
||||
top: 10,
|
||||
bottom: 20,
|
||||
},
|
||||
color: "#1d2428",
|
||||
},
|
||||
tooltip: {
|
||||
backgroundColor: "rgba(29, 36, 40, 0.9)",
|
||||
padding: 12,
|
||||
cornerRadius: 8,
|
||||
titleFont: {
|
||||
size: 14,
|
||||
},
|
||||
bodyFont: {
|
||||
size: 13,
|
||||
},
|
||||
callbacks: {
|
||||
label: (context: TooltipItem<"bar">) => {
|
||||
const value = context.parsed.y as number | null;
|
||||
return `${value ?? 0} Proben`;
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
scales: {
|
||||
y: {
|
||||
beginAtZero: true,
|
||||
ticks: {
|
||||
stepSize: 1,
|
||||
color: "#666",
|
||||
},
|
||||
grid: {
|
||||
color: "rgba(0, 0, 0, 0.05)",
|
||||
},
|
||||
title: {
|
||||
display: true,
|
||||
text: "Anzahl Proben",
|
||||
color: "#666",
|
||||
font: {
|
||||
size: 12,
|
||||
},
|
||||
},
|
||||
},
|
||||
x: {
|
||||
ticks: {
|
||||
color: "#666",
|
||||
maxRotation: 45,
|
||||
minRotation: 45,
|
||||
},
|
||||
grid: {
|
||||
display: false,
|
||||
},
|
||||
title: {
|
||||
display: true,
|
||||
text: "Tierarzt",
|
||||
color: "#666",
|
||||
font: {
|
||||
size: 12,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="page-stack">
|
||||
{/* Header Bereich */}
|
||||
<section className="hero-card admin-hero">
|
||||
<div>
|
||||
<p className="eyebrow">Administration</p>
|
||||
<h3>Administrator Dashboard</h3>
|
||||
<p className="muted-text">
|
||||
Übersicht über Tierärzte und Proben im System.
|
||||
</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{error ? (
|
||||
<div className="alert alert--error">{error}</div>
|
||||
) : null}
|
||||
|
||||
{/* Statistik-Karten */}
|
||||
<section className="metrics-grid admin-metrics">
|
||||
<article className="metric-card metric-card--primary">
|
||||
<span className="metric-card__label">Tierärzte</span>
|
||||
<strong className="metric-card__value--large">
|
||||
{loading ? "..." : stats?.totalVets ?? 0}
|
||||
</strong>
|
||||
</article>
|
||||
<article className="metric-card metric-card--secondary">
|
||||
<span className="metric-card__label">Proben insgesamt</span>
|
||||
<strong className="metric-card__value--large">
|
||||
{loading ? "..." : stats?.totalSamples ?? 0}
|
||||
</strong>
|
||||
</article>
|
||||
</section>
|
||||
|
||||
{/* Chart Bereich */}
|
||||
<section className="section-card">
|
||||
<div className="chart-container">
|
||||
{loading ? (
|
||||
<div className="empty-state">Chart wird geladen...</div>
|
||||
) : stats?.samplesPerVet.length === 0 ? (
|
||||
<div className="empty-state">Noch keine Proben vorhanden.</div>
|
||||
) : (
|
||||
<Bar data={chartData} options={chartOptions} />
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
|
||||
</div>
|
||||
);
|
||||
}
|
||||
365
frontend/src/pages/AdminProfilePage.tsx
Normal file
365
frontend/src/pages/AdminProfilePage.tsx
Normal file
@@ -0,0 +1,365 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { apiGet, apiPost } from "../lib/api";
|
||||
import { useSession } from "../lib/session";
|
||||
import type { UserRow } from "../lib/types";
|
||||
|
||||
export default function AdminProfilePage() {
|
||||
const { user, updateUser } = useSession();
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [message, setMessage] = useState<string | null>(null);
|
||||
|
||||
const [formData, setFormData] = useState({
|
||||
displayName: "",
|
||||
companyName: "",
|
||||
street: "",
|
||||
houseNumber: "",
|
||||
postalCode: "",
|
||||
city: "",
|
||||
email: "",
|
||||
phoneNumber: "",
|
||||
accountHolder: "",
|
||||
bankName: "",
|
||||
iban: "",
|
||||
bic: "",
|
||||
});
|
||||
|
||||
// Load current user data
|
||||
useEffect(() => {
|
||||
async function loadUserData() {
|
||||
try {
|
||||
const users = await apiGet<UserRow[]>("/portal/users");
|
||||
const currentUser = users.find((u) => u.id === user?.id);
|
||||
if (currentUser) {
|
||||
setFormData({
|
||||
displayName: currentUser.displayName || "",
|
||||
companyName: currentUser.companyName || "",
|
||||
street: currentUser.street || "",
|
||||
houseNumber: currentUser.houseNumber || "",
|
||||
postalCode: currentUser.postalCode || "",
|
||||
city: currentUser.city || "",
|
||||
email: currentUser.email || "",
|
||||
phoneNumber: currentUser.phoneNumber || "",
|
||||
accountHolder: currentUser.accountHolder || "",
|
||||
bankName: currentUser.bankName || "",
|
||||
iban: currentUser.iban || "",
|
||||
bic: currentUser.bic || "",
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
setMessage((error as Error).message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (user?.id) {
|
||||
void loadUserData();
|
||||
}
|
||||
}, [user?.id]);
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
|
||||
if (!formData.displayName.trim()) {
|
||||
setMessage("Name ist erforderlich.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!formData.email.trim()) {
|
||||
setMessage("E-Mail ist erforderlich.");
|
||||
return;
|
||||
}
|
||||
|
||||
setSaving(true);
|
||||
setMessage(null);
|
||||
|
||||
try {
|
||||
const response = await apiPost<UserRow>("/portal/users", {
|
||||
id: user?.id,
|
||||
displayName: formData.displayName.trim(),
|
||||
companyName: formData.companyName.trim() || null,
|
||||
street: formData.street.trim() || null,
|
||||
houseNumber: formData.houseNumber.trim() || null,
|
||||
postalCode: formData.postalCode.trim() || null,
|
||||
city: formData.city.trim() || null,
|
||||
email: formData.email.trim(),
|
||||
phoneNumber: formData.phoneNumber.trim() || null,
|
||||
accountHolder: formData.accountHolder.trim() || null,
|
||||
bankName: formData.bankName.trim() || null,
|
||||
iban: formData.iban.trim() || null,
|
||||
bic: formData.bic.trim() || null,
|
||||
active: true,
|
||||
});
|
||||
|
||||
// Update session user
|
||||
if (updateUser && user) {
|
||||
updateUser({
|
||||
...user,
|
||||
displayName: response.displayName,
|
||||
companyName: response.companyName,
|
||||
street: response.street,
|
||||
houseNumber: response.houseNumber,
|
||||
postalCode: response.postalCode,
|
||||
city: response.city,
|
||||
email: response.email,
|
||||
phoneNumber: response.phoneNumber,
|
||||
accountHolder: response.accountHolder,
|
||||
bankName: response.bankName,
|
||||
iban: response.iban,
|
||||
bic: response.bic,
|
||||
});
|
||||
}
|
||||
|
||||
setMessage("Stammdaten wurden erfolgreich gespeichert.");
|
||||
setTimeout(() => setMessage(null), 3000);
|
||||
} catch (error) {
|
||||
setMessage((error as Error).message);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="page-stack">
|
||||
<section className="section-card">
|
||||
<div className="empty-state">Stammdaten werden geladen...</div>
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="page-stack">
|
||||
{/* Header */}
|
||||
<section className="hero-card admin-hero">
|
||||
<div>
|
||||
<p className="eyebrow">Stammdaten</p>
|
||||
<h3>Meine Stammdaten</h3>
|
||||
<p className="muted-text">
|
||||
Verwalten Sie hier Ihre persönlichen, Unternehmens- und Bankdaten.
|
||||
</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Status-Meldung */}
|
||||
{message && (
|
||||
<div
|
||||
className={
|
||||
message.includes("erfolgreich")
|
||||
? "alert alert--success"
|
||||
: "alert alert--error"
|
||||
}
|
||||
>
|
||||
{message}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Persönliche Daten */}
|
||||
<section className="section-card">
|
||||
<div className="section-card__header">
|
||||
<div>
|
||||
<p className="eyebrow">Profil</p>
|
||||
<h3>Persönliche Daten</h3>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleSubmit} className="field-grid field-grid--2col">
|
||||
<label className="field">
|
||||
<span>Name *</span>
|
||||
<input
|
||||
type="text"
|
||||
value={formData.displayName}
|
||||
onChange={(e) =>
|
||||
setFormData({ ...formData, displayName: e.target.value })
|
||||
}
|
||||
placeholder="Ihr Name"
|
||||
required
|
||||
disabled={saving}
|
||||
/>
|
||||
</label>
|
||||
|
||||
<label className="field">
|
||||
<span>Firma</span>
|
||||
<input
|
||||
type="text"
|
||||
value={formData.companyName}
|
||||
onChange={(e) =>
|
||||
setFormData({ ...formData, companyName: e.target.value })
|
||||
}
|
||||
placeholder="Firmenname"
|
||||
disabled={saving}
|
||||
/>
|
||||
</label>
|
||||
|
||||
<label className="field">
|
||||
<span>Straße</span>
|
||||
<input
|
||||
type="text"
|
||||
value={formData.street}
|
||||
onChange={(e) =>
|
||||
setFormData({ ...formData, street: e.target.value })
|
||||
}
|
||||
placeholder="Straße"
|
||||
disabled={saving}
|
||||
/>
|
||||
</label>
|
||||
|
||||
<label className="field">
|
||||
<span>Hausnummer</span>
|
||||
<input
|
||||
type="text"
|
||||
value={formData.houseNumber}
|
||||
onChange={(e) =>
|
||||
setFormData({ ...formData, houseNumber: e.target.value })
|
||||
}
|
||||
placeholder="Hausnummer"
|
||||
disabled={saving}
|
||||
/>
|
||||
</label>
|
||||
|
||||
<label className="field">
|
||||
<span>PLZ</span>
|
||||
<input
|
||||
type="text"
|
||||
value={formData.postalCode}
|
||||
onChange={(e) =>
|
||||
setFormData({ ...formData, postalCode: e.target.value })
|
||||
}
|
||||
placeholder="Postleitzahl"
|
||||
disabled={saving}
|
||||
/>
|
||||
</label>
|
||||
|
||||
<label className="field">
|
||||
<span>Ort</span>
|
||||
<input
|
||||
type="text"
|
||||
value={formData.city}
|
||||
onChange={(e) =>
|
||||
setFormData({ ...formData, city: e.target.value })
|
||||
}
|
||||
placeholder="Ort"
|
||||
disabled={saving}
|
||||
/>
|
||||
</label>
|
||||
|
||||
<label className="field">
|
||||
<span>E-Mail *</span>
|
||||
<input
|
||||
type="email"
|
||||
value={formData.email}
|
||||
onChange={(e) =>
|
||||
setFormData({ ...formData, email: e.target.value })
|
||||
}
|
||||
placeholder="email@beispiel.de"
|
||||
required
|
||||
disabled={saving}
|
||||
/>
|
||||
</label>
|
||||
|
||||
<label className="field">
|
||||
<span>Telefon</span>
|
||||
<input
|
||||
type="tel"
|
||||
value={formData.phoneNumber}
|
||||
onChange={(e) =>
|
||||
setFormData({ ...formData, phoneNumber: e.target.value })
|
||||
}
|
||||
placeholder="Telefonnummer"
|
||||
disabled={saving}
|
||||
/>
|
||||
</label>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
{/* Bankverbindung */}
|
||||
<section className="section-card">
|
||||
<div className="section-card__header">
|
||||
<div>
|
||||
<p className="eyebrow">Zahlung</p>
|
||||
<h3>Bankverbindung</h3>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="field-grid field-grid--2col">
|
||||
<label className="field">
|
||||
<span>Kontoinhaber</span>
|
||||
<input
|
||||
type="text"
|
||||
value={formData.accountHolder}
|
||||
onChange={(e) =>
|
||||
setFormData({ ...formData, accountHolder: e.target.value })
|
||||
}
|
||||
placeholder="Name des Kontoinhabers"
|
||||
disabled={saving}
|
||||
/>
|
||||
</label>
|
||||
|
||||
<label className="field">
|
||||
<span>Bankname</span>
|
||||
<input
|
||||
type="text"
|
||||
value={formData.bankName}
|
||||
onChange={(e) =>
|
||||
setFormData({ ...formData, bankName: e.target.value })
|
||||
}
|
||||
placeholder="Name der Bank"
|
||||
disabled={saving}
|
||||
/>
|
||||
</label>
|
||||
|
||||
<label className="field">
|
||||
<span>IBAN</span>
|
||||
<input
|
||||
type="text"
|
||||
value={formData.iban}
|
||||
onChange={(e) =>
|
||||
setFormData({ ...formData, iban: e.target.value })
|
||||
}
|
||||
placeholder="DE12 3456 7890 1234 5678 90"
|
||||
disabled={saving}
|
||||
/>
|
||||
</label>
|
||||
|
||||
<label className="field">
|
||||
<span>BIC</span>
|
||||
<input
|
||||
type="text"
|
||||
value={formData.bic}
|
||||
onChange={(e) =>
|
||||
setFormData({ ...formData, bic: e.target.value })
|
||||
}
|
||||
placeholder="ABCDEFGHXXX"
|
||||
disabled={saving}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div className="field" style={{ marginTop: "1rem" }}>
|
||||
<button
|
||||
type="button"
|
||||
className="accent-button"
|
||||
onClick={handleSubmit}
|
||||
disabled={saving}
|
||||
>
|
||||
{saving ? "Wird gespeichert..." : "Stammdaten speichern"}
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Info-Box */}
|
||||
<section className="section-card">
|
||||
<div className="info-panel">
|
||||
<strong>Hinweis</strong>
|
||||
<p>
|
||||
Ihre Stammdaten werden für die Rechnungsstellung und
|
||||
Kommunikation verwendet. Stellen Sie sicher, dass die
|
||||
Daten aktuell und vollständig sind.
|
||||
</p>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,12 +1,13 @@
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { useNavigate, useParams } from "react-router-dom";
|
||||
import { apiGet, apiPut } from "../lib/api";
|
||||
import type { ActiveCatalogSummary, QuarterKey, QuarterView, SampleDetail } from "../lib/types";
|
||||
import type { ActiveCatalogSummary, PathogenKind, QuarterKey, QuarterView, SampleDetail } from "../lib/types";
|
||||
|
||||
type QuarterFormState = {
|
||||
pathogenBusinessKey: string;
|
||||
customPathogenName: string;
|
||||
cellCount: string;
|
||||
pathogenKind: PathogenKind | null;
|
||||
};
|
||||
|
||||
function quarterStateFromSample(sample: SampleDetail) {
|
||||
@@ -15,11 +16,18 @@ function quarterStateFromSample(sample: SampleDetail) {
|
||||
pathogenBusinessKey: quarter.pathogenBusinessKey ?? "",
|
||||
customPathogenName: quarter.customPathogenName ?? "",
|
||||
cellCount: quarter.cellCount ? String(quarter.cellCount) : "",
|
||||
pathogenKind: quarter.pathogenKind,
|
||||
};
|
||||
return accumulator;
|
||||
}, {});
|
||||
}
|
||||
|
||||
// Special pathogen options like in Lua
|
||||
const SPECIAL_PATHOGENS = [
|
||||
{ key: "NO_GROWTH", label: "Kein bakterielles Wachstum", kind: "NO_GROWTH" as PathogenKind },
|
||||
{ key: "CONTAMINATED", label: "Verunreinigte Probe", kind: "CONTAMINATED" as PathogenKind },
|
||||
];
|
||||
|
||||
export default function AnamnesisPage() {
|
||||
const { sampleId } = useParams();
|
||||
const navigate = useNavigate();
|
||||
@@ -30,6 +38,7 @@ export default function AnamnesisPage() {
|
||||
const [activeQuarter, setActiveQuarter] = useState<QuarterKey | null>(null);
|
||||
const [message, setMessage] = useState<string | null>(null);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [showValidation, setShowValidation] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
async function load() {
|
||||
@@ -70,10 +79,36 @@ export default function AnamnesisPage() {
|
||||
}));
|
||||
}
|
||||
|
||||
function quarterHasPathogen(quarterKey: QuarterKey) {
|
||||
const quarterState = quarterStates[quarterKey];
|
||||
return Boolean(quarterState?.pathogenBusinessKey || quarterState?.customPathogenName?.trim());
|
||||
}
|
||||
|
||||
function selectSpecialPathogen(quarterKey: QuarterKey, kind: PathogenKind) {
|
||||
updateQuarter(quarterKey, {
|
||||
pathogenBusinessKey: "",
|
||||
customPathogenName: "",
|
||||
pathogenKind: kind,
|
||||
});
|
||||
}
|
||||
|
||||
function isSpecialPathogenSelected(quarterKey: QuarterKey, kind: PathogenKind) {
|
||||
return quarterStates[quarterKey]?.pathogenKind === kind &&
|
||||
!quarterStates[quarterKey]?.pathogenBusinessKey &&
|
||||
!quarterStates[quarterKey]?.customPathogenName;
|
||||
}
|
||||
|
||||
async function handleSave() {
|
||||
if (!sampleId || !sample) {
|
||||
return;
|
||||
}
|
||||
setShowValidation(true);
|
||||
const missingQuarter = sample.quarters.find((quarter) => !quarterHasPathogen(quarter.quarterKey));
|
||||
if (missingQuarter) {
|
||||
setActiveQuarter(missingQuarter.quarterKey);
|
||||
setMessage("Bitte fuer jede Entnahmestelle einen Erreger auswaehlen oder eingeben.");
|
||||
return;
|
||||
}
|
||||
setSaving(true);
|
||||
setMessage(null);
|
||||
|
||||
@@ -104,6 +139,7 @@ export default function AnamnesisPage() {
|
||||
pathogenBusinessKey: "",
|
||||
customPathogenName: "",
|
||||
cellCount: "",
|
||||
pathogenKind: null,
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -134,11 +170,13 @@ export default function AnamnesisPage() {
|
||||
<button
|
||||
key={quarter.quarterKey}
|
||||
type="button"
|
||||
className={`tab-chip ${activeQuarter === quarter.quarterKey ? "is-active" : ""}`}
|
||||
className={`tab-chip ${activeQuarter === quarter.quarterKey ? "is-active" : ""} ${
|
||||
showValidation && !quarterHasPathogen(quarter.quarterKey) ? "is-invalid" : ""
|
||||
}`}
|
||||
onClick={() => setActiveQuarter(quarter.quarterKey)}
|
||||
>
|
||||
{quarter.label}
|
||||
{quarter.flagged ? " ⚠" : ""}
|
||||
{quarter.flagged ? " Auffällig" : ""}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
@@ -153,7 +191,26 @@ export default function AnamnesisPage() {
|
||||
<div className="info-chip">Auffaelliges Viertel markiert</div>
|
||||
) : null}
|
||||
|
||||
{/* Special pathogen options like in Lua */}
|
||||
<p className="required-label">Sonderfaelle</p>
|
||||
<div className="pathogen-grid">
|
||||
{SPECIAL_PATHOGENS.map((pathogen) => (
|
||||
<button
|
||||
key={pathogen.key}
|
||||
type="button"
|
||||
className={`pathogen-button ${
|
||||
isSpecialPathogenSelected(visibleQuarter.quarterKey, pathogen.kind) ? "is-selected" : ""
|
||||
}`}
|
||||
onClick={() => selectSpecialPathogen(visibleQuarter.quarterKey, pathogen.kind)}
|
||||
disabled={!sample.anamnesisEditable}
|
||||
>
|
||||
<strong>{pathogen.label}</strong>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<p className="required-label section-card__spacer">Erreger (Katalog)</p>
|
||||
<div className={`pathogen-grid ${showValidation && !quarterHasPathogen(visibleQuarter.quarterKey) ? "is-invalid" : ""}`}>
|
||||
{catalogs.pathogens.map((pathogen) => (
|
||||
<button
|
||||
key={pathogen.businessKey}
|
||||
@@ -165,24 +222,26 @@ export default function AnamnesisPage() {
|
||||
updateQuarter(visibleQuarter.quarterKey, {
|
||||
pathogenBusinessKey: pathogen.businessKey,
|
||||
customPathogenName: "",
|
||||
pathogenKind: null,
|
||||
})
|
||||
}
|
||||
disabled={!sample.anamnesisEditable}
|
||||
>
|
||||
<strong>{pathogen.name}</strong>
|
||||
<small>{pathogen.code ?? pathogen.kind}</small>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<label className="field">
|
||||
<label className="field field--required field--spaced">
|
||||
<span>Erreger manuell eingeben</span>
|
||||
<input
|
||||
className={showValidation && !quarterHasPathogen(visibleQuarter.quarterKey) ? "is-invalid" : ""}
|
||||
value={state.customPathogenName}
|
||||
onChange={(event) =>
|
||||
updateQuarter(visibleQuarter.quarterKey, {
|
||||
customPathogenName: event.target.value,
|
||||
pathogenBusinessKey: "",
|
||||
pathogenKind: null,
|
||||
})
|
||||
}
|
||||
disabled={!sample.anamnesisEditable}
|
||||
@@ -202,11 +261,11 @@ export default function AnamnesisPage() {
|
||||
/>
|
||||
</label>
|
||||
|
||||
<div className="info-panel">
|
||||
<div className="info-panel info-panel--spaced">
|
||||
<strong>Hinweis</strong>
|
||||
<p>
|
||||
Kein Wachstum oder verunreinigte Proben werden spaeter automatisch vom
|
||||
Antibiogramm ausgeschlossen.
|
||||
Bei "Kein bakterielles Wachstum" oder "Verunreinigte Probe" wird das Antibiogramm
|
||||
übersprungen und direkt zur Therapie weitergeleitet.
|
||||
</p>
|
||||
</div>
|
||||
</article>
|
||||
|
||||
@@ -167,9 +167,9 @@ export default function AntibiogramPage() {
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Antibiotikum</th>
|
||||
<th>S</th>
|
||||
<th>I</th>
|
||||
<th>R</th>
|
||||
<th className="matrix-col">Sensibel</th>
|
||||
<th className="matrix-col">Intermediär</th>
|
||||
<th className="matrix-col">Resistent</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@@ -180,7 +180,7 @@ export default function AntibiogramPage() {
|
||||
<small className="table-subtext">{antibiotic.code ?? "ANT"}</small>
|
||||
</td>
|
||||
{(["SENSITIVE", "INTERMEDIATE", "RESISTANT"] as SensitivityResult[]).map((result) => (
|
||||
<td key={result}>
|
||||
<td key={result} className="matrix-col">
|
||||
<button
|
||||
type="button"
|
||||
className={`matrix-button ${
|
||||
@@ -191,7 +191,7 @@ export default function AntibiogramPage() {
|
||||
onClick={() => updateResult(group.referenceQuarter, antibiotic.businessKey, result)}
|
||||
disabled={!sample.antibiogramEditable}
|
||||
>
|
||||
{result === "SENSITIVE" ? "S" : result === "INTERMEDIATE" ? "I" : "R"}
|
||||
{result === "SENSITIVE" ? "Sensibel" : result === "INTERMEDIATE" ? "Intermediär" : "Resistent"}
|
||||
</button>
|
||||
</td>
|
||||
))}
|
||||
|
||||
@@ -27,6 +27,7 @@ export default function HomePage() {
|
||||
const [sampleNumber, setSampleNumber] = useState("");
|
||||
const [message, setMessage] = useState<string | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [showValidation, setShowValidation] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
async function loadDashboard() {
|
||||
@@ -43,6 +44,7 @@ export default function HomePage() {
|
||||
|
||||
async function handleLookup(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
setShowValidation(true);
|
||||
if (!sampleNumber.trim()) {
|
||||
setMessage("Bitte eine Probennummer eingeben.");
|
||||
return;
|
||||
@@ -72,21 +74,19 @@ export default function HomePage() {
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<form className="hero-card__form" onSubmit={handleLookup}>
|
||||
<label className="field">
|
||||
<form className={`hero-card__form ${showValidation ? "show-validation" : ""}`} onSubmit={handleLookup}>
|
||||
<label className="field field--required">
|
||||
<span>Nummer</span>
|
||||
<input
|
||||
value={sampleNumber}
|
||||
onChange={(event) => setSampleNumber(event.target.value)}
|
||||
placeholder="z. B. 100203"
|
||||
inputMode="numeric"
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
<button type="submit" className="accent-button">
|
||||
Probe oeffnen
|
||||
</button>
|
||||
<button type="button" className="secondary-button" onClick={() => navigate("/samples/new")}>
|
||||
Neuanlage einer Probe
|
||||
Probe öffnen
|
||||
</button>
|
||||
</form>
|
||||
|
||||
@@ -162,7 +162,7 @@ export default function HomePage() {
|
||||
)
|
||||
}
|
||||
>
|
||||
Oeffnen
|
||||
Öffnen
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
640
frontend/src/pages/InvoiceManagementPage.tsx
Normal file
640
frontend/src/pages/InvoiceManagementPage.tsx
Normal file
@@ -0,0 +1,640 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { apiGet } from "../lib/api";
|
||||
import { useSession } from "../lib/session";
|
||||
import type { UserOption } from "../lib/types";
|
||||
import {
|
||||
createDefaultInvoiceStarterLayout,
|
||||
createMuhInvoiceContent,
|
||||
createPdfBlob as createTemplatePdfBlob,
|
||||
normalizeTemplateElements,
|
||||
type TemplateElement,
|
||||
} from "./InvoiceTemplatePage";
|
||||
|
||||
interface InvoiceSummary {
|
||||
id: string;
|
||||
invoiceNumber: string;
|
||||
customerName: string;
|
||||
invoiceDate: string;
|
||||
dueDate: string;
|
||||
totalAmount: number;
|
||||
status: "DRAFT" | "SENT" | "PAID" | "OVERDUE" | "CANCELLED";
|
||||
}
|
||||
|
||||
interface InvoiceOverview {
|
||||
invoices: InvoiceSummary[];
|
||||
}
|
||||
|
||||
interface CustomerDto {
|
||||
id: string;
|
||||
displayName: string;
|
||||
companyName: string | null;
|
||||
street: string | null;
|
||||
houseNumber: string | null;
|
||||
postalCode: string | null;
|
||||
city: string | null;
|
||||
email: string | null;
|
||||
phoneNumber: string | null;
|
||||
accountHolder: string | null;
|
||||
bankName: string | null;
|
||||
iban: string | null;
|
||||
bic: string | null;
|
||||
customerNumber: string | null;
|
||||
}
|
||||
|
||||
interface InvoiceData {
|
||||
invoiceNumber: string;
|
||||
invoiceDate: string;
|
||||
dueDate: string;
|
||||
customer: CustomerDto;
|
||||
templateElements: unknown[];
|
||||
netAmount: number;
|
||||
vatAmount: number;
|
||||
grossAmount: number;
|
||||
monthlyPrice: number;
|
||||
}
|
||||
|
||||
const STATUS_LABELS: Record<InvoiceSummary["status"], string> = {
|
||||
DRAFT: "Entwurf",
|
||||
SENT: "Versendet",
|
||||
PAID: "Bezahlt",
|
||||
OVERDUE: "Überfällig",
|
||||
CANCELLED: "Storniert",
|
||||
};
|
||||
|
||||
const STATUS_CLASSES: Record<InvoiceSummary["status"], string> = {
|
||||
DRAFT: "status-badge--draft",
|
||||
SENT: "status-badge--sent",
|
||||
PAID: "status-badge--success",
|
||||
OVERDUE: "status-badge--error",
|
||||
CANCELLED: "status-badge--neutral",
|
||||
};
|
||||
|
||||
function buildIssuerContact(user: UserOption | null) {
|
||||
const lines: string[] = [];
|
||||
if (user?.phoneNumber) {
|
||||
lines.push(`Tel.: ${user.phoneNumber}`);
|
||||
}
|
||||
if (user?.email) {
|
||||
lines.push(`E-Mail: ${user.email}`);
|
||||
}
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
function buildBankDetails(user: UserOption | null) {
|
||||
const lines = ["Bankverbindung:"];
|
||||
if (user?.accountHolder) {
|
||||
lines.push(`Kontoinhaber: ${user.accountHolder}`);
|
||||
}
|
||||
if (user?.iban) {
|
||||
lines.push(`IBAN: ${user.iban}`);
|
||||
}
|
||||
if (user?.bic) {
|
||||
lines.push(`BIC: ${user.bic}`);
|
||||
}
|
||||
if (user?.bankName) {
|
||||
lines.push(`Bank: ${user.bankName}`);
|
||||
}
|
||||
return lines.join("\n") || "Bankverbindung:";
|
||||
}
|
||||
|
||||
function resolveTemplateContent(
|
||||
element: TemplateElement,
|
||||
invoiceData: InvoiceData,
|
||||
issuer: UserOption | null,
|
||||
) {
|
||||
const customer = invoiceData.customer;
|
||||
|
||||
switch (element.paletteId) {
|
||||
case "issuer-name":
|
||||
return issuer?.companyName ?? issuer?.displayName ?? element.content;
|
||||
case "issuer-street":
|
||||
return issuer?.street ?? "";
|
||||
case "issuer-house-number":
|
||||
return issuer?.houseNumber ?? "";
|
||||
case "issuer-postal-code":
|
||||
return issuer?.postalCode ?? "";
|
||||
case "issuer-city":
|
||||
return issuer?.city ?? "";
|
||||
case "issuer-contact":
|
||||
return buildIssuerContact(issuer);
|
||||
case "invoice-title":
|
||||
return "Rechnung";
|
||||
case "invoice-number":
|
||||
return `Rechnungsnr.: ${invoiceData.invoiceNumber}`;
|
||||
case "invoice-date":
|
||||
return `Datum: ${invoiceData.invoiceDate}`;
|
||||
case "invoice-due-date":
|
||||
return `Fällig bis: ${invoiceData.dueDate}`;
|
||||
case "customer-name":
|
||||
return customer.companyName || customer.displayName;
|
||||
case "customer-street":
|
||||
return customer.street || "";
|
||||
case "customer-house-number":
|
||||
return customer.houseNumber || "";
|
||||
case "customer-postal-code":
|
||||
return customer.postalCode || "";
|
||||
case "customer-city":
|
||||
return customer.city || "";
|
||||
case "customer-email":
|
||||
return customer.email ? `E-Mail: ${customer.email}` : "";
|
||||
case "customer-phone":
|
||||
return customer.phoneNumber ? `Tel.: ${customer.phoneNumber}` : "";
|
||||
case "customer-number":
|
||||
return `Kunden-Nr.: ${customer.customerNumber || "-"}`;
|
||||
case "invoice-items-muh":
|
||||
return createMuhInvoiceContent(invoiceData.monthlyPrice, element.width);
|
||||
case "payment-terms":
|
||||
return "Zahlungsbedingungen: Zahlung innerhalb von 14 Tagen ohne Abzug.";
|
||||
case "bank-details":
|
||||
return buildBankDetails(issuer);
|
||||
default:
|
||||
return element.content;
|
||||
}
|
||||
}
|
||||
|
||||
function buildInvoiceElements(invoiceData: InvoiceData, issuer: UserOption | null) {
|
||||
const storedElements = normalizeTemplateElements(invoiceData.templateElements);
|
||||
const templateElements =
|
||||
storedElements && storedElements.length > 0
|
||||
? storedElements
|
||||
: createDefaultInvoiceStarterLayout(issuer, invoiceData.monthlyPrice);
|
||||
|
||||
return templateElements.map((element) => {
|
||||
if (element.kind !== "text") {
|
||||
return element;
|
||||
}
|
||||
|
||||
return {
|
||||
...element,
|
||||
content: resolveTemplateContent(element, invoiceData, issuer),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function createInvoicePdfBlob(invoiceData: InvoiceData, issuer: UserOption | null) {
|
||||
return createTemplatePdfBlob(buildInvoiceElements(invoiceData, issuer), invoiceData.monthlyPrice);
|
||||
}
|
||||
|
||||
export default function InvoiceManagementPage() {
|
||||
const { user } = useSession();
|
||||
const [invoices, setInvoices] = useState<InvoiceSummary[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
// Dialog states
|
||||
const [showCustomerDialog, setShowCustomerDialog] = useState(false);
|
||||
const [showPdfPreview, setShowPdfPreview] = useState(false);
|
||||
const [customers, setCustomers] = useState<CustomerDto[]>([]);
|
||||
const [selectedCustomerId, setSelectedCustomerId] = useState<string>("");
|
||||
const [invoiceData, setInvoiceData] = useState<InvoiceData | null>(null);
|
||||
const [pdfUrl, setPdfUrl] = useState<string | null>(null);
|
||||
const [isLoadingInvoice, setIsLoadingInvoice] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
apiGet<InvoiceOverview>("/admin/invoices")
|
||||
.then((response) => {
|
||||
if (!cancelled) {
|
||||
setInvoices(response.invoices);
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
if (!cancelled) {
|
||||
setInvoices([]);
|
||||
setError(null);
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
if (!cancelled) {
|
||||
setLoading(false);
|
||||
}
|
||||
});
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, []);
|
||||
|
||||
// Cleanup PDF URL
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (pdfUrl) {
|
||||
URL.revokeObjectURL(pdfUrl);
|
||||
}
|
||||
};
|
||||
}, [pdfUrl]);
|
||||
|
||||
// Handle Escape key for PDF preview
|
||||
useEffect(() => {
|
||||
function handleEscape(event: KeyboardEvent) {
|
||||
if (event.key === "Escape") {
|
||||
setShowPdfPreview(false);
|
||||
}
|
||||
}
|
||||
if (showPdfPreview) {
|
||||
window.addEventListener("keydown", handleEscape);
|
||||
return () => window.removeEventListener("keydown", handleEscape);
|
||||
}
|
||||
}, [showPdfPreview]);
|
||||
|
||||
const formatCurrency = (amount: number) => {
|
||||
return new Intl.NumberFormat("de-DE", {
|
||||
style: "currency",
|
||||
currency: "EUR",
|
||||
}).format(amount);
|
||||
};
|
||||
|
||||
const formatDate = (dateString: string) => {
|
||||
return new Intl.DateTimeFormat("de-DE", {
|
||||
dateStyle: "medium",
|
||||
}).format(new Date(dateString));
|
||||
};
|
||||
|
||||
const handleNewInvoice = async () => {
|
||||
setError(null);
|
||||
try {
|
||||
const customerList = await apiGet<CustomerDto[]>("/admin/customers/primary");
|
||||
setCustomers(customerList);
|
||||
setSelectedCustomerId(customerList[0]?.id || "");
|
||||
setShowCustomerDialog(true);
|
||||
} catch (err) {
|
||||
const errorMessage = err instanceof Error ? err.message : "Unbekannter Fehler";
|
||||
setError(`Kunden konnten nicht geladen werden: ${errorMessage}`);
|
||||
}
|
||||
};
|
||||
|
||||
const handleCreateInvoice = async () => {
|
||||
if (!selectedCustomerId) return;
|
||||
|
||||
setIsLoadingInvoice(true);
|
||||
setError(null);
|
||||
try {
|
||||
const data = await apiGet<InvoiceData>(`/admin/customers/${selectedCustomerId}/invoice-data`);
|
||||
|
||||
if (!data.customer) {
|
||||
throw new Error("Ungültige Rechnungsdaten: Kunde fehlt");
|
||||
}
|
||||
|
||||
setInvoiceData(data);
|
||||
|
||||
if (pdfUrl) {
|
||||
URL.revokeObjectURL(pdfUrl);
|
||||
}
|
||||
|
||||
const pdfBlob = createInvoicePdfBlob(data, user);
|
||||
const url = URL.createObjectURL(pdfBlob);
|
||||
setPdfUrl(url);
|
||||
|
||||
setShowCustomerDialog(false);
|
||||
setShowPdfPreview(true);
|
||||
} catch (err) {
|
||||
const errorMessage = err instanceof Error ? err.message : "Unbekannter Fehler";
|
||||
setError(`Rechnung konnte nicht erstellt werden: ${errorMessage}`);
|
||||
} finally {
|
||||
setIsLoadingInvoice(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleClosePdfPreview = () => {
|
||||
setShowPdfPreview(false);
|
||||
if (pdfUrl) {
|
||||
URL.revokeObjectURL(pdfUrl);
|
||||
setPdfUrl(null);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="page-stack">
|
||||
<section className="section-card section-card--hero">
|
||||
<div>
|
||||
<p className="eyebrow">Rechnungsverwaltung</p>
|
||||
<h3>Übersicht aller Rechnungen</h3>
|
||||
<p className="muted-text">
|
||||
Hier können Sie alle erstellten Rechnungen einsehen, deren Status verfolgen
|
||||
und geplante Rechnungen verwalten.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{error ? <div className="alert alert--error">{error}</div> : null}
|
||||
</section>
|
||||
|
||||
<section className="section-card">
|
||||
<div className="section-card__header">
|
||||
<div>
|
||||
<p className="eyebrow">Rechnungen</p>
|
||||
<h3>Rechnungsliste</h3>
|
||||
</div>
|
||||
<div className="page-actions">
|
||||
<button
|
||||
type="button"
|
||||
className="accent-button"
|
||||
onClick={handleNewInvoice}
|
||||
>
|
||||
Neue Rechnung
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{loading ? (
|
||||
<div className="empty-state">Rechnungen werden geladen...</div>
|
||||
) : invoices.length === 0 ? (
|
||||
<div className="empty-state">
|
||||
<p>Noch keine Rechnungen vorhanden.</p>
|
||||
<p className="muted-text">
|
||||
Erstellen Sie Ihre erste Rechnung mit dem Button "Neue Rechnung".
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="table-shell">
|
||||
<table className="data-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Rechnungsnr.</th>
|
||||
<th>Kunde</th>
|
||||
<th>Rechnungsdatum</th>
|
||||
<th>Fällig am</th>
|
||||
<th>Betrag</th>
|
||||
<th>Status</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{invoices.map((invoice) => (
|
||||
<tr key={invoice.id}>
|
||||
<td>{invoice.invoiceNumber}</td>
|
||||
<td>{invoice.customerName}</td>
|
||||
<td>{formatDate(invoice.invoiceDate)}</td>
|
||||
<td>{formatDate(invoice.dueDate)}</td>
|
||||
<td>{formatCurrency(invoice.totalAmount)}</td>
|
||||
<td>
|
||||
<span className={`status-badge ${STATUS_CLASSES[invoice.status]}`}>
|
||||
{STATUS_LABELS[invoice.status]}
|
||||
</span>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
|
||||
<section className="section-card">
|
||||
<div className="section-card__header">
|
||||
<div>
|
||||
<p className="eyebrow">Zusammenfassung</p>
|
||||
<h3>Statistik</h3>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="table-shell">
|
||||
<table className="data-table">
|
||||
<tbody>
|
||||
<tr>
|
||||
<td style={{ fontWeight: 500 }}>Gesamtrechnungen</td>
|
||||
<td style={{ textAlign: "right" }}>{invoices.length}</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td style={{ fontWeight: 500 }}>Bezahlt</td>
|
||||
<td style={{ textAlign: "right" }}>
|
||||
{invoices.filter((i) => i.status === "PAID").length}
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td style={{ fontWeight: 500 }}>Überfällig</td>
|
||||
<td style={{ textAlign: "right" }}>
|
||||
{invoices.filter((i) => i.status === "OVERDUE").length}
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td style={{ fontWeight: 500 }}>Gesamtumsatz</td>
|
||||
<td style={{ textAlign: "right" }}>
|
||||
{formatCurrency(
|
||||
invoices
|
||||
.filter((i) => i.status === "PAID")
|
||||
.reduce((sum, i) => sum + i.totalAmount, 0)
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Customer Selection Dialog */}
|
||||
{showCustomerDialog && (
|
||||
<div
|
||||
className="modal-overlay"
|
||||
onClick={() => setShowCustomerDialog(false)}
|
||||
style={{
|
||||
position: "fixed",
|
||||
top: 0,
|
||||
left: 0,
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
backgroundColor: "rgba(0, 0, 0, 0.5)",
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
zIndex: 1000,
|
||||
}}
|
||||
>
|
||||
<div
|
||||
className="modal-content"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
style={{
|
||||
backgroundColor: "white",
|
||||
borderRadius: "8px",
|
||||
padding: "24px",
|
||||
width: "100%",
|
||||
maxWidth: "480px",
|
||||
maxHeight: "90vh",
|
||||
overflow: "auto",
|
||||
}}
|
||||
>
|
||||
<h3 style={{ marginTop: 0, marginBottom: "16px" }}>
|
||||
Rechnung erstellen
|
||||
</h3>
|
||||
<p style={{ marginBottom: "20px", color: "#666" }}>
|
||||
Wählen Sie einen Hauptbenutzer aus, für den die Rechnung erstellt werden soll:
|
||||
</p>
|
||||
|
||||
<div style={{ marginBottom: "24px" }}>
|
||||
<label
|
||||
htmlFor="customer-select"
|
||||
style={{
|
||||
display: "block",
|
||||
marginBottom: "8px",
|
||||
fontWeight: 500,
|
||||
fontSize: "14px",
|
||||
}}
|
||||
>
|
||||
Kunde
|
||||
</label>
|
||||
<select
|
||||
id="customer-select"
|
||||
value={selectedCustomerId}
|
||||
onChange={(e) => setSelectedCustomerId(e.target.value)}
|
||||
style={{
|
||||
width: "100%",
|
||||
padding: "10px 12px",
|
||||
borderRadius: "6px",
|
||||
border: "1px solid #d1d5db",
|
||||
fontSize: "14px",
|
||||
backgroundColor: "white",
|
||||
}}
|
||||
>
|
||||
{customers.length === 0 && (
|
||||
<option value="">Keine Kunden verfügbar</option>
|
||||
)}
|
||||
{customers.map((customer) => (
|
||||
<option key={customer.id} value={customer.id}>
|
||||
{customer.companyName || customer.displayName}
|
||||
{customer.customerNumber ? ` (${customer.customerNumber})` : ""}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div style={{ display: "flex", gap: "12px", justifyContent: "flex-end" }}>
|
||||
<button
|
||||
type="button"
|
||||
className="secondary-button"
|
||||
onClick={() => setShowCustomerDialog(false)}
|
||||
style={{
|
||||
padding: "10px 20px",
|
||||
borderRadius: "6px",
|
||||
border: "1px solid #d1d5db",
|
||||
backgroundColor: "white",
|
||||
cursor: "pointer",
|
||||
}}
|
||||
>
|
||||
Abbrechen
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="accent-button"
|
||||
onClick={handleCreateInvoice}
|
||||
disabled={!selectedCustomerId || isLoadingInvoice}
|
||||
style={{
|
||||
padding: "10px 20px",
|
||||
borderRadius: "6px",
|
||||
border: "none",
|
||||
backgroundColor: "var(--primary-600, #2563eb)",
|
||||
color: "white",
|
||||
cursor: !selectedCustomerId || isLoadingInvoice ? "not-allowed" : "pointer",
|
||||
opacity: !selectedCustomerId || isLoadingInvoice ? 0.6 : 1,
|
||||
}}
|
||||
>
|
||||
{isLoadingInvoice ? "Wird erstellt..." : "Rechnung erstellen"}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* PDF Preview Dialog */}
|
||||
{showPdfPreview && pdfUrl && (
|
||||
<div
|
||||
className="modal-overlay"
|
||||
onClick={handleClosePdfPreview}
|
||||
style={{
|
||||
position: "fixed",
|
||||
top: 0,
|
||||
left: 0,
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
backgroundColor: "rgba(0, 0, 0, 0.7)",
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
zIndex: 1000,
|
||||
}}
|
||||
>
|
||||
<div
|
||||
className="modal-content"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
style={{
|
||||
backgroundColor: "white",
|
||||
borderRadius: "8px",
|
||||
width: "95%",
|
||||
maxWidth: "900px",
|
||||
height: "90vh",
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
overflow: "hidden",
|
||||
}}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
padding: "16px 24px",
|
||||
borderBottom: "1px solid #e5e7eb",
|
||||
display: "flex",
|
||||
justifyContent: "space-between",
|
||||
alignItems: "center",
|
||||
}}
|
||||
>
|
||||
<div>
|
||||
<h3 style={{ margin: 0, fontSize: "18px" }}>
|
||||
Rechnungsvorschau
|
||||
</h3>
|
||||
{invoiceData && (
|
||||
<p style={{ margin: "4px 0 0 0", fontSize: "14px", color: "#666" }}>
|
||||
{invoiceData.invoiceNumber} - {invoiceData.customer.companyName || invoiceData.customer.displayName}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<div style={{ display: "flex", gap: "12px" }}>
|
||||
<a
|
||||
href={pdfUrl}
|
||||
download={invoiceData ? `${invoiceData.invoiceNumber}.pdf` : "rechnung.pdf"}
|
||||
style={{
|
||||
padding: "8px 16px",
|
||||
borderRadius: "6px",
|
||||
border: "1px solid #d1d5db",
|
||||
backgroundColor: "white",
|
||||
color: "#374151",
|
||||
textDecoration: "none",
|
||||
fontSize: "14px",
|
||||
cursor: "pointer",
|
||||
}}
|
||||
>
|
||||
Download
|
||||
</a>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleClosePdfPreview}
|
||||
style={{
|
||||
padding: "8px 16px",
|
||||
borderRadius: "6px",
|
||||
border: "none",
|
||||
backgroundColor: "var(--primary-600, #2563eb)",
|
||||
color: "white",
|
||||
fontSize: "14px",
|
||||
cursor: "pointer",
|
||||
}}
|
||||
>
|
||||
Schließen
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style={{ flex: 1, overflow: "auto", backgroundColor: "#f3f4f6" }}>
|
||||
<iframe
|
||||
src={pdfUrl}
|
||||
title="Rechnungsvorschau"
|
||||
style={{
|
||||
width: "100%",
|
||||
height: "100%",
|
||||
border: "none",
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
2673
frontend/src/pages/InvoiceTemplatePage.tsx
Normal file
2673
frontend/src/pages/InvoiceTemplatePage.tsx
Normal file
File diff suppressed because it is too large
Load Diff
@@ -1,7 +1,13 @@
|
||||
import { FormEvent, useEffect, useState } from "react";
|
||||
import { apiGet, apiPost } from "../lib/api";
|
||||
import { FormEvent, useState } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { apiPost } from "../lib/api";
|
||||
import { useSession } from "../lib/session";
|
||||
import type { UserOption } from "../lib/types";
|
||||
import type { SessionResponse } from "../lib/types";
|
||||
|
||||
interface RegistrationResponse {
|
||||
userId: string;
|
||||
email: string;
|
||||
}
|
||||
|
||||
type FeedbackState =
|
||||
| { type: "error"; text: string }
|
||||
@@ -9,59 +15,50 @@ type FeedbackState =
|
||||
| null;
|
||||
|
||||
export default function LoginPage() {
|
||||
const [users, setUsers] = useState<UserOption[]>([]);
|
||||
const [manualCode, setManualCode] = useState("");
|
||||
const [identifier, setIdentifier] = useState("");
|
||||
const [showRegistration, setShowRegistration] = useState(false);
|
||||
const [email, setEmail] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
const [loginInputsUnlocked, setLoginInputsUnlocked] = useState(false);
|
||||
const [showLoginValidation, setShowLoginValidation] = useState(false);
|
||||
const [showRegisterValidation, setShowRegisterValidation] = useState(false);
|
||||
const [registration, setRegistration] = useState({
|
||||
companyName: "",
|
||||
address: "",
|
||||
street: "",
|
||||
houseNumber: "",
|
||||
postalCode: "",
|
||||
city: "",
|
||||
email: "",
|
||||
phoneNumber: "",
|
||||
password: "",
|
||||
passwordConfirmation: "",
|
||||
});
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [feedback, setFeedback] = useState<FeedbackState>(null);
|
||||
const { setUser } = useSession();
|
||||
const { setSession } = useSession();
|
||||
const navigate = useNavigate();
|
||||
|
||||
async function loadUsers() {
|
||||
setLoading(true);
|
||||
setFeedback(null);
|
||||
try {
|
||||
const response = await apiGet<UserOption[]>("/session/users");
|
||||
setUsers(response);
|
||||
} catch (loadError) {
|
||||
setFeedback({ type: "error", text: (loadError as Error).message });
|
||||
setUsers([]);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
void loadUsers();
|
||||
}, []);
|
||||
|
||||
async function handleCodeLogin(code: string) {
|
||||
if (!code.trim()) {
|
||||
setFeedback({ type: "error", text: "Bitte ein Benutzerkuerzel eingeben oder auswaehlen." });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const response = await apiPost<UserOption>("/session/login", { code });
|
||||
setUser(response);
|
||||
} catch (loginError) {
|
||||
setFeedback({ type: "error", text: (loginError as Error).message });
|
||||
}
|
||||
function unlockLoginInputs() {
|
||||
setLoginInputsUnlocked(true);
|
||||
}
|
||||
|
||||
async function handlePasswordLogin(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
setShowLoginValidation(true);
|
||||
if (!email.trim() || !password.trim()) {
|
||||
setFeedback({
|
||||
type: "error",
|
||||
text: "Bitte E-Mail und Passwort eingeben.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const response = await apiPost<UserOption>("/session/password-login", {
|
||||
identifier,
|
||||
setFeedback(null);
|
||||
const response = await apiPost<SessionResponse>("/session/password-login", {
|
||||
email: email.trim(),
|
||||
password,
|
||||
});
|
||||
setUser(response);
|
||||
setSession(response);
|
||||
// Admin zum Dashboard, Kunden zur Startseite
|
||||
navigate(response.user.role === "ADMIN" ? "/admin/dashboard" : "/home");
|
||||
} catch (loginError) {
|
||||
setFeedback({ type: "error", text: (loginError as Error).message });
|
||||
}
|
||||
@@ -69,13 +66,49 @@ export default function LoginPage() {
|
||||
|
||||
async function handleRegister(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
setShowRegisterValidation(true);
|
||||
if (
|
||||
!registration.companyName.trim()
|
||||
|| !registration.street.trim()
|
||||
|| !registration.houseNumber.trim()
|
||||
|| !registration.postalCode.trim()
|
||||
|| !registration.city.trim()
|
||||
|| !registration.email.trim()
|
||||
|| !registration.phoneNumber.trim()
|
||||
|| !registration.password.trim()
|
||||
) {
|
||||
setFeedback({
|
||||
type: "error",
|
||||
text: "Bitte alle Pflichtfelder inklusive Telefonnummer fuer die Registrierung ausfuellen.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (registration.password !== registration.passwordConfirmation) {
|
||||
setFeedback({ type: "error", text: "Die beiden Passwoerter stimmen nicht ueberein." });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const response = await apiPost<UserOption>("/session/register", registration);
|
||||
setFeedback(null);
|
||||
const { passwordConfirmation, ...registrationPayload } = registration;
|
||||
void passwordConfirmation;
|
||||
const response = await apiPost<RegistrationResponse>("/session/register", registrationPayload);
|
||||
setFeedback({
|
||||
type: "success",
|
||||
text: `Registrierung erfolgreich. Willkommen ${response.companyName ?? response.displayName}.`,
|
||||
text: `Registrierung erfolgreich. Ihr Account (${response.email}) wurde angelegt und muss durch einen Administrator freigegeben werden. Sie werden benachrichtigt, sobald die Freigabe erfolgt ist.`,
|
||||
});
|
||||
setUser(response);
|
||||
// Reset registration form and switch back to login
|
||||
setRegistration({
|
||||
companyName: "",
|
||||
street: "",
|
||||
houseNumber: "",
|
||||
postalCode: "",
|
||||
city: "",
|
||||
email: "",
|
||||
phoneNumber: "",
|
||||
password: "",
|
||||
passwordConfirmation: "",
|
||||
});
|
||||
setShowRegistration(false);
|
||||
} catch (registrationError) {
|
||||
setFeedback({ type: "error", text: (registrationError as Error).message });
|
||||
}
|
||||
@@ -88,7 +121,7 @@ export default function LoginPage() {
|
||||
<p className="eyebrow">MUH-App</p>
|
||||
<h1>Moderne Steuerung fuer Milchproben und Therapien.</h1>
|
||||
<p className="hero-text">
|
||||
Fokus auf klare Arbeitsablaeufe, schnelle Probenbearbeitung und ein Portal
|
||||
Fokus auf klare Arbeitsabläufe, schnelle Probenbearbeitung und ein Portal
|
||||
fuer Verwaltung, Berichtsdruck und Versandstatus.
|
||||
</p>
|
||||
</div>
|
||||
@@ -98,8 +131,7 @@ export default function LoginPage() {
|
||||
<p className="eyebrow">Zugang</p>
|
||||
<h2>Anmelden oder registrieren</h2>
|
||||
<p className="muted-text">
|
||||
Weiterhin moeglich: Direktanmeldung per Benutzerkuerzel. Neu: Login mit
|
||||
E-Mail/Benutzername und Passwort.
|
||||
Anmeldung per E-Mail mit Passwort sowie direkte Kundenregistrierung.
|
||||
</p>
|
||||
|
||||
{feedback ? (
|
||||
@@ -108,146 +140,198 @@ export default function LoginPage() {
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className="login-panel__section">
|
||||
<div className="section-card__header">
|
||||
<div>
|
||||
<p className="eyebrow">Schnelllogin</p>
|
||||
<h3>Benutzerkuerzel</h3>
|
||||
</div>
|
||||
<button type="button" className="secondary-button" onClick={() => void loadUsers()}>
|
||||
Neu laden
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{loading ? (
|
||||
<div className="empty-state">Benutzer werden geladen ...</div>
|
||||
) : users.length ? (
|
||||
<div className="user-grid">
|
||||
{users.map((user) => (
|
||||
<button
|
||||
key={user.id}
|
||||
type="button"
|
||||
className="user-card"
|
||||
onClick={() => void handleCodeLogin(user.code)}
|
||||
>
|
||||
<span className="user-card__code">{user.code}</span>
|
||||
<strong>{user.displayName}</strong>
|
||||
<small>
|
||||
{user.role === "ADMIN"
|
||||
? "Admin"
|
||||
: user.role === "CUSTOMER"
|
||||
? "Kunde"
|
||||
: "App"}
|
||||
</small>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className="page-stack">
|
||||
<div className="empty-state">
|
||||
Es wurden keine aktiven Benutzer geladen. Das Kuersel kann trotzdem direkt
|
||||
eingegeben werden.
|
||||
</div>
|
||||
<label className="field">
|
||||
<span>Benutzerkuerzel</span>
|
||||
<div className="auth-grid">
|
||||
{!showRegistration ? (
|
||||
<form
|
||||
className={`login-panel__section ${showLoginValidation ? "show-validation" : ""}`}
|
||||
onSubmit={handlePasswordLogin}
|
||||
autoComplete="off"
|
||||
>
|
||||
<label className="field field--required">
|
||||
<span>E-Mail</span>
|
||||
<input
|
||||
value={manualCode}
|
||||
onChange={(event) => setManualCode(event.target.value.toUpperCase())}
|
||||
placeholder="z. B. SV"
|
||||
type="email"
|
||||
name="login-email"
|
||||
value={email}
|
||||
onChange={(event) => setEmail(event.target.value)}
|
||||
onFocus={unlockLoginInputs}
|
||||
onPointerDown={unlockLoginInputs}
|
||||
placeholder="z. B. name@hof.de"
|
||||
autoComplete="off"
|
||||
readOnly={!loginInputsUnlocked}
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
<label className="field field--required">
|
||||
<span>Passwort</span>
|
||||
<input
|
||||
type="password"
|
||||
name="login-password"
|
||||
value={password}
|
||||
onChange={(event) => setPassword(event.target.value)}
|
||||
onFocus={unlockLoginInputs}
|
||||
onPointerDown={unlockLoginInputs}
|
||||
autoComplete="new-password"
|
||||
readOnly={!loginInputsUnlocked}
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
<div className="page-actions">
|
||||
<button type="submit" className="accent-button">
|
||||
Mit Passwort anmelden
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="accent-button"
|
||||
onClick={() => void handleCodeLogin(manualCode)}
|
||||
className="secondary-button"
|
||||
onClick={() => {
|
||||
setFeedback(null);
|
||||
setShowRegisterValidation(false);
|
||||
setShowRegistration(true);
|
||||
}}
|
||||
>
|
||||
Mit Kuerzel anmelden
|
||||
Registrieren
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
) : (
|
||||
<form className={`login-panel__section ${showRegisterValidation ? "show-validation" : ""}`} onSubmit={handleRegister} autoComplete="off">
|
||||
<div className="field-grid">
|
||||
<label className="field field--wide field--required">
|
||||
<span>Firmenname</span>
|
||||
<input
|
||||
value={registration.companyName}
|
||||
onChange={(event) =>
|
||||
setRegistration((current) => ({ ...current, companyName: event.target.value }))
|
||||
}
|
||||
placeholder="z. B. Muster Agrar GmbH"
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
<label className="field field--required">
|
||||
<span>Strasse</span>
|
||||
<input
|
||||
value={registration.street}
|
||||
onChange={(event) =>
|
||||
setRegistration((current) => ({ ...current, street: event.target.value }))
|
||||
}
|
||||
placeholder="z. B. Dorfstrasse"
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
<label className="field field--required">
|
||||
<span>Hausnummer</span>
|
||||
<input
|
||||
value={registration.houseNumber}
|
||||
onChange={(event) =>
|
||||
setRegistration((current) => ({ ...current, houseNumber: event.target.value }))
|
||||
}
|
||||
placeholder="z. B. 12a"
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
<label className="field field--required">
|
||||
<span>PLZ</span>
|
||||
<input
|
||||
value={registration.postalCode}
|
||||
onChange={(event) =>
|
||||
setRegistration((current) => ({ ...current, postalCode: event.target.value }))
|
||||
}
|
||||
placeholder="z. B. 12345"
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
<label className="field field--required">
|
||||
<span>Ort</span>
|
||||
<input
|
||||
value={registration.city}
|
||||
onChange={(event) =>
|
||||
setRegistration((current) => ({ ...current, city: event.target.value }))
|
||||
}
|
||||
placeholder="z. B. Musterstadt"
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
<label className="field field--required">
|
||||
<span>E-Mail</span>
|
||||
<input
|
||||
type="email"
|
||||
value={registration.email}
|
||||
onChange={(event) =>
|
||||
setRegistration((current) => ({ ...current, email: event.target.value }))
|
||||
}
|
||||
autoComplete="off"
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
<label className="field field--required">
|
||||
<span>Telefonnummer</span>
|
||||
<input
|
||||
type="tel"
|
||||
value={registration.phoneNumber}
|
||||
onChange={(event) =>
|
||||
setRegistration((current) => ({ ...current, phoneNumber: event.target.value }))
|
||||
}
|
||||
placeholder="z. B. 04531 181424"
|
||||
autoComplete="off"
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
<label className="field field--wide field--required">
|
||||
<span>Passwort</span>
|
||||
<input
|
||||
type="password"
|
||||
value={registration.password}
|
||||
onChange={(event) =>
|
||||
setRegistration((current) => ({ ...current, password: event.target.value }))
|
||||
}
|
||||
autoComplete="new-password"
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
<label className="field field--wide field--required">
|
||||
<span>Passwort wiederholen</span>
|
||||
<input
|
||||
type="password"
|
||||
value={registration.passwordConfirmation}
|
||||
className={
|
||||
showRegisterValidation
|
||||
&& registration.password !== registration.passwordConfirmation
|
||||
? "is-invalid"
|
||||
: ""
|
||||
}
|
||||
aria-invalid={
|
||||
showRegisterValidation && registration.password !== registration.passwordConfirmation
|
||||
}
|
||||
onChange={(event) =>
|
||||
setRegistration((current) => ({
|
||||
...current,
|
||||
passwordConfirmation: event.target.value,
|
||||
}))
|
||||
}
|
||||
autoComplete="new-password"
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
<div className="page-actions">
|
||||
<button type="submit" className="accent-button">
|
||||
Registrieren
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="secondary-button"
|
||||
onClick={() => {
|
||||
setFeedback(null);
|
||||
setShowLoginValidation(false);
|
||||
setShowRegistration(false);
|
||||
}}
|
||||
>
|
||||
Zurück
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="divider-label">oder mit Passwort</div>
|
||||
|
||||
<div className="auth-grid">
|
||||
<form className="login-panel__section" onSubmit={handlePasswordLogin}>
|
||||
<p className="eyebrow">Login</p>
|
||||
<h3>E-Mail oder Benutzername</h3>
|
||||
<label className="field">
|
||||
<span>E-Mail / Benutzername</span>
|
||||
<input
|
||||
value={identifier}
|
||||
onChange={(event) => setIdentifier(event.target.value)}
|
||||
placeholder="z. B. admin oder name@hof.de"
|
||||
/>
|
||||
</label>
|
||||
<label className="field">
|
||||
<span>Passwort</span>
|
||||
<input
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(event) => setPassword(event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<div className="page-actions">
|
||||
<button type="submit" className="accent-button">
|
||||
Mit Passwort anmelden
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<form className="login-panel__section" onSubmit={handleRegister}>
|
||||
<p className="eyebrow">Kundenregistrierung</p>
|
||||
<h3>Neues Kundenkonto anlegen</h3>
|
||||
<label className="field">
|
||||
<span>Firmenname</span>
|
||||
<input
|
||||
value={registration.companyName}
|
||||
onChange={(event) =>
|
||||
setRegistration((current) => ({ ...current, companyName: event.target.value }))
|
||||
}
|
||||
placeholder="z. B. Muster Agrar GmbH"
|
||||
/>
|
||||
</label>
|
||||
<label className="field">
|
||||
<span>Adresse</span>
|
||||
<textarea
|
||||
value={registration.address}
|
||||
onChange={(event) =>
|
||||
setRegistration((current) => ({ ...current, address: event.target.value }))
|
||||
}
|
||||
placeholder="Strasse, Hausnummer, PLZ Ort"
|
||||
/>
|
||||
</label>
|
||||
<label className="field">
|
||||
<span>E-Mail</span>
|
||||
<input
|
||||
type="email"
|
||||
value={registration.email}
|
||||
onChange={(event) =>
|
||||
setRegistration((current) => ({ ...current, email: event.target.value }))
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<label className="field">
|
||||
<span>Passwort</span>
|
||||
<input
|
||||
type="password"
|
||||
value={registration.password}
|
||||
onChange={(event) =>
|
||||
setRegistration((current) => ({ ...current, password: event.target.value }))
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<div className="page-actions">
|
||||
<button type="submit" className="accent-button">
|
||||
Registrieren
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
@@ -1,55 +1,25 @@
|
||||
import { FormEvent, useEffect, useMemo, useState } from "react";
|
||||
import { apiDelete, apiGet, apiPatch, apiPost, pdfUrl } from "../lib/api";
|
||||
import { apiDelete, apiGet, apiPost } from "../lib/api";
|
||||
import { useSession } from "../lib/session";
|
||||
import type { PortalSnapshot, UserRole } from "../lib/types";
|
||||
|
||||
function formatDate(value: string | null) {
|
||||
if (!value) {
|
||||
return "-";
|
||||
}
|
||||
return new Intl.DateTimeFormat("de-DE", {
|
||||
dateStyle: "medium",
|
||||
timeStyle: "short",
|
||||
}).format(new Date(value));
|
||||
}
|
||||
|
||||
export default function PortalPage() {
|
||||
const { user } = useSession();
|
||||
const [snapshot, setSnapshot] = useState<PortalSnapshot | null>(null);
|
||||
const [selectedFarmer, setSelectedFarmer] = useState("");
|
||||
const [farmerQuery, setFarmerQuery] = useState("");
|
||||
const [cowQuery, setCowQuery] = useState("");
|
||||
const [sampleNumberQuery, setSampleNumberQuery] = useState("");
|
||||
const [dateQuery, setDateQuery] = useState("");
|
||||
const [selectedReports, setSelectedReports] = useState<string[]>([]);
|
||||
const [message, setMessage] = useState<string | null>(null);
|
||||
const [userForm, setUserForm] = useState({
|
||||
code: "",
|
||||
displayName: "",
|
||||
email: "",
|
||||
portalLogin: "",
|
||||
password: "",
|
||||
role: "APP" as UserRole,
|
||||
role: "CUSTOMER" as UserRole,
|
||||
});
|
||||
const [passwordDrafts, setPasswordDrafts] = useState<Record<string, string>>({});
|
||||
const [showUserValidation, setShowUserValidation] = useState(false);
|
||||
const isAdmin = user?.role === "ADMIN";
|
||||
|
||||
async function loadSnapshot() {
|
||||
const params = new URLSearchParams();
|
||||
if (selectedFarmer) {
|
||||
params.set("farmerBusinessKey", selectedFarmer);
|
||||
}
|
||||
if (farmerQuery) {
|
||||
params.set("farmerQuery", farmerQuery);
|
||||
}
|
||||
if (cowQuery) {
|
||||
params.set("cowQuery", cowQuery);
|
||||
}
|
||||
if (sampleNumberQuery) {
|
||||
params.set("sampleNumber", sampleNumberQuery);
|
||||
}
|
||||
if (dateQuery) {
|
||||
params.set("date", dateQuery);
|
||||
}
|
||||
|
||||
const response = await apiGet<PortalSnapshot>(`/portal/snapshot?${params.toString()}`);
|
||||
const response = await apiGet<PortalSnapshot>("/portal/snapshot");
|
||||
setSnapshot(response);
|
||||
setSelectedReports(response.reportCandidates.map((candidate) => candidate.sampleId));
|
||||
}
|
||||
@@ -69,16 +39,6 @@ export default function PortalPage() {
|
||||
);
|
||||
}
|
||||
|
||||
async function handleSearch(event?: FormEvent) {
|
||||
event?.preventDefault();
|
||||
try {
|
||||
setMessage(null);
|
||||
await loadSnapshot();
|
||||
} catch (loadError) {
|
||||
setMessage((loadError as Error).message);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleDispatchReports() {
|
||||
try {
|
||||
const response = await apiPost<{ mailDeliveryActive: boolean }>("/portal/reports/send", {
|
||||
@@ -97,19 +57,23 @@ export default function PortalPage() {
|
||||
|
||||
async function handleCreateUser(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
setShowUserValidation(true);
|
||||
if (!isAdmin) {
|
||||
setMessage("Nur Administratoren koennen Benutzer anlegen.");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await apiPost("/portal/users", {
|
||||
...userForm,
|
||||
active: true,
|
||||
});
|
||||
setUserForm({
|
||||
code: "",
|
||||
displayName: "",
|
||||
email: "",
|
||||
portalLogin: "",
|
||||
password: "",
|
||||
role: "APP",
|
||||
role: "CUSTOMER",
|
||||
});
|
||||
setShowUserValidation(false);
|
||||
setMessage("Benutzer gespeichert.");
|
||||
await loadSnapshot();
|
||||
} catch (userError) {
|
||||
@@ -139,15 +103,6 @@ export default function PortalPage() {
|
||||
}
|
||||
}
|
||||
|
||||
async function handleToggleBlocked(sampleId: string, blocked: boolean) {
|
||||
try {
|
||||
await apiPatch(`/portal/reports/${sampleId}/block`, { blocked });
|
||||
await loadSnapshot();
|
||||
} catch (blockError) {
|
||||
setMessage((blockError as Error).message);
|
||||
}
|
||||
}
|
||||
|
||||
if (!snapshot) {
|
||||
return <div className="empty-state">Portal wird geladen ...</div>;
|
||||
}
|
||||
@@ -203,227 +158,97 @@ export default function PortalPage() {
|
||||
</div>
|
||||
</article>
|
||||
|
||||
<article className="section-card">
|
||||
<p className="eyebrow">Benutzerverwaltung</p>
|
||||
<form className="field-grid" onSubmit={handleCreateUser}>
|
||||
<label className="field">
|
||||
<span>Kuerzel</span>
|
||||
<input
|
||||
value={userForm.code}
|
||||
onChange={(event) => setUserForm((current) => ({ ...current, code: event.target.value }))}
|
||||
/>
|
||||
</label>
|
||||
<label className="field">
|
||||
<span>Name</span>
|
||||
<input
|
||||
value={userForm.displayName}
|
||||
onChange={(event) =>
|
||||
setUserForm((current) => ({ ...current, displayName: event.target.value }))
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<label className="field">
|
||||
<span>Login</span>
|
||||
<input
|
||||
value={userForm.portalLogin}
|
||||
onChange={(event) =>
|
||||
setUserForm((current) => ({ ...current, portalLogin: event.target.value }))
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<label className="field">
|
||||
<span>E-Mail</span>
|
||||
<input
|
||||
type="email"
|
||||
value={userForm.email}
|
||||
onChange={(event) => setUserForm((current) => ({ ...current, email: event.target.value }))}
|
||||
/>
|
||||
</label>
|
||||
<label className="field">
|
||||
<span>Passwort</span>
|
||||
<input
|
||||
value={userForm.password}
|
||||
onChange={(event) => setUserForm((current) => ({ ...current, password: event.target.value }))}
|
||||
type="password"
|
||||
/>
|
||||
</label>
|
||||
<label className="field">
|
||||
<span>Rolle</span>
|
||||
<select
|
||||
value={userForm.role}
|
||||
onChange={(event) => setUserForm((current) => ({ ...current, role: event.target.value as UserRole }))}
|
||||
>
|
||||
<option value="APP">APP</option>
|
||||
<option value="ADMIN">ADMIN</option>
|
||||
</select>
|
||||
</label>
|
||||
<div className="page-actions">
|
||||
<button type="submit" className="accent-button">
|
||||
Benutzer anlegen
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
{isAdmin ? (
|
||||
<article className="section-card">
|
||||
<p className="eyebrow">Benutzerverwaltung</p>
|
||||
<form className={`field-grid ${showUserValidation ? "show-validation" : ""}`} onSubmit={handleCreateUser}>
|
||||
<label className="field field--required">
|
||||
<span>Name</span>
|
||||
<input
|
||||
value={userForm.displayName}
|
||||
onChange={(event) =>
|
||||
setUserForm((current) => ({ ...current, displayName: event.target.value }))
|
||||
}
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
<label className="field">
|
||||
<span>E-Mail</span>
|
||||
<input
|
||||
type="email"
|
||||
value={userForm.email}
|
||||
onChange={(event) => setUserForm((current) => ({ ...current, email: event.target.value }))}
|
||||
/>
|
||||
</label>
|
||||
<label className="field">
|
||||
<span>Passwort</span>
|
||||
<input
|
||||
value={userForm.password}
|
||||
onChange={(event) => setUserForm((current) => ({ ...current, password: event.target.value }))}
|
||||
type="password"
|
||||
/>
|
||||
</label>
|
||||
<label className="field">
|
||||
<span>Rolle</span>
|
||||
<select
|
||||
value={userForm.role}
|
||||
onChange={(event) => setUserForm((current) => ({ ...current, role: event.target.value as UserRole }))}
|
||||
>
|
||||
<option value="CUSTOMER">CUSTOMER</option>
|
||||
<option value="ADMIN">ADMIN</option>
|
||||
</select>
|
||||
</label>
|
||||
<div className="page-actions">
|
||||
<button type="submit" className="accent-button">
|
||||
Benutzer anlegen
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<div className="table-shell">
|
||||
<table className="data-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Kuerzel</th>
|
||||
<th>Name</th>
|
||||
<th>E-Mail</th>
|
||||
<th>Login</th>
|
||||
<th>Rolle</th>
|
||||
<th>Passwort</th>
|
||||
<th />
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{snapshot.users.map((user) => (
|
||||
<tr key={user.id}>
|
||||
<td>{user.code}</td>
|
||||
<td>{user.displayName}</td>
|
||||
<td>{user.email ?? "-"}</td>
|
||||
<td>{user.portalLogin ?? "-"}</td>
|
||||
<td>{user.role}</td>
|
||||
<td>
|
||||
<input
|
||||
type="password"
|
||||
value={passwordDrafts[user.id] ?? ""}
|
||||
onChange={(event) =>
|
||||
setPasswordDrafts((current) => ({ ...current, [user.id]: event.target.value }))
|
||||
}
|
||||
placeholder="Neues Passwort"
|
||||
/>
|
||||
</td>
|
||||
<td className="table-actions">
|
||||
<button type="button" className="table-link" onClick={() => void handlePasswordChange(user.id)}>
|
||||
Speichern
|
||||
</button>
|
||||
<button type="button" className="table-link table-link--danger" onClick={() => void handleDeleteUser(user.id)}>
|
||||
Loeschen
|
||||
</button>
|
||||
</td>
|
||||
<div className="table-shell">
|
||||
<table className="data-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Name</th>
|
||||
<th>E-Mail</th>
|
||||
<th>Rolle</th>
|
||||
<th>Passwort</th>
|
||||
<th />
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</article>
|
||||
</section>
|
||||
|
||||
<section className="section-card">
|
||||
<form className="field-grid" onSubmit={handleSearch}>
|
||||
<label className="field">
|
||||
<span>Landwirt suchen</span>
|
||||
<input value={farmerQuery} onChange={(event) => setFarmerQuery(event.target.value)} />
|
||||
</label>
|
||||
<label className="field">
|
||||
<span>Gefundener Landwirt</span>
|
||||
<select value={selectedFarmer} onChange={(event) => setSelectedFarmer(event.target.value)}>
|
||||
<option value="">alle / noch keiner</option>
|
||||
{snapshot.farmers.map((farmer) => (
|
||||
<option key={farmer.businessKey} value={farmer.businessKey}>
|
||||
{farmer.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label className="field">
|
||||
<span>Kuh</span>
|
||||
<input value={cowQuery} onChange={(event) => setCowQuery(event.target.value)} />
|
||||
</label>
|
||||
<label className="field">
|
||||
<span>Probe-Nr.</span>
|
||||
<input value={sampleNumberQuery} onChange={(event) => setSampleNumberQuery(event.target.value)} />
|
||||
</label>
|
||||
<label className="field">
|
||||
<span>Datum</span>
|
||||
<input type="date" value={dateQuery} onChange={(event) => setDateQuery(event.target.value)} />
|
||||
</label>
|
||||
<div className="page-actions page-actions--align-end">
|
||||
<button type="submit" className="accent-button">
|
||||
Suche starten
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="secondary-button"
|
||||
onClick={() => {
|
||||
setSelectedFarmer("");
|
||||
setFarmerQuery("");
|
||||
setCowQuery("");
|
||||
setSampleNumberQuery("");
|
||||
setDateQuery("");
|
||||
void handleSearch();
|
||||
}}
|
||||
>
|
||||
Zuruecksetzen
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
<section className="section-card">
|
||||
<div className="section-card__header">
|
||||
<div>
|
||||
<p className="eyebrow">Suchergebnis</p>
|
||||
<h3>Gefundene Milchproben</h3>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="table-shell">
|
||||
<table className="data-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Probe</th>
|
||||
<th>Anlage</th>
|
||||
<th>Landwirt</th>
|
||||
<th>Kuh</th>
|
||||
<th>Typ</th>
|
||||
<th>Interne Bemerkung</th>
|
||||
<th>PDF</th>
|
||||
<th>Versand</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{snapshot.samples.map((sample) => (
|
||||
<tr key={sample.sampleId}>
|
||||
<td>{sample.sampleNumber}</td>
|
||||
<td>{formatDate(sample.createdAt)}</td>
|
||||
<td>{sample.farmerName}</td>
|
||||
<td>{sample.cowNumber}{sample.cowName ? ` / ${sample.cowName}` : ""}</td>
|
||||
<td>{sample.sampleKindLabel === "DRY_OFF" ? "Trockensteller" : "Milchprobe"}</td>
|
||||
<td>{sample.internalNote ?? "-"}</td>
|
||||
<td>
|
||||
{sample.completed ? (
|
||||
<a className="table-link" href={pdfUrl(sample.sampleId)} target="_blank" rel="noreferrer">
|
||||
PDF
|
||||
</a>
|
||||
) : (
|
||||
<span className="muted-text">-</span>
|
||||
)}
|
||||
</td>
|
||||
<td>
|
||||
<div className="table-actions">
|
||||
<span className={`status-pill ${sample.reportSent ? "status-pill--completed" : "status-pill--therapy"}`}>
|
||||
{sample.reportSent ? "versendet" : "offen"}
|
||||
</span>
|
||||
{sample.completed ? (
|
||||
<button
|
||||
type="button"
|
||||
className="table-link"
|
||||
onClick={() => void handleToggleBlocked(sample.sampleId, !sample.reportBlocked)}
|
||||
>
|
||||
{sample.reportBlocked ? "freigeben" : "blockieren"}
|
||||
</thead>
|
||||
<tbody>
|
||||
{snapshot.users.map((user) => (
|
||||
<tr key={user.id}>
|
||||
<td>{user.displayName}</td>
|
||||
<td>{user.email ?? "-"}</td>
|
||||
<td>{user.role}</td>
|
||||
<td>
|
||||
<input
|
||||
type="password"
|
||||
value={passwordDrafts[user.id] ?? ""}
|
||||
onChange={(event) =>
|
||||
setPasswordDrafts((current) => ({ ...current, [user.id]: event.target.value }))
|
||||
}
|
||||
placeholder="Neues Passwort"
|
||||
/>
|
||||
</td>
|
||||
<td className="table-actions">
|
||||
<button type="button" className="table-link" onClick={() => void handlePasswordChange(user.id)}>
|
||||
Speichern
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<button type="button" className="table-link table-link--danger" onClick={() => void handleDeleteUser(user.id)}>
|
||||
Loeschen
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</article>
|
||||
) : null}
|
||||
</section>
|
||||
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
160
frontend/src/pages/PricingPage.tsx
Normal file
160
frontend/src/pages/PricingPage.tsx
Normal file
@@ -0,0 +1,160 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { apiGet, apiPost } from "../lib/api";
|
||||
|
||||
interface PricingResponse {
|
||||
monthlyPrice: number | null;
|
||||
updatedAt: string | null;
|
||||
}
|
||||
|
||||
export default function PricingPage() {
|
||||
const [monthlyPrice, setMonthlyPrice] = useState<string>("");
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [message, setMessage] = useState<string | null>(null);
|
||||
const [lastUpdated, setLastUpdated] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
async function loadPricing() {
|
||||
try {
|
||||
const response = await apiGet<PricingResponse>("/admin/pricing");
|
||||
if (response.monthlyPrice !== null) {
|
||||
setMonthlyPrice(response.monthlyPrice.toString());
|
||||
}
|
||||
setLastUpdated(response.updatedAt);
|
||||
} catch (error) {
|
||||
setMessage((error as Error).message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
void loadPricing();
|
||||
}, []);
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
|
||||
const priceValue = parseFloat(monthlyPrice.replace(",", "."));
|
||||
if (isNaN(priceValue) || priceValue < 0) {
|
||||
setMessage("Bitte geben Sie einen gültigen Preis ein.");
|
||||
return;
|
||||
}
|
||||
|
||||
setSaving(true);
|
||||
setMessage(null);
|
||||
|
||||
try {
|
||||
const response = await apiPost<PricingResponse>("/admin/pricing", {
|
||||
monthlyPrice: priceValue,
|
||||
});
|
||||
setMonthlyPrice(response.monthlyPrice?.toString() ?? "");
|
||||
setLastUpdated(response.updatedAt);
|
||||
setMessage("Preis wurde erfolgreich gespeichert.");
|
||||
setTimeout(() => setMessage(null), 3000);
|
||||
} catch (error) {
|
||||
setMessage((error as Error).message);
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
function formatDate(value: string | null): string {
|
||||
if (!value) return "-";
|
||||
return new Intl.DateTimeFormat("de-DE", {
|
||||
dateStyle: "medium",
|
||||
timeStyle: "short",
|
||||
}).format(new Date(value));
|
||||
}
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="page-stack">
|
||||
<section className="section-card">
|
||||
<div className="empty-state">Preistabelle wird geladen...</div>
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="page-stack">
|
||||
{/* Header */}
|
||||
<section className="hero-card admin-hero">
|
||||
<div>
|
||||
<p className="eyebrow">Preistabelle</p>
|
||||
<h3>Monatlichen Systempreis festlegen</h3>
|
||||
<p className="muted-text">
|
||||
Legen Sie hier den monatlichen Preis für die Nutzung des Systems fest.
|
||||
Dieser Preis wird für die Rechnungsstellung verwendet.
|
||||
</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Status-Meldung */}
|
||||
{message && (
|
||||
<div
|
||||
className={
|
||||
message.includes("erfolgreich")
|
||||
? "alert alert--success"
|
||||
: "alert alert--error"
|
||||
}
|
||||
>
|
||||
{message}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Preis-Formular */}
|
||||
<section className="section-card">
|
||||
<div className="section-card__header">
|
||||
<div>
|
||||
<p className="eyebrow">Systempreis</p>
|
||||
<h3>Monatlicher Preis</h3>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleSubmit} className="field-grid field-grid--2col">
|
||||
<label className="field">
|
||||
<span>Preis pro Monat (€) *</span>
|
||||
<input
|
||||
type="text"
|
||||
value={monthlyPrice}
|
||||
onChange={(e) => setMonthlyPrice(e.target.value)}
|
||||
placeholder="z.B. 49,99"
|
||||
required
|
||||
disabled={saving}
|
||||
/>
|
||||
</label>
|
||||
|
||||
<div className="field" style={{ display: "flex", alignItems: "flex-end" }}>
|
||||
<button
|
||||
type="submit"
|
||||
className="accent-button"
|
||||
disabled={saving}
|
||||
style={{ width: "100%" }}
|
||||
>
|
||||
{saving ? "Wird gespeichert..." : "Preis speichern"}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
{lastUpdated && (
|
||||
<div style={{ marginTop: "1rem", fontSize: "0.875rem", color: "var(--muted-text)" }}>
|
||||
<strong>Zuletzt aktualisiert:</strong> {formatDate(lastUpdated)}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
|
||||
{/* Info-Box */}
|
||||
<section className="section-card">
|
||||
<div className="info-panel">
|
||||
<strong>Hinweis</strong>
|
||||
<p>
|
||||
Der hier festgelegte monatliche Preis wird als Grundlage für die Abrechnung
|
||||
mit den Nutzern verwendet. Änderungen werden sofort wirksam und bei der
|
||||
nächsten Rechnungsstellung berücksichtigt.
|
||||
</p>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
2265
frontend/src/pages/ReportTemplatePage.tsx
Normal file
2265
frontend/src/pages/ReportTemplatePage.tsx
Normal file
File diff suppressed because it is too large
Load Diff
@@ -18,6 +18,14 @@ const QUARTERS: { key: QuarterKey; label: string }[] = [
|
||||
{ key: "RIGHT_REAR", label: "Hinten rechts" },
|
||||
];
|
||||
|
||||
// Pretreatment options from Lua version
|
||||
const PRETREATMENT_OPTIONS = [
|
||||
{ key: "inUdderInjector", label: "Euterinjektor" },
|
||||
{ key: "systemicAntibiotics", label: "Systemische Antibiotika" },
|
||||
{ key: "painMedication", label: "Schmerzmittel" },
|
||||
{ key: "dryOffTreatment", label: "Trockensteller" },
|
||||
];
|
||||
|
||||
export default function SampleRegistrationPage() {
|
||||
const { sampleId } = useParams();
|
||||
const navigate = useNavigate();
|
||||
@@ -32,9 +40,19 @@ export default function SampleRegistrationPage() {
|
||||
const [sampleKind, setSampleKind] = useState<SampleKind>("LACTATION");
|
||||
const [samplingMode, setSamplingMode] = useState<SamplingMode>("SINGLE_SITE");
|
||||
const [flaggedQuarters, setFlaggedQuarters] = useState<QuarterKey[]>([]);
|
||||
// New fields from Lua version
|
||||
const [pretreatment, setPretreatment] = useState<Record<string, string>>({
|
||||
inUdderInjector: "",
|
||||
systemicAntibiotics: "",
|
||||
painMedication: "",
|
||||
dryOffTreatment: "",
|
||||
});
|
||||
const [clinicalExamDate, setClinicalExamDate] = useState("");
|
||||
const [internalNote, setInternalNote] = useState("");
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [message, setMessage] = useState<string | null>(null);
|
||||
const [showValidation, setShowValidation] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
async function load() {
|
||||
@@ -54,6 +72,17 @@ export default function SampleRegistrationPage() {
|
||||
setFlaggedQuarters(
|
||||
sample.quarters.filter((quarter) => quarter.flagged).map((quarter) => quarter.quarterKey),
|
||||
);
|
||||
// Load new fields
|
||||
if (sample.pretreatment) {
|
||||
setPretreatment({
|
||||
inUdderInjector: sample.pretreatment.inUdderInjector ?? "",
|
||||
systemicAntibiotics: sample.pretreatment.systemicAntibiotics ?? "",
|
||||
painMedication: sample.pretreatment.painMedication ?? "",
|
||||
dryOffTreatment: sample.pretreatment.dryOffTreatment ?? "",
|
||||
});
|
||||
}
|
||||
setClinicalExamDate(sample.clinicalExamDate ?? "");
|
||||
setInternalNote(sample.internalNote ?? "");
|
||||
} else {
|
||||
const dashboard = await apiGet<DashboardOverview>("/dashboard");
|
||||
setSampleNumber(dashboard.nextSampleNumber);
|
||||
@@ -77,8 +106,16 @@ export default function SampleRegistrationPage() {
|
||||
);
|
||||
}
|
||||
|
||||
function updatePretreatment(key: string, value: string) {
|
||||
setPretreatment((current) => ({
|
||||
...current,
|
||||
[key]: value,
|
||||
}));
|
||||
}
|
||||
|
||||
async function handleSubmit(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
setShowValidation(true);
|
||||
if (!user) {
|
||||
return;
|
||||
}
|
||||
@@ -97,8 +134,15 @@ export default function SampleRegistrationPage() {
|
||||
sampleKind,
|
||||
samplingMode,
|
||||
flaggedQuarters,
|
||||
userCode: user.code,
|
||||
userCode: user.displayName,
|
||||
userDisplayName: user.displayName,
|
||||
// New fields
|
||||
pretreatmentInUdderInjector: pretreatment.inUdderInjector || null,
|
||||
pretreatmentSystemicAntibiotics: pretreatment.systemicAntibiotics || null,
|
||||
pretreatmentPainMedication: pretreatment.painMedication || null,
|
||||
pretreatmentDryOffTreatment: pretreatment.dryOffTreatment || null,
|
||||
clinicalExamDate: clinicalExamDate || null,
|
||||
internalNote: internalNote || null,
|
||||
};
|
||||
|
||||
try {
|
||||
@@ -118,14 +162,14 @@ export default function SampleRegistrationPage() {
|
||||
}
|
||||
|
||||
return (
|
||||
<form className="page-stack" onSubmit={handleSubmit}>
|
||||
<form className={`page-stack ${showValidation ? "show-validation" : ""}`} onSubmit={handleSubmit}>
|
||||
<section className="section-card section-card--hero">
|
||||
<div>
|
||||
<p className="eyebrow">Neuanlage</p>
|
||||
<h3>Probe {sampleNumber ?? "..."}</h3>
|
||||
<p className="muted-text">
|
||||
Die Probenummer wird fortlaufend vergeben. Trockensteller lassen sich ueber den
|
||||
Schalter TS markieren.
|
||||
Die Probenummer wird fortlaufend vergeben. Trockensteller lassen sich über den
|
||||
Schalter Trockenstellerprobe markieren.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -138,31 +182,33 @@ export default function SampleRegistrationPage() {
|
||||
{message ? <div className="alert alert--error">{message}</div> : null}
|
||||
</section>
|
||||
|
||||
<section className="form-grid">
|
||||
<section className="form-grid form-grid--stacked">
|
||||
<article className="section-card">
|
||||
<p className="eyebrow">Stammdaten</p>
|
||||
<div className="field-grid">
|
||||
<label className="field">
|
||||
<div className="field-grid field-grid--stacked">
|
||||
<label className="field field--required">
|
||||
<span>Landwirt</span>
|
||||
<select
|
||||
value={farmerBusinessKey}
|
||||
onChange={(event) => setFarmerBusinessKey(event.target.value)}
|
||||
disabled={!editable}
|
||||
required
|
||||
>
|
||||
{catalogs?.farmers.map((farmer) => (
|
||||
<option key={farmer.businessKey} value={farmer.businessKey}>
|
||||
{farmer.name}
|
||||
{farmer.companyName}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
|
||||
<label className="field">
|
||||
<label className="field field--required">
|
||||
<span>Kuh-Nummer</span>
|
||||
<input
|
||||
value={cowNumber}
|
||||
onChange={(event) => setCowNumber(event.target.value)}
|
||||
disabled={!editable}
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
|
||||
@@ -194,7 +240,7 @@ export default function SampleRegistrationPage() {
|
||||
onClick={() => setSampleKind("DRY_OFF")}
|
||||
disabled={!editable}
|
||||
>
|
||||
TS
|
||||
Trockenstellerprobe
|
||||
</button>
|
||||
</div>
|
||||
|
||||
@@ -247,13 +293,62 @@ export default function SampleRegistrationPage() {
|
||||
disabled={!editable}
|
||||
>
|
||||
<span>{quarter.label}</span>
|
||||
<strong>{flaggedQuarters.includes(quarter.key) ? "⚠" : "OK"}</strong>
|
||||
<strong>{flaggedQuarters.includes(quarter.key) ? "Auffällig" : "OK"}</strong>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
) : null}
|
||||
|
||||
{/* New section: Pretreatment from Lua version */}
|
||||
<section className="section-card">
|
||||
<p className="eyebrow">Vorbehandelt mit</p>
|
||||
<div className="field-grid field-grid--stacked">
|
||||
{PRETREATMENT_OPTIONS.map((option) => (
|
||||
<label key={option.key} className="field">
|
||||
<span>{option.label}</span>
|
||||
<input
|
||||
type="text"
|
||||
value={pretreatment[option.key]}
|
||||
onChange={(event) => updatePretreatment(option.key, event.target.value)}
|
||||
disabled={!editable}
|
||||
placeholder="Ohne Vorbehandlung"
|
||||
/>
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* New section: Clinical Exam Date from Lua version */}
|
||||
<section className="form-grid">
|
||||
<article className="section-card">
|
||||
<p className="eyebrow">Klinische Untersuchung</p>
|
||||
<label className="field">
|
||||
<span>Untersuchungsdatum (TT.MM.JJJJ)</span>
|
||||
<input
|
||||
type="text"
|
||||
value={clinicalExamDate}
|
||||
onChange={(event) => setClinicalExamDate(event.target.value)}
|
||||
disabled={!editable}
|
||||
placeholder="z.B. 15.03.2024"
|
||||
/>
|
||||
</label>
|
||||
</article>
|
||||
|
||||
<article className="section-card">
|
||||
<p className="eyebrow">Interne Bemerkung</p>
|
||||
<label className="field">
|
||||
<span>Bemerkung zur Probe</span>
|
||||
<textarea
|
||||
value={internalNote}
|
||||
onChange={(event) => setInternalNote(event.target.value)}
|
||||
disabled={!editable}
|
||||
rows={3}
|
||||
/>
|
||||
</label>
|
||||
</article>
|
||||
</section>
|
||||
|
||||
<div className="page-actions">
|
||||
<button type="submit" className="accent-button" disabled={saving || !editable}>
|
||||
{saving ? "Speichern ..." : "Speichern"}
|
||||
|
||||
90
frontend/src/pages/SearchCalendarPage.tsx
Normal file
90
frontend/src/pages/SearchCalendarPage.tsx
Normal file
@@ -0,0 +1,90 @@
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import SampleSearchResultsSection from "../components/SampleSearchResultsSection";
|
||||
import { apiGet } from "../lib/api";
|
||||
import type { LookupResult, PortalSampleRow } from "../lib/types";
|
||||
import { useState } from "react";
|
||||
|
||||
function routeForLookup(result: LookupResult) {
|
||||
return result.sampleId && result.routeSegment ? `/samples/${result.sampleId}/${result.routeSegment}` : null;
|
||||
}
|
||||
|
||||
export default function SearchCalendarPage() {
|
||||
const navigate = useNavigate();
|
||||
const [selectedDate, setSelectedDate] = useState("");
|
||||
const [samples, setSamples] = useState<PortalSampleRow[]>([]);
|
||||
const [message, setMessage] = useState<string | null>(null);
|
||||
const [resultLabel, setResultLabel] = useState("Bitte Datum auswaehlen");
|
||||
|
||||
async function handleDateChange(nextDate: string) {
|
||||
setSelectedDate(nextDate);
|
||||
if (!nextDate) {
|
||||
setSamples([]);
|
||||
setMessage(null);
|
||||
setResultLabel("Bitte Datum auswaehlen");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const rows = await apiGet<PortalSampleRow[]>(
|
||||
`/portal/search/by-date?date=${encodeURIComponent(nextDate)}`,
|
||||
);
|
||||
setSamples(rows);
|
||||
setResultLabel(`Erfasste Proben am ${nextDate.split("-").reverse().join(".")}`);
|
||||
setMessage(rows.length ? null : "An diesem Tag wurden keine Proben erfasst.");
|
||||
} catch (dateError) {
|
||||
setSamples([]);
|
||||
setResultLabel("Keine Treffer");
|
||||
setMessage((dateError as Error).message);
|
||||
}
|
||||
}
|
||||
|
||||
async function openSample(sampleNumber: number) {
|
||||
try {
|
||||
const result = await apiGet<LookupResult>(`/dashboard/lookup/${sampleNumber}`);
|
||||
const target = routeForLookup(result);
|
||||
if (!result.found || !target) {
|
||||
setMessage(result.message);
|
||||
return;
|
||||
}
|
||||
navigate(target);
|
||||
} catch (openError) {
|
||||
setMessage((openError as Error).message);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="page-stack">
|
||||
<section className="section-card section-card--hero">
|
||||
<div>
|
||||
<p className="eyebrow">Suche | Kalendar</p>
|
||||
<h3>Proben nach Erfassungsdatum finden</h3>
|
||||
<p className="muted-text">
|
||||
Waehle einen Tag im Kalendar aus, um alle an diesem Datum erfassten Proben in der Liste zu sehen.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{message ? <div className="alert alert--error">{message}</div> : null}
|
||||
</section>
|
||||
|
||||
<section className="section-card">
|
||||
<label className="field field--required">
|
||||
<span>Kalendar</span>
|
||||
<input
|
||||
type="date"
|
||||
value={selectedDate}
|
||||
onChange={(event) => void handleDateChange(event.target.value)}
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
</section>
|
||||
|
||||
<SampleSearchResultsSection
|
||||
eyebrow="Suchergebnisse"
|
||||
title={resultLabel}
|
||||
emptyText="Bitte ein Datum im Kalendar auswaehlen."
|
||||
samples={samples}
|
||||
onOpen={(sampleNumber) => void openSample(sampleNumber)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
141
frontend/src/pages/SearchFarmerPage.tsx
Normal file
141
frontend/src/pages/SearchFarmerPage.tsx
Normal file
@@ -0,0 +1,141 @@
|
||||
import { FormEvent, useState } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import SampleSearchResultsSection from "../components/SampleSearchResultsSection";
|
||||
import { apiGet } from "../lib/api";
|
||||
import type { FarmerOption, LookupResult, PortalSampleRow, PortalSnapshot } from "../lib/types";
|
||||
|
||||
function routeForLookup(result: LookupResult) {
|
||||
return result.sampleId && result.routeSegment ? `/samples/${result.sampleId}/${result.routeSegment}` : null;
|
||||
}
|
||||
|
||||
export default function SearchFarmerPage() {
|
||||
const navigate = useNavigate();
|
||||
const [farmerQuery, setFarmerQuery] = useState("");
|
||||
const [farmers, setFarmers] = useState<FarmerOption[]>([]);
|
||||
const [samples, setSamples] = useState<PortalSampleRow[]>([]);
|
||||
const [message, setMessage] = useState<string | null>(null);
|
||||
const [showValidation, setShowValidation] = useState(false);
|
||||
const [resultLabel, setResultLabel] = useState("Bitte Landwirt suchen");
|
||||
|
||||
async function loadFarmerSamples(farmer: FarmerOption) {
|
||||
const response = await apiGet<PortalSnapshot>(
|
||||
`/portal/snapshot?farmerBusinessKey=${encodeURIComponent(farmer.businessKey)}`,
|
||||
);
|
||||
setSamples(response.samples);
|
||||
setResultLabel(`Proben von ${farmer.companyName}`);
|
||||
setMessage(response.samples.length ? null : "Zu diesem Landwirt wurden noch keine Proben gefunden.");
|
||||
}
|
||||
|
||||
async function handleSearch(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
setShowValidation(true);
|
||||
if (!farmerQuery.trim()) {
|
||||
setMessage("Bitte einen Landwirt eingeben.");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await apiGet<PortalSnapshot>(
|
||||
`/portal/snapshot?farmerQuery=${encodeURIComponent(farmerQuery.trim())}`,
|
||||
);
|
||||
setFarmers(response.farmers);
|
||||
if (!response.farmers.length) {
|
||||
setSamples([]);
|
||||
setResultLabel("Keine Treffer");
|
||||
setMessage("Kein passender Landwirt gefunden.");
|
||||
return;
|
||||
}
|
||||
if (response.farmers.length === 1) {
|
||||
await loadFarmerSamples(response.farmers[0]);
|
||||
return;
|
||||
}
|
||||
setSamples([]);
|
||||
setResultLabel("Landwirt auswaehlen");
|
||||
setMessage(null);
|
||||
} catch (searchError) {
|
||||
setFarmers([]);
|
||||
setSamples([]);
|
||||
setResultLabel("Keine Treffer");
|
||||
setMessage((searchError as Error).message);
|
||||
}
|
||||
}
|
||||
|
||||
async function openSample(sampleNumber: number) {
|
||||
try {
|
||||
const result = await apiGet<LookupResult>(`/dashboard/lookup/${sampleNumber}`);
|
||||
const target = routeForLookup(result);
|
||||
if (!result.found || !target) {
|
||||
setMessage(result.message);
|
||||
return;
|
||||
}
|
||||
navigate(target);
|
||||
} catch (openError) {
|
||||
setMessage((openError as Error).message);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="page-stack">
|
||||
<section className="section-card section-card--hero">
|
||||
<div>
|
||||
<p className="eyebrow">Suche | Landwirt</p>
|
||||
<h3>Proben nach Landwirt finden</h3>
|
||||
<p className="muted-text">
|
||||
Suche nach dem Landwirt und oeffne danach eine der zugehoerigen Proben direkt aus der Trefferliste.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{message ? <div className="alert alert--error">{message}</div> : null}
|
||||
</section>
|
||||
|
||||
<section className="section-card">
|
||||
<form className={`hero-card__form ${showValidation ? "show-validation" : ""}`} onSubmit={handleSearch}>
|
||||
<label className="field field--required">
|
||||
<span>Landwirt</span>
|
||||
<input
|
||||
value={farmerQuery}
|
||||
onChange={(event) => setFarmerQuery(event.target.value)}
|
||||
placeholder="z. B. Agrar Lindenblick"
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
<button type="submit" className="accent-button">
|
||||
Landwirt suchen
|
||||
</button>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
{farmers.length > 1 ? (
|
||||
<section className="section-card">
|
||||
<div className="section-card__header">
|
||||
<div>
|
||||
<p className="eyebrow">Treffer</p>
|
||||
<h3>Gefundene Landwirte</h3>
|
||||
</div>
|
||||
</div>
|
||||
<div className="user-grid">
|
||||
{farmers.map((farmer) => (
|
||||
<button
|
||||
key={farmer.businessKey}
|
||||
type="button"
|
||||
className="user-card"
|
||||
onClick={() => void loadFarmerSamples(farmer)}
|
||||
>
|
||||
<strong>{farmer.companyName}</strong>
|
||||
<small>{farmer.email ?? "ohne E-Mail"}</small>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
) : null}
|
||||
|
||||
<SampleSearchResultsSection
|
||||
eyebrow="Suchergebnisse"
|
||||
title={resultLabel}
|
||||
emptyText="Bitte zuerst einen Landwirt suchen oder aus der Trefferliste auswaehlen."
|
||||
samples={samples}
|
||||
onOpen={(sampleNumber) => void openSample(sampleNumber)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
119
frontend/src/pages/SearchPage.tsx
Normal file
119
frontend/src/pages/SearchPage.tsx
Normal file
@@ -0,0 +1,119 @@
|
||||
import { FormEvent, useState } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import SampleSearchResultsSection from "../components/SampleSearchResultsSection";
|
||||
import { apiGet } from "../lib/api";
|
||||
import type { LookupResult, PortalSampleRow, SampleDetail } from "../lib/types";
|
||||
|
||||
function routeForLookup(result: LookupResult) {
|
||||
return result.sampleId && result.routeSegment ? `/samples/${result.sampleId}/${result.routeSegment}` : null;
|
||||
}
|
||||
|
||||
function toPortalRow(sample: SampleDetail): PortalSampleRow {
|
||||
return {
|
||||
sampleId: sample.id,
|
||||
sampleNumber: sample.sampleNumber,
|
||||
createdAt: sample.createdAt,
|
||||
completedAt: sample.completedAt,
|
||||
farmerBusinessKey: sample.farmerBusinessKey,
|
||||
farmerName: sample.farmerName,
|
||||
farmerEmail: sample.farmerEmail,
|
||||
cowNumber: sample.cowNumber,
|
||||
cowName: sample.cowName,
|
||||
sampleKindLabel: sample.sampleKind,
|
||||
internalNote: sample.therapy?.internalNote ?? null,
|
||||
completed: sample.completed,
|
||||
reportSent: sample.reportSent,
|
||||
reportBlocked: sample.reportBlocked,
|
||||
};
|
||||
}
|
||||
|
||||
export default function SearchPage() {
|
||||
const navigate = useNavigate();
|
||||
const [sampleNumber, setSampleNumber] = useState("");
|
||||
const [samples, setSamples] = useState<PortalSampleRow[]>([]);
|
||||
const [message, setMessage] = useState<string | null>(null);
|
||||
const [showValidation, setShowValidation] = useState(false);
|
||||
const [resultLabel, setResultLabel] = useState("Bitte Probennummer eingeben");
|
||||
|
||||
async function handleSearchByNumber(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
setShowValidation(true);
|
||||
if (!sampleNumber.trim()) {
|
||||
setMessage("Bitte eine Probennummer eingeben.");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await apiGet<LookupResult>(`/dashboard/lookup/${sampleNumber.trim()}`);
|
||||
if (!result.found || !result.sampleId) {
|
||||
setMessage(result.message);
|
||||
setSamples([]);
|
||||
setResultLabel("Keine Treffer");
|
||||
return;
|
||||
}
|
||||
const sample = await apiGet<SampleDetail>(`/samples/by-number/${sampleNumber.trim()}`);
|
||||
setSamples([toPortalRow(sample)]);
|
||||
setResultLabel(`Suchtreffer fuer Probe ${sample.sampleNumber}`);
|
||||
setMessage(null);
|
||||
} catch (searchError) {
|
||||
setSamples([]);
|
||||
setMessage((searchError as Error).message);
|
||||
}
|
||||
}
|
||||
|
||||
async function openSample(sampleNumberToOpen: number) {
|
||||
try {
|
||||
const result = await apiGet<LookupResult>(`/dashboard/lookup/${sampleNumberToOpen}`);
|
||||
const target = routeForLookup(result);
|
||||
if (!result.found || !target) {
|
||||
setMessage(result.message);
|
||||
return;
|
||||
}
|
||||
navigate(target);
|
||||
} catch (openError) {
|
||||
setMessage((openError as Error).message);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="page-stack">
|
||||
<section className="section-card section-card--hero">
|
||||
<div>
|
||||
<p className="eyebrow">Suche | Probe</p>
|
||||
<h3>Probe per Nummer finden</h3>
|
||||
<p className="muted-text">
|
||||
Suche gezielt nach einer Probennummer und oeffne den passenden Arbeitsschritt direkt aus der Trefferliste.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{message ? <div className="alert alert--error">{message}</div> : null}
|
||||
</section>
|
||||
|
||||
<section className="section-card">
|
||||
<form className={`hero-card__form ${showValidation ? "show-validation" : ""}`} onSubmit={handleSearchByNumber}>
|
||||
<label className="field field--required">
|
||||
<span>Probennummer</span>
|
||||
<input
|
||||
value={sampleNumber}
|
||||
onChange={(event) => setSampleNumber(event.target.value)}
|
||||
inputMode="numeric"
|
||||
placeholder="z. B. 100203"
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
<button type="submit" className="accent-button">
|
||||
Probe suchen
|
||||
</button>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
<SampleSearchResultsSection
|
||||
eyebrow="Suchergebnisse"
|
||||
title={resultLabel}
|
||||
emptyText="Bitte eine Probennummer eingeben und die Suche starten."
|
||||
samples={samples}
|
||||
onOpen={(sampleNumberValue) => void openSample(sampleNumberValue)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -11,6 +11,12 @@ function medicationOptions(catalogs: ActiveCatalogSummary, category: MedicationC
|
||||
return catalogs.medications.filter((medication) => medication.category === category);
|
||||
}
|
||||
|
||||
// Options for dropdowns like in Lua version
|
||||
const COUNT_OPTIONS = ["1", "2", "3", "4", "5"];
|
||||
const DURATION_OPTIONS = ["1 Tag", "2 Tage", "3 Tage", "4 Tage", "5 Tage", "6 Tage", "7 Tage", "8 Tage", "10 Tage", "14 Tage"];
|
||||
const DOSAGE_OPTIONS = ["einmalig", "1 x", "2 x", "3 x"];
|
||||
const LOCATION_OPTIONS = ["i.m.", "i.v.", "s.c."];
|
||||
|
||||
export default function TherapyPage() {
|
||||
const { sampleId } = useParams();
|
||||
|
||||
@@ -26,6 +32,15 @@ export default function TherapyPage() {
|
||||
const [dryAntibioticKeys, setDryAntibioticKeys] = useState<string[]>([]);
|
||||
const [farmerNote, setFarmerNote] = useState("");
|
||||
const [internalNote, setInternalNote] = useState("");
|
||||
// New fields from Lua version
|
||||
const [inUdderCount, setInUdderCount] = useState("");
|
||||
const [inUdderDuration, setInUdderDuration] = useState("");
|
||||
const [systemicCount, setSystemicCount] = useState("");
|
||||
const [systemicDuration, setSystemicDuration] = useState("");
|
||||
const [systemicDosage, setSystemicDosage] = useState("");
|
||||
const [systemicLocation, setSystemicLocation] = useState("");
|
||||
const [startvacVaccination, setStartvacVaccination] = useState(false);
|
||||
const [noAntibioticTreatment, setNoAntibioticTreatment] = useState(false);
|
||||
const [message, setMessage] = useState<string | null>(null);
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
@@ -51,6 +66,15 @@ export default function TherapyPage() {
|
||||
setDryAntibioticKeys(sampleResponse.therapy?.dryAntibioticKeys ?? []);
|
||||
setFarmerNote(sampleResponse.therapy?.farmerNote ?? "");
|
||||
setInternalNote(sampleResponse.therapy?.internalNote ?? "");
|
||||
// Load new fields
|
||||
setInUdderCount(sampleResponse.therapy?.inUdderCount ?? "");
|
||||
setInUdderDuration(sampleResponse.therapy?.inUdderDuration ?? "");
|
||||
setSystemicCount(sampleResponse.therapy?.systemicCount ?? "");
|
||||
setSystemicDuration(sampleResponse.therapy?.systemicDuration ?? "");
|
||||
setSystemicDosage(sampleResponse.therapy?.systemicDosage ?? "");
|
||||
setSystemicLocation(sampleResponse.therapy?.systemicLocation ?? "");
|
||||
setStartvacVaccination(sampleResponse.therapy?.startvacVaccination ?? false);
|
||||
setNoAntibioticTreatment(sampleResponse.therapy?.noAntibioticTreatment ?? false);
|
||||
} catch (loadError) {
|
||||
setMessage((loadError as Error).message);
|
||||
}
|
||||
@@ -65,6 +89,14 @@ export default function TherapyPage() {
|
||||
setter(list.includes(value) ? list.filter((entry) => entry !== value) : [...list, value]);
|
||||
}
|
||||
|
||||
// Check if "Keine" (None) is selected for in-udder or systemic
|
||||
const noInUdderSelected = inUdderMedicationKeys.some(key =>
|
||||
catalogs?.medications.find(m => m.businessKey === key)?.name === "Keine"
|
||||
);
|
||||
const noSystemicSelected = systemicMedicationKeys.some(key =>
|
||||
catalogs?.medications.find(m => m.businessKey === key)?.name === "Keine"
|
||||
);
|
||||
|
||||
async function handleSave() {
|
||||
if (!sampleId) {
|
||||
return;
|
||||
@@ -83,6 +115,15 @@ export default function TherapyPage() {
|
||||
dryAntibioticKeys,
|
||||
farmerNote,
|
||||
internalNote,
|
||||
// New fields
|
||||
inUdderCount: inUdderCount || null,
|
||||
inUdderDuration: inUdderDuration || null,
|
||||
systemicCount: systemicCount || null,
|
||||
systemicDuration: systemicDuration || null,
|
||||
systemicDosage: systemicDosage || null,
|
||||
systemicLocation: systemicLocation || null,
|
||||
startvacVaccination,
|
||||
noAntibioticTreatment,
|
||||
});
|
||||
setSample(response);
|
||||
setMessage(response.completed ? "Probe gespeichert und abgeschlossen." : "Aenderung gespeichert.");
|
||||
@@ -168,7 +209,35 @@ export default function TherapyPage() {
|
||||
))}
|
||||
</div>
|
||||
|
||||
<label className="field">
|
||||
{/* In-Udder Details from Lua */}
|
||||
{!noInUdderSelected && inUdderMedicationKeys.length > 0 && (
|
||||
<div className="field-grid field-grid--2col section-card__spacer">
|
||||
<label className="field">
|
||||
<span>Anzahl</span>
|
||||
<select
|
||||
value={inUdderCount}
|
||||
onChange={(e) => setInUdderCount(e.target.value)}
|
||||
disabled={therapyLocked}
|
||||
>
|
||||
<option value="">-</option>
|
||||
{COUNT_OPTIONS.map(opt => <option key={opt} value={opt}>{opt}</option>)}
|
||||
</select>
|
||||
</label>
|
||||
<label className="field">
|
||||
<span>Dauer</span>
|
||||
<select
|
||||
value={inUdderDuration}
|
||||
onChange={(e) => setInUdderDuration(e.target.value)}
|
||||
disabled={therapyLocked}
|
||||
>
|
||||
<option value="">-</option>
|
||||
{DURATION_OPTIONS.map(opt => <option key={opt} value={opt}>{opt}</option>)}
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<label className="field section-card__spacer">
|
||||
<span>Sonstiges</span>
|
||||
<textarea
|
||||
value={inUdderOther}
|
||||
@@ -202,7 +271,57 @@ export default function TherapyPage() {
|
||||
)}
|
||||
</div>
|
||||
|
||||
<label className="field">
|
||||
{/* Systemic Details from Lua */}
|
||||
{!noSystemicSelected && systemicMedicationKeys.length > 0 && (
|
||||
<div className="field-grid field-grid--2col section-card__spacer">
|
||||
<label className="field">
|
||||
<span>Anzahl</span>
|
||||
<select
|
||||
value={systemicCount}
|
||||
onChange={(e) => setSystemicCount(e.target.value)}
|
||||
disabled={therapyLocked}
|
||||
>
|
||||
<option value="">-</option>
|
||||
{COUNT_OPTIONS.map(opt => <option key={opt} value={opt}>{opt}</option>)}
|
||||
</select>
|
||||
</label>
|
||||
<label className="field">
|
||||
<span>Dauer</span>
|
||||
<select
|
||||
value={systemicDuration}
|
||||
onChange={(e) => setSystemicDuration(e.target.value)}
|
||||
disabled={therapyLocked}
|
||||
>
|
||||
<option value="">-</option>
|
||||
{DURATION_OPTIONS.map(opt => <option key={opt} value={opt}>{opt}</option>)}
|
||||
</select>
|
||||
</label>
|
||||
<label className="field">
|
||||
<span>Dosierung</span>
|
||||
<select
|
||||
value={systemicDosage}
|
||||
onChange={(e) => setSystemicDosage(e.target.value)}
|
||||
disabled={therapyLocked}
|
||||
>
|
||||
<option value="">-</option>
|
||||
{DOSAGE_OPTIONS.map(opt => <option key={opt} value={opt}>{opt}</option>)}
|
||||
</select>
|
||||
</label>
|
||||
<label className="field">
|
||||
<span>Ort</span>
|
||||
<select
|
||||
value={systemicLocation}
|
||||
onChange={(e) => setSystemicLocation(e.target.value)}
|
||||
disabled={therapyLocked}
|
||||
>
|
||||
<option value="">-</option>
|
||||
{LOCATION_OPTIONS.map(opt => <option key={opt} value={opt}>{opt}</option>)}
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<label className="field section-card__spacer">
|
||||
<span>Sonstiges</span>
|
||||
<textarea
|
||||
value={systemicOther}
|
||||
@@ -254,6 +373,33 @@ export default function TherapyPage() {
|
||||
</section>
|
||||
)}
|
||||
|
||||
{/* Additional Options from Lua */}
|
||||
{sample.sampleKind === "LACTATION" && (
|
||||
<section className="section-card">
|
||||
<p className="eyebrow">Sonstiges</p>
|
||||
<div className="field-grid">
|
||||
<label className="field field--checkbox">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={noAntibioticTreatment}
|
||||
onChange={(e) => setNoAntibioticTreatment(e.target.checked)}
|
||||
disabled={therapyLocked}
|
||||
/>
|
||||
<span>Keine Antibiose, gut ausmelken (evtl. Oxytocin), als letzte melken, strikte Hygiene</span>
|
||||
</label>
|
||||
<label className="field field--checkbox">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={startvacVaccination}
|
||||
onChange={(e) => setStartvacVaccination(e.target.checked)}
|
||||
disabled={therapyLocked}
|
||||
/>
|
||||
<span>Startvac-Impfung</span>
|
||||
</label>
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
|
||||
<section className="form-grid">
|
||||
<article className="section-card">
|
||||
<label className="field">
|
||||
|
||||
586
frontend/src/pages/UserManagementPage.tsx
Normal file
586
frontend/src/pages/UserManagementPage.tsx
Normal file
@@ -0,0 +1,586 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { apiGet, apiPost } from "../lib/api";
|
||||
import { useSession } from "../lib/session";
|
||||
import type { UserRow } from "../lib/types";
|
||||
|
||||
interface SubUserRow {
|
||||
id: string;
|
||||
displayName: string;
|
||||
email: string | null;
|
||||
active: boolean;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export default function UserManagementPage() {
|
||||
const { user, updateUser } = useSession();
|
||||
const [users, setUsers] = useState<SubUserRow[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [message, setMessage] = useState<string | null>(null);
|
||||
const [showCreateForm, setShowCreateForm] = useState(false);
|
||||
const isAdmin = user?.role === "ADMIN";
|
||||
const isPrimaryUser = user?.primaryUser === true;
|
||||
const canManageUsers = isAdmin || isPrimaryUser;
|
||||
|
||||
// Form state for creating new sub-user
|
||||
const [newUserName, setNewUserName] = useState("");
|
||||
const [newUserEmail, setNewUserEmail] = useState("");
|
||||
const [newUserPassword, setNewUserPassword] = useState("");
|
||||
const [newUserPasswordConfirm, setNewUserPasswordConfirm] = useState("");
|
||||
const [creating, setCreating] = useState(false);
|
||||
|
||||
// Form state for editing own profile
|
||||
const [showProfileForm, setShowProfileForm] = useState(false);
|
||||
const [profileData, setProfileData] = useState({
|
||||
displayName: "",
|
||||
companyName: "",
|
||||
street: "",
|
||||
houseNumber: "",
|
||||
postalCode: "",
|
||||
city: "",
|
||||
email: "",
|
||||
phoneNumber: "",
|
||||
});
|
||||
const [savingProfile, setSavingProfile] = useState(false);
|
||||
|
||||
// Initialize profile data from session user
|
||||
useEffect(() => {
|
||||
if (user) {
|
||||
setProfileData({
|
||||
displayName: user.displayName || "",
|
||||
companyName: user.companyName || "",
|
||||
street: user.street || "",
|
||||
houseNumber: user.houseNumber || "",
|
||||
postalCode: user.postalCode || "",
|
||||
city: user.city || "",
|
||||
email: user.email || "",
|
||||
phoneNumber: user.phoneNumber || "",
|
||||
});
|
||||
}
|
||||
}, [user]);
|
||||
|
||||
function resetProfileData() {
|
||||
setProfileData({
|
||||
displayName: user?.displayName || "",
|
||||
companyName: user?.companyName || "",
|
||||
street: user?.street || "",
|
||||
houseNumber: user?.houseNumber || "",
|
||||
postalCode: user?.postalCode || "",
|
||||
city: user?.city || "",
|
||||
email: user?.email || "",
|
||||
phoneNumber: user?.phoneNumber || "",
|
||||
});
|
||||
}
|
||||
|
||||
function openProfileDialog() {
|
||||
resetProfileData();
|
||||
setShowProfileForm(true);
|
||||
}
|
||||
|
||||
function closeProfileDialog() {
|
||||
resetProfileData();
|
||||
setShowProfileForm(false);
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
async function loadUsers() {
|
||||
try {
|
||||
const response = await apiGet<UserRow[]>("/portal/users");
|
||||
if (isAdmin) {
|
||||
// Admin sieht alle Hauptnutzer (außer andere Admins)
|
||||
const primaryUsers = response
|
||||
.filter((u) => u.primaryUser && u.role !== "ADMIN")
|
||||
.map((u) => ({
|
||||
id: u.id,
|
||||
displayName: u.displayName,
|
||||
email: u.email,
|
||||
active: u.active,
|
||||
updatedAt: u.updatedAt,
|
||||
}));
|
||||
setUsers(primaryUsers);
|
||||
} else {
|
||||
// Hauptnutzer sieht alle seine Unterbenutzer (nicht-primary)
|
||||
const subUsers = response
|
||||
.filter((u) => !u.primaryUser)
|
||||
.map((u) => ({
|
||||
id: u.id,
|
||||
displayName: u.displayName,
|
||||
email: u.email,
|
||||
active: u.active,
|
||||
updatedAt: u.updatedAt,
|
||||
}));
|
||||
setUsers(subUsers);
|
||||
}
|
||||
} catch (error) {
|
||||
setMessage((error as Error).message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
void loadUsers();
|
||||
}, [isAdmin]);
|
||||
|
||||
async function toggleUserStatus(userId: string, newStatus: boolean) {
|
||||
try {
|
||||
const userToUpdate = users.find((u) => u.id === userId);
|
||||
if (!userToUpdate) return;
|
||||
|
||||
await apiPost("/portal/users", {
|
||||
...userToUpdate,
|
||||
active: newStatus,
|
||||
});
|
||||
|
||||
setUsers((current) =>
|
||||
current.map((u) => (u.id === userId ? { ...u, active: newStatus } : u))
|
||||
);
|
||||
|
||||
setMessage(
|
||||
`Benutzer "${userToUpdate.displayName}" wurde ${
|
||||
newStatus ? "freigegeben" : "gesperrt"
|
||||
}.`
|
||||
);
|
||||
|
||||
setTimeout(() => setMessage(null), 3000);
|
||||
} catch (error) {
|
||||
setMessage((error as Error).message);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleCreateUser(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
if (!newUserName.trim() || !newUserEmail.trim() || !newUserPassword.trim()) {
|
||||
setMessage("Bitte alle Felder ausfüllen.");
|
||||
return;
|
||||
}
|
||||
if (newUserPassword !== newUserPasswordConfirm) {
|
||||
setMessage("Die Passwörter stimmen nicht überein.");
|
||||
return;
|
||||
}
|
||||
|
||||
setCreating(true);
|
||||
try {
|
||||
await apiPost("/portal/users", {
|
||||
displayName: newUserName.trim(),
|
||||
email: newUserEmail.trim(),
|
||||
password: newUserPassword,
|
||||
});
|
||||
|
||||
// Reload users
|
||||
const response = await apiGet<UserRow[]>("/portal/users");
|
||||
const subUsers = response
|
||||
.filter((u) => !u.primaryUser)
|
||||
.map((u) => ({
|
||||
id: u.id,
|
||||
displayName: u.displayName,
|
||||
email: u.email,
|
||||
active: u.active,
|
||||
updatedAt: u.updatedAt,
|
||||
}));
|
||||
setUsers(subUsers);
|
||||
|
||||
// Reset form
|
||||
setNewUserName("");
|
||||
setNewUserEmail("");
|
||||
setNewUserPassword("");
|
||||
setNewUserPasswordConfirm("");
|
||||
setShowCreateForm(false);
|
||||
setMessage(`Benutzer "${newUserName}" wurde erstellt.`);
|
||||
setTimeout(() => setMessage(null), 3000);
|
||||
} catch (error) {
|
||||
setMessage((error as Error).message);
|
||||
} finally {
|
||||
setCreating(false);
|
||||
}
|
||||
}
|
||||
|
||||
function closeCreateUserDialog() {
|
||||
setShowCreateForm(false);
|
||||
setNewUserName("");
|
||||
setNewUserEmail("");
|
||||
setNewUserPassword("");
|
||||
setNewUserPasswordConfirm("");
|
||||
}
|
||||
|
||||
async function handleSaveProfile(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
if (!profileData.displayName.trim()) {
|
||||
setMessage("Name ist erforderlich.");
|
||||
return;
|
||||
}
|
||||
|
||||
setSavingProfile(true);
|
||||
try {
|
||||
const response = await apiPost<UserRow>("/portal/users", {
|
||||
id: user?.id,
|
||||
displayName: profileData.displayName.trim(),
|
||||
companyName: profileData.companyName.trim() || null,
|
||||
street: profileData.street.trim() || null,
|
||||
houseNumber: profileData.houseNumber.trim() || null,
|
||||
postalCode: profileData.postalCode.trim() || null,
|
||||
city: profileData.city.trim() || null,
|
||||
email: profileData.email.trim() || null,
|
||||
phoneNumber: profileData.phoneNumber.trim() || null,
|
||||
});
|
||||
|
||||
// Update session user
|
||||
if (updateUser && user) {
|
||||
updateUser({
|
||||
...user,
|
||||
displayName: response.displayName,
|
||||
companyName: response.companyName,
|
||||
street: response.street,
|
||||
houseNumber: response.houseNumber,
|
||||
postalCode: response.postalCode,
|
||||
city: response.city,
|
||||
email: response.email,
|
||||
phoneNumber: response.phoneNumber,
|
||||
});
|
||||
}
|
||||
|
||||
setShowProfileForm(false);
|
||||
setMessage("Ihre Stammdaten wurden aktualisiert.");
|
||||
setTimeout(() => setMessage(null), 3000);
|
||||
} catch (error) {
|
||||
setMessage((error as Error).message);
|
||||
} finally {
|
||||
setSavingProfile(false);
|
||||
}
|
||||
}
|
||||
|
||||
function formatDate(value: string) {
|
||||
return new Intl.DateTimeFormat("de-DE", {
|
||||
dateStyle: "medium",
|
||||
timeStyle: "short",
|
||||
}).format(new Date(value));
|
||||
}
|
||||
|
||||
if (!canManageUsers) {
|
||||
return (
|
||||
<div className="page-stack">
|
||||
<section className="section-card">
|
||||
<div className="alert alert--error">
|
||||
Zugriff verweigert. Diese Seite ist nur für Administratoren und Hauptbenutzer.
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="page-stack">
|
||||
{/* Header */}
|
||||
<section className="hero-card admin-hero">
|
||||
<div>
|
||||
<p className="eyebrow">Benutzerverwaltung</p>
|
||||
<h3>{isAdmin ? "Hauptnutzer freigeben oder sperren" : "Unterbenutzer verwalten"}</h3>
|
||||
<p className="muted-text">
|
||||
{isAdmin
|
||||
? "Verwalten Sie den Zugriff von Hauptnutzern auf das System. Gesperrte Benutzer können sich nicht mehr anmelden."
|
||||
: "Erstellen und verwalten Sie Unterbenutzer für Ihr Konto. Unterbenutzer können Proben registrieren und bearbeiten."}
|
||||
</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Status-Meldung */}
|
||||
{message ? (
|
||||
<div
|
||||
className={
|
||||
message.includes("freigegeben") ||
|
||||
message.includes("gesperrt") ||
|
||||
message.includes("erstellt") ||
|
||||
message.includes("aktualisiert")
|
||||
? "alert alert--success"
|
||||
: "alert alert--error"
|
||||
}
|
||||
>
|
||||
{message}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{/* Own Profile Form (nur für Hauptbenutzer) */}
|
||||
{isPrimaryUser && !isAdmin && (
|
||||
<section className="section-card">
|
||||
<div className="section-card__header user-management-page__profile-header">
|
||||
<div>
|
||||
<p className="eyebrow">Meine Stammdaten</p>
|
||||
<h3>{user?.displayName}</h3>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className="accent-button"
|
||||
onClick={openProfileDialog}
|
||||
>
|
||||
Bearbeiten
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
|
||||
{/* Tabelle mit Benutzern */}
|
||||
<section className="section-card">
|
||||
<div className="section-card__header">
|
||||
<div>
|
||||
<p className="eyebrow">{isAdmin ? "Hauptnutzer" : "Unterbenutzer"}</p>
|
||||
<h3>{isAdmin ? "Registrierte Hauptnutzer" : "Ihre Unterbenutzer"}</h3>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{loading ? (
|
||||
<div className="empty-state">Benutzer werden geladen...</div>
|
||||
) : users.length === 0 ? (
|
||||
<div className="empty-state">
|
||||
{isAdmin ? "Keine Hauptnutzer vorhanden." : "Keine Unterbenutzer vorhanden."}
|
||||
</div>
|
||||
) : (
|
||||
<div className="table-shell">
|
||||
<table className="data-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Name</th>
|
||||
{isAdmin && <th>Firma</th>}
|
||||
<th>E-Mail</th>
|
||||
<th>Status</th>
|
||||
<th>Letzte Änderung</th>
|
||||
<th>Aktion</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{users.map((entry) => (
|
||||
<tr key={entry.id} className={!entry.active ? "table-row--inactive" : ""}>
|
||||
<td>
|
||||
<strong>{entry.displayName}</strong>
|
||||
</td>
|
||||
{isAdmin && <td>{(entry as SubUserRow & { companyName?: string }).companyName ?? "-"}</td>}
|
||||
<td>{entry.email ?? "-"}</td>
|
||||
<td>
|
||||
<span
|
||||
className={`status-pill ${
|
||||
entry.active ? "status-pill--active" : "status-pill--inactive"
|
||||
}`}
|
||||
>
|
||||
{entry.active ? "Freigegeben" : "Gesperrt"}
|
||||
</span>
|
||||
</td>
|
||||
<td className="text-muted">{formatDate(entry.updatedAt)}</td>
|
||||
<td>
|
||||
<button
|
||||
type="button"
|
||||
className={`action-button ${
|
||||
entry.active ? "action-button--danger" : "action-button--success"
|
||||
}`}
|
||||
onClick={() => toggleUserStatus(entry.id, !entry.active)}
|
||||
>
|
||||
{entry.active ? "Sperren" : "Freigeben"}
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{isPrimaryUser && !isAdmin ? (
|
||||
<div className="page-actions page-actions--space-between user-management-page__create-action">
|
||||
<button
|
||||
type="button"
|
||||
className="accent-button"
|
||||
onClick={() => setShowCreateForm(true)}
|
||||
>
|
||||
+ Benutzer anlegen
|
||||
</button>
|
||||
</div>
|
||||
) : null}
|
||||
</section>
|
||||
|
||||
{isPrimaryUser && !isAdmin && showCreateForm ? (
|
||||
<div className="dialog-backdrop" onClick={closeCreateUserDialog}>
|
||||
<form className="dialog" onClick={(event) => event.stopPropagation()} onSubmit={handleCreateUser}>
|
||||
<div className="dialog__header">
|
||||
<div>
|
||||
<p className="eyebrow">Neuer Unterbenutzer</p>
|
||||
<h4>Benutzer anlegen</h4>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="dialog__body dialog__body--form">
|
||||
<div className="field-grid field-grid--2col">
|
||||
<label className="field">
|
||||
<span>Name *</span>
|
||||
<input
|
||||
type="text"
|
||||
value={newUserName}
|
||||
onChange={(e) => setNewUserName(e.target.value)}
|
||||
placeholder="Name des Benutzers"
|
||||
autoComplete="off"
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
<label className="field">
|
||||
<span>E-Mail *</span>
|
||||
<input
|
||||
type="email"
|
||||
value={newUserEmail}
|
||||
onChange={(e) => setNewUserEmail(e.target.value)}
|
||||
placeholder="email@beispiel.de"
|
||||
autoComplete="off"
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
<label className="field">
|
||||
<span>Passwort *</span>
|
||||
<input
|
||||
type="password"
|
||||
value={newUserPassword}
|
||||
onChange={(e) => setNewUserPassword(e.target.value)}
|
||||
placeholder="Passwort"
|
||||
autoComplete="new-password"
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
<label className="field">
|
||||
<span>Passwort wiederholen *</span>
|
||||
<input
|
||||
type="password"
|
||||
value={newUserPasswordConfirm}
|
||||
onChange={(e) => setNewUserPasswordConfirm(e.target.value)}
|
||||
placeholder="Passwort wiederholen"
|
||||
autoComplete="new-password"
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="dialog__actions dialog__actions--start">
|
||||
<button
|
||||
type="button"
|
||||
className="secondary-button"
|
||||
onClick={closeCreateUserDialog}
|
||||
disabled={creating}
|
||||
>
|
||||
Abbrechen
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
className="accent-button"
|
||||
disabled={creating}
|
||||
>
|
||||
{creating ? "Wird erstellt..." : "Benutzer erstellen"}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{isPrimaryUser && !isAdmin && showProfileForm ? (
|
||||
<div className="dialog-backdrop" onClick={closeProfileDialog}>
|
||||
<form className="dialog" onClick={(event) => event.stopPropagation()} onSubmit={handleSaveProfile}>
|
||||
<div className="dialog__header">
|
||||
<div>
|
||||
<p className="eyebrow">Meine Stammdaten</p>
|
||||
<h4>Stammdaten bearbeiten</h4>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="dialog__body dialog__body--form">
|
||||
<div className="field-grid field-grid--2col">
|
||||
<label className="field">
|
||||
<span>Name *</span>
|
||||
<input
|
||||
type="text"
|
||||
value={profileData.displayName}
|
||||
onChange={(e) => setProfileData({ ...profileData, displayName: e.target.value })}
|
||||
placeholder="Ihr Name"
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
<label className="field">
|
||||
<span>Firma</span>
|
||||
<input
|
||||
type="text"
|
||||
value={profileData.companyName}
|
||||
onChange={(e) => setProfileData({ ...profileData, companyName: e.target.value })}
|
||||
placeholder="Firmenname"
|
||||
/>
|
||||
</label>
|
||||
<label className="field">
|
||||
<span>Straße</span>
|
||||
<input
|
||||
type="text"
|
||||
value={profileData.street}
|
||||
onChange={(e) => setProfileData({ ...profileData, street: e.target.value })}
|
||||
placeholder="Straße"
|
||||
/>
|
||||
</label>
|
||||
<label className="field">
|
||||
<span>Hausnummer</span>
|
||||
<input
|
||||
type="text"
|
||||
value={profileData.houseNumber}
|
||||
onChange={(e) => setProfileData({ ...profileData, houseNumber: e.target.value })}
|
||||
placeholder="Hausnummer"
|
||||
/>
|
||||
</label>
|
||||
<label className="field">
|
||||
<span>PLZ</span>
|
||||
<input
|
||||
type="text"
|
||||
value={profileData.postalCode}
|
||||
onChange={(e) => setProfileData({ ...profileData, postalCode: e.target.value })}
|
||||
placeholder="Postleitzahl"
|
||||
/>
|
||||
</label>
|
||||
<label className="field">
|
||||
<span>Ort</span>
|
||||
<input
|
||||
type="text"
|
||||
value={profileData.city}
|
||||
onChange={(e) => setProfileData({ ...profileData, city: e.target.value })}
|
||||
placeholder="Ort"
|
||||
/>
|
||||
</label>
|
||||
<label className="field">
|
||||
<span>E-Mail</span>
|
||||
<input
|
||||
type="email"
|
||||
value={profileData.email}
|
||||
onChange={(e) => setProfileData({ ...profileData, email: e.target.value })}
|
||||
placeholder="email@beispiel.de"
|
||||
/>
|
||||
</label>
|
||||
<label className="field">
|
||||
<span>Telefon</span>
|
||||
<input
|
||||
type="tel"
|
||||
value={profileData.phoneNumber}
|
||||
onChange={(e) => setProfileData({ ...profileData, phoneNumber: e.target.value })}
|
||||
placeholder="Telefonnummer"
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="dialog__actions dialog__actions--start">
|
||||
<button
|
||||
type="button"
|
||||
className="secondary-button"
|
||||
onClick={closeProfileDialog}
|
||||
disabled={savingProfile}
|
||||
>
|
||||
Abbrechen
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
className="accent-button"
|
||||
disabled={savingProfile}
|
||||
>
|
||||
{savingProfile ? "Wird gespeichert..." : "Stammdaten speichern"}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
1
frontend/src/vite-env.d.ts
vendored
1
frontend/src/vite-env.d.ts
vendored
@@ -1,4 +1,5 @@
|
||||
interface ImportMetaEnv {
|
||||
readonly DEV: boolean;
|
||||
readonly VITE_API_URL?: string;
|
||||
}
|
||||
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -1,7 +1,26 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { defineConfig } from "vite";
|
||||
import react from "@vitejs/plugin-react";
|
||||
const CONFIG_DIR = path.dirname(fileURLToPath(import.meta.url));
|
||||
const POM_PATH = path.resolve(CONFIG_DIR, "../backend/pom.xml");
|
||||
function resolveAppVersion() {
|
||||
const content = fs.readFileSync(POM_PATH, "utf8");
|
||||
const parentRange = content.indexOf("<parent>");
|
||||
const parentEnd = content.indexOf("</parent>");
|
||||
const withoutParent = content.slice(0, parentRange) + content.slice(parentEnd + "</parent>".length);
|
||||
const match = withoutParent.match(/<version>(\d+\.\d+\.\d+)<\/version>/);
|
||||
if (match) {
|
||||
return match[1];
|
||||
}
|
||||
throw new Error(`Version konnte nicht aus ${POM_PATH} ermittelt werden.`);
|
||||
}
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
define: {
|
||||
__APP_VERSION__: JSON.stringify(resolveAppVersion()),
|
||||
},
|
||||
server: {
|
||||
port: 5173,
|
||||
host: "0.0.0.0",
|
||||
|
||||
@@ -1,8 +1,53 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { defineConfig } from "vite";
|
||||
import react from "@vitejs/plugin-react";
|
||||
|
||||
const CONFIG_DIR = path.dirname(fileURLToPath(import.meta.url));
|
||||
const APPLICATION_CONFIG_PATH = path.resolve(CONFIG_DIR, "../backend/src/main/resources/application.yml");
|
||||
|
||||
function resolveAppVersion(): string {
|
||||
const lines = fs.readFileSync(APPLICATION_CONFIG_PATH, "utf8").split(/\r?\n/);
|
||||
let inMuhSection = false;
|
||||
let inAppSection = false;
|
||||
|
||||
for (const line of lines) {
|
||||
const trimmedLine = line.trim();
|
||||
if (!trimmedLine || trimmedLine.startsWith("#")) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const indentation = line.length - line.trimStart().length;
|
||||
|
||||
if (indentation === 0) {
|
||||
inMuhSection = trimmedLine === "muh:";
|
||||
inAppSection = false;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (inMuhSection && indentation === 2) {
|
||||
inAppSection = trimmedLine === "app:";
|
||||
continue;
|
||||
}
|
||||
|
||||
if (inMuhSection && inAppSection && indentation === 4 && trimmedLine.startsWith("version:")) {
|
||||
const version = trimmedLine.slice("version:".length).trim().replace(/^['"]|['"]$/g, "");
|
||||
if (/^\d+\.\d+\.\d+$/.test(version)) {
|
||||
return version;
|
||||
}
|
||||
throw new Error(`Ungueltige Versionsnummer in ${APPLICATION_CONFIG_PATH}: ${version}`);
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error(`muh.app.version konnte nicht aus ${APPLICATION_CONFIG_PATH} ermittelt werden.`);
|
||||
}
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
define: {
|
||||
__APP_VERSION__: JSON.stringify(resolveAppVersion()),
|
||||
},
|
||||
server: {
|
||||
port: 5173,
|
||||
host: "0.0.0.0",
|
||||
|
||||
Reference in New Issue
Block a user