/**
* Kasico API Client
* JavaScript-Modul für die Integration mit der REST API
*/
class KasicoAPI {
constructor() {
this.baseURL = '/api/v1/';
this.csrfToken = this.getCSRFToken();
}
/**
* CSRF Token aus dem DOM extrahieren
*/
getCSRFToken() {
const token = document.querySelector('[name=csrfmiddlewaretoken]');
return token ? token.value : '';
}
/**
* HTTP Request Helper
*/
async request(endpoint, options = {}) {
const url = this.baseURL + endpoint;
const config = {
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': this.csrfToken,
'X-Requested-With': 'XMLHttpRequest',
},
...options
};
try {
const response = await fetch(url, config);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return await response.json();
} catch (error) {
console.error('API Request failed:', error);
throw error;
}
}
/**
* GET Request
*/
async get(endpoint, params = {}) {
const queryString = new URLSearchParams(params).toString();
const url = queryString ? `${endpoint}?${queryString}` : endpoint;
return this.request(url, { method: 'GET' });
}
/**
* POST Request
*/
async post(endpoint, data = {}) {
return this.request(endpoint, {
method: 'POST',
body: JSON.stringify(data)
});
}
/**
* PUT Request
*/
async put(endpoint, data = {}) {
return this.request(endpoint, {
method: 'PUT',
body: JSON.stringify(data)
});
}
/**
* DELETE Request
*/
async delete(endpoint) {
return this.request(endpoint, { method: 'DELETE' });
}
// ===== PRODUKT API =====
/**
* Alle Produkte abrufen
*/
async getProducts(params = {}) {
return this.get('products/', params);
}
/**
* Einzelnes Produkt abrufen
*/
async getProduct(productId) {
return this.get(`products/${productId}/`);
}
/**
* Featured Produkte abrufen
*/
async getFeaturedProducts() {
return this.get('products/featured/');
}
/**
* Produkte im Angebot abrufen
*/
async getOnSaleProducts() {
return this.get('products/on-sale/');
}
/**
* Produkte mit niedrigem Lagerbestand abrufen
*/
async getLowStockProducts() {
return this.get('products/low-stock/');
}
/**
* Produkt-Statistiken abrufen
*/
async getProductStats() {
return this.get('products/stats/');
}
/**
* Produkt zur Wunschliste hinzufügen
*/
async addToWishlist(productId) {
return this.post(`products/${productId}/add-to-wishlist/`);
}
/**
* Produkt von Wunschliste entfernen
*/
async removeFromWishlist(productId) {
return this.post(`products/${productId}/remove-from-wishlist/`);
}
// ===== KATEGORIE API =====
/**
* Alle Kategorien abrufen
*/
async getCategories() {
return this.get('categories/');
}
/**
* Einzelne Kategorie abrufen
*/
async getCategory(categoryId) {
return this.get(`categories/${categoryId}/`);
}
/**
* Produkte einer Kategorie abrufen
*/
async getCategoryProducts(categoryId) {
return this.get(`categories/${categoryId}/products/`);
}
// ===== REVIEW API =====
/**
* Reviews für ein Produkt abrufen
*/
async getProductReviews(productId) {
return this.get('reviews/', { product: productId });
}
/**
* Review erstellen
*/
async createReview(data) {
return this.post('reviews/', data);
}
/**
* Meine Reviews abrufen
*/
async getMyReviews() {
return this.get('reviews/my-reviews/');
}
// ===== WUNSCHLISTE API =====
/**
* Wunschliste abrufen
*/
async getWishlist() {
return this.get('wishlist/');
}
/**
* Produkt zur Wunschliste hinzufügen
*/
async addProductToWishlist(productId) {
return this.post('wishlist/add-product/', { product_id: productId });
}
/**
* Produkt von Wunschliste entfernen
*/
async removeProductFromWishlist(productId) {
return this.post('wishlist/remove-product/', { product_id: productId });
}
// ===== CUSTOM ORDER API =====
/**
* Custom Orders abrufen
*/
async getCustomOrders() {
return this.get('custom-orders/');
}
/**
* Custom Order erstellen
*/
async createCustomOrder(data) {
return this.post('custom-orders/', data);
}
/**
* Custom Order Status aktualisieren
*/
async updateCustomOrderStatus(orderId, status) {
return this.post(`custom-orders/${orderId}/update-status/`, { status });
}
// ===== GALERIE API =====
/**
* Galerie-Bilder abrufen
*/
async getGalleryImages(params = {}) {
return this.get('gallery/', params);
}
/**
* Featured Galerie-Bilder abrufen
*/
async getFeaturedGalleryImages() {
return this.get('gallery/featured/');
}
/**
* Galerie-Bilder nach Produkt filtern
*/
async getGalleryImagesByProduct(productId) {
return this.get('gallery/by-product/', { product_id: productId });
}
// ===== WARENKORB API =====
/**
* Warenkorb abrufen
*/
async getCart() {
return this.get('cart/get/');
}
/**
* Item zum Warenkorb hinzufügen
*/
async addToCart(productId, quantity = 1) {
return this.post('cart/add-item/', { product_id: productId, quantity });
}
/**
* Warenkorb-Menge aktualisieren
*/
async updateCartQuantity(itemId, quantity) {
return this.post('cart/update-quantity/', { item_id: itemId, quantity });
}
/**
* Item aus Warenkorb entfernen
*/
async removeFromCart(itemId) {
return this.post('cart/remove-item/', { item_id: itemId });
}
/**
* Warenkorb leeren
*/
async clearCart() {
return this.post('cart/clear/');
}
// ===== SUCH API =====
/**
* Produkte suchen
*/
async searchProducts(params = {}) {
return this.get('search/products/', params);
}
// ===== UTILITY FUNCTIONS =====
/**
* Benachrichtigung anzeigen
*/
showNotification(message, type = 'info') {
// Verwende die bestehende showNotification Funktion
if (typeof window.showNotification === 'function') {
window.showNotification(message, type);
} else {
// Fallback: Alert
alert(message);
}
}
/**
* Warenkorb-Counter aktualisieren
*/
updateCartCounter(count) {
const cartCounter = document.getElementById('cartCounter');
if (cartCounter) {
cartCounter.textContent = count;
cartCounter.style.display = count > 0 ? 'block' : 'none';
}
}
/**
* Loading State verwalten
*/
setLoading(element, loading = true) {
if (element) {
if (loading) {
element.disabled = true;
element.innerHTML = 'Laden...';
} else {
element.disabled = false;
element.innerHTML = element.dataset.originalText || element.innerHTML;
}
}
}
/**
* Error Handler
*/
handleError(error, userMessage = 'Ein Fehler ist aufgetreten.') {
console.error('API Error:', error);
this.showNotification(userMessage, 'error');
}
}
// Globale API-Instanz erstellen
window.kasicoAPI = new KasicoAPI();
// ===== AJAX INTEGRATION =====
/**
* AJAX Warenkorb-Funktionen
*/
window.ajaxCart = {
async addToCart(productId, quantity = 1) {
try {
const button = event.target.closest('button');
const originalText = button.innerHTML;
// Loading State
kasicoAPI.setLoading(button, true);
const response = await kasicoAPI.addToCart(productId, quantity);
// Success Animation
button.innerHTML = 'Hinzugefügt!';
button.classList.add('btn-success');
// Counter aktualisieren
if (response.cart_count) {
kasicoAPI.updateCartCounter(response.cart_count);
}
// Benachrichtigung
kasicoAPI.showNotification('Produkt zum Warenkorb hinzugefügt!', 'success');
// Reset nach 2 Sekunden
setTimeout(() => {
button.innerHTML = originalText;
button.classList.remove('btn-success');
kasicoAPI.setLoading(button, false);
}, 2000);
} catch (error) {
kasicoAPI.handleError(error, 'Fehler beim Hinzufügen zum Warenkorb.');
kasicoAPI.setLoading(button, false);
}
},
async updateQuantity(itemId, change) {
try {
const response = await kasicoAPI.updateCartQuantity(itemId, change);
// Seite neu laden für aktualisierte Preise
window.location.reload();
} catch (error) {
kasicoAPI.handleError(error, 'Fehler beim Aktualisieren der Menge.');
}
},
async removeFromCart(itemId) {
if (confirm('Sind Sie sicher, dass Sie dieses Produkt entfernen möchten?')) {
try {
const response = await kasicoAPI.removeFromCart(itemId);
// Animation
const cartItem = event.target.closest('.cart-item');
cartItem.style.transform = 'translateX(-100%)';
cartItem.style.opacity = '0';
setTimeout(() => {
window.location.reload();
}, 300);
} catch (error) {
kasicoAPI.handleError(error, 'Fehler beim Entfernen aus dem Warenkorb.');
}
}
}
};
/**
* AJAX Wunschliste-Funktionen
*/
window.ajaxWishlist = {
async addToWishlist(productId) {
try {
const response = await kasicoAPI.addToWishlist(productId);
kasicoAPI.showNotification('Zur Wunschliste hinzugefügt!', 'success');
} catch (error) {
kasicoAPI.handleError(error, 'Fehler beim Hinzufügen zur Wunschliste.');
}
},
async removeFromWishlist(productId) {
try {
const response = await kasicoAPI.removeFromWishlist(productId);
kasicoAPI.showNotification('Von Wunschliste entfernt!', 'info');
} catch (error) {
kasicoAPI.handleError(error, 'Fehler beim Entfernen von der Wunschliste.');
}
}
};
/**
* AJAX Filter-Funktionen
*/
window.ajaxFilter = {
async applyFilters(formData) {
try {
const params = new URLSearchParams(formData);
const response = await kasicoAPI.searchProducts(Object.fromEntries(params));
// Ergebnisse aktualisieren
this.updateResults(response.results);
// URL aktualisieren
const newUrl = `${window.location.pathname}?${params.toString()}`;
window.history.pushState({}, '', newUrl);
} catch (error) {
kasicoAPI.handleError(error, 'Fehler beim Anwenden der Filter.');
// Fallback: Seite neu laden
window.location.reload();
}
},
updateResults(results) {
const container = document.querySelector('#product-grid, #gallery, .masonry-grid');
if (container) {
// Hier würde die DOM-Manipulation für die Ergebnisse implementiert
console.log('Results updated:', results);
}
}
};
// ===== INITIALIZATION =====
document.addEventListener('DOMContentLoaded', function() {
// API verfügbar machen
window.api = kasicoAPI;
console.log('Kasico API Client initialized');
});