Initialer Commit: Projekt Start
This commit is contained in:
82
lib/services/coupon_service.dart
Normal file
82
lib/services/coupon_service.dart
Normal file
@@ -0,0 +1,82 @@
|
||||
import 'dart:convert';
|
||||
import 'package:http/http.dart' as http;
|
||||
import '../models/coupon.dart';
|
||||
import 'woocommerce_service.dart';
|
||||
|
||||
class CouponService {
|
||||
/// Validiert einen Gutschein-Code
|
||||
Future<Coupon> validateCoupon(String code) async {
|
||||
try {
|
||||
final queryParams = {
|
||||
'code': code,
|
||||
'status': 'publish',
|
||||
'consumer_key': WooCommerceService.consumerKey,
|
||||
'consumer_secret': WooCommerceService.consumerSecret,
|
||||
};
|
||||
|
||||
final uri = Uri.parse('${WooCommerceService.baseUrl}/wp-json/wc/v3/coupons').replace(
|
||||
queryParameters: queryParams,
|
||||
);
|
||||
|
||||
final response = await http.get(uri);
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
final List<dynamic> data = json.decode(response.body);
|
||||
|
||||
if (data.isNotEmpty) {
|
||||
final couponData = data[0];
|
||||
return Coupon(
|
||||
code: couponData['code'] ?? code,
|
||||
description: couponData['description'],
|
||||
discountType: couponData['discount_type'] ?? 'fixed_cart',
|
||||
amount: couponData['amount'] ?? '0',
|
||||
isValid: true,
|
||||
);
|
||||
} else {
|
||||
return Coupon(
|
||||
code: code,
|
||||
discountType: 'fixed_cart',
|
||||
amount: '0',
|
||||
isValid: false,
|
||||
errorMessage: 'Gutschein-Code nicht gefunden',
|
||||
);
|
||||
}
|
||||
} else {
|
||||
return Coupon(
|
||||
code: code,
|
||||
discountType: 'fixed_cart',
|
||||
amount: '0',
|
||||
isValid: false,
|
||||
errorMessage: 'Fehler beim Validieren des Gutscheins',
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
return Coupon(
|
||||
code: code,
|
||||
discountType: 'fixed_cart',
|
||||
amount: '0',
|
||||
isValid: false,
|
||||
errorMessage: 'Fehler: $e',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Berechnet den Rabatt für einen Warenkorb
|
||||
double calculateDiscount(Coupon coupon, double cartTotal) {
|
||||
if (!coupon.isValid) return 0.0;
|
||||
|
||||
final amount = double.tryParse(coupon.amount) ?? 0.0;
|
||||
|
||||
switch (coupon.discountType) {
|
||||
case 'percent':
|
||||
case 'percent_product':
|
||||
return (cartTotal * amount) / 100;
|
||||
case 'fixed_cart':
|
||||
case 'fixed_product':
|
||||
return amount;
|
||||
default:
|
||||
return 0.0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user