Untitled
unknown
typescript
2 years ago
5.7 kB
10
Indexable
import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { AngularFirestore } from '@angular/fire/compat/firestore';
import { AngularFireStorage } from '@angular/fire/compat/storage';
import { tap } from 'rxjs';
@Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['./dashboard.component.scss']
})
export class DashboardComponent implements OnInit {
fileExtensionToLogo = {
'.eps': '../../assets/eps_logo.png',
'.psd': '../../assets/psd_logo.png',
'.pdf': '../../assets/pdf_logo.png',
'.ai': '../../assets/ai_logo.png',
};
bestellungData: any;
currentItemId: string | null = null;
jsonData: any;
selectedFiles: File[] = [];
constructor(private http: HttpClient, private firestore: AngularFirestore, private storage: AngularFireStorage){}
ngOnInit(): void {
this.fetchJsonData().subscribe(() => {
this.checkDocument();
this.getItems();
})
}
isImage(filename: string): boolean {
const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp'];
const extension = filename.split('.').pop()?.toLowerCase();
return imageExtensions.includes(`.${extension}`);
}
getProgramLogo(filename: string): string {
const urlParts = filename.split('/');
const lastPart = urlParts[urlParts.length - 1];
const filenameParts = lastPart.split('?');
const filenameWithExtension = filenameParts[0];
const extension = filenameWithExtension.split('.').pop()?.toLowerCase();
const programLogo = (this.fileExtensionToLogo as { [key: string]: string })[`.${extension}`];
console.log(extension);
if (programLogo) {
return programLogo;
} else if (this.isImage(filenameWithExtension)) {
return filename;
} else {
return '../../assets/pdf_logo.png';
}
}
fetchJsonData() {
const jsonUrl = 'https://api.npoint.io/fcb78b12c1b21e7ee262';
return this.http.get(jsonUrl).pipe(
tap((data: any) => {
console.log(data);
this.jsonData = data;
})
);
}
checkDocument() {
if (this.jsonData) {
const documentId = this.jsonData.id.toString();
this.firestore
.collection('bestellungen')
.doc(documentId)
.get()
.subscribe((doc) => {
if (!doc.exists) {
this.firestore.collection('bestellungen').doc(documentId).set({
bestellNr: documentId
}).then(() => {
this.firestore.collection('bestellungen').doc(documentId).set({
items: this.jsonData.line_items
})
})
}
});
}
}
getItems(){
this.firestore.collection('bestellungen').doc(this.jsonData?.id.toString()).valueChanges().subscribe((res) => {
this.bestellungData = res;
})
}
logitem(id: any){
console.log(id);
}
deleteImage(index: number, imageindex: any) {
if (this.bestellungData.items[index]) {
if (this.bestellungData.items[index].images) {
this.bestellungData.items[index].images.splice(imageindex, 1);
const id = this.jsonData?.id.toString();
this.firestore.collection('bestellungen').doc(id).update({
items: this.bestellungData.items,
});
}
}
}
downloadImage(imageUrl: string) {
window.open(imageUrl, '_blank');
}
onitem(itemId: any) {
this.currentItemId = itemId;
}
onFileSelected(event: Event) {
const inputElement = event.target as HTMLInputElement;
if (inputElement.files && this.currentItemId) {
const files = Array.from(inputElement.files) as File[];
// hurensohn funktion für später merken wegen datentypen
const allowedExtensions = ['.eps', '.psd', '.pdf', '.ai', '.jpeg', '.jpg', '.png'];
const validFiles = files.filter(file => {
const extension = file.name?.split('.').pop()?.toLowerCase();
if (extension) {
return allowedExtensions.includes(`.${extension}`);
}
return false;
});
validFiles.forEach(file => {
const name = file.name;
const extension = name.split('.').pop()?.toLowerCase();
console.log(`File: ${name}, Extension: ${extension}`);
});
if (validFiles.length === 0) {
console.error('No valid files selected');
return;
}
const storagePromises = validFiles.map(async (file) => {
const storageRef = this.storage.ref('images/');
const filePath = `${new Date().getTime()}_${file.name}`;
const fileRef = storageRef.child(filePath);
const uploadTask = fileRef.put(file);
const metadata = await uploadTask.then((snapshot) => snapshot.ref.getMetadata());
const contentType = metadata.contentType;
return {
fileRef,
contentType,
};
});
Promise.all(storagePromises)
.then(async (fileRefsAndContentTypes) => {
const downloadUrlsArray = await Promise.all(fileRefsAndContentTypes.map(async ({ fileRef }) => {
return await fileRef.getDownloadURL().toPromise();
}));
const currentItem = this.bestellungData?.items.find((item: { id: any }) => item.id === this.currentItemId);
if (currentItem) {
currentItem.images = currentItem.images || [];
currentItem.images.push(...downloadUrlsArray);
const id = this.jsonData?.id.toString();
await this.firestore.collection('bestellungen').doc(id).update({
items: this.bestellungData.items,
});
}
})
.catch((error) => {
console.error('fehler beim hochladen firebase:', error);
});
this.selectedFiles = [...this.selectedFiles, ...validFiles];
}
}
}
Editor is loading...