Compare commits
5 Commits
1585129e1f
...
2491b0142d
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2491b0142d | ||
|
|
7511596b11 | ||
|
|
8df2420aa0 | ||
|
|
9173f9b625 | ||
|
|
b1b1c3173b |
@@ -0,0 +1,114 @@
|
|||||||
|
/* /src/app/shared/components/form/multi-select-dropdown/multi-select-dropdown.component.css */
|
||||||
|
|
||||||
|
:host {
|
||||||
|
display: block;
|
||||||
|
}
|
||||||
|
|
||||||
|
.custom-select-wrapper {
|
||||||
|
position: relative;
|
||||||
|
}
|
||||||
|
|
||||||
|
.select-display {
|
||||||
|
width: 100%;
|
||||||
|
text-align: left;
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
padding: 0.5rem 2.5rem 0.5rem 1rem;
|
||||||
|
min-height: 54px;
|
||||||
|
border: 1px solid var(--color-border);
|
||||||
|
border-radius: var(--border-radius-md);
|
||||||
|
background-color: var(--color-surface);
|
||||||
|
cursor: pointer;
|
||||||
|
transition: border-color var(--transition-speed);
|
||||||
|
}
|
||||||
|
|
||||||
|
.select-display:focus {
|
||||||
|
outline: none;
|
||||||
|
border-color: var(--color-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.selected-pills {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 0.5rem;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.placeholder-text {
|
||||||
|
color: var(--color-text-light);
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-label {
|
||||||
|
position: absolute;
|
||||||
|
top: 50%;
|
||||||
|
left: 1rem;
|
||||||
|
transform: translateY(-50%);
|
||||||
|
color: var(--color-text-light);
|
||||||
|
background-color: var(--color-surface);
|
||||||
|
padding: 0 0.25rem;
|
||||||
|
transition: all 0.2s ease-out;
|
||||||
|
pointer-events: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.select-display:focus ~ .form-label,
|
||||||
|
.form-label.has-value {
|
||||||
|
top: 0;
|
||||||
|
font-size: 0.8rem;
|
||||||
|
color: var(--color-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.select-display::after {
|
||||||
|
content: "";
|
||||||
|
position: absolute;
|
||||||
|
top: 50%;
|
||||||
|
right: 1rem;
|
||||||
|
transform: translateY(-50%);
|
||||||
|
width: 0.8em;
|
||||||
|
height: 0.5em;
|
||||||
|
background-color: var(--color-text-light);
|
||||||
|
clip-path: polygon(100% 0%, 0 0%, 50% 100%);
|
||||||
|
transition: transform 0.2s ease-out;
|
||||||
|
}
|
||||||
|
|
||||||
|
.custom-select-wrapper.is-open .select-display::after {
|
||||||
|
transform: translateY(-50%) rotate(180deg);
|
||||||
|
}
|
||||||
|
|
||||||
|
.options-list {
|
||||||
|
position: absolute;
|
||||||
|
top: calc(100% + 4px);
|
||||||
|
left: 0;
|
||||||
|
right: 0;
|
||||||
|
background-color: var(--color-surface);
|
||||||
|
border: 1px solid var(--color-border);
|
||||||
|
border-radius: var(--border-radius-md);
|
||||||
|
box-shadow: var(--box-shadow-md);
|
||||||
|
z-index: 1000;
|
||||||
|
padding: 0.5rem;
|
||||||
|
animation: fadeInDown 0.2s ease-out forwards;
|
||||||
|
}
|
||||||
|
|
||||||
|
.category-checkbox-group {
|
||||||
|
max-height: 220px;
|
||||||
|
overflow-y: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.category-checkbox-group label {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.75rem;
|
||||||
|
padding: 0.75rem;
|
||||||
|
border-radius: var(--border-radius-sm);
|
||||||
|
cursor: pointer;
|
||||||
|
transition: background-color 0.15s ease-out;
|
||||||
|
}
|
||||||
|
|
||||||
|
.category-checkbox-group label:hover {
|
||||||
|
background-color: var(--color-body-bg-hover);
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes fadeInDown {
|
||||||
|
from { opacity: 0; transform: translateY(-10px); }
|
||||||
|
to { opacity: 1; transform: translateY(0); }
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
<!-- /src/app/shared/components/form/multi-select-dropdown/multi-select-dropdown.component.html -->
|
||||||
|
|
||||||
|
<div class="custom-select-wrapper" [class.is-open]="isOpen">
|
||||||
|
<!-- Der klickbare Bereich, der die Pills anzeigt -->
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="form-input select-display"
|
||||||
|
(click)="toggleDropdown($event)">
|
||||||
|
|
||||||
|
<div class="selected-pills">
|
||||||
|
<app-status-pill
|
||||||
|
*ngFor="let value of selectedValues"
|
||||||
|
[text]="getLabelForValue(value)"
|
||||||
|
status="info"
|
||||||
|
[removable]="true"
|
||||||
|
(remove)="onPillRemove(value, $event)">
|
||||||
|
</app-status-pill>
|
||||||
|
<span *ngIf="selectedValues.length === 0" class="placeholder-text">{{ placeholder }}</span>
|
||||||
|
</div>
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<!-- Das schwebende Label -->
|
||||||
|
<label class="form-label" [class.has-value]="selectedValues.length > 0">
|
||||||
|
{{ label }}
|
||||||
|
</label>
|
||||||
|
|
||||||
|
<!-- Die aufklappbare Liste mit den Checkboxen -->
|
||||||
|
<div *ngIf="isOpen" class="options-list">
|
||||||
|
<div class="category-checkbox-group">
|
||||||
|
<label *ngFor="let option of options">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
[value]="option.value"
|
||||||
|
[checked]="isSelected(option.value)"
|
||||||
|
(change)="onOptionToggle(option.value)" />
|
||||||
|
{{ option.label }}
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
// /src/app/shared/components/form/product-category-dropdown/product-category-dropdown.component.ts
|
||||||
|
|
||||||
|
import { Component, Input, forwardRef, HostListener, ElementRef, inject } from '@angular/core';
|
||||||
|
import { CommonModule } from '@angular/common';
|
||||||
|
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
|
||||||
|
import { StatusPillComponent } from '../../../../shared/components/ui/status-pill/status-pill.component';
|
||||||
|
|
||||||
|
// Eine wiederverwendbare Schnittstelle für die Optionen
|
||||||
|
export interface SelectOption {
|
||||||
|
value: any;
|
||||||
|
label: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-product-category-dropdown',
|
||||||
|
standalone: true,
|
||||||
|
imports: [CommonModule, StatusPillComponent],
|
||||||
|
templateUrl: './product-category-dropdown.component.html',
|
||||||
|
styleUrls: ['./product-category-dropdown.component.css'],
|
||||||
|
providers: [
|
||||||
|
{
|
||||||
|
provide: NG_VALUE_ACCESSOR,
|
||||||
|
useExisting: forwardRef(() => ProductCategoryDropdownComponent),
|
||||||
|
multi: true,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
})
|
||||||
|
export class ProductCategoryDropdownComponent implements ControlValueAccessor {
|
||||||
|
@Input() label = '';
|
||||||
|
@Input() options: SelectOption[] = [];
|
||||||
|
@Input() placeholder = 'Bitte wählen...';
|
||||||
|
|
||||||
|
public isOpen = false;
|
||||||
|
public selectedValues: any[] = [];
|
||||||
|
private elementRef = inject(ElementRef);
|
||||||
|
|
||||||
|
onChange: (value: any[]) => void = () => {};
|
||||||
|
onTouched: () => void = () => {};
|
||||||
|
|
||||||
|
writeValue(values: any[]): void { this.selectedValues = Array.isArray(values) ? values : []; }
|
||||||
|
registerOnChange(fn: any): void { this.onChange = fn; }
|
||||||
|
registerOnTouched(fn: any): void { this.onTouched = fn; }
|
||||||
|
|
||||||
|
@HostListener('document:click', ['$event'])
|
||||||
|
onDocumentClick(event: Event): void {
|
||||||
|
if (this.isOpen && !this.elementRef.nativeElement.contains(event.target)) {
|
||||||
|
this.closeDropdown();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
toggleDropdown(event: Event): void {
|
||||||
|
event.stopPropagation();
|
||||||
|
this.isOpen = !this.isOpen;
|
||||||
|
if (!this.isOpen) { this.onTouched(); }
|
||||||
|
}
|
||||||
|
|
||||||
|
closeDropdown(): void {
|
||||||
|
if (this.isOpen) {
|
||||||
|
this.isOpen = false;
|
||||||
|
this.onTouched();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
onOptionToggle(value: any): void {
|
||||||
|
const index = this.selectedValues.indexOf(value);
|
||||||
|
if (index > -1) {
|
||||||
|
this.selectedValues.splice(index, 1);
|
||||||
|
} else {
|
||||||
|
this.selectedValues.push(value);
|
||||||
|
}
|
||||||
|
this.onChange([...this.selectedValues]); // Wichtig: Neue Array-Instanz senden
|
||||||
|
}
|
||||||
|
|
||||||
|
onPillRemove(value: any, event: any): void { // Typ korrigiert
|
||||||
|
event.stopPropagation();
|
||||||
|
this.onOptionToggle(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
isSelected(value: any): boolean { return this.selectedValues.includes(value); }
|
||||||
|
getLabelForValue(value: any): string { return this.options.find(opt => opt.value === value)?.label || ''; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
.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;
|
||||||
|
font-size: 1.5rem;
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--color-text);
|
||||||
|
}
|
||||||
|
|
||||||
|
.loading-container {
|
||||||
|
display: flex;
|
||||||
|
justify-content: center;
|
||||||
|
align-items: center;
|
||||||
|
min-height: 300px;
|
||||||
|
color: var(--text-color-secondary);
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
<!-- /src/app/features/admin/components/products/product-create/product-create.component.html -->
|
||||||
|
<div *ngIf="isLoading; else formContent" class="loading-container">
|
||||||
|
<p>Lade Formulardaten...</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<ng-template #formContent>
|
||||||
|
<div class="form-header">
|
||||||
|
<h3 card-header>Neues Produkt erstellen</h3>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<app-product-form
|
||||||
|
[productForm]="productForm"
|
||||||
|
[allCategories]="(allCategories$ | async) || []"
|
||||||
|
[supplierOptions]="(supplierOptions$ | async) || []"
|
||||||
|
[allImages]="allImagesForForm"
|
||||||
|
[isLoading]="isLoading"
|
||||||
|
submitButtonText="Produkt erstellen"
|
||||||
|
(formSubmit)="onSubmit()"
|
||||||
|
(formCancel)="cancel()"
|
||||||
|
(filesSelected)="onFilesSelected($event)"
|
||||||
|
(setMainImage)="onSetMainImage($event)"
|
||||||
|
(deleteImage)="onDeleteImage($event)">
|
||||||
|
</app-product-form>
|
||||||
|
</ng-template>
|
||||||
@@ -0,0 +1,256 @@
|
|||||||
|
// /src/app/features/admin/components/products/product-create/product-create.component.ts
|
||||||
|
|
||||||
|
import { Component, OnInit, OnDestroy, inject } from '@angular/core';
|
||||||
|
import { CommonModule } from '@angular/common';
|
||||||
|
import { Router } from '@angular/router';
|
||||||
|
import {
|
||||||
|
FormBuilder,
|
||||||
|
FormGroup,
|
||||||
|
FormArray,
|
||||||
|
ReactiveFormsModule,
|
||||||
|
Validators,
|
||||||
|
FormControl,
|
||||||
|
} from '@angular/forms';
|
||||||
|
import { DomSanitizer, SafeUrl } from '@angular/platform-browser';
|
||||||
|
import { Observable, Subscription } from 'rxjs';
|
||||||
|
import {
|
||||||
|
debounceTime,
|
||||||
|
distinctUntilChanged,
|
||||||
|
map,
|
||||||
|
startWith,
|
||||||
|
} from 'rxjs/operators';
|
||||||
|
|
||||||
|
// Models, Services und UI-Komponenten
|
||||||
|
import { Category } from '../../../../core/models/category.model';
|
||||||
|
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';
|
||||||
|
import {
|
||||||
|
ImagePreview,
|
||||||
|
ProductFormComponent,
|
||||||
|
} from '../product-form/product-form.component';
|
||||||
|
import { SelectOption } from '../../../../shared/components/form/form-select/form-select.component';
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-product-create',
|
||||||
|
standalone: true,
|
||||||
|
imports: [
|
||||||
|
CommonModule,
|
||||||
|
ReactiveFormsModule,
|
||||||
|
|
||||||
|
ProductFormComponent,
|
||||||
|
],
|
||||||
|
templateUrl: './product-create.component.html',
|
||||||
|
styleUrls: ['./product-create.component.css'],
|
||||||
|
})
|
||||||
|
export class ProductCreateComponent implements OnInit, OnDestroy {
|
||||||
|
// --- Injektionen ---
|
||||||
|
private sanitizer = inject(DomSanitizer);
|
||||||
|
private router = inject(Router);
|
||||||
|
private productService = inject(ProductService);
|
||||||
|
private categoryService = inject(CategoryService);
|
||||||
|
private supplierService = inject(SupplierService);
|
||||||
|
private fb = inject(FormBuilder);
|
||||||
|
private snackbarService = inject(SnackbarService);
|
||||||
|
|
||||||
|
// --- Komponenten-Status ---
|
||||||
|
isLoading = true;
|
||||||
|
productForm: FormGroup;
|
||||||
|
allCategories$!: Observable<Category[]>;
|
||||||
|
supplierOptions$!: Observable<SelectOption[]>;
|
||||||
|
private nameChangeSubscription?: Subscription;
|
||||||
|
|
||||||
|
// --- Bild-Management State ---
|
||||||
|
newImageFiles: File[] = [];
|
||||||
|
mainImageIdentifier: string | null = null;
|
||||||
|
allImagesForForm: ImagePreview[] = [];
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
this.productForm = this.fb.group({
|
||||||
|
name: ['', Validators.required],
|
||||||
|
slug: ['', Validators.required],
|
||||||
|
sku: ['', Validators.required],
|
||||||
|
price: [0, [Validators.required, Validators.min(0)]],
|
||||||
|
stockQuantity: [0, [Validators.required, Validators.min(0)]],
|
||||||
|
description: [''],
|
||||||
|
oldPrice: [null, [Validators.min(0)]],
|
||||||
|
purchasePrice: [null, [Validators.min(0)]],
|
||||||
|
weight: [null, [Validators.min(0)]],
|
||||||
|
isActive: [true],
|
||||||
|
isFeatured: [false],
|
||||||
|
featuredDisplayOrder: [0],
|
||||||
|
supplierId: [null],
|
||||||
|
categorieIds: new FormControl([]),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Lifecycle Hooks ---
|
||||||
|
ngOnInit(): void {
|
||||||
|
this.loadDropdownData();
|
||||||
|
this.subscribeToNameChanges();
|
||||||
|
this.isLoading = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
ngOnDestroy(): void {
|
||||||
|
this.nameChangeSubscription?.unsubscribe();
|
||||||
|
// BEST PRACTICE: Temporäre Bild-URLs aus dem Speicher entfernen, um Memory Leaks zu vermeiden
|
||||||
|
this.allImagesForForm.forEach((image) =>
|
||||||
|
URL.revokeObjectURL(image.url as string)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Öffentliche Methoden & Event-Handler ---
|
||||||
|
loadDropdownData(): void {
|
||||||
|
this.allCategories$ = this.categoryService.getAll();
|
||||||
|
this.supplierOptions$ = this.supplierService.getAll().pipe(
|
||||||
|
map((suppliers) =>
|
||||||
|
suppliers.map((s) => ({ value: s.id, label: s.name || 'Unbenannt' }))
|
||||||
|
),
|
||||||
|
startWith([])
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
onSubmit(): void {
|
||||||
|
if (this.productForm.invalid) {
|
||||||
|
this.productForm.markAllAsTouched();
|
||||||
|
this.snackbarService.show('Bitte füllen Sie alle Pflichtfelder aus.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// NEU: Stellt sicher, dass Slug/SKU vor dem Senden generiert werden, falls sie leer sind
|
||||||
|
this.prepareSubmissionData();
|
||||||
|
const formData = this.createFormData();
|
||||||
|
|
||||||
|
this.productService.create(formData).subscribe({
|
||||||
|
next: () => {
|
||||||
|
this.snackbarService.show('Produkt erfolgreich erstellt');
|
||||||
|
this.router.navigate(['/shop/products']);
|
||||||
|
},
|
||||||
|
error: (err) => {
|
||||||
|
this.snackbarService.show('Ein Fehler ist aufgetreten.');
|
||||||
|
console.error(err);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
cancel(): void {
|
||||||
|
this.router.navigate(['/shop/products']);
|
||||||
|
}
|
||||||
|
|
||||||
|
onFilesSelected(files: File[]): void {
|
||||||
|
this.newImageFiles.push(...files);
|
||||||
|
if (!this.mainImageIdentifier && this.newImageFiles.length > 0) {
|
||||||
|
this.mainImageIdentifier = this.newImageFiles[0].name;
|
||||||
|
}
|
||||||
|
this.rebuildAllImagesForForm();
|
||||||
|
}
|
||||||
|
|
||||||
|
onSetMainImage(identifier: string): void {
|
||||||
|
this.mainImageIdentifier = identifier;
|
||||||
|
this.rebuildAllImagesForForm();
|
||||||
|
}
|
||||||
|
|
||||||
|
onDeleteImage(identifier: string): void {
|
||||||
|
this.newImageFiles = this.newImageFiles.filter(
|
||||||
|
(file) => file.name !== identifier
|
||||||
|
);
|
||||||
|
if (this.mainImageIdentifier === identifier) {
|
||||||
|
this.mainImageIdentifier =
|
||||||
|
this.newImageFiles.length > 0 ? this.newImageFiles[0].name : null;
|
||||||
|
}
|
||||||
|
this.rebuildAllImagesForForm();
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Private Helfermethoden ---
|
||||||
|
private rebuildAllImagesForForm(): void {
|
||||||
|
// Alte URLs freigeben, um Memory Leaks zu verhindern
|
||||||
|
this.allImagesForForm.forEach((image) =>
|
||||||
|
URL.revokeObjectURL(image.url as string)
|
||||||
|
);
|
||||||
|
|
||||||
|
this.allImagesForForm = this.newImageFiles.map((file) => ({
|
||||||
|
identifier: file.name,
|
||||||
|
url: this.sanitizer.bypassSecurityTrustUrl(URL.createObjectURL(file)),
|
||||||
|
isMainImage: file.name === this.mainImageIdentifier,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
private prepareSubmissionData(): void {
|
||||||
|
const name = this.productForm.get('name')?.value;
|
||||||
|
const slugControl = this.productForm.get('slug');
|
||||||
|
const skuControl = this.productForm.get('sku');
|
||||||
|
|
||||||
|
if (name && slugControl && !slugControl.value) {
|
||||||
|
slugControl.setValue(this.generateSlug(name), { emitEvent: false });
|
||||||
|
}
|
||||||
|
if (name && skuControl && !skuControl.value) {
|
||||||
|
skuControl.setValue(this.generateSkuValue(name), { emitEvent: false });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private createFormData(): FormData {
|
||||||
|
const formData = new FormData();
|
||||||
|
const formValue = this.productForm.getRawValue();
|
||||||
|
|
||||||
|
Object.keys(formValue).forEach((key) => {
|
||||||
|
const value = formValue[key];
|
||||||
|
if (key === 'categorieIds') {
|
||||||
|
(value as string[]).forEach((id) =>
|
||||||
|
formData.append('CategorieIds', id)
|
||||||
|
);
|
||||||
|
} else if (value !== null && value !== undefined && value !== '') {
|
||||||
|
formData.append(this.capitalizeFirstLetter(key), value.toString());
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const mainImageFile = this.newImageFiles.find(
|
||||||
|
(f) => f.name === this.mainImageIdentifier
|
||||||
|
);
|
||||||
|
if (mainImageFile) {
|
||||||
|
formData.append('MainImageFile', mainImageFile);
|
||||||
|
}
|
||||||
|
|
||||||
|
// KORREKTUR: Die Logik für 'MainImageId' wurde entfernt, da sie hier nicht relevant ist.
|
||||||
|
|
||||||
|
this.newImageFiles
|
||||||
|
.filter((f) => f.name !== this.mainImageIdentifier)
|
||||||
|
.forEach((file) => formData.append('AdditionalImageFiles', file));
|
||||||
|
|
||||||
|
return formData;
|
||||||
|
}
|
||||||
|
|
||||||
|
private subscribeToNameChanges(): void {
|
||||||
|
this.nameChangeSubscription = this.productForm
|
||||||
|
.get('name')
|
||||||
|
?.valueChanges.pipe(debounceTime(400), distinctUntilChanged())
|
||||||
|
.subscribe((name: any) => {
|
||||||
|
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) => ({ ä: 'ae', ö: 'oe', ü: 'ue', ß: 'ss' }[char] || '')
|
||||||
|
)
|
||||||
|
.replace(/[^a-z0-9-]/g, '')
|
||||||
|
.replace(/-+/g, '-');
|
||||||
|
}
|
||||||
|
|
||||||
|
private generateSkuValue(name: string): string {
|
||||||
|
const prefix = name.substring(0, 4).toUpperCase().replace(/\s+/g, '');
|
||||||
|
const randomPart = Math.random().toString(36).substring(2, 8).toUpperCase();
|
||||||
|
return `${prefix}-${randomPart}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
private capitalizeFirstLetter(string: string): string {
|
||||||
|
return string.charAt(0).toUpperCase() + string.slice(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,3 @@
|
|||||||
:host { display: block; }
|
|
||||||
|
|
||||||
.form-header {
|
.form-header {
|
||||||
display: flex;
|
display: flex;
|
||||||
justify-content: space-between;
|
justify-content: space-between;
|
||||||
@@ -9,56 +7,17 @@
|
|||||||
border-bottom: 1px solid var(--color-border);
|
border-bottom: 1px solid var(--color-border);
|
||||||
}
|
}
|
||||||
|
|
||||||
h3[card-header] { margin: 0; }
|
h3[card-header] {
|
||||||
|
margin: 0;
|
||||||
.form-section { margin-bottom: 1.5rem; }
|
font-size: 1.5rem;
|
||||||
.section-title { font-size: 1.1rem; font-weight: 600; margin-bottom: 1.25rem; color: var(--color-text); }
|
font-weight: 600;
|
||||||
|
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; }
|
.loading-container {
|
||||||
|
display: flex;
|
||||||
.input-with-button { display: flex; gap: 0.5rem; }
|
justify-content: center;
|
||||||
.input-with-button input { flex-grow: 1; }
|
align-items: center;
|
||||||
|
min-height: 300px;
|
||||||
.category-checkbox-group {
|
color: var(--text-color-secondary);
|
||||||
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; }
|
|
||||||
}
|
|
||||||
@@ -1,108 +1,25 @@
|
|||||||
<!-- /src/app/features/admin/components/products/product-edit/product-edit.component.html -->
|
<!-- /src/app/features/admin/components/products/product-edit/product-edit.component.html -->
|
||||||
|
|
||||||
<app-card>
|
<div *ngIf="isLoading; else formContent" class="loading-container">
|
||||||
<div *ngIf="isLoading; else formContent" class="loading-container">
|
<p>Lade Produktdaten...</p>
|
||||||
<p>Lade Produktdaten...</p>
|
</div>
|
||||||
|
|
||||||
|
<ng-template #formContent>
|
||||||
|
<div class="form-header">
|
||||||
|
<h3 card-header>Produkt bearbeiten</h3>
|
||||||
</div>
|
</div>
|
||||||
|
<app-product-form
|
||||||
<ng-template #formContent>
|
[productForm]="productForm"
|
||||||
<form [formGroup]="productForm" (ngSubmit)="onSubmit()" novalidate>
|
[allCategories]="(allCategories$ | async) || []"
|
||||||
<div class="form-header">
|
[supplierOptions]="(supplierOptions$ | async) || []"
|
||||||
<h3 card-header>{{ isEditMode ? "Produkt bearbeiten" : "Neues Produkt erstellen" }}</h3>
|
[allImages]="allImagesForForm"
|
||||||
</div>
|
[isLoading]="isLoading"
|
||||||
|
submitButtonText="Änderungen speichern"
|
||||||
<div class="edit-layout">
|
(formSubmit)="onSubmit()"
|
||||||
<!-- LINKE SPALTE -->
|
(formCancel)="cancel()"
|
||||||
<div class="main-content">
|
(filesSelected)="onFilesSelected($event)"
|
||||||
<app-card>
|
(setMainImage)="onSetMainImage($event)"
|
||||||
<h4 card-header>Allgemein</h4>
|
(deleteImage)="onDeleteImage($event)"
|
||||||
<div class="form-section">
|
>
|
||||||
<app-form-field label="Name"><input type="text" formControlName="name"></app-form-field>
|
</app-product-form>
|
||||||
<app-form-field label="Slug"><input type="text" formControlName="slug"></app-form-field>
|
</ng-template>
|
||||||
<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>
|
|
||||||
|
|||||||
@@ -3,38 +3,50 @@
|
|||||||
import { Component, OnInit, OnDestroy, inject } from '@angular/core';
|
import { Component, OnInit, OnDestroy, inject } from '@angular/core';
|
||||||
import { CommonModule } from '@angular/common';
|
import { CommonModule } from '@angular/common';
|
||||||
import { ActivatedRoute, Router } from '@angular/router';
|
import { ActivatedRoute, Router } from '@angular/router';
|
||||||
import { FormBuilder, FormGroup, FormArray, FormControl, ReactiveFormsModule, Validators } from '@angular/forms';
|
import {
|
||||||
|
FormBuilder,
|
||||||
|
FormGroup,
|
||||||
|
FormArray,
|
||||||
|
FormControl,
|
||||||
|
ReactiveFormsModule,
|
||||||
|
Validators,
|
||||||
|
} from '@angular/forms';
|
||||||
|
import { DomSanitizer } from '@angular/platform-browser';
|
||||||
import { Observable, Subscription } from 'rxjs';
|
import { Observable, Subscription } from 'rxjs';
|
||||||
import { debounceTime, distinctUntilChanged, map, startWith, tap } from 'rxjs/operators';
|
import {
|
||||||
|
map,
|
||||||
|
startWith,
|
||||||
|
debounceTime,
|
||||||
|
distinctUntilChanged,
|
||||||
|
finalize,
|
||||||
|
} from 'rxjs/operators';
|
||||||
|
|
||||||
// Models
|
// Models, Services und UI-Komponenten
|
||||||
import { AdminProduct, ProductImage } from '../../../../core/models/product.model';
|
import {
|
||||||
|
AdminProduct,
|
||||||
|
ProductImage,
|
||||||
|
} from '../../../../core/models/product.model';
|
||||||
import { Category } from '../../../../core/models/category.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 { 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 { SnackbarService } from '../../../../shared/services/snackbar.service';
|
||||||
|
|
||||||
// Wiederverwendbare UI- & Form-Komponenten
|
|
||||||
import { CardComponent } from '../../../../shared/components/ui/card/card.component';
|
import { CardComponent } from '../../../../shared/components/ui/card/card.component';
|
||||||
import { ButtonComponent } from '../../../../shared/components/ui/button/button.component';
|
import {
|
||||||
import { IconComponent } from '../../../../shared/components/ui/icon/icon.component';
|
ImagePreview,
|
||||||
import { FormFieldComponent } from '../../../../shared/components/form/form-field/form-field.component';
|
ProductFormComponent,
|
||||||
import { FormSelectComponent, SelectOption } from '../../../../shared/components/form/form-select/form-select.component';
|
} from '../product-form/product-form.component';
|
||||||
import { FormTextareaComponent } from '../../../../shared/components/form/form-textarea/form-textarea.component';
|
import { SelectOption } from '../../../../shared/components/form/form-select/form-select.component';
|
||||||
import { SlideToggleComponent } from '../../../../shared/components/form/slide-toggle/slide-toggle.component';
|
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-product-edit',
|
selector: 'app-product-edit',
|
||||||
standalone: true,
|
standalone: true,
|
||||||
imports: [ CommonModule, ReactiveFormsModule, CardComponent, ButtonComponent, IconComponent, FormFieldComponent, FormSelectComponent, FormTextareaComponent, SlideToggleComponent ],
|
imports: [CommonModule, ReactiveFormsModule, ProductFormComponent],
|
||||||
templateUrl: './product-edit.component.html',
|
templateUrl: './product-edit.component.html',
|
||||||
styleUrl: './product-edit.component.css'
|
styleUrls: ['./product-edit.component.css'],
|
||||||
})
|
})
|
||||||
export class ProductEditComponent implements OnInit, OnDestroy {
|
export class ProductEditComponent implements OnInit, OnDestroy {
|
||||||
|
// --- Injektionen ---
|
||||||
private route = inject(ActivatedRoute);
|
private route = inject(ActivatedRoute);
|
||||||
private router = inject(Router);
|
private router = inject(Router);
|
||||||
private productService = inject(ProductService);
|
private productService = inject(ProductService);
|
||||||
@@ -42,126 +54,122 @@ export class ProductEditComponent implements OnInit, OnDestroy {
|
|||||||
private supplierService = inject(SupplierService);
|
private supplierService = inject(SupplierService);
|
||||||
private fb = inject(FormBuilder);
|
private fb = inject(FormBuilder);
|
||||||
private snackbarService = inject(SnackbarService);
|
private snackbarService = inject(SnackbarService);
|
||||||
|
private sanitizer = inject(DomSanitizer);
|
||||||
|
|
||||||
productId: string | null = null;
|
// --- Komponenten-Status ---
|
||||||
isEditMode = false;
|
productId!: string;
|
||||||
isLoading = true;
|
isLoading = true;
|
||||||
productForm: FormGroup;
|
productForm: FormGroup;
|
||||||
|
private nameChangeSubscription?: Subscription;
|
||||||
allCategories$!: Observable<Category[]>;
|
allCategories$!: Observable<Category[]>;
|
||||||
supplierOptions$!: Observable<SelectOption[]>;
|
supplierOptions$!: Observable<SelectOption[]>;
|
||||||
allCategories: Category[] = [];
|
|
||||||
|
|
||||||
private nameChangeSubscription?: Subscription;
|
// --- NEUER STATE FÜR BILD-MANAGEMENT ---
|
||||||
existingImages: ProductImage[] = [];
|
existingImages: ProductImage[] = [];
|
||||||
mainImageFile: File | null = null;
|
newImageFiles: File[] = [];
|
||||||
additionalImageFiles: File[] = [];
|
mainImageIdentifier: string | null = null; // Hält die ID oder den Dateinamen des Hauptbildes
|
||||||
|
allImagesForForm: ImagePreview[] = []; // Die kombinierte Liste für die Child-Komponente
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
this.productForm = this.fb.group({
|
this.productForm = this.fb.group({
|
||||||
name: ['', Validators.required], slug: ['', Validators.required], sku: ['', Validators.required],
|
id: ['', Validators.required],
|
||||||
description: [''], price: [0, [Validators.required, Validators.min(0)]],
|
name: ['', Validators.required],
|
||||||
oldPrice: [null, [Validators.min(0)]], purchasePrice: [null, [Validators.min(0)]],
|
slug: ['', Validators.required],
|
||||||
stockQuantity: [0, [Validators.required, Validators.min(0)]], weight: [null, [Validators.min(0)]],
|
sku: ['', Validators.required],
|
||||||
isActive: [true], isFeatured: [false], featuredDisplayOrder: [0],
|
price: [0, [Validators.required, Validators.min(0)]],
|
||||||
supplierId: [null], categorieIds: this.fb.array([]), imagesToDelete: this.fb.array([])
|
stockQuantity: [0, [Validators.required, Validators.min(0)]],
|
||||||
|
description: [''],
|
||||||
|
oldPrice: [null, [Validators.min(0)]],
|
||||||
|
purchasePrice: [null, [Validators.min(0)]],
|
||||||
|
weight: [null, [Validators.min(0)]],
|
||||||
|
isActive: [true],
|
||||||
|
isFeatured: [false],
|
||||||
|
featuredDisplayOrder: [0],
|
||||||
|
supplierId: [null],
|
||||||
|
categorieIds: new FormControl([]),
|
||||||
|
imagesToDelete: this.fb.array([]),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
get categorieIds(): FormArray { return this.productForm.get('categorieIds') as FormArray; }
|
get imagesToDelete(): FormArray {
|
||||||
get imagesToDelete(): FormArray { return this.productForm.get('imagesToDelete') as FormArray; }
|
return this.productForm.get('imagesToDelete') as FormArray;
|
||||||
|
}
|
||||||
|
|
||||||
ngOnInit(): void {
|
ngOnInit(): void {
|
||||||
this.productId = this.route.snapshot.paramMap.get('id');
|
const id = this.route.snapshot.paramMap.get('id');
|
||||||
this.isEditMode = !!this.productId;
|
if (!id) {
|
||||||
|
this.snackbarService.show('Produkt-ID fehlt.');
|
||||||
this.loadDropdownData();
|
this.router.navigate(['/shop/products']);
|
||||||
this.subscribeToNameChanges();
|
return;
|
||||||
|
|
||||||
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;
|
|
||||||
}
|
}
|
||||||
|
this.productId = id;
|
||||||
|
this.loadDropdownData();
|
||||||
|
this.loadProductData();
|
||||||
|
this.subscribeToNameChanges();
|
||||||
}
|
}
|
||||||
|
|
||||||
ngOnDestroy(): void {
|
ngOnDestroy(): void {
|
||||||
this.nameChangeSubscription?.unsubscribe();
|
this.nameChangeSubscription?.unsubscribe();
|
||||||
|
this.allImagesForForm.forEach((image) => {
|
||||||
|
if (typeof image.url === 'object') {
|
||||||
|
// Nur Object-URLs von neuen Bildern freigeben
|
||||||
|
URL.revokeObjectURL(image.url as string);
|
||||||
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
loadDropdownData(): void {
|
loadDropdownData(): void {
|
||||||
this.allCategories$ = this.categoryService.getAll().pipe(
|
this.allCategories$ = this.categoryService.getAll();
|
||||||
tap(categories => this.allCategories = categories)
|
|
||||||
);
|
|
||||||
this.supplierOptions$ = this.supplierService.getAll().pipe(
|
this.supplierOptions$ = this.supplierService.getAll().pipe(
|
||||||
map(suppliers => suppliers.map(s => ({ value: s.id, label: s.name || 'Unbenannt' }))),
|
map((suppliers) =>
|
||||||
|
suppliers.map((s) => ({ value: s.id, label: s.name || 'Unbenannt' }))
|
||||||
|
),
|
||||||
startWith([])
|
startWith([])
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
populateForm(product: AdminProduct): void {
|
loadProductData(): void {
|
||||||
this.productForm.patchValue(product);
|
this.isLoading = true;
|
||||||
this.categorieIds.clear();
|
this.productService
|
||||||
product.categorieIds?.forEach(id => this.categorieIds.push(this.fb.control(id)));
|
.getById(this.productId)
|
||||||
this.existingImages = product.images || [];
|
.pipe(
|
||||||
|
finalize(() => {
|
||||||
|
this.isLoading = false;
|
||||||
|
})
|
||||||
|
)
|
||||||
|
.subscribe({
|
||||||
|
next: (product) => {
|
||||||
|
if (product) {
|
||||||
|
this.populateForm(product);
|
||||||
|
} else {
|
||||||
|
this.snackbarService.show('Produkt nicht gefunden.');
|
||||||
|
this.router.navigate(['/shop/products']);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
error: (err) => {
|
||||||
|
this.snackbarService.show('Fehler beim Laden des Produkts.');
|
||||||
|
console.error('Fehler beim Laden der Produktdaten:', err);
|
||||||
|
this.router.navigate(['/shop/products']);
|
||||||
|
},
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
onMainFileChange(event: Event): void {
|
// AFTER (CORRECT)
|
||||||
const file = (event.target as HTMLInputElement).files?.[0];
|
populateForm(product: AdminProduct): void {
|
||||||
if (file) this.mainImageFile = file;
|
// This single line handles ALL form controls, including setting
|
||||||
}
|
// the 'categorieIds' FormControl to the array from the product object.
|
||||||
|
this.productForm.patchValue(product);
|
||||||
onAdditionalFilesChange(event: Event): void {
|
|
||||||
const files = (event.target as HTMLInputElement).files;
|
|
||||||
if (files) this.additionalImageFiles = Array.from(files);
|
|
||||||
}
|
|
||||||
|
|
||||||
deleteExistingImage(imageId: string, event: Event): void {
|
// The obsolete FormArray logic has been removed.
|
||||||
event.preventDefault();
|
|
||||||
this.imagesToDelete.push(this.fb.control(imageId));
|
|
||||||
this.existingImages = this.existingImages.filter(img => img.id !== imageId);
|
|
||||||
}
|
|
||||||
|
|
||||||
onCategoryChange(event: Event): void {
|
this.existingImages = product.images || [];
|
||||||
const checkbox = event.target as HTMLInputElement;
|
const mainImage = this.existingImages.find((img) => img.isMainImage);
|
||||||
const categoryId = checkbox.value;
|
this.mainImageIdentifier =
|
||||||
if (checkbox.checked) {
|
mainImage?.id ||
|
||||||
if (!this.categorieIds.value.includes(categoryId)) this.categorieIds.push(new FormControl(categoryId));
|
(this.existingImages.length > 0 ? this.existingImages[0].id : null);
|
||||||
} else {
|
|
||||||
const index = this.categorieIds.controls.findIndex(x => x.value === categoryId);
|
|
||||||
if (index !== -1) this.categorieIds.removeAt(index);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
isCategorySelected(categoryId: string): boolean {
|
this.rebuildAllImagesForForm();
|
||||||
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 {
|
onSubmit(): void {
|
||||||
if (this.productForm.invalid) {
|
if (this.productForm.invalid) {
|
||||||
@@ -169,60 +177,173 @@ export class ProductEditComponent implements OnInit, OnDestroy {
|
|||||||
this.snackbarService.show('Bitte füllen Sie alle Pflichtfelder aus.');
|
this.snackbarService.show('Bitte füllen Sie alle Pflichtfelder aus.');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
this.prepareSubmissionData();
|
||||||
const formData = new FormData();
|
const formData = this.createFormData();
|
||||||
const formValue = this.productForm.value;
|
this.productService.update(this.productId, formData).subscribe({
|
||||||
|
|
||||||
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: () => {
|
next: () => {
|
||||||
this.snackbarService.show(this.isEditMode ? 'Produkt aktualisiert' : 'Produkt erstellt');
|
this.snackbarService.show('Produkt erfolgreich aktualisiert');
|
||||||
this.router.navigate(['/admin/products']);
|
this.router.navigate(['/shop/products']);
|
||||||
},
|
},
|
||||||
error: (err: any) => {
|
error: (err) => {
|
||||||
this.snackbarService.show('Ein Fehler ist aufgetreten.');
|
this.snackbarService.show('Ein Fehler ist aufgetreten.');
|
||||||
console.error(err);
|
console.error(err);
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
cancel(): void {
|
cancel(): void {
|
||||||
this.router.navigate(['/admin/products']);
|
this.router.navigate(['/shop/products']);
|
||||||
}
|
}
|
||||||
|
|
||||||
private subscribeToNameChanges(): void {
|
// --- NEUE EVENT-HANDLER FÜR BILDER ---
|
||||||
this.nameChangeSubscription = this.productForm.get('name')?.valueChanges.pipe(debounceTime(300), distinctUntilChanged())
|
onFilesSelected(files: File[]): void {
|
||||||
.subscribe((name) => {
|
this.newImageFiles.push(...files);
|
||||||
if (name && !this.productForm.get('slug')?.dirty) {
|
if (!this.mainImageIdentifier && this.newImageFiles.length > 0) {
|
||||||
const slug = this.generateSlug(name);
|
this.mainImageIdentifier = this.newImageFiles[0].name;
|
||||||
this.productForm.get('slug')?.setValue(slug);
|
}
|
||||||
}
|
this.rebuildAllImagesForForm();
|
||||||
|
}
|
||||||
|
|
||||||
|
onSetMainImage(identifier: string): void {
|
||||||
|
this.mainImageIdentifier = identifier;
|
||||||
|
this.rebuildAllImagesForForm();
|
||||||
|
}
|
||||||
|
|
||||||
|
onDeleteImage(identifier: string): void {
|
||||||
|
const isExisting = this.existingImages.some((img) => img.id === identifier);
|
||||||
|
if (isExisting) {
|
||||||
|
this.imagesToDelete.push(new FormControl(identifier));
|
||||||
|
this.existingImages = this.existingImages.filter(
|
||||||
|
(img) => img.id !== identifier
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
this.newImageFiles = this.newImageFiles.filter(
|
||||||
|
(file) => file.name !== identifier
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.mainImageIdentifier === identifier) {
|
||||||
|
const firstExisting =
|
||||||
|
this.existingImages.length > 0 ? this.existingImages[0].id : null;
|
||||||
|
const firstNew =
|
||||||
|
this.newImageFiles.length > 0 ? this.newImageFiles[0].name : null;
|
||||||
|
this.mainImageIdentifier = firstExisting || firstNew;
|
||||||
|
}
|
||||||
|
this.rebuildAllImagesForForm();
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Private Helfermethoden ---
|
||||||
|
private rebuildAllImagesForForm(): void {
|
||||||
|
this.allImagesForForm.forEach((image) => {
|
||||||
|
if (typeof image.url === 'object')
|
||||||
|
URL.revokeObjectURL(image.url as string);
|
||||||
|
});
|
||||||
|
|
||||||
|
const combined: ImagePreview[] = [];
|
||||||
|
this.existingImages
|
||||||
|
.filter((img) => !!img.url) // Stellt sicher, dass nur Bilder mit URL verwendet werden
|
||||||
|
.forEach((img) => {
|
||||||
|
combined.push({
|
||||||
|
identifier: img.id,
|
||||||
|
url: img.url!,
|
||||||
|
isMainImage: img.id === this.mainImageIdentifier,
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
this.newImageFiles.forEach((file) => {
|
||||||
|
combined.push({
|
||||||
|
identifier: file.name,
|
||||||
|
url: this.sanitizer.bypassSecurityTrustUrl(URL.createObjectURL(file)),
|
||||||
|
isMainImage: file.name === this.mainImageIdentifier,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
this.allImagesForForm = combined;
|
||||||
|
}
|
||||||
|
|
||||||
|
private createFormData(): FormData {
|
||||||
|
const formData = new FormData();
|
||||||
|
const formValue = this.productForm.getRawValue();
|
||||||
|
|
||||||
|
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 !== '') {
|
||||||
|
formData.append(this.capitalizeFirstLetter(key), value.toString());
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const mainImageFile = this.newImageFiles.find(
|
||||||
|
(f) => f.name === this.mainImageIdentifier
|
||||||
|
);
|
||||||
|
if (mainImageFile) {
|
||||||
|
formData.append('MainImageFile', mainImageFile);
|
||||||
|
} else if (this.mainImageIdentifier) {
|
||||||
|
formData.append('MainImageId', this.mainImageIdentifier);
|
||||||
|
}
|
||||||
|
|
||||||
|
this.newImageFiles
|
||||||
|
.filter((f) => f.name !== this.mainImageIdentifier)
|
||||||
|
.forEach((file) => formData.append('AdditionalImageFiles', file));
|
||||||
|
|
||||||
|
return formData;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Private Helfermethoden
|
||||||
|
private prepareSubmissionData(): void {
|
||||||
|
const nameControl = this.productForm.get('name');
|
||||||
|
const slugControl = this.productForm.get('slug');
|
||||||
|
const skuControl = this.productForm.get('sku');
|
||||||
|
|
||||||
|
if (nameControl && slugControl && !slugControl.value) {
|
||||||
|
slugControl.setValue(this.generateSlug(nameControl.value), {
|
||||||
|
emitEvent: false,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (nameControl && skuControl && !skuControl.value) {
|
||||||
|
skuControl.setValue(this.generateSkuValue(nameControl.value), {
|
||||||
|
emitEvent: false,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private subscribeToNameChanges(): void {
|
||||||
|
const nameControl = this.productForm.get('name');
|
||||||
|
const slugControl = this.productForm.get('slug');
|
||||||
|
|
||||||
|
if (nameControl && slugControl) {
|
||||||
|
this.nameChangeSubscription = nameControl.valueChanges
|
||||||
|
.pipe(debounceTime(400), distinctUntilChanged())
|
||||||
|
.subscribe((name) => {
|
||||||
|
if (name && !slugControl.dirty) {
|
||||||
|
slugControl.setValue(this.generateSlug(name));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private generateSlug(name: string): string {
|
private generateSlug(name: string): string {
|
||||||
return name.toLowerCase().replace(/\s+/g, '-').replace(/[äöüß]/g, (char) => {
|
return name
|
||||||
switch (char) { case 'ä': return 'ae'; case 'ö': return 'oe'; case 'ü': return 'ue'; case 'ß': return 'ss'; default: return ''; }
|
.toLowerCase()
|
||||||
}).replace(/[^a-z0-9-]/g, '').replace(/-+/g, '-');
|
.replace(/\s+/g, '-')
|
||||||
|
.replace(
|
||||||
|
/[äöüß]/g,
|
||||||
|
(char) => ({ ä: 'ae', ö: 'oe', ü: 'ue', ß: 'ss' }[char] || '')
|
||||||
|
)
|
||||||
|
.replace(/[^a-z0-9-]/g, '')
|
||||||
|
.replace(/-+/g, '-');
|
||||||
|
}
|
||||||
|
|
||||||
|
private generateSkuValue(name: string): string {
|
||||||
|
const prefix = name.substring(0, 4).toUpperCase().replace(/\s+/g, '');
|
||||||
|
const randomPart = Math.random().toString(36).substring(2, 8).toUpperCase();
|
||||||
|
return `${prefix}-${randomPart}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
private capitalizeFirstLetter(string: string): string {
|
private capitalizeFirstLetter(string: string): string {
|
||||||
return string.charAt(0).toUpperCase() + string.slice(1);
|
return string.charAt(0).toUpperCase() + string.slice(1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,115 @@
|
|||||||
|
/* /src/app/features/admin/components/products/product-form/product-form.component.css */
|
||||||
|
|
||||||
|
:host {
|
||||||
|
--form-spacing-vertical: 1.5rem;
|
||||||
|
--form-spacing-horizontal: 1.5rem;
|
||||||
|
--grid-gap: 1.5rem;
|
||||||
|
--border-radius: 8px;
|
||||||
|
--text-color-secondary: #64748b;
|
||||||
|
--background-color-light: #f8fafc;
|
||||||
|
}
|
||||||
|
|
||||||
|
.edit-layout { display: grid; grid-template-columns: 2fr 1fr; gap: var(--grid-gap); }
|
||||||
|
.main-content, .sidebar-content { display: flex; flex-direction: column; gap: var(--grid-gap); }
|
||||||
|
app-card { display: block; width: 100%; }
|
||||||
|
.form-section { padding: var(--form-spacing-horizontal); display: flex; flex-direction: column; gap: var(--form-spacing-vertical); }
|
||||||
|
h4[card-header] { margin-bottom: 0; }
|
||||||
|
.form-field { display: flex; flex-direction: column; gap: 0.5rem; }
|
||||||
|
.form-label { font-weight: 500; color: #334155; }
|
||||||
|
.required-indicator { color: var(--color-danger); margin-left: 4px; }
|
||||||
|
.form-hint { font-size: 0.875rem; color: var(--text-color-secondary); margin-top: -0.75rem; }
|
||||||
|
.input-with-button { display: flex; flex-direction: row; gap: 0.5rem; }
|
||||||
|
.sku-input {width: 100%;}
|
||||||
|
.input-with-button .form-input { flex-grow: 1; }
|
||||||
|
.price-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(120px, 1fr)); gap: var(--grid-gap); }
|
||||||
|
|
||||||
|
/* ==========================================================================
|
||||||
|
BILDER-MANAGEMENT STYLING (FINAL & KORRIGIERT)
|
||||||
|
========================================================================== */
|
||||||
|
.image-upload-section {
|
||||||
|
border-bottom: 1px solid var(--color-border);
|
||||||
|
padding-bottom: 1.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.gallery-title { font-size: 1rem; font-weight: 600; color: var(--text-color-secondary); margin-bottom: 0.25rem; }
|
||||||
|
|
||||||
|
.image-gallery-grid {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
|
||||||
|
gap: 1.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.image-preview-container {
|
||||||
|
position: relative; /* Wichtig für die Positionierung des Buttons */
|
||||||
|
width: 100px;
|
||||||
|
height: 100px;
|
||||||
|
border-radius: var(--border-radius-md);
|
||||||
|
overflow: visible; /* Erlaubt dem Button, leicht überzulappen */
|
||||||
|
border: 3px solid transparent;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: border-color 0.2s ease-in-out, transform 0.2s ease-in-out;
|
||||||
|
}
|
||||||
|
|
||||||
|
.image-preview-container:hover {
|
||||||
|
transform: scale(1.05);
|
||||||
|
}
|
||||||
|
|
||||||
|
.image-preview-container.is-main {
|
||||||
|
border-color: var(--color-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.image-preview {
|
||||||
|
width: 100%;
|
||||||
|
height: 100%;
|
||||||
|
object-fit: cover;
|
||||||
|
border-radius: var(--border-radius); /* Abgerundete Ecken für das Bild selbst */
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Styling für den Löschen-Button als Overlay */
|
||||||
|
.delete-overlay-button {
|
||||||
|
position: absolute;
|
||||||
|
top: -8px;
|
||||||
|
right: -8px;
|
||||||
|
z-index: 10;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
width: 26px;
|
||||||
|
height: 26px;
|
||||||
|
background-color: var(--color-danger);
|
||||||
|
color: white;
|
||||||
|
border: 2px solid var(--color-body-bg-lighter, white);
|
||||||
|
border-radius: 50%;
|
||||||
|
padding: 0;
|
||||||
|
cursor: pointer;
|
||||||
|
opacity: 0;
|
||||||
|
transform: scale(0.8);
|
||||||
|
transition: opacity 0.2s ease-in-out, transform 0.2s ease-in-out;
|
||||||
|
}
|
||||||
|
|
||||||
|
.image-preview-container:hover .delete-overlay-button {
|
||||||
|
opacity: 1;
|
||||||
|
transform: scale(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
.delete-overlay-button app-icon {
|
||||||
|
width: 16px;
|
||||||
|
height: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ==========================================================================
|
||||||
|
Kategorien- & Formular-Aktionen
|
||||||
|
========================================================================== */
|
||||||
|
.multi-select-container { border: 1px solid var(--color-border); border-radius: var(--border-radius); }
|
||||||
|
.selected-pills { display: flex; flex-wrap: wrap; gap: 0.5rem; padding: 0.75rem; border-bottom: 1px solid var(--color-border); }
|
||||||
|
.pill { display: flex; align-items: center; gap: 0.5rem; background-color: var(--background-color-light); border: 1px solid var(--color-border); padding: 0.25rem 0.75rem; border-radius: 16px; font-size: 0.875rem; }
|
||||||
|
.pill app-icon { cursor: pointer; width: 16px; height: 16px; }
|
||||||
|
.pill app-icon:hover { color: var(--color-danger); }
|
||||||
|
.placeholder { color: var(--text-color-secondary); }
|
||||||
|
.category-checkbox-group { max-height: 200px; overflow-y: auto; padding: 0.75rem; }
|
||||||
|
.category-checkbox-group label { display: flex; align-items: center; gap: 0.75rem; padding: 0.5rem 0; }
|
||||||
|
.form-actions { display: flex; justify-content: flex-end; gap: 1rem; margin-top: var(--grid-gap); padding-top: var(--grid-gap); border-top: none; }
|
||||||
|
|
||||||
|
@media (max-width: 1024px) {
|
||||||
|
.edit-layout { grid-template-columns: 1fr; }
|
||||||
|
}
|
||||||
@@ -0,0 +1,113 @@
|
|||||||
|
<!-- /src/app/features/admin/components/products/product-form/product-form.component.html -->
|
||||||
|
|
||||||
|
<form [formGroup]="productForm" (ngSubmit)="onSubmit()" novalidate>
|
||||||
|
<div class="edit-layout">
|
||||||
|
<div class="main-content">
|
||||||
|
<!-- Card: Allgemeine Produktinformationen -->
|
||||||
|
|
||||||
|
<app-form-group title="Allgemein" description="Hier kannst du Allgemeine PRodukt Informationen ändern....">
|
||||||
|
|
||||||
|
<app-form-field label="Name" type="text" formControlName="name" [control]="productForm.get('name')"></app-form-field>
|
||||||
|
<app-form-field label="Slug" type="text" formControlName="slug" [control]="productForm.get('slug')"></app-form-field>
|
||||||
|
<app-form-textarea label="Beschreibung" [rows]="8" formControlName="description" [control]="productForm.get('description')"></app-form-textarea>
|
||||||
|
|
||||||
|
</app-form-group>
|
||||||
|
|
||||||
|
|
||||||
|
<!-- Card: Bild-Management (Komplett überarbeitet) -->
|
||||||
|
<app-form-group title="Bild-Management" description="Wählen Sie Bilder für Ihr Produkt aus. Klicken Sie auf ein Bild um es es Hauptbild zu nutzen.">
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<input id="file-upload" type="file" accept="image/*" multiple (change)="onFilesSelected($event)" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
|
||||||
|
<div *ngIf="hasImages">
|
||||||
|
|
||||||
|
<div class="image-gallery-grid">
|
||||||
|
<!-- Einheitliche Schleife mit neuem Löschen-Button -->
|
||||||
|
<div
|
||||||
|
*ngFor="let image of allImages"
|
||||||
|
class="image-preview-container"
|
||||||
|
(click)="setAsMainImage(image.identifier)"
|
||||||
|
[ngClass]="{ 'is-main': image.isMainImage }">
|
||||||
|
|
||||||
|
<img [src]="image.url" [alt]="'Bildvorschau'" class="image-preview" />
|
||||||
|
|
||||||
|
<!-- Löschen-Button als Overlay für JEDES Bild -->
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="delete-overlay-button"
|
||||||
|
(click)="requestImageDeletion(image.identifier, $event)"
|
||||||
|
aria-label="Bild entfernen">
|
||||||
|
<app-icon iconName="x"></app-icon>
|
||||||
|
</button>
|
||||||
|
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<p class="gallery-hint">Klicken Sie auf ein Bild, um es als Hauptbild festzulegen.</p>
|
||||||
|
</div>
|
||||||
|
</app-form-group>
|
||||||
|
|
||||||
|
<!-- Card: Preisgestaltung -->
|
||||||
|
<app-form-group title="Preisgestaltung" description="Produktpreise und Einkaufspreise festlegen.">
|
||||||
|
|
||||||
|
<div class="form-grid price-grid">
|
||||||
|
<app-form-field label="Preis (€)" type="number" formControlName="price" [control]="productForm.get('price')"></app-form-field>
|
||||||
|
<app-form-field label="Alter Preis (€)" type="number" formControlName="oldPrice" [control]="productForm.get('oldPrice')"></app-form-field>
|
||||||
|
<app-form-field label="Einkaufspreis (€)" type="number" formControlName="purchasePrice" [control]="productForm.get('purchasePrice')"></app-form-field>
|
||||||
|
</div>
|
||||||
|
</app-form-group>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- RECHTE SPALTE -->
|
||||||
|
<div class="sidebar-content">
|
||||||
|
<app-form-group title="Status" description="Ein Deaktiviertes Produkt ist im Shop nicht sichtbar. Hervorgehobene Produkte werden bevorzugt angezeigt.">
|
||||||
|
|
||||||
|
|
||||||
|
<app-slide-toggle label="Aktiv (im Shop sichtbar)" labelPosition="right" formControlName="isActive"></app-slide-toggle>
|
||||||
|
|
||||||
|
|
||||||
|
<app-slide-toggle label="Hervorheben" labelPosition="right" formControlName="isFeatured"></app-slide-toggle>
|
||||||
|
<app-form-field *ngIf="productForm.get('isFeatured')?.value" label="Priorität" type="number" formControlName="featuredDisplayOrder" [control]="productForm.get('featuredDisplayOrder')"></app-form-field>
|
||||||
|
|
||||||
|
|
||||||
|
</app-form-group>
|
||||||
|
|
||||||
|
<app-form-group title="Organisation" description="">
|
||||||
|
|
||||||
|
|
||||||
|
<div class="input-with-button">
|
||||||
|
<app-form-field class="sku-input" label="SKU (Artikelnummer)" type="text" formControlName="sku" [control]="productForm.get('sku')"></app-form-field>
|
||||||
|
<app-button buttonType="icon" (click)="generateSku()" iconName="placeholder"></app-button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<app-form-field label="Lagerbestand" type="number" formControlName="stockQuantity" [control]="productForm.get('stockQuantity')"></app-form-field>
|
||||||
|
<app-form-field label="Gewicht (kg)" type="number" formControlName="weight" [control]="productForm.get('weight')"></app-form-field>
|
||||||
|
<app-form-select label="Lieferant" [options]="supplierOptions" formControlName="supplierId" [control]="productForm.get('supplierId')"></app-form-select>
|
||||||
|
|
||||||
|
|
||||||
|
<app-product-category-dropdown
|
||||||
|
label="Kategorien"
|
||||||
|
|
||||||
|
[options]="categoryOptions"
|
||||||
|
formControlName="categorieIds"
|
||||||
|
>
|
||||||
|
|
||||||
|
|
||||||
|
</app-product-category-dropdown>
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
</app-form-group>
|
||||||
|
|
||||||
|
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- FORMULAR-AKTIONEN -->
|
||||||
|
<div class="form-actions">
|
||||||
|
<app-button buttonType="stroked" (click)="cancel()">Abbrechen</app-button>
|
||||||
|
<app-button submitType="submit" buttonType="primary" [disabled]="!productForm.valid || isLoading">{{ submitButtonText }}</app-button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
@@ -0,0 +1,107 @@
|
|||||||
|
// /src/app/features/admin/components/products/product-form/product-form.component.ts (CORRECTED)
|
||||||
|
|
||||||
|
import { Component, Input, Output, EventEmitter, inject, SimpleChanges } from '@angular/core';
|
||||||
|
import { CommonModule, NgClass } from '@angular/common';
|
||||||
|
import { FormGroup, ReactiveFormsModule } from '@angular/forms'; // FormArray and FormControl no longer needed here
|
||||||
|
import { SafeUrl } from '@angular/platform-browser';
|
||||||
|
|
||||||
|
// Models & UI Components
|
||||||
|
import { Category } from '../../../../core/models/category.model';
|
||||||
|
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';
|
||||||
|
import { SnackbarService } from '../../../../shared/services/snackbar.service';
|
||||||
|
import { FormGroupComponent } from '../../../../shared/components/form/form-group/form-group.component';
|
||||||
|
import { ProductCategoryDropdownComponent } from '../product-category-dropdown/product-category-dropdown.component';
|
||||||
|
|
||||||
|
export interface ImagePreview {
|
||||||
|
identifier: string;
|
||||||
|
url: string | SafeUrl;
|
||||||
|
isMainImage: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Component({
|
||||||
|
selector: 'app-product-form',
|
||||||
|
standalone: true,
|
||||||
|
imports: [
|
||||||
|
CommonModule, NgClass, ReactiveFormsModule, ButtonComponent, IconComponent,
|
||||||
|
FormFieldComponent, FormSelectComponent, FormTextareaComponent,
|
||||||
|
SlideToggleComponent, FormGroupComponent, ProductCategoryDropdownComponent
|
||||||
|
],
|
||||||
|
templateUrl: './product-form.component.html',
|
||||||
|
styleUrls: ['./product-form.component.css'],
|
||||||
|
})
|
||||||
|
export class ProductFormComponent {
|
||||||
|
// --- Inputs ---
|
||||||
|
@Input() productForm!: FormGroup;
|
||||||
|
@Input() allCategories: Category[] = [];
|
||||||
|
@Input() supplierOptions: SelectOption[] = [];
|
||||||
|
@Input() isLoading = false;
|
||||||
|
@Input() submitButtonText = 'Speichern';
|
||||||
|
@Input() allImages: ImagePreview[] = [];
|
||||||
|
|
||||||
|
// --- Outputs ---
|
||||||
|
@Output() formSubmit = new EventEmitter<void>();
|
||||||
|
@Output() formCancel = new EventEmitter<void>();
|
||||||
|
@Output() filesSelected = new EventEmitter<File[]>();
|
||||||
|
@Output() setMainImage = new EventEmitter<string>();
|
||||||
|
@Output() deleteImage = new EventEmitter<string>();
|
||||||
|
|
||||||
|
private snackbarService = inject(SnackbarService);
|
||||||
|
public categoryOptions: SelectOption[] = [];
|
||||||
|
|
||||||
|
// --- GETTER ---
|
||||||
|
get hasImages(): boolean {
|
||||||
|
return this.allImages && this.allImages.length > 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- LIFECYCLE HOOKS ---
|
||||||
|
ngOnChanges(changes: SimpleChanges): void {
|
||||||
|
if (changes['allCategories']) {
|
||||||
|
this.categoryOptions = this.allCategories
|
||||||
|
.filter(cat => !!cat.name)
|
||||||
|
.map(cat => ({
|
||||||
|
value: cat.id,
|
||||||
|
label: cat.name!
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- EVENT-HANDLERS ---
|
||||||
|
onSubmit(): void { this.formSubmit.emit(); }
|
||||||
|
cancel(): void { this.formCancel.emit(); }
|
||||||
|
|
||||||
|
onFilesSelected(event: Event): void {
|
||||||
|
const files = (event.target as HTMLInputElement).files;
|
||||||
|
if (files && files.length > 0) {
|
||||||
|
this.filesSelected.emit(Array.from(files));
|
||||||
|
}
|
||||||
|
(event.target as HTMLInputElement).value = '';
|
||||||
|
}
|
||||||
|
|
||||||
|
setAsMainImage(identifier: string): void {
|
||||||
|
this.setMainImage.emit(identifier);
|
||||||
|
}
|
||||||
|
|
||||||
|
requestImageDeletion(identifier: string, event: MouseEvent): void {
|
||||||
|
event.stopPropagation();
|
||||||
|
this.deleteImage.emit(identifier);
|
||||||
|
}
|
||||||
|
|
||||||
|
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!');
|
||||||
|
}
|
||||||
|
|
||||||
|
// ALL OBSOLETE CATEGORY HELPER FUNCTIONS HAVE BEEN REMOVED
|
||||||
|
}
|
||||||
@@ -3,18 +3,12 @@
|
|||||||
import { Component, OnInit, inject } from '@angular/core';
|
import { Component, OnInit, inject } from '@angular/core';
|
||||||
import { Router } from '@angular/router';
|
import { Router } from '@angular/router';
|
||||||
import { CommonModule, CurrencyPipe, DatePipe } from '@angular/common';
|
import { CommonModule, CurrencyPipe, DatePipe } from '@angular/common';
|
||||||
import {
|
import { AdminProduct, ProductImage } from '../../../../core/models/product.model';
|
||||||
AdminProduct,
|
|
||||||
ProductImage,
|
|
||||||
} from '../../../../core/models/product.model';
|
|
||||||
import { ProductService } from '../../../services/product.service';
|
import { ProductService } from '../../../services/product.service';
|
||||||
import { SupplierService } from '../../../services/supplier.service';
|
import { SupplierService } from '../../../services/supplier.service';
|
||||||
import { SnackbarService } from '../../../../shared/services/snackbar.service';
|
import { SnackbarService } from '../../../../shared/services/snackbar.service';
|
||||||
import { StorageService } from '../../../../core/services/storage.service';
|
import { StorageService } from '../../../../core/services/storage.service';
|
||||||
import {
|
import { GenericTableComponent, ColumnConfig } from '../../../../shared/components/data-display/generic-table/generic-table.component';
|
||||||
GenericTableComponent,
|
|
||||||
ColumnConfig,
|
|
||||||
} from '../../../../shared/components/data-display/generic-table/generic-table.component';
|
|
||||||
import { SearchBarComponent } from '../../../../shared/components/layout/search-bar/search-bar.component';
|
import { SearchBarComponent } from '../../../../shared/components/layout/search-bar/search-bar.component';
|
||||||
import { ButtonComponent } from '../../../../shared/components/ui/button/button.component';
|
import { ButtonComponent } from '../../../../shared/components/ui/button/button.component';
|
||||||
import { IconComponent } from '../../../../shared/components/ui/icon/icon.component';
|
import { IconComponent } from '../../../../shared/components/ui/icon/icon.component';
|
||||||
@@ -22,18 +16,10 @@ import { IconComponent } from '../../../../shared/components/ui/icon/icon.compon
|
|||||||
@Component({
|
@Component({
|
||||||
selector: 'app-product-list',
|
selector: 'app-product-list',
|
||||||
standalone: true,
|
standalone: true,
|
||||||
imports: [
|
imports: [CommonModule, CurrencyPipe, GenericTableComponent, SearchBarComponent, ButtonComponent, IconComponent],
|
||||||
CommonModule,
|
|
||||||
CurrencyPipe,
|
|
||||||
DatePipe,
|
|
||||||
GenericTableComponent,
|
|
||||||
SearchBarComponent,
|
|
||||||
ButtonComponent,
|
|
||||||
IconComponent,
|
|
||||||
],
|
|
||||||
providers: [DatePipe],
|
providers: [DatePipe],
|
||||||
templateUrl: './product-list.component.html',
|
templateUrl: './product-list.component.html',
|
||||||
styleUrl: './product-list.component.css',
|
styleUrl: './product-list.component.css'
|
||||||
})
|
})
|
||||||
export class ProductListComponent implements OnInit {
|
export class ProductListComponent implements OnInit {
|
||||||
private productService = inject(ProductService);
|
private productService = inject(ProductService);
|
||||||
@@ -42,66 +28,35 @@ export class ProductListComponent implements OnInit {
|
|||||||
private snackbar = inject(SnackbarService);
|
private snackbar = inject(SnackbarService);
|
||||||
private storageService = inject(StorageService);
|
private storageService = inject(StorageService);
|
||||||
private datePipe = inject(DatePipe);
|
private datePipe = inject(DatePipe);
|
||||||
|
|
||||||
private readonly TABLE_SETTINGS_KEY = 'product-table-columns';
|
private readonly TABLE_SETTINGS_KEY = 'product-table-columns';
|
||||||
|
|
||||||
allProducts: (AdminProduct & {
|
allProducts: (AdminProduct & { mainImage?: string; supplierName?: string })[] = [];
|
||||||
mainImage?: string;
|
filteredProducts: (AdminProduct & { mainImage?: string; supplierName?: string })[] = [];
|
||||||
supplierName?: string;
|
|
||||||
})[] = [];
|
|
||||||
filteredProducts: (AdminProduct & {
|
|
||||||
mainImage?: string;
|
|
||||||
supplierName?: string;
|
|
||||||
})[] = [];
|
|
||||||
isColumnFilterVisible = false;
|
isColumnFilterVisible = false;
|
||||||
|
|
||||||
readonly allTableColumns: ColumnConfig[] = [
|
readonly allTableColumns: ColumnConfig[] = [
|
||||||
{ key: 'mainImage', title: 'Bild', type: 'image' },
|
{ key: 'mainImage', title: 'Bild', type: 'image' },
|
||||||
{ key: 'name', title: 'Name', type: 'text', subKey: 'sku' },
|
{ key: 'name', title: 'Name', type: 'text', subKey: 'sku' },
|
||||||
{ key: 'price', title: 'Preis', type: 'currency', cssClass: 'text-right' },
|
{ key: 'price', title: 'Preis', type: 'currency', cssClass: 'text-right' },
|
||||||
{
|
{ key: 'stockQuantity', title: 'Lager', type: 'text', cssClass: 'text-right' },
|
||||||
key: 'stockQuantity',
|
|
||||||
title: 'Lager',
|
|
||||||
type: 'text',
|
|
||||||
cssClass: 'text-right',
|
|
||||||
},
|
|
||||||
{ key: 'supplierName', title: 'Lieferant', type: 'text' },
|
{ key: 'supplierName', title: 'Lieferant', type: 'text' },
|
||||||
{ key: 'isActive', title: 'Aktiv', type: 'status' },
|
{ key: 'isActive', title: 'Aktiv', type: 'status' },
|
||||||
{ key: 'id', title: 'ID', type: 'text' },
|
{ key: 'id', title: 'ID', type: 'text' },
|
||||||
{ key: 'description', title: 'Beschreibung', type: 'text' },
|
{ key: 'description', title: 'Beschreibung', type: 'text' },
|
||||||
{
|
{ key: 'oldPrice', title: 'Alter Preis', type: 'currency', cssClass: 'text-right' },
|
||||||
key: 'oldPrice',
|
{ key: 'purchasePrice', title: 'Einkaufspreis', type: 'currency', cssClass: 'text-right' },
|
||||||
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: 'isInStock', title: 'Auf Lager', type: 'status' },
|
||||||
{ key: 'weight', title: 'Gewicht', type: 'number', cssClass: 'text-right' },
|
{ key: 'weight', title: 'Gewicht', type: 'text', cssClass: 'text-right' },
|
||||||
{ key: 'slug', title: 'Slug', type: 'text' },
|
{ key: 'slug', title: 'Slug', type: 'text' },
|
||||||
{ key: 'createdDate', title: 'Erstellt am', type: 'date' },
|
{ key: 'createdDate', title: 'Erstellt am', type: 'text' },
|
||||||
{ key: 'lastModifiedDate', title: 'Zuletzt geändert', type: 'date' },
|
{ key: 'lastModifiedDate', title: 'Zuletzt geändert', type: 'text' },
|
||||||
{ key: 'supplierId', title: 'Lieferanten-ID', type: 'text' },
|
{ key: 'supplierId', title: 'Lieferanten-ID', type: 'text' },
|
||||||
{ key: 'categorieIds', title: 'Kategorie-IDs', type: 'text' },
|
{ key: 'categorieIds', title: 'Kategorie-IDs', type: 'text' },
|
||||||
{ key: 'isFeatured', title: 'Hervorgehoben', type: 'status' },
|
{ key: 'isFeatured', title: 'Hervorgehoben', type: 'status' },
|
||||||
{
|
{ key: 'featuredDisplayOrder', title: 'Anzeigereihenfolge (hervorgehoben)', type: 'number', cssClass: 'text-right' },
|
||||||
key: 'featuredDisplayOrder',
|
{ key: 'actions', title: 'Aktionen', type: 'actions', cssClass: 'text-right' }
|
||||||
title: 'Anzeigereihenfolge (hervorgehoben)',
|
];
|
||||||
type: 'number',
|
|
||||||
cssClass: 'text-right',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
key: 'actions',
|
|
||||||
title: 'Aktionen',
|
|
||||||
type: 'actions',
|
|
||||||
cssClass: 'text-right',
|
|
||||||
},
|
|
||||||
];
|
|
||||||
visibleTableColumns: ColumnConfig[] = [];
|
visibleTableColumns: ColumnConfig[] = [];
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
@@ -113,16 +68,15 @@ export class ProductListComponent implements OnInit {
|
|||||||
}
|
}
|
||||||
|
|
||||||
loadProducts(): void {
|
loadProducts(): void {
|
||||||
this.productService.getAll().subscribe((products) => {
|
this.productService.getAll().subscribe(products => {
|
||||||
this.supplierService.getAll().subscribe((suppliers) => {
|
this.supplierService.getAll().subscribe(suppliers => {
|
||||||
this.allProducts = products.map((p) => {
|
this.allProducts = products.map(p => {
|
||||||
const supplier = suppliers.find((s) => s.id === p.supplierId);
|
const supplier = suppliers.find(s => s.id === p.supplierId);
|
||||||
return {
|
return {
|
||||||
...p,
|
...p,
|
||||||
mainImage: this.getMainImageUrl(p.images),
|
mainImage: this.getMainImageUrl(p.images),
|
||||||
supplierName: supplier?.name || '-',
|
supplierName: supplier?.name || '-',
|
||||||
createdDate:
|
createdDate: this.datePipe.transform(p.createdDate, 'dd.MM.yyyy HH:mm') || '-',
|
||||||
this.datePipe.transform(p.createdDate, 'dd.MM.yyyy HH:mm') || '-',
|
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
this.onSearch('');
|
this.onSearch('');
|
||||||
@@ -132,19 +86,18 @@ export class ProductListComponent implements OnInit {
|
|||||||
|
|
||||||
onSearch(term: string): void {
|
onSearch(term: string): void {
|
||||||
const lowerTerm = term.toLowerCase();
|
const lowerTerm = term.toLowerCase();
|
||||||
this.filteredProducts = this.allProducts.filter(
|
this.filteredProducts = this.allProducts.filter(p =>
|
||||||
(p) =>
|
p.name?.toLowerCase().includes(lowerTerm) ||
|
||||||
p.name?.toLowerCase().includes(lowerTerm) ||
|
p.sku?.toLowerCase().includes(lowerTerm)
|
||||||
p.sku?.toLowerCase().includes(lowerTerm)
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
onAddNew(): void {
|
onAddNew(): void {
|
||||||
this.router.navigate(['/shop/products/new']);
|
this.router.navigate(['/shop/products/create']);
|
||||||
}
|
}
|
||||||
|
|
||||||
onEditProduct(productId: string): void {
|
onEditProduct(productId: string): void {
|
||||||
this.router.navigate(['/shop/products', productId]);
|
this.router.navigate(['/shop/products/edit', productId]);
|
||||||
}
|
}
|
||||||
|
|
||||||
onDeleteProduct(productId: string): void {
|
onDeleteProduct(productId: string): void {
|
||||||
@@ -157,26 +110,14 @@ export class ProductListComponent implements OnInit {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private loadTableSettings(): void {
|
private loadTableSettings(): void {
|
||||||
const savedKeys = this.storageService.getItem<string[]>(
|
const savedKeys = this.storageService.getItem<string[]>(this.TABLE_SETTINGS_KEY);
|
||||||
this.TABLE_SETTINGS_KEY
|
const defaultKeys = ['mainImage', 'name', 'price', 'stockQuantity', 'isActive', 'actions'];
|
||||||
);
|
const keysToUse = (savedKeys && savedKeys.length > 0) ? savedKeys : defaultKeys;
|
||||||
const defaultKeys = [
|
this.visibleTableColumns = this.allTableColumns.filter(c => keysToUse.includes(c.key));
|
||||||
'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 {
|
private saveTableSettings(): void {
|
||||||
const visibleKeys = this.visibleTableColumns.map((c) => c.key);
|
const visibleKeys = this.visibleTableColumns.map(c => c.key);
|
||||||
this.storageService.setItem(this.TABLE_SETTINGS_KEY, visibleKeys);
|
this.storageService.setItem(this.TABLE_SETTINGS_KEY, visibleKeys);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -185,29 +126,26 @@ export class ProductListComponent implements OnInit {
|
|||||||
}
|
}
|
||||||
|
|
||||||
isColumnVisible(columnKey: string): boolean {
|
isColumnVisible(columnKey: string): boolean {
|
||||||
return this.visibleTableColumns.some((c) => c.key === columnKey);
|
return this.visibleTableColumns.some(c => c.key === columnKey);
|
||||||
}
|
}
|
||||||
|
|
||||||
onColumnToggle(column: ColumnConfig, event: Event): void {
|
onColumnToggle(column: ColumnConfig, event: Event): void {
|
||||||
const checkbox = event.target as HTMLInputElement;
|
const checkbox = event.target as HTMLInputElement;
|
||||||
if (checkbox.checked) {
|
if (checkbox.checked) {
|
||||||
this.visibleTableColumns.push(column);
|
this.visibleTableColumns.push(column);
|
||||||
this.visibleTableColumns.sort(
|
this.visibleTableColumns.sort((a, b) =>
|
||||||
(a, b) =>
|
this.allTableColumns.findIndex(c => c.key === a.key) -
|
||||||
this.allTableColumns.findIndex((c) => c.key === a.key) -
|
this.allTableColumns.findIndex(c => c.key === b.key)
|
||||||
this.allTableColumns.findIndex((c) => c.key === b.key)
|
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
this.visibleTableColumns = this.visibleTableColumns.filter(
|
this.visibleTableColumns = this.visibleTableColumns.filter(c => c.key !== column.key);
|
||||||
(c) => c.key !== column.key
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
this.saveTableSettings();
|
this.saveTableSettings();
|
||||||
}
|
}
|
||||||
|
|
||||||
getMainImageUrl(images?: ProductImage[]): string {
|
getMainImageUrl(images?: ProductImage[]): string {
|
||||||
if (!images || images.length === 0) return 'https://via.placeholder.com/50';
|
if (!images || images.length === 0) return 'https://via.placeholder.com/50';
|
||||||
const mainImage = images.find((img) => img.isMainImage);
|
const mainImage = images.find(img => img.isMainImage);
|
||||||
return mainImage?.url || images[0]?.url || 'https://via.placeholder.com/50';
|
return mainImage?.url || images[0]?.url || 'https://via.placeholder.com/50';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1 +0,0 @@
|
|||||||
<p>product-new works!</p>
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
import { Component } from '@angular/core';
|
|
||||||
|
|
||||||
@Component({
|
|
||||||
selector: 'app-product-new',
|
|
||||||
imports: [],
|
|
||||||
templateUrl: './product-new.component.html',
|
|
||||||
styleUrl: './product-new.component.css'
|
|
||||||
})
|
|
||||||
export class ProductNewComponent {
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -3,21 +3,22 @@
|
|||||||
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';
|
import { ProductEditComponent } from './product-edit/product-edit.component';
|
||||||
|
import { ProductCreateComponent } from './product-create/product-create.component';
|
||||||
|
|
||||||
export const PRODUCTS_ROUTES: Routes = [
|
export const PRODUCTS_ROUTES: Routes = [
|
||||||
{
|
{
|
||||||
path: '',
|
path: '',
|
||||||
component: ProductListComponent,
|
component: ProductListComponent,
|
||||||
title: 'Produktübersicht'
|
title: 'Produktübersicht',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
path: 'new',
|
path: 'create',
|
||||||
component: ProductEditComponent,
|
component: ProductCreateComponent,
|
||||||
title: 'Neues Produkt erstellen'
|
title: 'Product | Create',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
path: ':id',
|
path: 'edit/:id',
|
||||||
component: ProductEditComponent,
|
component: ProductEditComponent,
|
||||||
title: 'Produkt bearbeiten'
|
title: 'Product | Edit',
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|||||||
@@ -23,7 +23,7 @@
|
|||||||
padding: 0.85rem 1rem;
|
padding: 0.85rem 1rem;
|
||||||
border: 1px solid var(--color-border);
|
border: 1px solid var(--color-border);
|
||||||
border-radius: var(--border-radius-md);
|
border-radius: var(--border-radius-md);
|
||||||
|
|
||||||
/* Aussehen & Typografie */
|
/* Aussehen & Typografie */
|
||||||
background-color: var(--color-surface);
|
background-color: var(--color-surface);
|
||||||
color: var(--color-text);
|
color: var(--color-text);
|
||||||
@@ -46,14 +46,18 @@
|
|||||||
position: absolute;
|
position: absolute;
|
||||||
top: 50%; /* Vertikal zentrieren (Schritt 1) */
|
top: 50%; /* Vertikal zentrieren (Schritt 1) */
|
||||||
left: 1rem; /* Linken Abstand wie beim Input-Padding halten */
|
left: 1rem; /* Linken Abstand wie beim Input-Padding halten */
|
||||||
transform: translateY(-50%); /* Vertikal zentrieren (Schritt 2 - Feinjustierung) */
|
transform: translateY(
|
||||||
|
-50%
|
||||||
|
); /* Vertikal zentrieren (Schritt 2 - Feinjustierung) */
|
||||||
|
|
||||||
border-radius: 4px;
|
border-radius: 4px;
|
||||||
/* Aussehen & Typografie */
|
/* Aussehen & Typografie */
|
||||||
color: var(--color-text-light);
|
color: var(--color-text-light);
|
||||||
background-color: var(--color-surface); /* WICHTIG: Überdeckt die Input-Linie beim Schweben */
|
background-color: var(
|
||||||
|
--color-surface
|
||||||
|
); /* WICHTIG: Überdeckt die Input-Linie beim Schweben */
|
||||||
padding: 0 0.25rem;
|
padding: 0 0.25rem;
|
||||||
|
|
||||||
/* Verhalten */
|
/* Verhalten */
|
||||||
transition: all 0.2s ease-out; /* Animiert alle Änderungen (top, font-size, color) */
|
transition: all 0.2s ease-out; /* Animiert alle Änderungen (top, font-size, color) */
|
||||||
pointer-events: none; /* Erlaubt Klicks "durch" das Label auf das Input-Feld darunter */
|
pointer-events: none; /* Erlaubt Klicks "durch" das Label auf das Input-Feld darunter */
|
||||||
@@ -75,7 +79,9 @@
|
|||||||
.form-input:focus ~ .form-label,
|
.form-input:focus ~ .form-label,
|
||||||
.form-input:not(:placeholder-shown) ~ .form-label {
|
.form-input:not(:placeholder-shown) ~ .form-label {
|
||||||
top: 0;
|
top: 0;
|
||||||
transform: translateY(-50%); /* Bleibt für die Zentrierung auf der Border-Linie wichtig */
|
transform: translateY(
|
||||||
|
-50%
|
||||||
|
); /* Bleibt für die Zentrierung auf der Border-Linie wichtig */
|
||||||
font-size: 0.8rem;
|
font-size: 0.8rem;
|
||||||
color: var(--color-primary);
|
color: var(--color-primary);
|
||||||
}
|
}
|
||||||
@@ -87,12 +93,12 @@
|
|||||||
* und die richtige Farbe bekommt.
|
* und die richtige Farbe bekommt.
|
||||||
*/
|
*/
|
||||||
.form-input:-webkit-autofill,
|
.form-input:-webkit-autofill,
|
||||||
.form-input:-webkit-autofill:hover,
|
.form-input:-webkit-autofill:hover,
|
||||||
.form-input:-webkit-autofill:focus,
|
.form-input:-webkit-autofill:focus,
|
||||||
.form-input:-webkit-autofill:active {
|
.form-input:-webkit-autofill:active {
|
||||||
/* OPTIONAL: Überschreibt den unschönen gelben/blauen Autofill-Hintergrund */
|
/* OPTIONAL: Überschreibt den unschönen gelben/blauen Autofill-Hintergrund */
|
||||||
-webkit-box-shadow: 0 0 0 30px var(--color-surface) inset !important;
|
-webkit-box-shadow: 0 0 0 30px var(--color-surface) inset !important;
|
||||||
-webkit-text-fill-color: var(--color-text) !important;
|
-webkit-text-fill-color: var(--color-text) !important;
|
||||||
}
|
}
|
||||||
|
|
||||||
.form-input:-webkit-autofill ~ .form-label {
|
.form-input:-webkit-autofill ~ .form-label {
|
||||||
@@ -100,4 +106,18 @@
|
|||||||
transform: translateY(-50%);
|
transform: translateY(-50%);
|
||||||
font-size: 0.8rem;
|
font-size: 0.8rem;
|
||||||
color: var(--color-primary);
|
color: var(--color-primary);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.required-indicator {
|
||||||
|
color: var(--color-danger);
|
||||||
|
font-weight: bold;
|
||||||
|
margin-left: 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Styling für die Fehlermeldung */
|
||||||
|
.error-message {
|
||||||
|
color: var(--color-danger);
|
||||||
|
font-size: 0.875rem;
|
||||||
|
margin-top: 0.25rem;
|
||||||
|
padding-left: 0.25rem;
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,13 +1,26 @@
|
|||||||
<div class="form-field">
|
<!-- /src/app/shared/components/form/form-field/form-field.component.html -->
|
||||||
<input
|
|
||||||
[type]="type"
|
<div class="form-field-wrapper">
|
||||||
class="form-input"
|
<div class="form-field">
|
||||||
[id]="controlId"
|
<input
|
||||||
placeholder=" "
|
[type]="type"
|
||||||
[disabled]="disabled"
|
class="form-input"
|
||||||
[(ngModel)]="value"
|
[id]="controlId"
|
||||||
(ngModelChange)="onChange($event)"
|
placeholder=" "
|
||||||
(blur)="onTouched()">
|
[disabled]="disabled"
|
||||||
|
[(ngModel)]="value"
|
||||||
<label [for]="controlId" class="form-label">{{ label }}</label>
|
(ngModelChange)="onChange($event)"
|
||||||
|
(blur)="onTouched()">
|
||||||
|
|
||||||
|
<label [for]="controlId" class="form-label">
|
||||||
|
{{ label }}
|
||||||
|
<!-- Der Indikator wird jetzt nur bei Bedarf angezeigt -->
|
||||||
|
<span *ngIf="isRequired" class="required-indicator">*</span>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Anzeige für Validierungsfehler -->
|
||||||
|
<div *ngIf="showErrors && errorMessage" class="error-message">
|
||||||
|
{{ errorMessage }}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
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 { AbstractControl, FormsModule, NG_VALUE_ACCESSOR, ReactiveFormsModule } from '@angular/forms';
|
import { AbstractControl, FormsModule, NG_VALUE_ACCESSOR, ReactiveFormsModule, Validators } from '@angular/forms'; // Validators importieren
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-form-field',
|
selector: 'app-form-field',
|
||||||
@@ -10,10 +10,10 @@ import { AbstractControl, FormsModule, NG_VALUE_ACCESSOR, ReactiveFormsModule }
|
|||||||
imports: [
|
imports: [
|
||||||
CommonModule,
|
CommonModule,
|
||||||
FormsModule,
|
FormsModule,
|
||||||
ReactiveFormsModule // <-- WICHTIG: Hinzufügen, um mit AbstractControl zu arbeiten
|
ReactiveFormsModule
|
||||||
],
|
],
|
||||||
templateUrl: './form-field.component.html',
|
templateUrl: './form-field.component.html',
|
||||||
styleUrl: './form-field.component.css',
|
styleUrls: ['./form-field.component.css'],
|
||||||
providers: [
|
providers: [
|
||||||
{
|
{
|
||||||
provide: NG_VALUE_ACCESSOR,
|
provide: NG_VALUE_ACCESSOR,
|
||||||
@@ -23,44 +23,42 @@ import { AbstractControl, FormsModule, NG_VALUE_ACCESSOR, ReactiveFormsModule }
|
|||||||
],
|
],
|
||||||
})
|
})
|
||||||
export class FormFieldComponent {
|
export class FormFieldComponent {
|
||||||
// --- KORREKTUR: Erweitere die erlaubten Typen ---
|
|
||||||
@Input() type: 'text' | 'email' | 'password' | 'number' | 'tel' | 'url' = 'text';
|
@Input() type: 'text' | 'email' | 'password' | 'number' | 'tel' | 'url' = 'text';
|
||||||
@Input() label: string = '';
|
@Input() label: string = '';
|
||||||
|
@Input() control?: AbstractControl | null;
|
||||||
// Neuer Input, um das FormControl für die Fehleranzeige zu erhalten
|
@Input() showErrors = true;
|
||||||
@Input() control?: AbstractControl;
|
|
||||||
@Input() showErrors = true; // Standardmäßig Fehler anzeigen
|
|
||||||
|
|
||||||
controlId = `form-field-${Math.random().toString(36).substring(2, 9)}`;
|
controlId = `form-field-${Math.random().toString(36).substring(2, 9)}`;
|
||||||
|
|
||||||
// --- Eigenschaften & Methoden für ControlValueAccessor ---
|
|
||||||
value: string | number = '';
|
value: string | number = '';
|
||||||
onChange: (value: any) => void = () => {};
|
onChange: (value: any) => void = () => {};
|
||||||
onTouched: () => void = () => {};
|
onTouched: () => void = () => {};
|
||||||
disabled = false;
|
disabled = false;
|
||||||
|
|
||||||
writeValue(value: any): void {
|
// NEU: Getter, der automatisch prüft, ob das Feld ein Pflichtfeld ist.
|
||||||
this.value = value;
|
get isRequired(): boolean {
|
||||||
}
|
if (!this.control) {
|
||||||
registerOnChange(fn: any): void {
|
return false;
|
||||||
this.onChange = fn;
|
}
|
||||||
}
|
// hasValidator prüft, ob ein bestimmter Validator auf dem Control gesetzt ist.
|
||||||
registerOnTouched(fn: any): void {
|
return this.control.hasValidator(Validators.required);
|
||||||
this.onTouched = fn;
|
|
||||||
}
|
|
||||||
setDisabledState?(isDisabled: boolean): void {
|
|
||||||
this.disabled = isDisabled;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Hilfsfunktion für das Template, um Fehler zu finden
|
|
||||||
get errorMessage(): string | null {
|
get errorMessage(): string | null {
|
||||||
if (!this.control || !this.control.errors || (!this.control.touched && !this.control.dirty)) {
|
if (!this.control || !this.control.errors || (!this.control.touched && !this.control.dirty)) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
if (this.control.hasError('required')) return 'Dieses Feld ist erforderlich.';
|
const errors = this.control.errors;
|
||||||
if (this.control.hasError('email')) return 'Bitte geben Sie eine gültige E-Mail-Adresse ein.';
|
if (errors['required']) return 'Dieses Feld ist erforderlich.';
|
||||||
if (this.control.hasError('min')) return `Der Wert muss mindestens ${this.control.errors['min'].min} sein.`;
|
if (errors['email']) return 'Bitte geben Sie eine gültige E-Mail-Adresse ein.';
|
||||||
// ... weitere Fehlermeldungen hier
|
if (errors['min']) return `Der Wert muss mindestens ${errors['min'].min} sein.`;
|
||||||
|
if (errors['max']) return `Der Wert darf maximal ${errors['max'].max} sein.`;
|
||||||
|
if (errors['minlength']) return `Mindestens ${errors['minlength'].requiredLength} Zeichen erforderlich.`;
|
||||||
|
|
||||||
return 'Ungültige Eingabe.';
|
return 'Ungültige Eingabe.';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
writeValue(value: any): void { this.value = value; }
|
||||||
|
registerOnChange(fn: any): void { this.onChange = fn; }
|
||||||
|
registerOnTouched(fn: any): void { this.onTouched = fn; }
|
||||||
|
setDisabledState?(isDisabled: boolean): void { this.disabled = isDisabled; }
|
||||||
}
|
}
|
||||||
@@ -23,7 +23,7 @@
|
|||||||
font-size: 0.9rem;
|
font-size: 0.9rem;
|
||||||
color: var(--color-text-light);
|
color: var(--color-text-light);
|
||||||
margin-top: -0.75rem; /* Rücken wir näher an den Titel */
|
margin-top: -0.75rem; /* Rücken wir näher an den Titel */
|
||||||
margin-bottom: 1.5rem;
|
margin-bottom: 1rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
.form-group-content {
|
.form-group-content {
|
||||||
|
|||||||
@@ -9,12 +9,6 @@
|
|||||||
{{ description }}
|
{{ description }}
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
<!--
|
|
||||||
HIER IST DIE MAGIE:
|
|
||||||
<ng-content> ist ein Platzhalter. Alles, was Sie in Demo2Component
|
|
||||||
zwischen <app-form-group> und </app-form-group> schreiben,
|
|
||||||
wird genau an dieser Stelle eingefügt.
|
|
||||||
-->
|
|
||||||
<div class="form-group-content">
|
<div class="form-group-content">
|
||||||
<ng-content></ng-content>
|
<ng-content></ng-content>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { Component, Input, forwardRef, HostListener, ElementRef } from '@angular/core';
|
import { Component, Input, forwardRef, HostListener, ElementRef } from '@angular/core';
|
||||||
import { ControlValueAccessor, NG_VALUE_ACCESSOR, ReactiveFormsModule, FormsModule } from '@angular/forms';
|
import { ControlValueAccessor, NG_VALUE_ACCESSOR, ReactiveFormsModule, FormsModule, AbstractControl } from '@angular/forms';
|
||||||
import { CommonModule } from '@angular/common';
|
import { CommonModule } from '@angular/common';
|
||||||
import { animate, style, transition, trigger } from '@angular/animations';
|
import { animate, style, transition, trigger } from '@angular/animations';
|
||||||
|
|
||||||
@@ -39,10 +39,12 @@ export interface SelectOption {
|
|||||||
export class FormSelectComponent implements ControlValueAccessor {
|
export class FormSelectComponent implements ControlValueAccessor {
|
||||||
@Input() label: string = '';
|
@Input() label: string = '';
|
||||||
@Input() options: SelectOption[] = [];
|
@Input() options: SelectOption[] = [];
|
||||||
|
@Input() control: AbstractControl | null = null;
|
||||||
|
|
||||||
// NEU: Zustand für das Dropdown-Menü und das angezeigte Label
|
|
||||||
isOpen = false;
|
isOpen = false;
|
||||||
selectedLabel: string | null = null;
|
|
||||||
|
// -- ENTFERNEN SIE DIESE ZEILE --
|
||||||
|
// selectedLabel: string | null = null;
|
||||||
|
|
||||||
controlId = `form-select-${Math.random().toString(36).substring(2)}`;
|
controlId = `form-select-${Math.random().toString(36).substring(2)}`;
|
||||||
value: any = null;
|
value: any = null;
|
||||||
@@ -50,46 +52,47 @@ export class FormSelectComponent implements ControlValueAccessor {
|
|||||||
onTouched: () => void = () => {};
|
onTouched: () => void = () => {};
|
||||||
disabled = false;
|
disabled = false;
|
||||||
|
|
||||||
|
// ++ FÜGEN SIE DIESEN GETTER HINZU ++
|
||||||
|
// Dieser Getter wird immer dann neu berechnet, wenn Angular die Ansicht prüft.
|
||||||
|
// Er hat immer Zugriff auf die aktuellsten `options` und den aktuellsten `value`.
|
||||||
|
get selectedLabel(): string | null {
|
||||||
|
const selectedOption = this.options.find(opt => opt.value === this.value);
|
||||||
|
return selectedOption ? selectedOption.label : null;
|
||||||
|
}
|
||||||
|
|
||||||
constructor(private elementRef: ElementRef) {}
|
constructor(private elementRef: ElementRef) {}
|
||||||
|
|
||||||
// NEU: Schließt das Dropdown, wenn außerhalb des Elements geklickt wird
|
|
||||||
@HostListener('document:click', ['$event'])
|
@HostListener('document:click', ['$event'])
|
||||||
onDocumentClick(event: MouseEvent): void {
|
onDocumentClick(event: MouseEvent): void {
|
||||||
// Diese Logik ist jetzt sicher, weil Klicks innerhalb der Komponente sie nie erreichen
|
|
||||||
if (!this.elementRef.nativeElement.contains(event.target)) {
|
if (!this.elementRef.nativeElement.contains(event.target)) {
|
||||||
this.isOpen = false;
|
this.isOpen = false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ÜBERARBEITET: writeValue aktualisiert jetzt auch das sichtbare Label
|
// KORRIGIERT: writeValue setzt jetzt nur noch den Wert.
|
||||||
writeValue(value: any): void {
|
writeValue(value: any): void {
|
||||||
this.value = value;
|
this.value = value;
|
||||||
const selectedOption = this.options.find(opt => opt.value === value);
|
// Die Zeile, die `selectedLabel` gesetzt hat, wird nicht mehr benötigt.
|
||||||
this.selectedLabel = selectedOption ? selectedOption.label : null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
registerOnChange(fn: any): void { this.onChange = fn; }
|
registerOnChange(fn: any): void { this.onChange = fn; }
|
||||||
registerOnTouched(fn: any): void { this.onTouched = fn; }
|
registerOnTouched(fn: any): void { this.onTouched = fn; }
|
||||||
setDisabledState?(isDisabled: boolean): void { this.disabled = isDisabled; }
|
setDisabledState?(isDisabled: boolean): void { this.disabled = isDisabled; }
|
||||||
|
|
||||||
// NEU: Methode zum Öffnen/Schließen des Menüs
|
|
||||||
// ÜBERARBEITET: Nimmt das Event entgegen und stoppt es
|
|
||||||
toggleDropdown(event: MouseEvent): void {
|
toggleDropdown(event: MouseEvent): void {
|
||||||
event.stopPropagation(); // <-- WICHTIGSTE KORREKTUR
|
event.stopPropagation();
|
||||||
if (!this.disabled) {
|
if (!this.disabled) {
|
||||||
this.isOpen = !this.isOpen;
|
this.isOpen = !this.isOpen;
|
||||||
if (!this.isOpen) {
|
if (!this.isOpen) { this.onTouched(); }
|
||||||
this.onTouched();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ÜBERARBEITET: Nimmt das Event entgegen und stoppt es
|
// KORRIGIERT: selectOption setzt jetzt nur noch den Wert.
|
||||||
selectOption(option: SelectOption, event: MouseEvent): void {
|
selectOption(option: SelectOption, event: MouseEvent): void {
|
||||||
event.stopPropagation(); // <-- WICHTIGE KORREKTUR
|
event.stopPropagation();
|
||||||
if (!this.disabled) {
|
if (!this.disabled) {
|
||||||
this.value = option.value;
|
this.value = option.value;
|
||||||
this.selectedLabel = option.label;
|
// Die Zeile, die `selectedLabel` gesetzt hat, wird nicht mehr benötigt.
|
||||||
this.onChange(this.value);
|
this.onChange(this.value);
|
||||||
this.onTouched();
|
this.onTouched();
|
||||||
this.isOpen = false;
|
this.isOpen = false;
|
||||||
|
|||||||
@@ -76,4 +76,18 @@ border-radius: 4px;
|
|||||||
top: 0;
|
top: 0;
|
||||||
font-size: 0.8rem;
|
font-size: 0.8rem;
|
||||||
color: var(--color-primary);
|
color: var(--color-primary);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.required-indicator {
|
||||||
|
color: var(--color-danger);
|
||||||
|
font-weight: bold;
|
||||||
|
margin-left: 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Styling für die Fehlermeldung */
|
||||||
|
.error-message {
|
||||||
|
color: var(--color-danger);
|
||||||
|
font-size: 0.875rem;
|
||||||
|
margin-top: 0.25rem;
|
||||||
|
padding-left: 0.25rem;
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,13 +1,24 @@
|
|||||||
<div class="form-field">
|
<!-- /src/app/shared/components/form/form-textarea/form-textarea.component.html -->
|
||||||
<textarea
|
|
||||||
class="form-input"
|
<div class="form-field-wrapper">
|
||||||
[id]="controlId"
|
<div class="form-field">
|
||||||
placeholder=" "
|
<textarea
|
||||||
[rows]="rows"
|
class="form-input"
|
||||||
[(ngModel)]="value"
|
[id]="controlId"
|
||||||
(ngModelChange)="onChange($event)"
|
[rows]="rows"
|
||||||
(blur)="onTouched()"
|
placeholder=" "
|
||||||
[disabled]="disabled"></textarea>
|
[disabled]="disabled"
|
||||||
|
[(ngModel)]="value"
|
||||||
|
(ngModelChange)="onChange($event)"
|
||||||
|
(blur)="onTouched()"></textarea>
|
||||||
|
|
||||||
|
<label [for]="controlId" class="form-label">
|
||||||
|
{{ label }}
|
||||||
|
<span *ngIf="isRequired" class="required-indicator">*</span>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
|
||||||
<label [for]="controlId" class="form-label">{{ label }}</label>
|
<div *ngIf="showErrors && errorMessage" class="error-message">
|
||||||
|
{{ errorMessage }}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -1,38 +1,54 @@
|
|||||||
|
// /src/app/shared/components/form/form-textarea/form-textarea.component.ts
|
||||||
|
|
||||||
import { Component, Input, forwardRef } from '@angular/core';
|
import { Component, Input, forwardRef } from '@angular/core';
|
||||||
import { ControlValueAccessor, NG_VALUE_ACCESSOR, ReactiveFormsModule, FormsModule } from '@angular/forms';
|
|
||||||
import { CommonModule } from '@angular/common';
|
import { CommonModule } from '@angular/common';
|
||||||
|
import { AbstractControl, FormsModule, NG_VALUE_ACCESSOR, ReactiveFormsModule, Validators } from '@angular/forms';
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-form-textarea',
|
selector: 'app-form-textarea',
|
||||||
standalone: true,
|
standalone: true,
|
||||||
imports: [
|
imports: [ CommonModule, FormsModule, ReactiveFormsModule ],
|
||||||
CommonModule,
|
|
||||||
ReactiveFormsModule,
|
|
||||||
FormsModule // Wichtig für [(ngModel)]
|
|
||||||
],
|
|
||||||
templateUrl: './form-textarea.component.html',
|
templateUrl: './form-textarea.component.html',
|
||||||
styleUrl: './form-textarea.component.css',
|
styleUrls: ['./form-textarea.component.css'],
|
||||||
providers: [
|
providers: [
|
||||||
{
|
{
|
||||||
provide: NG_VALUE_ACCESSOR,
|
provide: NG_VALUE_ACCESSOR,
|
||||||
useExisting: forwardRef(() => FormTextareaComponent),
|
useExisting: forwardRef(() => FormTextareaComponent),
|
||||||
multi: true
|
multi: true,
|
||||||
}
|
},
|
||||||
]
|
],
|
||||||
})
|
})
|
||||||
export class FormTextareaComponent implements ControlValueAccessor {
|
export class FormTextareaComponent {
|
||||||
@Input() label: string = '';
|
@Input() label: string = '';
|
||||||
@Input() rows = 3; // Standardanzahl der Zeilen
|
@Input() rows: number = 4;
|
||||||
|
|
||||||
|
// NEU: Hinzufügen des 'control' Inputs, genau wie in form-field
|
||||||
|
@Input() control?: AbstractControl | null;
|
||||||
|
|
||||||
|
@Input() showErrors = true;
|
||||||
|
|
||||||
// Eindeutige ID für die Verknüpfung
|
controlId = `form-textarea-${Math.random().toString(36).substring(2, 9)}`;
|
||||||
controlId = `form-textarea-${Math.random().toString(36).substring(2)}`;
|
|
||||||
|
|
||||||
// --- Logik für ControlValueAccessor ---
|
|
||||||
value: string = '';
|
value: string = '';
|
||||||
onChange: (value: any) => void = () => {};
|
onChange: (value: any) => void = () => {};
|
||||||
onTouched: () => void = () => {};
|
onTouched: () => void = () => {};
|
||||||
disabled = false;
|
disabled = false;
|
||||||
|
|
||||||
|
get isRequired(): boolean {
|
||||||
|
if (!this.control) return false;
|
||||||
|
return this.control.hasValidator(Validators.required);
|
||||||
|
}
|
||||||
|
|
||||||
|
get errorMessage(): string | null {
|
||||||
|
if (!this.control || !this.control.errors || (!this.control.touched && !this.control.dirty)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const errors = this.control.errors;
|
||||||
|
if (errors['required']) return 'Dieses Feld ist erforderlich.';
|
||||||
|
if (errors['minlength']) return `Mindestens ${errors['minlength'].requiredLength} Zeichen erforderlich.`;
|
||||||
|
|
||||||
|
return 'Ungültige Eingabe.';
|
||||||
|
}
|
||||||
|
|
||||||
writeValue(value: any): void { this.value = value; }
|
writeValue(value: any): void { this.value = value; }
|
||||||
registerOnChange(fn: any): void { this.onChange = fn; }
|
registerOnChange(fn: any): void { this.onChange = fn; }
|
||||||
registerOnTouched(fn: any): void { this.onTouched = fn; }
|
registerOnTouched(fn: any): void { this.onTouched = fn; }
|
||||||
|
|||||||
@@ -48,4 +48,6 @@
|
|||||||
:host-context(body.dark-theme) .pill-active { color: #a7f3d0; background-color: #166534; border-color: #22c55e; }
|
: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; }
|
.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; }
|
:host-context(body.dark-theme) .pill-inactive { color: rgb(168, 168, 168); background-color: #ececec; border-color: #777777; }
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
<!-- /src/app/shared/components/ui/status-pill/status-pill.component.html -->
|
||||||
|
|
||||||
<div class="status-pill" [ngClass]="cssClass">
|
<div class="status-pill" [ngClass]="cssClass">
|
||||||
{{ displayText }}
|
<span>{{ displayText }}</span>
|
||||||
</div>
|
</div>
|
||||||
@@ -1,24 +1,35 @@
|
|||||||
import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';
|
// /src/app/shared/components/ui/status-pill/status-pill.component.ts
|
||||||
|
|
||||||
|
import { Component, Input, Output, EventEmitter, OnChanges, SimpleChanges } from '@angular/core';
|
||||||
import { CommonModule, NgClass } from '@angular/common';
|
import { CommonModule, NgClass } from '@angular/common';
|
||||||
// import { OrderStatus } from '../../../../core/types/order';
|
|
||||||
|
|
||||||
@Component({
|
@Component({
|
||||||
selector: 'app-status-pill',
|
selector: 'app-status-pill',
|
||||||
standalone: true,
|
standalone: true,
|
||||||
imports: [CommonModule, NgClass],
|
imports: [CommonModule, NgClass], // IconComponent hinzufügen
|
||||||
templateUrl: './status-pill.component.html',
|
templateUrl: './status-pill.component.html',
|
||||||
styleUrl: './status-pill.component.css'
|
styleUrls: ['./status-pill.component.css']
|
||||||
})
|
})
|
||||||
export class StatusPillComponent implements OnChanges {
|
export class StatusPillComponent implements OnChanges {
|
||||||
// Nimmt jetzt den neuen, sprechenden Status entgegen
|
// --- INPUTS ---
|
||||||
@Input() status: string | boolean = 'info';
|
// Nimmt den Status für die Farbe entgegen
|
||||||
|
@Input() status: string | boolean = 'info';
|
||||||
|
|
||||||
// Diese Eigenschaften werden vom Template verwendet
|
// NEU: Nimmt einen expliziten Text entgegen. Hat Vorrang vor dem Status-Text.
|
||||||
|
@Input() text?: string;
|
||||||
|
|
||||||
|
// NEU: Steuert, ob der "Entfernen"-Button angezeigt wird
|
||||||
|
@Input() removable = false;
|
||||||
|
|
||||||
|
// --- OUTPUT ---
|
||||||
|
// NEU: Wird ausgelöst, wenn der Entfernen-Button geklickt wird
|
||||||
|
@Output() remove = new EventEmitter<void>();
|
||||||
|
|
||||||
|
// --- Interne Eigenschaften für das Template ---
|
||||||
public displayText = '';
|
public displayText = '';
|
||||||
public cssClass = '';
|
public cssClass = '';
|
||||||
|
|
||||||
// Eine Map, die Statusnamen auf Text und CSS-Klasse abbildet
|
private statusMap = new Map<any, { text: string, css: string }>([
|
||||||
private statusMap = new Map<any, { text: string, css: string }>([
|
|
||||||
['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' }],
|
||||||
@@ -27,17 +38,25 @@ export class StatusPillComponent implements OnChanges {
|
|||||||
['inactive', { text: 'Nein', css: 'pill-inactive' }]
|
['inactive', { text: 'Nein', css: 'pill-inactive' }]
|
||||||
]);
|
]);
|
||||||
|
|
||||||
ngOnChanges(changes: SimpleChanges): void {
|
ngOnChanges(changes: SimpleChanges): void {
|
||||||
if (changes['status']) {
|
if (changes['status'] || changes['text']) {
|
||||||
let statusKey = this.status;
|
let statusKey = this.status;
|
||||||
|
|
||||||
|
// Konvertiere boolean in einen String-Key
|
||||||
if (typeof statusKey === 'boolean') {
|
if (typeof statusKey === 'boolean') {
|
||||||
statusKey = statusKey ? 'active' : 'inactive';
|
statusKey = statusKey ? 'active' : 'inactive';
|
||||||
}
|
}
|
||||||
|
|
||||||
const details = this.statusMap.get(statusKey as string) || { text: statusKey.toString(), css: 'pill-secondary' };
|
const details = this.statusMap.get(statusKey as string) || { text: 'Info', css: 'pill-secondary' };
|
||||||
this.displayText = details.text;
|
|
||||||
|
// NEUE LOGIK: Wenn ein expliziter Text übergeben wird, hat dieser Vorrang
|
||||||
|
this.displayText = this.text ?? details.text;
|
||||||
this.cssClass = details.css;
|
this.cssClass = details.css;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Methode, die das Event auslöst
|
||||||
|
onRemove(): void {
|
||||||
|
this.remove.emit();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Reference in New Issue
Block a user