Compare commits
5 Commits
dfb2968510
...
1585129e1f
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1585129e1f | ||
|
|
05bedfedfb | ||
|
|
4549149e48 | ||
|
|
fd68b47414 | ||
|
|
1ec7ac6ccc |
@@ -3,7 +3,7 @@ name: Build and Push Docker Image
|
|||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
branches:
|
branches:
|
||||||
- master
|
- build
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
build-and-push:
|
build-and-push:
|
||||||
|
|||||||
1
public/icons/filter.svg
Normal file
1
public/icons/filter.svg
Normal file
@@ -0,0 +1 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960" width="24px" fill="#666666"><path d="M440-160q-17 0-28.5-11.5T400-200v-240L168-736q-15-20-4.5-42t36.5-22h560q26 0 36.5 22t-4.5 42L560-440v240q0 17-11.5 28.5T520-160h-80Zm40-308 198-252H282l198 252Zm0 0Z"/></svg>
|
||||||
|
After Width: | Height: | Size: 290 B |
1
public/icons/menu.svg
Normal file
1
public/icons/menu.svg
Normal file
@@ -0,0 +1 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960" width="24px" fill="#666666"><path d="M120-240v-80h720v80H120Zm0-200v-80h720v80H120Zm0-200v-80h720v80H120Z"/></svg>
|
||||||
|
After Width: | Height: | Size: 193 B |
1
public/icons/plus.svg
Normal file
1
public/icons/plus.svg
Normal file
@@ -0,0 +1 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 -960 960 960" width="24px" fill="#666666"><path d="M440-440H200v-80h240v-240h80v240h240v80H520v240h-80v-240Z"/></svg>
|
||||||
|
After Width: | Height: | Size: 182 B |
@@ -1,53 +1,53 @@
|
|||||||
import { Component, OnInit, Inject, PLATFORM_ID } from '@angular/core';
|
// /src/app/core/components/cookie-consent/cookie-consent.component.ts
|
||||||
import { isPlatformBrowser, CommonModule } from '@angular/common'; // isPlatformBrowser importieren
|
|
||||||
|
import { Component, OnInit, inject } from '@angular/core';
|
||||||
|
import { CommonModule } from '@angular/common';
|
||||||
|
import { StorageService } from '../../services/storage.service'; // <-- NEUER IMPORT
|
||||||
|
|
||||||
|
// Ein Enum für die verschiedenen Zustände ist typsicherer als reine Strings
|
||||||
|
type ConsentStatus = 'accepted' | 'declined';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-cookie-consent',
|
selector: 'app-cookie-consent',
|
||||||
|
standalone: true, // <-- standalone: true hinzufügen, falls es fehlt
|
||||||
imports: [CommonModule],
|
imports: [CommonModule],
|
||||||
templateUrl: './cookie-consent.component.html',
|
templateUrl: './cookie-consent.component.html',
|
||||||
styleUrl: './cookie-consent.component.css'
|
styleUrl: './cookie-consent.component.css'
|
||||||
})
|
})
|
||||||
export class CookieConsentComponent implements OnInit {
|
export class CookieConsentComponent implements OnInit {
|
||||||
|
// --- Abhängigkeiten mit moderner inject()-Syntax ---
|
||||||
|
private storageService = inject(StorageService);
|
||||||
|
|
||||||
isVisible = false;
|
isVisible = false;
|
||||||
private readonly consentKey = 'cookie_consent_status';
|
private readonly consentKey = 'cookie_consent_status';
|
||||||
private isBrowser: boolean;
|
|
||||||
|
|
||||||
// Wir injizieren PLATFORM_ID, um die aktuelle Plattform (Browser/Server) zu ermitteln.
|
// Der Konstruktor wird viel sauberer oder kann ganz entfallen
|
||||||
constructor(@Inject(PLATFORM_ID) private platformId: Object) {
|
constructor() {}
|
||||||
// Speichere das Ergebnis in einer Eigenschaft, um es wiederverwenden zu können.
|
|
||||||
this.isBrowser = isPlatformBrowser(this.platformId);
|
|
||||||
}
|
|
||||||
|
|
||||||
ngOnInit(): void {
|
ngOnInit(): void {
|
||||||
// Wir führen die Prüfung nur aus, wenn der Code im Browser läuft.
|
// Der Service kümmert sich um die Browser-Prüfung.
|
||||||
if (this.isBrowser) {
|
// Wir können ihn einfach immer aufrufen.
|
||||||
this.checkConsent();
|
this.checkConsent();
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
private checkConsent(): void {
|
private checkConsent(): void {
|
||||||
const consent = localStorage.getItem(this.consentKey);
|
const consent = this.storageService.getItem<ConsentStatus>(this.consentKey);
|
||||||
|
// Das Banner wird nur angezeigt, wenn noch gar nichts gespeichert wurde (consent ist null)
|
||||||
if (!consent) {
|
if (!consent) {
|
||||||
this.isVisible = true;
|
this.isVisible = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
accept(): void {
|
accept(): void {
|
||||||
// Wir stellen sicher, dass wir localStorage nur im Browser schreiben.
|
// Der Service kümmert sich um die Browser-Prüfung und Serialisierung.
|
||||||
if (this.isBrowser) {
|
this.storageService.setItem(this.consentKey, 'accepted');
|
||||||
localStorage.setItem(this.consentKey, 'accepted');
|
|
||||||
this.isVisible = false;
|
this.isVisible = false;
|
||||||
console.log('Cookies wurden akzeptiert.');
|
console.log('Cookies wurden akzeptiert.');
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
decline(): void {
|
decline(): void {
|
||||||
// Wir stellen sicher, dass wir localStorage nur im Browser schreiben.
|
this.storageService.setItem(this.consentKey, 'declined');
|
||||||
if (this.isBrowser) {
|
|
||||||
localStorage.setItem(this.consentKey, 'declined');
|
|
||||||
this.isVisible = false;
|
this.isVisible = false;
|
||||||
console.log('Cookies wurden abgelehnt.');
|
console.log('Cookies wurden abgelehnt.');
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -1,17 +1,18 @@
|
|||||||
// /src/app/core/services/auth.service.ts
|
// /src/app/core/services/auth.service.ts
|
||||||
|
|
||||||
import { Injectable, PLATFORM_ID, inject } from '@angular/core';
|
import { Injectable, inject } from '@angular/core';
|
||||||
import { HttpClient } from '@angular/common/http';
|
import { HttpClient } from '@angular/common/http';
|
||||||
import { isPlatformBrowser } from '@angular/common';
|
|
||||||
import { Router } from '@angular/router';
|
import { Router } from '@angular/router';
|
||||||
import { Observable, BehaviorSubject, of } from 'rxjs';
|
import { Observable, BehaviorSubject, of } from 'rxjs';
|
||||||
import { tap, catchError } from 'rxjs/operators';
|
import { tap, catchError } from 'rxjs/operators';
|
||||||
import { jwtDecode } from 'jwt-decode';
|
import { jwtDecode } from 'jwt-decode';
|
||||||
|
|
||||||
|
// Eigene Imports
|
||||||
import { LoginRequest, AuthResponse, RegisterRequest } from '../models/auth.models';
|
import { LoginRequest, AuthResponse, RegisterRequest } from '../models/auth.models';
|
||||||
import { API_URL } from '../tokens/api-url.token';
|
import { API_URL } from '../tokens/api-url.token';
|
||||||
|
import { StorageService } from './storage.service';
|
||||||
|
|
||||||
// Ein Hilfs-Interface, um die Struktur des dekodierten Tokens typsicher zu machen.
|
// Hilfs-Interface für die dekodierten Token-Daten.
|
||||||
interface DecodedToken {
|
interface DecodedToken {
|
||||||
exp: number; // Expiration time als UNIX-Timestamp in Sekunden
|
exp: number; // Expiration time als UNIX-Timestamp in Sekunden
|
||||||
// Hier könnten weitere Claims wie 'email', 'sub', 'role' etc. stehen
|
// Hier könnten weitere Claims wie 'email', 'sub', 'role' etc. stehen
|
||||||
@@ -21,24 +22,22 @@ interface DecodedToken {
|
|||||||
providedIn: 'root'
|
providedIn: 'root'
|
||||||
})
|
})
|
||||||
export class AuthService {
|
export class AuthService {
|
||||||
// --- Injizierte Abhängigkeiten mit moderner Syntax ---
|
// --- Injizierte Abhängigkeiten ---
|
||||||
private http = inject(HttpClient);
|
private http = inject(HttpClient);
|
||||||
private router = inject(Router);
|
private router = inject(Router);
|
||||||
private platformId = inject(PLATFORM_ID);
|
private storageService = inject(StorageService); // <-- NEU
|
||||||
private apiUrl = inject(API_URL);
|
private apiUrl = inject(API_URL);
|
||||||
|
|
||||||
private readonly endpoint = '/Auth';
|
private readonly endpoint = '/Auth';
|
||||||
private readonly TOKEN_KEY = 'auth-token';
|
private readonly TOKEN_KEY = 'auth-token';
|
||||||
private readonly ROLES_KEY = 'auth-user-roles';
|
private readonly ROLES_KEY = 'auth-user-roles';
|
||||||
|
|
||||||
private loggedInStatus = new BehaviorSubject<boolean>(this.isBrowser() && !!this.getToken());
|
private loggedInStatus = new BehaviorSubject<boolean>(!!this.getToken());
|
||||||
public isLoggedIn$ = this.loggedInStatus.asObservable();
|
public isLoggedIn$ = this.loggedInStatus.asObservable();
|
||||||
|
|
||||||
private tokenExpirationTimer: any;
|
private tokenExpirationTimer: any;
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
// Beim Initialisieren des Services prüfen, ob bereits ein Token vorhanden ist
|
|
||||||
// und ggf. den Logout-Timer dafür starten (z.B. nach einem Neuladen der Seite).
|
|
||||||
this.initTokenCheck();
|
this.initTokenCheck();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -47,7 +46,7 @@ export class AuthService {
|
|||||||
tap(response => {
|
tap(response => {
|
||||||
if (response?.isAuthSuccessful) {
|
if (response?.isAuthSuccessful) {
|
||||||
this.setSession(response);
|
this.setSession(response);
|
||||||
this.startTokenExpirationTimer(); // Timer nach erfolgreichem Login starten
|
this.startTokenExpirationTimer();
|
||||||
}
|
}
|
||||||
}),
|
}),
|
||||||
catchError(() => {
|
catchError(() => {
|
||||||
@@ -62,7 +61,7 @@ export class AuthService {
|
|||||||
tap(response => {
|
tap(response => {
|
||||||
if (response?.isAuthSuccessful) {
|
if (response?.isAuthSuccessful) {
|
||||||
this.setSession(response);
|
this.setSession(response);
|
||||||
this.startTokenExpirationTimer(); // Timer nach erfolgreichem Login starten
|
this.startTokenExpirationTimer();
|
||||||
}
|
}
|
||||||
}),
|
}),
|
||||||
catchError(() => {
|
catchError(() => {
|
||||||
@@ -80,7 +79,6 @@ export class AuthService {
|
|||||||
|
|
||||||
logout(): void {
|
logout(): void {
|
||||||
this.clearSession();
|
this.clearSession();
|
||||||
// Den proaktiven Timer stoppen, da der Logout manuell erfolgt.
|
|
||||||
if (this.tokenExpirationTimer) {
|
if (this.tokenExpirationTimer) {
|
||||||
clearTimeout(this.tokenExpirationTimer);
|
clearTimeout(this.tokenExpirationTimer);
|
||||||
}
|
}
|
||||||
@@ -88,13 +86,11 @@ export class AuthService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
getToken(): string | null {
|
getToken(): string | null {
|
||||||
return this.isBrowser() ? localStorage.getItem(this.TOKEN_KEY) : null;
|
return this.storageService.getItem<string>(this.TOKEN_KEY);
|
||||||
}
|
}
|
||||||
|
|
||||||
getUserRoles(): string[] {
|
getUserRoles(): string[] {
|
||||||
if (!this.isBrowser()) return [];
|
return this.storageService.getItem<string[]>(this.ROLES_KEY) || [];
|
||||||
const roles = localStorage.getItem(this.ROLES_KEY);
|
|
||||||
return roles ? JSON.parse(roles) : [];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
hasRole(requiredRole: string): boolean {
|
hasRole(requiredRole: string): boolean {
|
||||||
@@ -102,25 +98,19 @@ export class AuthService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private setSession(authResponse: AuthResponse): void {
|
private setSession(authResponse: AuthResponse): void {
|
||||||
if (this.isBrowser() && authResponse?.token && authResponse?.roles) {
|
if (authResponse?.token && authResponse?.roles) {
|
||||||
localStorage.setItem(this.TOKEN_KEY, authResponse.token);
|
this.storageService.setItem(this.TOKEN_KEY, authResponse.token);
|
||||||
localStorage.setItem(this.ROLES_KEY, JSON.stringify(authResponse.roles));
|
this.storageService.setItem(this.ROLES_KEY, authResponse.roles);
|
||||||
this.loggedInStatus.next(true);
|
this.loggedInStatus.next(true);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private clearSession(): void {
|
private clearSession(): void {
|
||||||
if (this.isBrowser()) {
|
this.storageService.removeItem(this.TOKEN_KEY);
|
||||||
localStorage.removeItem(this.TOKEN_KEY);
|
this.storageService.removeItem(this.ROLES_KEY);
|
||||||
localStorage.removeItem(this.ROLES_KEY);
|
|
||||||
}
|
|
||||||
this.loggedInStatus.next(false);
|
this.loggedInStatus.next(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
private isBrowser(): boolean {
|
|
||||||
return isPlatformBrowser(this.platformId);
|
|
||||||
}
|
|
||||||
|
|
||||||
private startTokenExpirationTimer(): void {
|
private startTokenExpirationTimer(): void {
|
||||||
if (this.tokenExpirationTimer) {
|
if (this.tokenExpirationTimer) {
|
||||||
clearTimeout(this.tokenExpirationTimer);
|
clearTimeout(this.tokenExpirationTimer);
|
||||||
@@ -133,18 +123,21 @@ export class AuthService {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
const decodedToken = jwtDecode<DecodedToken>(token);
|
const decodedToken = jwtDecode<DecodedToken>(token);
|
||||||
const expirationDate = new Date(decodedToken.exp * 1000); // JWT 'exp' ist in Sekunden, Date() braucht Millisekunden
|
const expirationDate = new Date(decodedToken.exp * 1000);
|
||||||
const timeoutDuration = expirationDate.getTime() - new Date().getTime();
|
const timeoutDuration = expirationDate.getTime() - new Date().getTime();
|
||||||
|
|
||||||
if (timeoutDuration > 0) {
|
// Puffer, um Clock-Skew-Probleme zu vermeiden
|
||||||
|
const clockSkewBuffer = 5000; // 5 Sekunden
|
||||||
|
|
||||||
|
if (timeoutDuration > clockSkewBuffer) {
|
||||||
this.tokenExpirationTimer = setTimeout(() => {
|
this.tokenExpirationTimer = setTimeout(() => {
|
||||||
console.warn('Sitzung proaktiv beendet, da das Token abgelaufen ist.');
|
console.warn('Sitzung proaktiv beendet, da das Token abgelaufen ist.');
|
||||||
this.logout();
|
this.logout();
|
||||||
// Hier könnte man eine Snackbar-Nachricht anzeigen
|
|
||||||
}, timeoutDuration);
|
}, timeoutDuration);
|
||||||
} else {
|
} else {
|
||||||
// Das gespeicherte Token ist bereits abgelaufen
|
if (this.getToken()) {
|
||||||
this.clearSession();
|
this.logout();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Fehler beim Dekodieren des Tokens. Session wird bereinigt.', error);
|
console.error('Fehler beim Dekodieren des Tokens. Session wird bereinigt.', error);
|
||||||
@@ -153,8 +146,7 @@ export class AuthService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private initTokenCheck(): void {
|
private initTokenCheck(): void {
|
||||||
if (this.isBrowser()) {
|
// Der StorageService ist bereits SSR-sicher, wir brauchen hier keine extra Prüfung.
|
||||||
this.startTokenExpirationTimer();
|
this.startTokenExpirationTimer();
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}
|
}
|
||||||
87
src/app/core/services/storage.service.ts
Normal file
87
src/app/core/services/storage.service.ts
Normal file
@@ -0,0 +1,87 @@
|
|||||||
|
// /src/app/core/services/storage.service.ts
|
||||||
|
|
||||||
|
import { Injectable, PLATFORM_ID, inject } from '@angular/core';
|
||||||
|
import { isPlatformBrowser } from '@angular/common';
|
||||||
|
|
||||||
|
// Definiert die verfügbaren Speichertypen
|
||||||
|
export type StorageType = 'localStorage' | 'sessionStorage';
|
||||||
|
|
||||||
|
@Injectable({
|
||||||
|
providedIn: 'root'
|
||||||
|
})
|
||||||
|
export class StorageService {
|
||||||
|
private platformId = inject(PLATFORM_ID);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Speichert einen Wert im angegebenen Web Storage.
|
||||||
|
* Serialisiert Objekte automatisch zu JSON.
|
||||||
|
* @param key Der Schlüssel, unter dem der Wert gespeichert wird.
|
||||||
|
* @param value Der zu speichernde Wert.
|
||||||
|
* @param storageType Der zu verwendende Speicher ('localStorage' oder 'sessionStorage'). Standard ist 'localStorage'.
|
||||||
|
*/
|
||||||
|
setItem<T>(key: string, value: T, storageType: StorageType = 'localStorage'): void {
|
||||||
|
if (isPlatformBrowser(this.platformId)) {
|
||||||
|
try {
|
||||||
|
const storage = this.getStorage(storageType);
|
||||||
|
const serializedValue = JSON.stringify(value);
|
||||||
|
storage.setItem(key, serializedValue);
|
||||||
|
} catch (e) {
|
||||||
|
console.error(`Error saving to ${storageType} with key "${key}"`, e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ruft einen Wert aus dem angegebenen Web Storage ab.
|
||||||
|
* Deserialisiert JSON-Strings automatisch in Objekte.
|
||||||
|
* @param key Der Schlüssel des abzurufenden Wertes.
|
||||||
|
* @param storageType Der zu verwendende Speicher ('localStorage' oder 'sessionStorage'). Standard ist 'localStorage'.
|
||||||
|
* @returns Der abgerufene Wert (typsicher) oder null, wenn der Schlüssel nicht existiert oder ein Fehler auftritt.
|
||||||
|
*/
|
||||||
|
getItem<T>(key: string, storageType: StorageType = 'localStorage'): T | null {
|
||||||
|
if (isPlatformBrowser(this.platformId)) {
|
||||||
|
try {
|
||||||
|
const storage = this.getStorage(storageType);
|
||||||
|
const serializedValue = storage.getItem(key);
|
||||||
|
if (serializedValue === null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return JSON.parse(serializedValue) as T;
|
||||||
|
} catch (e) {
|
||||||
|
console.error(`Error reading from ${storageType} with key "${key}"`, e);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Entfernt einen Wert aus dem angegebenen Web Storage.
|
||||||
|
* @param key Der Schlüssel des zu entfernenden Wertes.
|
||||||
|
* @param storageType Der zu verwendende Speicher ('localStorage' oder 'sessionStorage'). Standard ist 'localStorage'.
|
||||||
|
*/
|
||||||
|
removeItem(key: string, storageType: StorageType = 'localStorage'): void {
|
||||||
|
if (isPlatformBrowser(this.platformId)) {
|
||||||
|
const storage = this.getStorage(storageType);
|
||||||
|
storage.removeItem(key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Löscht alle Einträge im angegebenen Web Storage.
|
||||||
|
* @param storageType Der zu leerende Speicher ('localStorage' oder 'sessionStorage'). Standard ist 'localStorage'.
|
||||||
|
*/
|
||||||
|
clear(storageType: StorageType = 'localStorage'): void {
|
||||||
|
if (isPlatformBrowser(this.platformId)) {
|
||||||
|
const storage = this.getStorage(storageType);
|
||||||
|
storage.clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Private Hilfsfunktion, um das korrekte Storage-Objekt zurückzugeben.
|
||||||
|
*/
|
||||||
|
private getStorage(storageType: StorageType): Storage {
|
||||||
|
return storageType === 'localStorage' ? window.localStorage : window.sessionStorage;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -66,6 +66,30 @@ export class DashboardPageComponent {
|
|||||||
amount: '€87.00',
|
amount: '€87.00',
|
||||||
status: 'info', // NEU: Sprechender Status
|
status: 'info', // NEU: Sprechender Status
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
id: 'a2d4b',
|
||||||
|
user: { name: 'Max Mustermann', email: 'max@test.de', avatarUrl: 'https://i.pravatar.cc/150?u=max' },
|
||||||
|
amount: '€129.99',
|
||||||
|
status: 'completed', // NEU: Sprechender Status
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'f8e9c',
|
||||||
|
user: { name: 'Erika Musterfrau', email: 'erika@test.de', avatarUrl: 'https://i.pravatar.cc/150?u=erika' },
|
||||||
|
amount: '€49.50',
|
||||||
|
status: 'processing', // NEU: Sprechender Status
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'h1g3j',
|
||||||
|
user: { name: 'John Doe', email: 'john.d@test.com', avatarUrl: 'https://i.pravatar.cc/150?u=john' },
|
||||||
|
amount: '€87.00',
|
||||||
|
status: 'cancelled', // NEU: Sprechender Status
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'h1g3j',
|
||||||
|
user: { name: 'John Doe', email: 'john.d@test.com', avatarUrl: 'https://i.pravatar.cc/150?u=john' },
|
||||||
|
amount: '€87.00',
|
||||||
|
status: 'info', // NEU: Sprechender Status
|
||||||
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
handleDeleteOrder(orderId: string): void {
|
handleDeleteOrder(orderId: string): void {
|
||||||
|
|||||||
@@ -0,0 +1,64 @@
|
|||||||
|
:host { display: block; }
|
||||||
|
|
||||||
|
.form-header {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
padding-bottom: 1rem;
|
||||||
|
margin-bottom: 1.5rem;
|
||||||
|
border-bottom: 1px solid var(--color-border);
|
||||||
|
}
|
||||||
|
|
||||||
|
h3[card-header] { margin: 0; }
|
||||||
|
|
||||||
|
.form-section { margin-bottom: 1.5rem; }
|
||||||
|
.section-title { font-size: 1.1rem; font-weight: 600; margin-bottom: 1.25rem; color: var(--color-text); }
|
||||||
|
|
||||||
|
.form-grid {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
|
||||||
|
gap: 1.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.grid-col-span-2 { grid-column: 1 / -1; }
|
||||||
|
|
||||||
|
.input-with-button { display: flex; gap: 0.5rem; }
|
||||||
|
.input-with-button input { flex-grow: 1; }
|
||||||
|
|
||||||
|
.category-checkbox-group {
|
||||||
|
max-height: 150px;
|
||||||
|
overflow-y: auto;
|
||||||
|
border: 1px solid var(--color-border);
|
||||||
|
border-radius: var(--border-radius-md);
|
||||||
|
padding: 0.75rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.checkbox-item { display: flex; align-items: center; gap: 0.5rem; margin-bottom: 0.5rem; }
|
||||||
|
.checkbox-item input { margin: 0; }
|
||||||
|
.checkbox-item label { font-weight: normal; }
|
||||||
|
|
||||||
|
.image-management {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: 1fr 2fr;
|
||||||
|
gap: 1.5rem;
|
||||||
|
align-items: start;
|
||||||
|
}
|
||||||
|
|
||||||
|
.image-upload-fields { display: flex; flex-direction: column; gap: 1rem; }
|
||||||
|
.image-preview-grid { display: flex; flex-wrap: wrap; gap: 0.75rem; }
|
||||||
|
.image-preview-item { position: relative; }
|
||||||
|
.image-preview-item img {
|
||||||
|
width: 80px; height: 80px; object-fit: cover;
|
||||||
|
border-radius: var(--border-radius-md);
|
||||||
|
border: 2px solid var(--color-border);
|
||||||
|
}
|
||||||
|
.image-preview-item img.main-image { border-color: var(--color-success); }
|
||||||
|
.image-preview-item app-button { position: absolute; top: -10px; right: -10px; }
|
||||||
|
|
||||||
|
.checkbox-group { display: flex; align-items: center; gap: 2rem; }
|
||||||
|
.form-actions { display: flex; justify-content: flex-end; gap: 1rem; margin-top: 2rem; }
|
||||||
|
.divider { border: none; border-top: 1px solid var(--color-border); margin: 2rem 0; }
|
||||||
|
|
||||||
|
@media (max-width: 992px) {
|
||||||
|
.image-management { grid-template-columns: 1fr; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
<!-- /src/app/features/admin/components/products/product-edit/product-edit.component.html -->
|
||||||
|
|
||||||
|
<app-card>
|
||||||
|
<div *ngIf="isLoading; else formContent" class="loading-container">
|
||||||
|
<p>Lade Produktdaten...</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<ng-template #formContent>
|
||||||
|
<form [formGroup]="productForm" (ngSubmit)="onSubmit()" novalidate>
|
||||||
|
<div class="form-header">
|
||||||
|
<h3 card-header>{{ isEditMode ? "Produkt bearbeiten" : "Neues Produkt erstellen" }}</h3>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="edit-layout">
|
||||||
|
<!-- LINKE SPALTE -->
|
||||||
|
<div class="main-content">
|
||||||
|
<app-card>
|
||||||
|
<h4 card-header>Allgemein</h4>
|
||||||
|
<div class="form-section">
|
||||||
|
<app-form-field label="Name"><input type="text" formControlName="name"></app-form-field>
|
||||||
|
<app-form-field label="Slug"><input type="text" formControlName="slug"></app-form-field>
|
||||||
|
<app-form-textarea label="Beschreibung" [rows]="8" formControlName="description"></app-form-textarea>
|
||||||
|
</div>
|
||||||
|
</app-card>
|
||||||
|
|
||||||
|
<app-card>
|
||||||
|
<h4 card-header>Produktbilder</h4>
|
||||||
|
<!-- ... (Bild-Management bleibt gleich) ... -->
|
||||||
|
</app-card>
|
||||||
|
|
||||||
|
<app-card>
|
||||||
|
<h4 card-header>Preisgestaltung</h4>
|
||||||
|
<div class="form-grid price-grid">
|
||||||
|
<!-- KORREKTUR: Wrapper entfernt, formControlName auf die Komponente -->
|
||||||
|
<app-form-field label="Preis (€)" type="number" formControlName="price"></app-form-field>
|
||||||
|
<app-form-field label="Alter Preis (€)" type="number" formControlName="oldPrice"></app-form-field>
|
||||||
|
<app-form-field label="Einkaufspreis (€)" type="number" formControlName="purchasePrice"></app-form-field>
|
||||||
|
</div>
|
||||||
|
</app-card>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- RECHTE SPALTE -->
|
||||||
|
<div class="sidebar-content">
|
||||||
|
<app-card>
|
||||||
|
<h4 card-header>Status</h4>
|
||||||
|
<div class="form-section">
|
||||||
|
<app-slide-toggle formControlName="isActive">Aktiv (im Shop sichtbar)</app-slide-toggle>
|
||||||
|
</div>
|
||||||
|
</app-card>
|
||||||
|
|
||||||
|
<app-card>
|
||||||
|
<h4 card-header>Organisation</h4>
|
||||||
|
<div class="form-section">
|
||||||
|
<div class="form-field">
|
||||||
|
<label class="form-label">SKU (Artikelnummer)</label>
|
||||||
|
<div class="input-with-button">
|
||||||
|
<input type="text" class="form-input" formControlName="sku" />
|
||||||
|
<app-button buttonType="icon" (click)="generateSku()" iconName="placeholder"></app-button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<app-form-field label="Lagerbestand" type="number" formControlName="stockQuantity"></app-form-field>
|
||||||
|
<app-form-field label="Gewicht (kg)" type="number" formControlName="weight"></app-form-field>
|
||||||
|
<app-form-select label="Lieferant" [options]="(supplierOptions$ | async) || []" formControlName="supplierId"></app-form-select>
|
||||||
|
</div>
|
||||||
|
</app-card>
|
||||||
|
|
||||||
|
<app-card>
|
||||||
|
<h4 card-header>Kategorien</h4>
|
||||||
|
<div class="form-section">
|
||||||
|
<div class="multi-select-container">
|
||||||
|
<div class="selected-pills">
|
||||||
|
<span *ngFor="let catId of categorieIds.value" class="pill">
|
||||||
|
{{ getCategoryName(catId) }}
|
||||||
|
<app-icon iconName="x" (click)="removeCategoryById(catId)"></app-icon>
|
||||||
|
</span>
|
||||||
|
<span *ngIf="categorieIds.length === 0" class="placeholder">Keine ausgewählt</span>
|
||||||
|
</div>
|
||||||
|
<div class="category-checkbox-group">
|
||||||
|
<label *ngFor="let category of allCategories$ | async">
|
||||||
|
<input type="checkbox" [value]="category.id" [checked]="isCategorySelected(category.id)" (change)="onCategoryChange($event)">
|
||||||
|
{{ category.name }}
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</app-card>
|
||||||
|
|
||||||
|
<app-card>
|
||||||
|
<h4 card-header>Hervorheben</h4>
|
||||||
|
<div class="form-section">
|
||||||
|
<app-slide-toggle formControlName="isFeatured">Auf Startseite anzeigen</app-slide-toggle>
|
||||||
|
<app-form-field *ngIf="productForm.get('isFeatured')?.value" label="Anzeigereihenfolge">
|
||||||
|
<input type="number" formControlName="featuredDisplayOrder">
|
||||||
|
</app-form-field>
|
||||||
|
</div>
|
||||||
|
</app-card>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="form-actions">
|
||||||
|
<app-button buttonType="stroked" (click)="cancel()">Abbrechen</app-button>
|
||||||
|
<app-button submitType="submit" buttonType="primary" [disabled]="productForm.invalid || isLoading">
|
||||||
|
{{ isEditMode ? "Änderungen speichern" : "Produkt erstellen" }}
|
||||||
|
</app-button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</ng-template>
|
||||||
|
</app-card>
|
||||||
@@ -0,0 +1,228 @@
|
|||||||
|
// /src/app/features/admin/components/products/product-edit/product-edit.component.ts
|
||||||
|
|
||||||
|
import { Component, OnInit, OnDestroy, inject } from '@angular/core';
|
||||||
|
import { CommonModule } from '@angular/common';
|
||||||
|
import { ActivatedRoute, Router } from '@angular/router';
|
||||||
|
import { FormBuilder, FormGroup, FormArray, FormControl, ReactiveFormsModule, Validators } from '@angular/forms';
|
||||||
|
import { Observable, Subscription } from 'rxjs';
|
||||||
|
import { debounceTime, distinctUntilChanged, map, startWith, tap } from 'rxjs/operators';
|
||||||
|
|
||||||
|
// Models
|
||||||
|
import { AdminProduct, ProductImage } from '../../../../core/models/product.model';
|
||||||
|
import { Category } from '../../../../core/models/category.model';
|
||||||
|
import { Supplier } from '../../../../core/models/supplier.model';
|
||||||
|
|
||||||
|
// Services
|
||||||
|
import { ProductService } from '../../../services/product.service';
|
||||||
|
import { CategoryService } from '../../../services/category.service';
|
||||||
|
import { SupplierService } from '../../../services/supplier.service';
|
||||||
|
import { SnackbarService } from '../../../../shared/services/snackbar.service';
|
||||||
|
|
||||||
|
// Wiederverwendbare UI- & Form-Komponenten
|
||||||
|
import { CardComponent } from '../../../../shared/components/ui/card/card.component';
|
||||||
|
import { ButtonComponent } from '../../../../shared/components/ui/button/button.component';
|
||||||
|
import { IconComponent } from '../../../../shared/components/ui/icon/icon.component';
|
||||||
|
import { FormFieldComponent } from '../../../../shared/components/form/form-field/form-field.component';
|
||||||
|
import { FormSelectComponent, SelectOption } from '../../../../shared/components/form/form-select/form-select.component';
|
||||||
|
import { FormTextareaComponent } from '../../../../shared/components/form/form-textarea/form-textarea.component';
|
||||||
|
import { SlideToggleComponent } from '../../../../shared/components/form/slide-toggle/slide-toggle.component';
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-product-edit',
|
||||||
|
standalone: true,
|
||||||
|
imports: [ CommonModule, ReactiveFormsModule, CardComponent, ButtonComponent, IconComponent, FormFieldComponent, FormSelectComponent, FormTextareaComponent, SlideToggleComponent ],
|
||||||
|
templateUrl: './product-edit.component.html',
|
||||||
|
styleUrl: './product-edit.component.css'
|
||||||
|
})
|
||||||
|
export class ProductEditComponent implements OnInit, OnDestroy {
|
||||||
|
private route = inject(ActivatedRoute);
|
||||||
|
private router = inject(Router);
|
||||||
|
private productService = inject(ProductService);
|
||||||
|
private categoryService = inject(CategoryService);
|
||||||
|
private supplierService = inject(SupplierService);
|
||||||
|
private fb = inject(FormBuilder);
|
||||||
|
private snackbarService = inject(SnackbarService);
|
||||||
|
|
||||||
|
productId: string | null = null;
|
||||||
|
isEditMode = false;
|
||||||
|
isLoading = true;
|
||||||
|
productForm: FormGroup;
|
||||||
|
|
||||||
|
allCategories$!: Observable<Category[]>;
|
||||||
|
supplierOptions$!: Observable<SelectOption[]>;
|
||||||
|
allCategories: Category[] = [];
|
||||||
|
|
||||||
|
private nameChangeSubscription?: Subscription;
|
||||||
|
existingImages: ProductImage[] = [];
|
||||||
|
mainImageFile: File | null = null;
|
||||||
|
additionalImageFiles: File[] = [];
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
this.productForm = this.fb.group({
|
||||||
|
name: ['', Validators.required], slug: ['', Validators.required], sku: ['', Validators.required],
|
||||||
|
description: [''], price: [0, [Validators.required, Validators.min(0)]],
|
||||||
|
oldPrice: [null, [Validators.min(0)]], purchasePrice: [null, [Validators.min(0)]],
|
||||||
|
stockQuantity: [0, [Validators.required, Validators.min(0)]], weight: [null, [Validators.min(0)]],
|
||||||
|
isActive: [true], isFeatured: [false], featuredDisplayOrder: [0],
|
||||||
|
supplierId: [null], categorieIds: this.fb.array([]), imagesToDelete: this.fb.array([])
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
get categorieIds(): FormArray { return this.productForm.get('categorieIds') as FormArray; }
|
||||||
|
get imagesToDelete(): FormArray { return this.productForm.get('imagesToDelete') as FormArray; }
|
||||||
|
|
||||||
|
ngOnInit(): void {
|
||||||
|
this.productId = this.route.snapshot.paramMap.get('id');
|
||||||
|
this.isEditMode = !!this.productId;
|
||||||
|
|
||||||
|
this.loadDropdownData();
|
||||||
|
this.subscribeToNameChanges();
|
||||||
|
|
||||||
|
if (this.isEditMode && this.productId) {
|
||||||
|
this.isLoading = true;
|
||||||
|
this.productService.getById(this.productId).subscribe(product => {
|
||||||
|
if (product) {
|
||||||
|
this.populateForm(product);
|
||||||
|
}
|
||||||
|
this.isLoading = false;
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
this.isLoading = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ngOnDestroy(): void {
|
||||||
|
this.nameChangeSubscription?.unsubscribe();
|
||||||
|
}
|
||||||
|
|
||||||
|
loadDropdownData(): void {
|
||||||
|
this.allCategories$ = this.categoryService.getAll().pipe(
|
||||||
|
tap(categories => this.allCategories = categories)
|
||||||
|
);
|
||||||
|
this.supplierOptions$ = this.supplierService.getAll().pipe(
|
||||||
|
map(suppliers => suppliers.map(s => ({ value: s.id, label: s.name || 'Unbenannt' }))),
|
||||||
|
startWith([])
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
populateForm(product: AdminProduct): void {
|
||||||
|
this.productForm.patchValue(product);
|
||||||
|
this.categorieIds.clear();
|
||||||
|
product.categorieIds?.forEach(id => this.categorieIds.push(this.fb.control(id)));
|
||||||
|
this.existingImages = product.images || [];
|
||||||
|
}
|
||||||
|
|
||||||
|
onMainFileChange(event: Event): void {
|
||||||
|
const file = (event.target as HTMLInputElement).files?.[0];
|
||||||
|
if (file) this.mainImageFile = file;
|
||||||
|
}
|
||||||
|
|
||||||
|
onAdditionalFilesChange(event: Event): void {
|
||||||
|
const files = (event.target as HTMLInputElement).files;
|
||||||
|
if (files) this.additionalImageFiles = Array.from(files);
|
||||||
|
}
|
||||||
|
|
||||||
|
deleteExistingImage(imageId: string, event: Event): void {
|
||||||
|
event.preventDefault();
|
||||||
|
this.imagesToDelete.push(this.fb.control(imageId));
|
||||||
|
this.existingImages = this.existingImages.filter(img => img.id !== imageId);
|
||||||
|
}
|
||||||
|
|
||||||
|
onCategoryChange(event: Event): void {
|
||||||
|
const checkbox = event.target as HTMLInputElement;
|
||||||
|
const categoryId = checkbox.value;
|
||||||
|
if (checkbox.checked) {
|
||||||
|
if (!this.categorieIds.value.includes(categoryId)) this.categorieIds.push(new FormControl(categoryId));
|
||||||
|
} else {
|
||||||
|
const index = this.categorieIds.controls.findIndex(x => x.value === categoryId);
|
||||||
|
if (index !== -1) this.categorieIds.removeAt(index);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
isCategorySelected(categoryId: string): boolean {
|
||||||
|
return this.categorieIds.value.includes(categoryId);
|
||||||
|
}
|
||||||
|
|
||||||
|
getCategoryName(categoryId: string): string {
|
||||||
|
return this.allCategories.find(c => c.id === categoryId)?.name || '';
|
||||||
|
}
|
||||||
|
|
||||||
|
removeCategoryById(categoryId: string): void {
|
||||||
|
const index = this.categorieIds.controls.findIndex(x => x.value === categoryId);
|
||||||
|
if (index !== -1) {
|
||||||
|
this.categorieIds.removeAt(index);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
generateSku(): void {
|
||||||
|
const name = this.productForm.get('name')?.value || 'PROD';
|
||||||
|
const prefix = name.substring(0, 4).toUpperCase().replace(/\s+/g, '');
|
||||||
|
const randomPart = Math.random().toString(36).substring(2, 8).toUpperCase();
|
||||||
|
const sku = `${prefix}-${randomPart}`;
|
||||||
|
this.productForm.get('sku')?.setValue(sku);
|
||||||
|
this.snackbarService.show('Neue SKU generiert!');
|
||||||
|
}
|
||||||
|
|
||||||
|
onSubmit(): void {
|
||||||
|
if (this.productForm.invalid) {
|
||||||
|
this.productForm.markAllAsTouched();
|
||||||
|
this.snackbarService.show('Bitte füllen Sie alle Pflichtfelder aus.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const formData = new FormData();
|
||||||
|
const formValue = this.productForm.value;
|
||||||
|
|
||||||
|
Object.keys(formValue).forEach((key) => {
|
||||||
|
const value = formValue[key];
|
||||||
|
if (key === 'categorieIds' || key === 'imagesToDelete') {
|
||||||
|
(value as string[]).forEach((id) => formData.append(this.capitalizeFirstLetter(key), id));
|
||||||
|
} else if (value !== null && value !== undefined && value !== '') {
|
||||||
|
if (['oldPrice', 'purchasePrice', 'weight'].includes(key) && value === '') return;
|
||||||
|
formData.append(this.capitalizeFirstLetter(key), value.toString());
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
if (this.mainImageFile) formData.append('MainImageFile', this.mainImageFile);
|
||||||
|
this.additionalImageFiles.forEach((file) => formData.append('AdditionalImageFiles', file));
|
||||||
|
|
||||||
|
const operation: Observable<any> = this.isEditMode
|
||||||
|
? this.productService.update(this.productId!, formData)
|
||||||
|
: this.productService.create(formData);
|
||||||
|
|
||||||
|
operation.subscribe({
|
||||||
|
next: () => {
|
||||||
|
this.snackbarService.show(this.isEditMode ? 'Produkt aktualisiert' : 'Produkt erstellt');
|
||||||
|
this.router.navigate(['/admin/products']);
|
||||||
|
},
|
||||||
|
error: (err: any) => {
|
||||||
|
this.snackbarService.show('Ein Fehler ist aufgetreten.');
|
||||||
|
console.error(err);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
cancel(): void {
|
||||||
|
this.router.navigate(['/admin/products']);
|
||||||
|
}
|
||||||
|
|
||||||
|
private subscribeToNameChanges(): void {
|
||||||
|
this.nameChangeSubscription = this.productForm.get('name')?.valueChanges.pipe(debounceTime(300), distinctUntilChanged())
|
||||||
|
.subscribe((name) => {
|
||||||
|
if (name && !this.productForm.get('slug')?.dirty) {
|
||||||
|
const slug = this.generateSlug(name);
|
||||||
|
this.productForm.get('slug')?.setValue(slug);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private generateSlug(name: string): string {
|
||||||
|
return name.toLowerCase().replace(/\s+/g, '-').replace(/[äöüß]/g, (char) => {
|
||||||
|
switch (char) { case 'ä': return 'ae'; case 'ö': return 'oe'; case 'ü': return 'ue'; case 'ß': return 'ss'; default: return ''; }
|
||||||
|
}).replace(/[^a-z0-9-]/g, '').replace(/-+/g, '-');
|
||||||
|
}
|
||||||
|
|
||||||
|
private capitalizeFirstLetter(string: string): string {
|
||||||
|
return string.charAt(0).toUpperCase() + string.slice(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
/* /src/app/features/admin/components/products/product-list/product-list.component.css */
|
||||||
|
|
||||||
|
.table-header {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
margin-bottom: 1.5rem;
|
||||||
|
gap: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
app-search-bar {
|
||||||
|
flex-grow: 1;
|
||||||
|
max-width: 400px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.header-actions {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.75rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.column-filter-container {
|
||||||
|
position: relative;
|
||||||
|
}
|
||||||
|
|
||||||
|
.column-filter-dropdown {
|
||||||
|
position: absolute;
|
||||||
|
top: 100%;
|
||||||
|
right: 0;
|
||||||
|
margin-top: 0.5rem;
|
||||||
|
background-color: var(--color-surface);
|
||||||
|
border: 1px solid var(--color-border);
|
||||||
|
border-radius: var(--border-radius-md);
|
||||||
|
box-shadow: var(--box-shadow-lg);
|
||||||
|
padding: 0.75rem;
|
||||||
|
z-index: 10;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 0.5rem;
|
||||||
|
min-width: 180px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.column-filter-dropdown label {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.5rem;
|
||||||
|
cursor: pointer;
|
||||||
|
padding: 0.25rem;
|
||||||
|
border-radius: var(--border-radius-sm);
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.column-filter-dropdown label:hover {
|
||||||
|
background-color: var(--color-body-bg-hover);
|
||||||
|
}
|
||||||
@@ -1,227 +1,30 @@
|
|||||||
<div>
|
<!-- /src/app/features/admin/components/products/product-list/product-list.component.html -->
|
||||||
<h1>Produkte verwalten</h1>
|
|
||||||
|
|
||||||
<!-- Das Formular bleibt unverändert und ist bereits korrekt -->
|
<div class="page-container">
|
||||||
<form [formGroup]="productForm" (ngSubmit)="onSubmit()">
|
<div class="header">
|
||||||
<!-- ... (Dein komplettes Formular hier) ... -->
|
<h1 class="page-title">Produktübersicht</h1>
|
||||||
<h3>
|
<app-button buttonType="primary" (click)="onAddNew()">
|
||||||
{{ selectedProductId ? "Produkt bearbeiten" : "Neues Produkt erstellen" }}
|
<app-icon iconName="plus"></app-icon> Neues Produkt
|
||||||
</h3>
|
</app-button>
|
||||||
<h4>Basis-Informationen</h4>
|
|
||||||
<div><label>Name:</label><input type="text" formControlName="name" /></div>
|
|
||||||
<div>
|
|
||||||
<label>Slug (automatisch generiert):</label
|
|
||||||
><input type="text" formControlName="slug" />
|
|
||||||
</div>
|
</div>
|
||||||
<div>
|
|
||||||
<label>SKU (Artikelnummer):</label>
|
|
||||||
<div style="display: flex; align-items: center; gap: 10px">
|
|
||||||
<input
|
|
||||||
id="sku"
|
|
||||||
type="text"
|
|
||||||
formControlName="sku"
|
|
||||||
style="flex-grow: 1"
|
|
||||||
/><button type="button" (click)="generateSku()">Generieren</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<label>Beschreibung:</label
|
|
||||||
><textarea formControlName="description" rows="5"></textarea>
|
|
||||||
</div>
|
|
||||||
<hr />
|
|
||||||
<h4>Preis & Lager</h4>
|
|
||||||
<div>
|
|
||||||
<label>Preis (€):</label><input type="number" formControlName="price" />
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<label>Alter Preis (€) (optional):</label
|
|
||||||
><input type="number" formControlName="oldPrice" />
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<label>Einkaufspreis (€) (optional):</label
|
|
||||||
><input type="number" formControlName="purchasePrice" />
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<label>Lagerbestand:</label
|
|
||||||
><input type="number" formControlName="stockQuantity" />
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<label>Gewicht (in kg) (optional):</label
|
|
||||||
><input type="number" formControlName="weight" />
|
|
||||||
</div>
|
|
||||||
<hr />
|
|
||||||
<h4>Zuweisungen</h4>
|
|
||||||
<div>
|
|
||||||
<label>Lieferant:</label
|
|
||||||
><select formControlName="supplierId">
|
|
||||||
<option [ngValue]="null">-- Kein Lieferant --</option>
|
|
||||||
<option
|
|
||||||
*ngFor="let supplier of allSuppliers$ | async"
|
|
||||||
[value]="supplier.id"
|
|
||||||
>
|
|
||||||
{{ supplier.name }}
|
|
||||||
</option>
|
|
||||||
</select>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<label>Kategorien:</label>
|
|
||||||
<div
|
|
||||||
class="category-checkbox-group"
|
|
||||||
style="
|
|
||||||
height: 100px;
|
|
||||||
overflow-y: auto;
|
|
||||||
border: 1px solid #ccc;
|
|
||||||
padding: 5px;
|
|
||||||
margin-top: 5px;
|
|
||||||
"
|
|
||||||
>
|
|
||||||
<div *ngFor="let category of allCategories$ | async">
|
|
||||||
<label
|
|
||||||
><input
|
|
||||||
type="checkbox"
|
|
||||||
[value]="category.id"
|
|
||||||
[checked]="isCategorySelected(category.id)"
|
|
||||||
(change)="onCategoryChange($event)"
|
|
||||||
/>{{ category.name }}</label
|
|
||||||
>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<hr />
|
|
||||||
<h4>Produktbilder</h4>
|
|
||||||
<div *ngIf="selectedProductId && existingImages.length > 0">
|
|
||||||
<p>Bestehende Bilder:</p>
|
|
||||||
<div
|
|
||||||
style="display: flex; gap: 10px; flex-wrap: wrap; margin-bottom: 15px"
|
|
||||||
>
|
|
||||||
<div *ngFor="let img of existingImages" style="position: relative">
|
|
||||||
<img
|
|
||||||
[src]="img.url"
|
|
||||||
[alt]="productForm.get('name')?.value"
|
|
||||||
style="
|
|
||||||
width: 100px;
|
|
||||||
height: 100px;
|
|
||||||
object-fit: cover;
|
|
||||||
border: 2px solid;
|
|
||||||
"
|
|
||||||
[style.borderColor]="img.isMainImage ? 'green' : 'gray'"
|
|
||||||
/><button
|
|
||||||
(click)="deleteExistingImage(img.id, $event)"
|
|
||||||
style="
|
|
||||||
position: absolute;
|
|
||||||
top: -5px;
|
|
||||||
right: -5px;
|
|
||||||
background: red;
|
|
||||||
color: white;
|
|
||||||
border-radius: 50%;
|
|
||||||
width: 20px;
|
|
||||||
height: 20px;
|
|
||||||
border: none;
|
|
||||||
cursor: pointer;
|
|
||||||
line-height: 20px;
|
|
||||||
text-align: center;
|
|
||||||
padding: 0;
|
|
||||||
"
|
|
||||||
>
|
|
||||||
X
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<label for="main-image">Hauptbild (ersetzt bestehendes Hauptbild)</label
|
|
||||||
><input
|
|
||||||
id="main-image"
|
|
||||||
type="file"
|
|
||||||
(change)="onMainFileChange($event)"
|
|
||||||
accept="image/*"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<label for="additional-images">Zusätzliche Bilder hinzufügen</label
|
|
||||||
><input
|
|
||||||
id="additional-images"
|
|
||||||
type="file"
|
|
||||||
(change)="onAdditionalFilesChange($event)"
|
|
||||||
accept="image/*"
|
|
||||||
multiple
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<hr />
|
|
||||||
<h4>Status & Sichtbarkeit</h4>
|
|
||||||
<div>
|
|
||||||
<label
|
|
||||||
><input type="checkbox" formControlName="isActive" /> Aktiv (im Shop
|
|
||||||
sichtbar)</label
|
|
||||||
>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<label
|
|
||||||
><input type="checkbox" formControlName="isFeatured" /> Hervorgehoben
|
|
||||||
(z.B. auf Startseite)</label
|
|
||||||
>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<label>Anzeigereihenfolge (Hervorgehoben):</label
|
|
||||||
><input type="number" formControlName="featuredDisplayOrder" />
|
|
||||||
</div>
|
|
||||||
<br /><br />
|
|
||||||
<button type="submit" [disabled]="productForm.invalid">
|
|
||||||
{{ selectedProductId ? "Aktualisieren" : "Erstellen" }}
|
|
||||||
</button>
|
|
||||||
<button type="button" *ngIf="selectedProductId" (click)="clearSelection()">
|
|
||||||
Abbrechen
|
|
||||||
</button>
|
|
||||||
</form>
|
|
||||||
|
|
||||||
<hr />
|
<div class="table-header">
|
||||||
<h2>Bestehende Produkte</h2>
|
<app-search-bar placeholder="Produkte nach Name oder SKU suchen..." (search)="onSearch($event)"></app-search-bar>
|
||||||
|
<div class="column-filter-container">
|
||||||
|
<app-button buttonType="stroked" (click)="toggleColumnFilter()" iconName="filter">Spalten</app-button>
|
||||||
|
<div class="column-filter-dropdown" *ngIf="isColumnFilterVisible">
|
||||||
|
<label *ngFor="let col of allTableColumns">
|
||||||
|
<input type="checkbox" [checked]="isColumnVisible(col.key)" (change)="onColumnToggle(col, $event)">
|
||||||
|
{{ col.title }}
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<table style="width: 100%; border-collapse: collapse;">
|
<app-generic-table
|
||||||
<thead>
|
[data]="filteredProducts"
|
||||||
<tr >
|
[columns]="visibleTableColumns"
|
||||||
<th style="padding: 8px; border: 1px solid #ddd;">Bild</th>
|
(edit)="onEditProduct($event.id)"
|
||||||
<th style="padding: 8px; border: 1px solid #ddd;">Name</th>
|
(delete)="onDeleteProduct($event.id)">
|
||||||
<th style="padding: 8px; border: 1px solid #ddd;">SKU</th>
|
</app-generic-table>
|
||||||
<th style="padding: 8px; border: 1px solid #ddd;">Preis</th>
|
</div>
|
||||||
<th style="padding: 8px; border: 1px solid #ddd;">Lagerbestand</th>
|
|
||||||
<th style="padding: 8px; border: 1px solid #ddd;">Aktiv</th>
|
|
||||||
<th style="padding: 8px; border: 1px solid #ddd;">Aktionen</th>
|
|
||||||
</tr>
|
|
||||||
</thead>
|
|
||||||
<tbody>
|
|
||||||
<ng-container *ngIf="products$ | async as products; else loading">
|
|
||||||
<tr *ngIf="products.length === 0">
|
|
||||||
<td colspan="7" style="text-align: center; padding: 16px;">Keine Produkte gefunden.</td>
|
|
||||||
</tr>
|
|
||||||
<tr *ngFor="let product of products">
|
|
||||||
<td style="padding: 8px; border: 1px solid #ddd; text-align: center;">
|
|
||||||
<!-- +++ HIER IST DIE KORREKTUR +++ -->
|
|
||||||
<img
|
|
||||||
[src]="getMainImageUrl(product.images)"
|
|
||||||
[alt]="product.name"
|
|
||||||
style="width: 50px; height: 50px; object-fit: cover;">
|
|
||||||
</td>
|
|
||||||
<td style="padding: 8px; border: 1px solid #ddd;">
|
|
||||||
<strong>{{ product.name }}</strong><br>
|
|
||||||
<small style="color: #777;">Slug: {{ product.slug }}</small>
|
|
||||||
</td>
|
|
||||||
<td style="padding: 8px; border: 1px solid #ddd;">{{ product.sku }}</td>
|
|
||||||
<td style="padding: 8px; border: 1px solid #ddd;">{{ product.price | currency:'EUR' }}</td>
|
|
||||||
<td style="padding: 8px; border: 1px solid #ddd;">{{ product.stockQuantity }}</td>
|
|
||||||
<td style="padding: 8px; border: 1px solid #ddd; text-align: center;" [style.color]="product.isActive ? 'green' : 'red'">
|
|
||||||
{{ product.isActive ? 'Ja' : 'Nein' }}
|
|
||||||
</td>
|
|
||||||
<td style="padding: 8px; border: 1px solid #ddd; width: 150px; text-align: center;">
|
|
||||||
<button (click)="selectProduct(product)">Bearbeiten</button>
|
|
||||||
<button (click)="onDelete(product.id)" style="margin-left: 5px; background-color: #dc3545; color: white;">Löschen</button>
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
</ng-container>
|
|
||||||
<ng-template #loading>
|
|
||||||
<tr>
|
|
||||||
<td colspan="7" style="text-align: center; padding: 16px;">Lade Produkte...</td>
|
|
||||||
</tr>
|
|
||||||
</ng-template>
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
@@ -1,282 +1,213 @@
|
|||||||
import { Component, OnInit, OnDestroy, inject } from '@angular/core';
|
// /src/app/features/admin/components/products/product-list/product-list.component.ts
|
||||||
import { CommonModule } from '@angular/common';
|
|
||||||
import {
|
|
||||||
FormBuilder,
|
|
||||||
FormGroup,
|
|
||||||
FormArray,
|
|
||||||
FormControl,
|
|
||||||
ReactiveFormsModule,
|
|
||||||
Validators,
|
|
||||||
} from '@angular/forms';
|
|
||||||
import { Observable, Subscription } from 'rxjs';
|
|
||||||
import { debounceTime, distinctUntilChanged } from 'rxjs/operators';
|
|
||||||
|
|
||||||
// Models
|
import { Component, OnInit, inject } from '@angular/core';
|
||||||
|
import { Router } from '@angular/router';
|
||||||
|
import { CommonModule, CurrencyPipe, DatePipe } from '@angular/common';
|
||||||
import {
|
import {
|
||||||
AdminProduct,
|
AdminProduct,
|
||||||
ProductImage,
|
ProductImage,
|
||||||
} from '../../../../core/models/product.model';
|
} from '../../../../core/models/product.model';
|
||||||
import { Category } from '../../../../core/models/category.model';
|
|
||||||
import { Supplier } from '../../../../core/models/supplier.model';
|
|
||||||
|
|
||||||
// Services
|
|
||||||
import { ProductService } from '../../../services/product.service';
|
import { ProductService } from '../../../services/product.service';
|
||||||
import { CategoryService } from '../../../services/category.service';
|
|
||||||
import { SupplierService } from '../../../services/supplier.service';
|
import { SupplierService } from '../../../services/supplier.service';
|
||||||
|
import { SnackbarService } from '../../../../shared/services/snackbar.service';
|
||||||
|
import { StorageService } from '../../../../core/services/storage.service';
|
||||||
|
import {
|
||||||
|
GenericTableComponent,
|
||||||
|
ColumnConfig,
|
||||||
|
} from '../../../../shared/components/data-display/generic-table/generic-table.component';
|
||||||
|
import { SearchBarComponent } from '../../../../shared/components/layout/search-bar/search-bar.component';
|
||||||
|
import { ButtonComponent } from '../../../../shared/components/ui/button/button.component';
|
||||||
|
import { IconComponent } from '../../../../shared/components/ui/icon/icon.component';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-product-list',
|
selector: 'app-product-list',
|
||||||
standalone: true,
|
standalone: true,
|
||||||
imports: [CommonModule, ReactiveFormsModule],
|
imports: [
|
||||||
|
CommonModule,
|
||||||
|
CurrencyPipe,
|
||||||
|
DatePipe,
|
||||||
|
GenericTableComponent,
|
||||||
|
SearchBarComponent,
|
||||||
|
ButtonComponent,
|
||||||
|
IconComponent,
|
||||||
|
],
|
||||||
|
providers: [DatePipe],
|
||||||
templateUrl: './product-list.component.html',
|
templateUrl: './product-list.component.html',
|
||||||
|
styleUrl: './product-list.component.css',
|
||||||
})
|
})
|
||||||
export class ProductListComponent implements OnInit, OnDestroy {
|
export class ProductListComponent implements OnInit {
|
||||||
private productService = inject(ProductService);
|
private productService = inject(ProductService);
|
||||||
private categoryService = inject(CategoryService);
|
|
||||||
private supplierService = inject(SupplierService);
|
private supplierService = inject(SupplierService);
|
||||||
private fb = inject(FormBuilder);
|
private router = inject(Router);
|
||||||
|
private snackbar = inject(SnackbarService);
|
||||||
|
private storageService = inject(StorageService);
|
||||||
|
private datePipe = inject(DatePipe);
|
||||||
|
|
||||||
products$!: Observable<AdminProduct[]>;
|
private readonly TABLE_SETTINGS_KEY = 'product-table-columns';
|
||||||
allCategories$!: Observable<Category[]>;
|
|
||||||
allSuppliers$!: Observable<Supplier[]>;
|
|
||||||
|
|
||||||
productForm: FormGroup;
|
allProducts: (AdminProduct & {
|
||||||
selectedProductId: string | null = null;
|
mainImage?: string;
|
||||||
private nameChangeSubscription?: Subscription;
|
supplierName?: string;
|
||||||
|
})[] = [];
|
||||||
|
filteredProducts: (AdminProduct & {
|
||||||
|
mainImage?: string;
|
||||||
|
supplierName?: string;
|
||||||
|
})[] = [];
|
||||||
|
isColumnFilterVisible = false;
|
||||||
|
|
||||||
// Eigenschaften für das Bild-Management
|
readonly allTableColumns: ColumnConfig[] = [
|
||||||
existingImages: ProductImage[] = [];
|
{ key: 'mainImage', title: 'Bild', type: 'image' },
|
||||||
mainImageFile: File | null = null;
|
{ key: 'name', title: 'Name', type: 'text', subKey: 'sku' },
|
||||||
additionalImageFiles: File[] = [];
|
{ key: 'price', title: 'Preis', type: 'currency', cssClass: 'text-right' },
|
||||||
|
{
|
||||||
|
key: 'stockQuantity',
|
||||||
|
title: 'Lager',
|
||||||
|
type: 'text',
|
||||||
|
cssClass: 'text-right',
|
||||||
|
},
|
||||||
|
{ key: 'supplierName', title: 'Lieferant', type: 'text' },
|
||||||
|
{ key: 'isActive', title: 'Aktiv', type: 'status' },
|
||||||
|
{ key: 'id', title: 'ID', type: 'text' },
|
||||||
|
{ key: 'description', title: 'Beschreibung', type: 'text' },
|
||||||
|
{
|
||||||
|
key: 'oldPrice',
|
||||||
|
title: 'Alter Preis',
|
||||||
|
type: 'currency',
|
||||||
|
cssClass: 'text-right',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'purchasePrice',
|
||||||
|
title: 'Einkaufspreis',
|
||||||
|
type: 'currency',
|
||||||
|
cssClass: 'text-right',
|
||||||
|
},
|
||||||
|
{ key: 'isInStock', title: 'Auf Lager', type: 'status' },
|
||||||
|
{ key: 'weight', title: 'Gewicht', type: 'number', cssClass: 'text-right' },
|
||||||
|
{ key: 'slug', title: 'Slug', type: 'text' },
|
||||||
|
{ key: 'createdDate', title: 'Erstellt am', type: 'date' },
|
||||||
|
{ key: 'lastModifiedDate', title: 'Zuletzt geändert', type: 'date' },
|
||||||
|
{ key: 'supplierId', title: 'Lieferanten-ID', type: 'text' },
|
||||||
|
{ key: 'categorieIds', title: 'Kategorie-IDs', type: 'text' },
|
||||||
|
{ key: 'isFeatured', title: 'Hervorgehoben', type: 'status' },
|
||||||
|
{
|
||||||
|
key: 'featuredDisplayOrder',
|
||||||
|
title: 'Anzeigereihenfolge (hervorgehoben)',
|
||||||
|
type: 'number',
|
||||||
|
cssClass: 'text-right',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'actions',
|
||||||
|
title: 'Aktionen',
|
||||||
|
type: 'actions',
|
||||||
|
cssClass: 'text-right',
|
||||||
|
},
|
||||||
|
];
|
||||||
|
visibleTableColumns: ColumnConfig[] = [];
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
this.productForm = this.fb.group({
|
this.loadTableSettings();
|
||||||
name: ['', Validators.required],
|
|
||||||
slug: ['', Validators.required],
|
|
||||||
sku: ['', Validators.required],
|
|
||||||
description: [''],
|
|
||||||
price: [0, [Validators.required, Validators.min(0)]],
|
|
||||||
oldPrice: [null, [Validators.min(0)]],
|
|
||||||
purchasePrice: [null, [Validators.min(0)]],
|
|
||||||
stockQuantity: [0, [Validators.required, Validators.min(0)]],
|
|
||||||
weight: [null, [Validators.min(0)]],
|
|
||||||
isActive: [true],
|
|
||||||
isFeatured: [false],
|
|
||||||
featuredDisplayOrder: [0],
|
|
||||||
supplierId: [null],
|
|
||||||
categorieIds: this.fb.array([]),
|
|
||||||
imagesToDelete: this.fb.array([]), // FormArray für die IDs der zu löschenden Bilder
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// Getter für einfachen Zugriff auf FormArrays
|
|
||||||
get categorieIds(): FormArray {
|
|
||||||
return this.productForm.get('categorieIds') as FormArray;
|
|
||||||
}
|
|
||||||
|
|
||||||
get imagesToDelete(): FormArray {
|
|
||||||
return this.productForm.get('imagesToDelete') as FormArray;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
ngOnInit(): void {
|
ngOnInit(): void {
|
||||||
this.loadInitialData();
|
this.loadProducts();
|
||||||
this.subscribeToNameChanges();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
ngOnDestroy(): void {
|
loadProducts(): void {
|
||||||
this.nameChangeSubscription?.unsubscribe();
|
this.productService.getAll().subscribe((products) => {
|
||||||
}
|
this.supplierService.getAll().subscribe((suppliers) => {
|
||||||
|
this.allProducts = products.map((p) => {
|
||||||
loadInitialData(): void {
|
const supplier = suppliers.find((s) => s.id === p.supplierId);
|
||||||
this.products$ = this.productService.getAll();
|
return {
|
||||||
this.allCategories$ = this.categoryService.getAll();
|
...p,
|
||||||
this.allSuppliers$ = this.supplierService.getAll();
|
mainImage: this.getMainImageUrl(p.images),
|
||||||
}
|
supplierName: supplier?.name || '-',
|
||||||
|
createdDate:
|
||||||
selectProduct(product: AdminProduct): void {
|
this.datePipe.transform(p.createdDate, 'dd.MM.yyyy HH:mm') || '-',
|
||||||
this.selectedProductId = product.id;
|
};
|
||||||
this.productForm.patchValue(product);
|
});
|
||||||
|
this.onSearch('');
|
||||||
this.categorieIds.clear();
|
});
|
||||||
product.categorieIds?.forEach((id) =>
|
|
||||||
this.categorieIds.push(this.fb.control(id))
|
|
||||||
);
|
|
||||||
|
|
||||||
this.existingImages = product.images || [];
|
|
||||||
}
|
|
||||||
|
|
||||||
clearSelection(): void {
|
|
||||||
this.selectedProductId = null;
|
|
||||||
this.productForm.reset({
|
|
||||||
name: '',
|
|
||||||
slug: '',
|
|
||||||
sku: '',
|
|
||||||
description: '',
|
|
||||||
price: 0,
|
|
||||||
oldPrice: null,
|
|
||||||
purchasePrice: null,
|
|
||||||
stockQuantity: 0,
|
|
||||||
weight: null,
|
|
||||||
isActive: true,
|
|
||||||
isFeatured: false,
|
|
||||||
featuredDisplayOrder: 0,
|
|
||||||
supplierId: null,
|
|
||||||
});
|
});
|
||||||
this.categorieIds.clear();
|
|
||||||
this.imagesToDelete.clear();
|
|
||||||
this.existingImages = [];
|
|
||||||
this.mainImageFile = null;
|
|
||||||
this.additionalImageFiles = [];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
onMainFileChange(event: Event): void {
|
onSearch(term: string): void {
|
||||||
const file = (event.target as HTMLInputElement).files?.[0];
|
const lowerTerm = term.toLowerCase();
|
||||||
if (file) this.mainImageFile = file;
|
this.filteredProducts = this.allProducts.filter(
|
||||||
}
|
(p) =>
|
||||||
|
p.name?.toLowerCase().includes(lowerTerm) ||
|
||||||
onAdditionalFilesChange(event: Event): void {
|
p.sku?.toLowerCase().includes(lowerTerm)
|
||||||
const files = (event.target as HTMLInputElement).files;
|
|
||||||
if (files) this.additionalImageFiles = Array.from(files);
|
|
||||||
}
|
|
||||||
|
|
||||||
deleteExistingImage(imageId: string, event: Event): void {
|
|
||||||
event.preventDefault();
|
|
||||||
this.imagesToDelete.push(this.fb.control(imageId));
|
|
||||||
this.existingImages = this.existingImages.filter(
|
|
||||||
(img) => img.id !== imageId
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
onCategoryChange(event: Event): void {
|
onAddNew(): void {
|
||||||
|
this.router.navigate(['/shop/products/new']);
|
||||||
|
}
|
||||||
|
|
||||||
|
onEditProduct(productId: string): void {
|
||||||
|
this.router.navigate(['/shop/products', productId]);
|
||||||
|
}
|
||||||
|
|
||||||
|
onDeleteProduct(productId: string): void {
|
||||||
|
if (confirm('Möchten Sie dieses Produkt wirklich löschen?')) {
|
||||||
|
this.productService.delete(productId).subscribe(() => {
|
||||||
|
this.snackbar.show('Produkt erfolgreich gelöscht.');
|
||||||
|
this.loadProducts();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private loadTableSettings(): void {
|
||||||
|
const savedKeys = this.storageService.getItem<string[]>(
|
||||||
|
this.TABLE_SETTINGS_KEY
|
||||||
|
);
|
||||||
|
const defaultKeys = [
|
||||||
|
'mainImage',
|
||||||
|
'name',
|
||||||
|
'price',
|
||||||
|
'stockQuantity',
|
||||||
|
'isActive',
|
||||||
|
'actions',
|
||||||
|
];
|
||||||
|
const keysToUse =
|
||||||
|
savedKeys && savedKeys.length > 0 ? savedKeys : defaultKeys;
|
||||||
|
this.visibleTableColumns = this.allTableColumns.filter((c) =>
|
||||||
|
keysToUse.includes(c.key)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private saveTableSettings(): void {
|
||||||
|
const visibleKeys = this.visibleTableColumns.map((c) => c.key);
|
||||||
|
this.storageService.setItem(this.TABLE_SETTINGS_KEY, visibleKeys);
|
||||||
|
}
|
||||||
|
|
||||||
|
toggleColumnFilter(): void {
|
||||||
|
this.isColumnFilterVisible = !this.isColumnFilterVisible;
|
||||||
|
}
|
||||||
|
|
||||||
|
isColumnVisible(columnKey: string): boolean {
|
||||||
|
return this.visibleTableColumns.some((c) => c.key === columnKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
onColumnToggle(column: ColumnConfig, event: Event): void {
|
||||||
const checkbox = event.target as HTMLInputElement;
|
const checkbox = event.target as HTMLInputElement;
|
||||||
const categoryId = checkbox.value;
|
|
||||||
if (checkbox.checked) {
|
if (checkbox.checked) {
|
||||||
if (!this.categorieIds.value.includes(categoryId)) {
|
this.visibleTableColumns.push(column);
|
||||||
this.categorieIds.push(new FormControl(categoryId));
|
this.visibleTableColumns.sort(
|
||||||
}
|
(a, b) =>
|
||||||
} else {
|
this.allTableColumns.findIndex((c) => c.key === a.key) -
|
||||||
const index = this.categorieIds.controls.findIndex(
|
this.allTableColumns.findIndex((c) => c.key === b.key)
|
||||||
(x) => x.value === categoryId
|
|
||||||
);
|
);
|
||||||
if (index !== -1) {
|
|
||||||
this.categorieIds.removeAt(index);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
isCategorySelected(categoryId: string): boolean {
|
|
||||||
return this.categorieIds.value.includes(categoryId);
|
|
||||||
}
|
|
||||||
|
|
||||||
generateSku(): void {
|
|
||||||
const name = this.productForm.get('name')?.value || 'PROD';
|
|
||||||
const prefix = name.substring(0, 4).toUpperCase().replace(/\s+/g, '');
|
|
||||||
const randomPart = Math.random().toString(36).substring(2, 8).toUpperCase();
|
|
||||||
const sku = `${prefix}-${randomPart}`;
|
|
||||||
this.productForm.get('sku')?.setValue(sku);
|
|
||||||
}
|
|
||||||
|
|
||||||
onSubmit(): void {
|
|
||||||
if (this.productForm.invalid) return;
|
|
||||||
|
|
||||||
const formData = new FormData();
|
|
||||||
const formValue = this.productForm.value;
|
|
||||||
|
|
||||||
Object.keys(formValue).forEach((key) => {
|
|
||||||
const value = formValue[key];
|
|
||||||
if (key === 'categorieIds' || key === 'imagesToDelete') {
|
|
||||||
// FormArrays müssen speziell behandelt werden
|
|
||||||
(value as string[]).forEach((id) =>
|
|
||||||
formData.append(this.capitalizeFirstLetter(key), id)
|
|
||||||
);
|
|
||||||
} else if (value !== null && value !== undefined && value !== '') {
|
|
||||||
// Leere Strings für optionale number-Felder nicht mitsenden
|
|
||||||
if (
|
|
||||||
['oldPrice', 'purchasePrice', 'weight'].includes(key) &&
|
|
||||||
value === ''
|
|
||||||
)
|
|
||||||
return;
|
|
||||||
formData.append(this.capitalizeFirstLetter(key), value);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
if (this.mainImageFile) {
|
|
||||||
formData.append('MainImageFile', this.mainImageFile);
|
|
||||||
}
|
|
||||||
this.additionalImageFiles.forEach((file) => {
|
|
||||||
formData.append('AdditionalImageFiles', file);
|
|
||||||
});
|
|
||||||
|
|
||||||
if (this.selectedProductId) {
|
|
||||||
formData.append('Id', this.selectedProductId);
|
|
||||||
this.productService
|
|
||||||
.update(this.selectedProductId, formData)
|
|
||||||
.subscribe(() => this.reset());
|
|
||||||
} else {
|
} else {
|
||||||
this.productService.create(formData).subscribe(() => this.reset());
|
this.visibleTableColumns = this.visibleTableColumns.filter(
|
||||||
|
(c) => c.key !== column.key
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
this.saveTableSettings();
|
||||||
}
|
}
|
||||||
|
|
||||||
onDelete(id: string): void {
|
|
||||||
if (confirm('Produkt wirklich löschen?')) {
|
|
||||||
this.productService.delete(id).subscribe(() => this.loadInitialData());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private reset(): void {
|
|
||||||
this.loadInitialData();
|
|
||||||
this.clearSelection();
|
|
||||||
}
|
|
||||||
|
|
||||||
private subscribeToNameChanges(): void {
|
|
||||||
this.nameChangeSubscription = this.productForm
|
|
||||||
.get('name')
|
|
||||||
?.valueChanges.pipe(debounceTime(300), distinctUntilChanged())
|
|
||||||
.subscribe((name) => {
|
|
||||||
if (name && !this.productForm.get('slug')?.dirty) {
|
|
||||||
const slug = this.generateSlug(name);
|
|
||||||
this.productForm.get('slug')?.setValue(slug);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
private generateSlug(name: string): string {
|
|
||||||
return name
|
|
||||||
.toLowerCase()
|
|
||||||
.replace(/\s+/g, '-')
|
|
||||||
.replace(/[äöüß]/g, (char) => {
|
|
||||||
switch (char) {
|
|
||||||
case 'ä':
|
|
||||||
return 'ae';
|
|
||||||
case 'ö':
|
|
||||||
return 'oe';
|
|
||||||
case 'ü':
|
|
||||||
return 'ue';
|
|
||||||
case 'ß':
|
|
||||||
return 'ss';
|
|
||||||
default:
|
|
||||||
return '';
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.replace(/[^a-z0-9-]/g, '')
|
|
||||||
.replace(/-+/g, '-');
|
|
||||||
}
|
|
||||||
|
|
||||||
private capitalizeFirstLetter(string: string): string {
|
|
||||||
return string.charAt(0).toUpperCase() + string.slice(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Sucht das Hauptbild aus der Bilderliste eines Produkts und gibt dessen URL zurück.
|
|
||||||
* Gibt eine Platzhalter-URL zurück, wenn kein Hauptbild gefunden wird.
|
|
||||||
* @param images Die Liste der Produktbilder.
|
|
||||||
* @returns Die URL des Hauptbildes oder eine Platzhalter-URL.
|
|
||||||
*/
|
|
||||||
getMainImageUrl(images?: ProductImage[]): string {
|
getMainImageUrl(images?: ProductImage[]): string {
|
||||||
if (!images || images.length === 0) {
|
if (!images || images.length === 0) return 'https://via.placeholder.com/50';
|
||||||
return ''; // Platzhalter, wenn gar keine Bilder vorhanden sind
|
const mainImage = images.find((img) => img.isMainImage);
|
||||||
}
|
return mainImage?.url || images[0]?.url || 'https://via.placeholder.com/50';
|
||||||
const mainImage = images.find(img => img.isMainImage);
|
|
||||||
return mainImage?.url || images[0].url || ''; // Fallback auf das erste Bild, wenn kein Hauptbild markiert ist
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1 @@
|
|||||||
|
<p>product-new works!</p>
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
import { Component } from '@angular/core';
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-product-new',
|
||||||
|
imports: [],
|
||||||
|
templateUrl: './product-new.component.html',
|
||||||
|
styleUrl: './product-new.component.css'
|
||||||
|
})
|
||||||
|
export class ProductNewComponent {
|
||||||
|
|
||||||
|
}
|
||||||
@@ -1,10 +1,23 @@
|
|||||||
|
// /src/app/features/admin/components/products/products.routes.ts
|
||||||
|
|
||||||
import { Routes } from '@angular/router';
|
import { Routes } from '@angular/router';
|
||||||
import { ProductListComponent } from './product-list/product-list.component';
|
import { ProductListComponent } from './product-list/product-list.component';
|
||||||
|
import { ProductEditComponent } from './product-edit/product-edit.component';
|
||||||
|
|
||||||
export const PRODUCTS_ROUTES: Routes = [
|
export const PRODUCTS_ROUTES: Routes = [
|
||||||
{
|
{
|
||||||
path: '',
|
path: '',
|
||||||
component: ProductListComponent,
|
component: ProductListComponent,
|
||||||
title: '',
|
title: 'Produktübersicht'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'new',
|
||||||
|
component: ProductEditComponent,
|
||||||
|
title: 'Neues Produkt erstellen'
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: ':id',
|
||||||
|
component: ProductEditComponent,
|
||||||
|
title: 'Produkt bearbeiten'
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
/* /src/app/shared/components/table/generic-table/generic-table.component.css */
|
||||||
|
|
||||||
|
:host {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
height: 100%;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
.table-container {
|
||||||
|
overflow-x: auto;
|
||||||
|
flex-grow: 1;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.modern-table {
|
||||||
|
width: 100%;
|
||||||
|
border-collapse: collapse;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.modern-table thead th {
|
||||||
|
padding: 0.75rem 1.5rem;
|
||||||
|
color: var(--color-text-light);
|
||||||
|
font-size: 0.85rem;
|
||||||
|
font-weight: 600;
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: 0.5px;
|
||||||
|
text-align: left;
|
||||||
|
border-bottom: 2px solid var(--color-border);
|
||||||
|
}
|
||||||
|
|
||||||
|
.modern-table tbody tr {
|
||||||
|
transition: background-color var(--transition-speed);
|
||||||
|
border-bottom: 1px solid var(--color-border);
|
||||||
|
}
|
||||||
|
|
||||||
|
.modern-table tbody tr:last-of-type {
|
||||||
|
border-bottom: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.modern-table tbody tr:hover {
|
||||||
|
background-color: var(--color-body-bg-hover);
|
||||||
|
}
|
||||||
|
|
||||||
|
.modern-table tbody td {
|
||||||
|
padding: 1rem 1.5rem;
|
||||||
|
vertical-align: middle;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Spezifische Zell-Stile */
|
||||||
|
.user-cell {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.user-cell img {
|
||||||
|
width: 40px;
|
||||||
|
height: 40px;
|
||||||
|
border-radius: 50%;
|
||||||
|
object-fit: cover;
|
||||||
|
}
|
||||||
|
|
||||||
|
.user-name {
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--color-text);
|
||||||
|
}
|
||||||
|
|
||||||
|
.user-email {
|
||||||
|
font-size: 0.9rem;
|
||||||
|
color: var(--color-text-light);
|
||||||
|
}
|
||||||
|
|
||||||
|
.amount {
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mono {
|
||||||
|
font-family: "Courier New", Courier, monospace;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Verwendet die von dir definierte Klasse für die rechten Aktionen */
|
||||||
|
.actions-cell {
|
||||||
|
display: flex;
|
||||||
|
justify-content: flex-end;
|
||||||
|
gap: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Hilfsklasse für rechtsbündigen Text */
|
||||||
|
.text-right {
|
||||||
|
text-align: right;
|
||||||
|
}
|
||||||
|
|
||||||
|
.no-data-cell {
|
||||||
|
text-align: center;
|
||||||
|
padding: 2rem;
|
||||||
|
color: var(--color-text-light);
|
||||||
|
}
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
<!-- /src/app/shared/components/table/generic-table/generic-table.component.html -->
|
||||||
|
|
||||||
|
<div class="table-container">
|
||||||
|
<table class="modern-table">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th *ngFor="let col of columns" [ngClass]="col.cssClass">{{ col.title }}</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
<tr *ngFor="let item of displayedData">
|
||||||
|
<td *ngFor="let col of columns" [ngClass]="col.cssClass">
|
||||||
|
|
||||||
|
<ng-container [ngSwitch]="col.type">
|
||||||
|
|
||||||
|
<ng-container *ngSwitchCase="'text'">
|
||||||
|
<div>
|
||||||
|
<span [class.mono]="col.key === 'id' || col.key === 'orderNumber' || col.key === 'sku'">
|
||||||
|
{{ getProperty(item, col.key) }}
|
||||||
|
</span>
|
||||||
|
<div *ngIf="col.subKey" class="user-email">
|
||||||
|
{{ getProperty(item, col.subKey) }}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</ng-container>
|
||||||
|
|
||||||
|
<ng-container *ngSwitchCase="'currency'">
|
||||||
|
<span class="amount">{{ getProperty(item, col.key) | currency:'EUR' }}</span>
|
||||||
|
</ng-container>
|
||||||
|
|
||||||
|
<!-- VEREINFACHT: Wir übergeben den Wert direkt, die Pille kümmert sich um den Rest. -->
|
||||||
|
<ng-container *ngSwitchCase="'status'">
|
||||||
|
<app-status-pill [status]="getProperty(item, col.key)"></app-status-pill>
|
||||||
|
</ng-container>
|
||||||
|
|
||||||
|
<ng-container *ngSwitchCase="'image-text'">
|
||||||
|
<div class="user-cell">
|
||||||
|
<img [src]="getProperty(item, col.imageKey!) || 'https://via.placeholder.com/40'"
|
||||||
|
[alt]="'Bild von ' + getProperty(item, col.key)" />
|
||||||
|
<div>
|
||||||
|
<div class="user-name">{{ getProperty(item, col.key) }}</div>
|
||||||
|
<div class="user-email">{{ getProperty(item, col.subKey!) }}</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</ng-container>
|
||||||
|
|
||||||
|
<ng-container *ngSwitchCase="'image'">
|
||||||
|
<img [src]="getProperty(item, col.key) || 'https://via.placeholder.com/50'"
|
||||||
|
alt="Bild"
|
||||||
|
style="width: 50px; height: 50px; object-fit: cover; border-radius: 4px;">
|
||||||
|
</ng-container>
|
||||||
|
|
||||||
|
<ng-container *ngSwitchCase="'actions'">
|
||||||
|
<div class="actions-cell">
|
||||||
|
<app-button buttonType="icon" tooltip="Details anzeigen" iconName="eye" (click)="view.emit(item)"></app-button>
|
||||||
|
<app-button buttonType="icon" tooltip="Bearbeiten" iconName="edit" (click)="edit.emit(item)"></app-button>
|
||||||
|
<app-button buttonType="icon-danger" tooltip="Löschen" iconName="delete" (click)="delete.emit(item)"></app-button>
|
||||||
|
</div>
|
||||||
|
</ng-container>
|
||||||
|
|
||||||
|
</ng-container>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
<tr *ngIf="!displayedData || displayedData.length === 0">
|
||||||
|
<td [attr.colspan]="columns.length" class="no-data-cell">Keine Daten gefunden.</td>
|
||||||
|
</tr>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
<div *ngIf="data.length > itemsPerPage">
|
||||||
|
<app-paginator
|
||||||
|
[currentPage]="currentPage"
|
||||||
|
[totalItems]="data.length"
|
||||||
|
[itemsPerPage]="itemsPerPage"
|
||||||
|
(pageChange)="onPageChange($event)"
|
||||||
|
></app-paginator>
|
||||||
|
</div>
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
// /src/app/shared/components/table/generic-table/generic-table.component.ts
|
||||||
|
|
||||||
|
import { Component, Input, Output, EventEmitter, SimpleChanges, OnChanges, OnInit } from '@angular/core';
|
||||||
|
import { CommonModule, CurrencyPipe } from '@angular/common';
|
||||||
|
import { StatusPillComponent } from '../../ui/status-pill/status-pill.component';
|
||||||
|
import { ButtonComponent } from '../../ui/button/button.component';
|
||||||
|
import { PaginatorComponent } from '../paginator/paginator.component';
|
||||||
|
|
||||||
|
export type ColumnType = 'text' | 'currency' | 'status' | 'image-text' | 'image' | 'actions' | 'date' | 'number';
|
||||||
|
|
||||||
|
export interface ColumnConfig {
|
||||||
|
key: string;
|
||||||
|
title: string;
|
||||||
|
type: ColumnType;
|
||||||
|
imageKey?: string;
|
||||||
|
subKey?: string;
|
||||||
|
cssClass?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-generic-table',
|
||||||
|
standalone: true,
|
||||||
|
imports: [ CommonModule, CurrencyPipe, StatusPillComponent, ButtonComponent, PaginatorComponent ],
|
||||||
|
templateUrl: './generic-table.component.html',
|
||||||
|
styleUrl: './generic-table.component.css',
|
||||||
|
})
|
||||||
|
export class GenericTableComponent implements OnChanges, OnInit {
|
||||||
|
@Input() data: any[] = [];
|
||||||
|
@Input() columns: ColumnConfig[] = [];
|
||||||
|
@Input() itemsPerPage = 10;
|
||||||
|
|
||||||
|
@Output() view = new EventEmitter<any>();
|
||||||
|
@Output() edit = new EventEmitter<any>();
|
||||||
|
@Output() delete = new EventEmitter<any>();
|
||||||
|
|
||||||
|
public displayedData: any[] = [];
|
||||||
|
public currentPage = 1;
|
||||||
|
|
||||||
|
ngOnInit(): void { this.updatePagination(); }
|
||||||
|
ngOnChanges(changes: SimpleChanges): void { if (changes['data']) { this.currentPage = 1; this.updatePagination(); } }
|
||||||
|
onPageChange(newPage: number): void { this.currentPage = newPage; this.updatePagination(); }
|
||||||
|
|
||||||
|
private updatePagination(): void {
|
||||||
|
const startIndex = (this.currentPage - 1) * this.itemsPerPage;
|
||||||
|
const endIndex = startIndex + this.itemsPerPage;
|
||||||
|
this.displayedData = this.data.slice(startIndex, endIndex);
|
||||||
|
}
|
||||||
|
|
||||||
|
getProperty(item: any, key: string): any {
|
||||||
|
if (!key) return '';
|
||||||
|
return key.split('.').reduce((obj, part) => obj && obj[part], item);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,57 +1,66 @@
|
|||||||
|
// /src/app/shared/components/form/form-field/form-field.component.ts
|
||||||
|
|
||||||
import { Component, Input, forwardRef } from '@angular/core';
|
import { Component, Input, forwardRef } from '@angular/core';
|
||||||
import { CommonModule } from '@angular/common';
|
import { CommonModule } from '@angular/common';
|
||||||
import {
|
import { AbstractControl, FormsModule, NG_VALUE_ACCESSOR, ReactiveFormsModule } from '@angular/forms';
|
||||||
FormsModule,
|
|
||||||
ControlValueAccessor,
|
|
||||||
NG_VALUE_ACCESSOR,
|
|
||||||
} from '@angular/forms';
|
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-form-field',
|
selector: 'app-form-field',
|
||||||
standalone: true,
|
standalone: true,
|
||||||
imports: [
|
imports: [
|
||||||
CommonModule,
|
CommonModule,
|
||||||
FormsModule, // Wichtig für [(ngModel)] im Template
|
FormsModule,
|
||||||
|
ReactiveFormsModule // <-- WICHTIG: Hinzufügen, um mit AbstractControl zu arbeiten
|
||||||
],
|
],
|
||||||
templateUrl: './form-field.component.html',
|
templateUrl: './form-field.component.html',
|
||||||
styleUrl: './form-field.component.css',
|
styleUrl: './form-field.component.css',
|
||||||
providers: [
|
providers: [
|
||||||
{
|
{
|
||||||
// Stellt diese Komponente als "Value Accessor" zur Verfügung
|
|
||||||
provide: NG_VALUE_ACCESSOR,
|
provide: NG_VALUE_ACCESSOR,
|
||||||
useExisting: forwardRef(() => FormFieldComponent),
|
useExisting: forwardRef(() => FormFieldComponent),
|
||||||
multi: true,
|
multi: true,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
})
|
})
|
||||||
// Die Komponente implementiert die ControlValueAccessor-Schnittstelle
|
export class FormFieldComponent {
|
||||||
export class FormFieldComponent implements ControlValueAccessor {
|
// --- KORREKTUR: Erweitere die erlaubten Typen ---
|
||||||
|
@Input() type: 'text' | 'email' | 'password' | 'number' | 'tel' | 'url' = 'text';
|
||||||
@Input() label: string = '';
|
@Input() label: string = '';
|
||||||
@Input() type: 'text' | 'email' | 'password' = 'text';
|
|
||||||
|
|
||||||
controlId = `form-field-${Math.random().toString(36)}`;
|
// Neuer Input, um das FormControl für die Fehleranzeige zu erhalten
|
||||||
|
@Input() control?: AbstractControl;
|
||||||
|
@Input() showErrors = true; // Standardmäßig Fehler anzeigen
|
||||||
|
|
||||||
// --- Eigenschaften für ControlValueAccessor ---
|
controlId = `form-field-${Math.random().toString(36).substring(2, 9)}`;
|
||||||
value: string = '';
|
|
||||||
|
// --- Eigenschaften & Methoden für ControlValueAccessor ---
|
||||||
|
value: string | number = '';
|
||||||
onChange: (value: any) => void = () => {};
|
onChange: (value: any) => void = () => {};
|
||||||
onTouched: () => void = () => {};
|
onTouched: () => void = () => {};
|
||||||
disabled = false;
|
disabled = false;
|
||||||
|
|
||||||
// --- Methoden, die von Angular Forms aufgerufen werden ---
|
|
||||||
|
|
||||||
writeValue(value: any): void {
|
writeValue(value: any): void {
|
||||||
this.value = value;
|
this.value = value;
|
||||||
}
|
}
|
||||||
|
|
||||||
registerOnChange(fn: any): void {
|
registerOnChange(fn: any): void {
|
||||||
this.onChange = fn;
|
this.onChange = fn;
|
||||||
}
|
}
|
||||||
|
|
||||||
registerOnTouched(fn: any): void {
|
registerOnTouched(fn: any): void {
|
||||||
this.onTouched = fn;
|
this.onTouched = fn;
|
||||||
}
|
}
|
||||||
|
|
||||||
setDisabledState?(isDisabled: boolean): void {
|
setDisabledState?(isDisabled: boolean): void {
|
||||||
this.disabled = isDisabled;
|
this.disabled = isDisabled;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Hilfsfunktion für das Template, um Fehler zu finden
|
||||||
|
get errorMessage(): string | null {
|
||||||
|
if (!this.control || !this.control.errors || (!this.control.touched && !this.control.dirty)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (this.control.hasError('required')) return 'Dieses Feld ist erforderlich.';
|
||||||
|
if (this.control.hasError('email')) return 'Bitte geben Sie eine gültige E-Mail-Adresse ein.';
|
||||||
|
if (this.control.hasError('min')) return `Der Wert muss mindestens ${this.control.errors['min'].min} sein.`;
|
||||||
|
// ... weitere Fehlermeldungen hier
|
||||||
|
return 'Ungültige Eingabe.';
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -1,76 +1,51 @@
|
|||||||
import { Component, Inject, PLATFORM_ID, OnInit } from '@angular/core';
|
// /src/app/core/components/default-layout/sidebar/sidebar.component.ts
|
||||||
import { CommonModule, isPlatformBrowser } from '@angular/common';
|
|
||||||
|
import { Component, OnInit, inject } from '@angular/core';
|
||||||
|
import { CommonModule } from '@angular/common';
|
||||||
|
import { RouterLink, RouterLinkActive } from '@angular/router'; // RouterLink und RouterLinkActive importieren
|
||||||
import { IconComponent } from '../../ui/icon/icon.component';
|
import { IconComponent } from '../../ui/icon/icon.component';
|
||||||
|
import { StorageService } from '../../../../core/services/storage.service';
|
||||||
import { Router } from '@angular/router';
|
import { Router } from '@angular/router';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-sidebar',
|
selector: 'app-sidebar',
|
||||||
standalone: true,
|
standalone: true,
|
||||||
imports: [CommonModule, IconComponent],
|
imports: [CommonModule, IconComponent], // RouterLink und RouterLinkActive hier hinzufügen
|
||||||
templateUrl: './sidebar.component.html',
|
templateUrl: './sidebar.component.html',
|
||||||
styleUrl: './sidebar.component.css',
|
styleUrl: './sidebar.component.css',
|
||||||
})
|
})
|
||||||
export class SidebarComponent implements OnInit {
|
export class SidebarComponent implements OnInit {
|
||||||
// 1. OnInit implementieren
|
// --- Abhängigkeiten mit moderner inject()-Syntax ---
|
||||||
// Key für localStorage, genau wie beim Dark Mode
|
private storageService = inject(StorageService);
|
||||||
private readonly sidebarCollapsedKey = 'app-sidebar-collapsed-setting';
|
|
||||||
|
|
||||||
// Dummy-Eigenschaft für die aktive Route
|
private readonly sidebarCollapsedKey = 'app-sidebar-collapsed';
|
||||||
activeRoute = 'dashboard';
|
|
||||||
|
|
||||||
// Der Standardwert ist 'false' (aufgeklappt), wird aber sofort überschrieben
|
|
||||||
public isCollapsed = false;
|
public isCollapsed = false;
|
||||||
|
|
||||||
// 2. PLATFORM_ID injizieren, um localStorage sicher zu verwenden
|
activeRoute = 'dashboard';
|
||||||
constructor(
|
constructor(private router: Router) {}
|
||||||
@Inject(PLATFORM_ID) private platformId: Object,
|
|
||||||
private router: Router
|
|
||||||
) {}
|
|
||||||
|
|
||||||
// 3. Beim Start der Komponente den gespeicherten Zustand laden
|
|
||||||
ngOnInit(): void {
|
ngOnInit(): void {
|
||||||
this.loadCollapsedState();
|
this.loadCollapsedState();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Dummy-Methode
|
|
||||||
setActive(route: string): void {
|
setActive(route: string): void {
|
||||||
this.activeRoute = route;
|
this.activeRoute = route;
|
||||||
this.router.navigateByUrl('/shop/' + route);
|
this.router.navigateByUrl('/shop/' + route);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 4. Die Umschalt-Methode aktualisieren, damit sie den neuen Zustand speichert
|
|
||||||
toggleSidebar(): void {
|
toggleSidebar(): void {
|
||||||
// Zuerst den Zustand ändern
|
|
||||||
this.isCollapsed = !this.isCollapsed;
|
this.isCollapsed = !this.isCollapsed;
|
||||||
// Dann den neuen Zustand speichern
|
|
||||||
this.saveCollapsedState();
|
this.saveCollapsedState();
|
||||||
}
|
}
|
||||||
|
|
||||||
// 5. Methode zum Laden des Zustands (kopiert vom Dark-Mode-Muster)
|
|
||||||
private loadCollapsedState(): void {
|
private loadCollapsedState(): void {
|
||||||
if (isPlatformBrowser(this.platformId)) {
|
// Der Service kümmert sich um die Browser-Prüfung und gibt boolean oder null zurück
|
||||||
try {
|
this.isCollapsed =
|
||||||
const storedValue = localStorage.getItem(this.sidebarCollapsedKey);
|
this.storageService.getItem<boolean>(this.sidebarCollapsedKey) ?? false;
|
||||||
// Setze den Zustand der Komponente basierend auf dem gespeicherten Wert
|
|
||||||
this.isCollapsed = storedValue === 'true';
|
|
||||||
} catch (e) {
|
|
||||||
console.error('Could not access localStorage for sidebar state:', e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 6. Methode zum Speichern des Zustands (kopiert vom Dark-Mode-Muster)
|
|
||||||
private saveCollapsedState(): void {
|
private saveCollapsedState(): void {
|
||||||
if (isPlatformBrowser(this.platformId)) {
|
// Der Service kümmert sich um die Serialisierung des booleans
|
||||||
try {
|
this.storageService.setItem(this.sidebarCollapsedKey, this.isCollapsed);
|
||||||
localStorage.setItem(
|
|
||||||
this.sidebarCollapsedKey,
|
|
||||||
String(this.isCollapsed)
|
|
||||||
);
|
|
||||||
} catch (e) {
|
|
||||||
console.error('Could not write to localStorage for sidebar state:', e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -43,3 +43,9 @@
|
|||||||
|
|
||||||
.pill-info { color: #1d4ed8; background-color: #eff6ff; border-color: #bfdbfe; }
|
.pill-info { color: #1d4ed8; background-color: #eff6ff; border-color: #bfdbfe; }
|
||||||
:host-context(body.dark-theme) .pill-info { color: #93c5fd; background-color: #1e40af; border-color: #3b82f6; }
|
:host-context(body.dark-theme) .pill-info { color: #93c5fd; background-color: #1e40af; border-color: #3b82f6; }
|
||||||
|
|
||||||
|
.pill-active { color: #15803d; background-color: #ecfdf5; border-color: #bbf7d0; }
|
||||||
|
:host-context(body.dark-theme) .pill-active { color: #a7f3d0; background-color: #166534; border-color: #22c55e; }
|
||||||
|
|
||||||
|
.pill-inactive { color: rgb(168, 168, 168); background-color: #ececec; border-color: #777777; }
|
||||||
|
:host-context(body.dark-theme) .pill-inactive { color: rgb(168, 168, 168); background-color: #ececec; border-color: #777777; }
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import { Component, Input, OnChanges } from '@angular/core';
|
import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';
|
||||||
import { CommonModule, NgClass } from '@angular/common';
|
import { CommonModule, NgClass } from '@angular/common';
|
||||||
// import { OrderStatus } from '../../../../core/types/order';
|
// import { OrderStatus } from '../../../../core/types/order';
|
||||||
|
|
||||||
@@ -11,7 +11,7 @@ import { CommonModule, NgClass } from '@angular/common';
|
|||||||
})
|
})
|
||||||
export class StatusPillComponent implements OnChanges {
|
export class StatusPillComponent implements OnChanges {
|
||||||
// Nimmt jetzt den neuen, sprechenden Status entgegen
|
// Nimmt jetzt den neuen, sprechenden Status entgegen
|
||||||
@Input() status: any = 'info';
|
@Input() status: string | boolean = 'info';
|
||||||
|
|
||||||
// Diese Eigenschaften werden vom Template verwendet
|
// Diese Eigenschaften werden vom Template verwendet
|
||||||
public displayText = '';
|
public displayText = '';
|
||||||
@@ -22,13 +22,22 @@ export class StatusPillComponent implements OnChanges {
|
|||||||
['completed', { text: 'Abgeschlossen', css: 'pill-success' }],
|
['completed', { text: 'Abgeschlossen', css: 'pill-success' }],
|
||||||
['processing', { text: 'In Bearbeitung', css: 'pill-warning' }],
|
['processing', { text: 'In Bearbeitung', css: 'pill-warning' }],
|
||||||
['cancelled', { text: 'Storniert', css: 'pill-danger' }],
|
['cancelled', { text: 'Storniert', css: 'pill-danger' }],
|
||||||
['info', { text: 'Info', css: 'pill-info' }]
|
['info', { text: 'Info', css: 'pill-info' }],
|
||||||
|
['active', { text: 'Ja', css: 'pill-active' }],
|
||||||
|
['inactive', { text: 'Nein', css: 'pill-inactive' }]
|
||||||
]);
|
]);
|
||||||
|
|
||||||
ngOnChanges(): void {
|
ngOnChanges(changes: SimpleChanges): void {
|
||||||
// Wenn sich der Input-Status ändert, aktualisieren wir Text und Klasse
|
if (changes['status']) {
|
||||||
const details = this.statusMap.get(this.status) || this.statusMap.get('info')!;
|
let statusKey = this.status;
|
||||||
|
|
||||||
|
if (typeof statusKey === 'boolean') {
|
||||||
|
statusKey = statusKey ? 'active' : 'inactive';
|
||||||
|
}
|
||||||
|
|
||||||
|
const details = this.statusMap.get(statusKey as string) || { text: statusKey.toString(), css: 'pill-secondary' };
|
||||||
this.displayText = details.text;
|
this.displayText = details.text;
|
||||||
this.cssClass = details.css;
|
this.cssClass = details.css;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Reference in New Issue
Block a user