verpfuschter stand von codex
This commit is contained in:
@@ -56,6 +56,117 @@ class PackageController extends Controller
|
|||||||
return $this->handlePaidPurchase($request, $package, $tenant);
|
return $this->handlePaidPurchase($request, $package, $tenant);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function createPaymentIntent(Request $request): JsonResponse
|
||||||
|
{
|
||||||
|
$request->validate([
|
||||||
|
'package_id' => 'required|exists:packages,id',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$package = Package::findOrFail($request->package_id);
|
||||||
|
$tenant = $request->attributes->get('tenant');
|
||||||
|
|
||||||
|
if (!$tenant) {
|
||||||
|
throw ValidationException::withMessages(['tenant' => 'Tenant not found.']);
|
||||||
|
}
|
||||||
|
|
||||||
|
\Stripe\Stripe::setApiKey(config('services.stripe.secret'));
|
||||||
|
|
||||||
|
$paymentIntent = \Stripe\PaymentIntent::create([
|
||||||
|
'amount' => $package->price * 100,
|
||||||
|
'currency' => 'eur',
|
||||||
|
'metadata' => [
|
||||||
|
'tenant_id' => $tenant->id,
|
||||||
|
'package_id' => $package->id,
|
||||||
|
'type' => 'endcustomer_event',
|
||||||
|
],
|
||||||
|
]);
|
||||||
|
|
||||||
|
return response()->json([
|
||||||
|
'client_secret' => $paymentIntent->client_secret,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function completePurchase(Request $request): JsonResponse
|
||||||
|
{
|
||||||
|
$request->validate([
|
||||||
|
'package_id' => 'required|exists:packages,id',
|
||||||
|
'payment_method_id' => 'required|string',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$package = Package::findOrFail($request->package_id);
|
||||||
|
$tenant = $request->attributes->get('tenant');
|
||||||
|
|
||||||
|
if (!$tenant) {
|
||||||
|
throw ValidationException::withMessages(['tenant' => 'Tenant not found.']);
|
||||||
|
}
|
||||||
|
|
||||||
|
DB::transaction(function () use ($request, $package, $tenant) {
|
||||||
|
PackagePurchase::create([
|
||||||
|
'tenant_id' => $tenant->id,
|
||||||
|
'package_id' => $package->id,
|
||||||
|
'provider_id' => $request->payment_method_id,
|
||||||
|
'price' => $package->price,
|
||||||
|
'type' => 'endcustomer_event',
|
||||||
|
'purchased_at' => now(),
|
||||||
|
'metadata' => json_encode(['note' => 'Wizard purchase']),
|
||||||
|
]);
|
||||||
|
|
||||||
|
TenantPackage::create([
|
||||||
|
'tenant_id' => $tenant->id,
|
||||||
|
'package_id' => $package->id,
|
||||||
|
'price' => $package->price,
|
||||||
|
'purchased_at' => now(),
|
||||||
|
'active' => true,
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
return response()->json([
|
||||||
|
'message' => 'Purchase completed successfully.',
|
||||||
|
], 201);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function assignFree(Request $request): JsonResponse
|
||||||
|
{
|
||||||
|
$request->validate([
|
||||||
|
'package_id' => 'required|exists:packages,id',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$package = Package::findOrFail($request->package_id);
|
||||||
|
$tenant = $request->attributes->get('tenant');
|
||||||
|
|
||||||
|
if (!$tenant) {
|
||||||
|
throw ValidationException::withMessages(['tenant' => 'Tenant not found.']);
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($package->price != 0) {
|
||||||
|
throw ValidationException::withMessages(['package' => 'Not a free package.']);
|
||||||
|
}
|
||||||
|
|
||||||
|
DB::transaction(function () use ($request, $package, $tenant) {
|
||||||
|
PackagePurchase::create([
|
||||||
|
'tenant_id' => $tenant->id,
|
||||||
|
'package_id' => $package->id,
|
||||||
|
'provider_id' => 'free_wizard',
|
||||||
|
'price' => $package->price,
|
||||||
|
'type' => 'endcustomer_event',
|
||||||
|
'purchased_at' => now(),
|
||||||
|
'metadata' => json_encode(['note' => 'Free via wizard']),
|
||||||
|
]);
|
||||||
|
|
||||||
|
TenantPackage::create([
|
||||||
|
'tenant_id' => $tenant->id,
|
||||||
|
'package_id' => $package->id,
|
||||||
|
'price' => $package->price,
|
||||||
|
'purchased_at' => now(),
|
||||||
|
'active' => true,
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
return response()->json([
|
||||||
|
'message' => 'Free package assigned successfully.',
|
||||||
|
], 201);
|
||||||
|
}
|
||||||
|
|
||||||
private function handleFreePurchase(Request $request, Package $package, $tenant): JsonResponse
|
private function handleFreePurchase(Request $request, Package $package, $tenant): JsonResponse
|
||||||
{
|
{
|
||||||
DB::transaction(function () use ($request, $package, $tenant) {
|
DB::transaction(function () use ($request, $package, $tenant) {
|
||||||
|
|||||||
@@ -123,6 +123,22 @@ class MarketingController extends Controller
|
|||||||
return $this->checkout($request, $packageId);
|
return $this->checkout($request, $packageId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Render the purchase wizard.
|
||||||
|
*/
|
||||||
|
public function purchaseWizard(Request $request, $packageId)
|
||||||
|
{
|
||||||
|
$package = Package::findOrFail($packageId)->append(['features', 'limits']);
|
||||||
|
$stripePublishableKey = config('services.stripe.key');
|
||||||
|
$privacyHtml = view('legal.datenschutz-partial', ['locale' => app()->getLocale()])->render();
|
||||||
|
|
||||||
|
return Inertia::render('marketing/PurchaseWizard', [
|
||||||
|
'package' => $package,
|
||||||
|
'stripePublishableKey' => $stripePublishableKey,
|
||||||
|
'paypalClientId' => config('services.paypal.client_id'),
|
||||||
|
'privacyHtml' => $privacyHtml,
|
||||||
|
]);
|
||||||
|
}
|
||||||
/**
|
/**
|
||||||
* Checkout for Stripe with auth metadata.
|
* Checkout for Stripe with auth metadata.
|
||||||
*/
|
*/
|
||||||
|
|||||||
465
app/Http/Controllers/PurchaseWizardController.php
Normal file
465
app/Http/Controllers/PurchaseWizardController.php
Normal file
@@ -0,0 +1,465 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Models\Package;
|
||||||
|
use App\Models\PackagePurchase;
|
||||||
|
use App\Models\Tenant;
|
||||||
|
use App\Models\TenantPackage;
|
||||||
|
use App\Models\User;
|
||||||
|
use Illuminate\Auth\Events\Registered;
|
||||||
|
use Illuminate\Http\JsonResponse;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Illuminate\Support\Facades\Auth;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
use Illuminate\Support\Facades\Hash;
|
||||||
|
use Illuminate\Support\Facades\Log;
|
||||||
|
use Illuminate\Support\Facades\Mail;
|
||||||
|
use Illuminate\Support\Str;
|
||||||
|
use Illuminate\Validation\ValidationException;
|
||||||
|
use PayPalCheckout\OrdersCaptureRequest;
|
||||||
|
use PayPalCheckout\OrdersCreateRequest;
|
||||||
|
use PayPalHttp\Client;
|
||||||
|
use PayPalHttp\HttpException;
|
||||||
|
use Stripe\PaymentIntent;
|
||||||
|
use Stripe\Stripe;
|
||||||
|
|
||||||
|
class PurchaseWizardController extends Controller
|
||||||
|
{
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
public function login(Request $request): JsonResponse
|
||||||
|
{
|
||||||
|
$data = $request->validate([
|
||||||
|
'login' => ['required', 'string'],
|
||||||
|
'password' => ['required', 'string'],
|
||||||
|
'remember' => ['nullable', 'boolean'],
|
||||||
|
]);
|
||||||
|
|
||||||
|
$credentials = ['password' => $data['password']];
|
||||||
|
|
||||||
|
if (filter_var($data['login'], FILTER_VALIDATE_EMAIL)) {
|
||||||
|
$credentials['email'] = $data['login'];
|
||||||
|
} else {
|
||||||
|
$credentials['username'] = $data['login'];
|
||||||
|
}
|
||||||
|
|
||||||
|
if (! Auth::attempt($credentials, (bool) ($data['remember'] ?? false))) {
|
||||||
|
throw ValidationException::withMessages([
|
||||||
|
'login' => __('auth.failed'),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
$request->session()->regenerate();
|
||||||
|
|
||||||
|
$user = $request->user();
|
||||||
|
|
||||||
|
return response()->json([
|
||||||
|
'status' => 'authenticated',
|
||||||
|
'user' => $this->transformUser($user),
|
||||||
|
'next_step' => 'payment',
|
||||||
|
'needs_verification' => $user?->email_verified_at === null,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function register(Request $request): JsonResponse
|
||||||
|
{
|
||||||
|
$data = $request->validate([
|
||||||
|
'username' => ['required', 'string', 'max:255', 'unique:users,username'],
|
||||||
|
'email' => ['required', 'string', 'lowercase', 'email', 'max:255', 'unique:users,email'],
|
||||||
|
'password' => ['required', 'confirmed', \Illuminate\Validation\Rules\Password::defaults()],
|
||||||
|
'first_name' => ['required', 'string', 'max:255'],
|
||||||
|
'last_name' => ['required', 'string', 'max:255'],
|
||||||
|
'address' => ['required', 'string', 'max:500'],
|
||||||
|
'phone' => ['required', 'string', 'max:20'],
|
||||||
|
'privacy_consent' => ['accepted'],
|
||||||
|
'package_id' => ['nullable', 'exists:packages,id'],
|
||||||
|
]);
|
||||||
|
|
||||||
|
$shouldAutoVerify = app()->environment(['local', 'testing']);
|
||||||
|
$package = $data['package_id'] ? Package::find($data['package_id']) : null;
|
||||||
|
|
||||||
|
DB::beginTransaction();
|
||||||
|
|
||||||
|
try {
|
||||||
|
$user = User::create([
|
||||||
|
'username' => $data['username'],
|
||||||
|
'email' => $data['email'],
|
||||||
|
'first_name' => $data['first_name'],
|
||||||
|
'last_name' => $data['last_name'],
|
||||||
|
'address' => $data['address'],
|
||||||
|
'phone' => $data['phone'],
|
||||||
|
'password' => Hash::make($data['password']),
|
||||||
|
'role' => 'user',
|
||||||
|
'pending_purchase' => $package && (($package->price ?? 0) > 0),
|
||||||
|
]);
|
||||||
|
|
||||||
|
$tenant = Tenant::create([
|
||||||
|
'user_id' => $user->id,
|
||||||
|
'name' => trim($data['first_name'].' '.$data['last_name']),
|
||||||
|
'slug' => Str::slug($data['first_name'].' '.$data['last_name'].'-'.now()->timestamp),
|
||||||
|
'email' => $data['email'],
|
||||||
|
'is_active' => true,
|
||||||
|
'is_suspended' => false,
|
||||||
|
'event_credits_balance' => 0,
|
||||||
|
'subscription_tier' => 'free',
|
||||||
|
'subscription_expires_at' => null,
|
||||||
|
'settings' => json_encode([
|
||||||
|
'branding' => [
|
||||||
|
'logo_url' => null,
|
||||||
|
'primary_color' => '#3B82F6',
|
||||||
|
'secondary_color' => '#1F2937',
|
||||||
|
'font_family' => 'Inter, sans-serif',
|
||||||
|
],
|
||||||
|
'features' => [
|
||||||
|
'photo_likes_enabled' => false,
|
||||||
|
'event_checklist' => false,
|
||||||
|
'custom_domain' => false,
|
||||||
|
'advanced_analytics' => false,
|
||||||
|
],
|
||||||
|
'custom_domain' => null,
|
||||||
|
'contact_email' => $data['email'],
|
||||||
|
'event_default_type' => 'general',
|
||||||
|
]),
|
||||||
|
]);
|
||||||
|
|
||||||
|
if ($shouldAutoVerify) {
|
||||||
|
$user->forceFill(['email_verified_at' => now()])->save();
|
||||||
|
}
|
||||||
|
|
||||||
|
$assignedPackage = null;
|
||||||
|
|
||||||
|
if ($package && (float) $package->price <= 0.0) {
|
||||||
|
$assignedPackage = $package;
|
||||||
|
|
||||||
|
TenantPackage::updateOrCreate(
|
||||||
|
[
|
||||||
|
'tenant_id' => $tenant->id,
|
||||||
|
'package_id' => $package->id,
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'price' => 0,
|
||||||
|
'active' => true,
|
||||||
|
'purchased_at' => now(),
|
||||||
|
'expires_at' => now()->addYear(),
|
||||||
|
]
|
||||||
|
);
|
||||||
|
|
||||||
|
PackagePurchase::create([
|
||||||
|
'tenant_id' => $tenant->id,
|
||||||
|
'package_id' => $package->id,
|
||||||
|
'provider_id' => 'free',
|
||||||
|
'price' => 0,
|
||||||
|
'type' => $package->type === 'endcustomer' ? 'endcustomer_event' : 'reseller_subscription',
|
||||||
|
'purchased_at' => now(),
|
||||||
|
'refunded' => false,
|
||||||
|
]);
|
||||||
|
|
||||||
|
$tenant->update(['subscription_status' => 'active']);
|
||||||
|
$user->forceFill(['pending_purchase' => false, 'role' => 'tenant_admin'])->save();
|
||||||
|
}
|
||||||
|
|
||||||
|
DB::commit();
|
||||||
|
} catch (\Throwable $e) {
|
||||||
|
DB::rollBack();
|
||||||
|
throw $e;
|
||||||
|
}
|
||||||
|
|
||||||
|
event(new Registered($user));
|
||||||
|
|
||||||
|
Auth::login($user);
|
||||||
|
$request->session()->regenerate();
|
||||||
|
|
||||||
|
Mail::to($user)->queue(new \App\Mail\Welcome($user));
|
||||||
|
|
||||||
|
$nextStep = 'payment';
|
||||||
|
|
||||||
|
if ($assignedPackage) {
|
||||||
|
$nextStep = 'success';
|
||||||
|
}
|
||||||
|
|
||||||
|
return response()->json([
|
||||||
|
'status' => 'registered',
|
||||||
|
'user' => $this->transformUser($user),
|
||||||
|
'next_step' => $nextStep,
|
||||||
|
'needs_verification' => $user->email_verified_at === null,
|
||||||
|
'package' => $package ? [
|
||||||
|
'id' => $package->id,
|
||||||
|
'name' => $package->name,
|
||||||
|
'price' => $package->price,
|
||||||
|
'type' => $package->type,
|
||||||
|
] : null,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
public function createStripeIntent(Request $request): JsonResponse
|
||||||
|
{
|
||||||
|
$data = $request->validate([
|
||||||
|
'package_id' => ['required', 'exists:packages,id'],
|
||||||
|
]);
|
||||||
|
|
||||||
|
$user = $request->user();
|
||||||
|
if (! $user) {
|
||||||
|
throw ValidationException::withMessages(['auth' => __('auth.login')]);
|
||||||
|
}
|
||||||
|
|
||||||
|
$tenant = $user->tenant;
|
||||||
|
if (! $tenant) {
|
||||||
|
throw ValidationException::withMessages(['tenant' => 'Tenant not found']);
|
||||||
|
}
|
||||||
|
|
||||||
|
$package = Package::findOrFail($data['package_id']);
|
||||||
|
if ($package->price <= 0) {
|
||||||
|
throw ValidationException::withMessages(['package_id' => 'Stripe payment is not required for this package.']);
|
||||||
|
}
|
||||||
|
|
||||||
|
Stripe::setApiKey(config('services.stripe.secret'));
|
||||||
|
|
||||||
|
$intent = PaymentIntent::create([
|
||||||
|
'amount' => (int) round($package->price * 100),
|
||||||
|
'currency' => 'eur',
|
||||||
|
'metadata' => [
|
||||||
|
'user_id' => $user->id,
|
||||||
|
'tenant_id' => $tenant->id,
|
||||||
|
'package_id' => $package->id,
|
||||||
|
'package_type' => $package->type,
|
||||||
|
],
|
||||||
|
'automatic_payment_methods' => ['enabled' => true],
|
||||||
|
]);
|
||||||
|
|
||||||
|
return response()->json([
|
||||||
|
'client_secret' => $intent->client_secret,
|
||||||
|
'payment_intent_id' => $intent->id,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function completeStripe(Request $request): JsonResponse
|
||||||
|
{
|
||||||
|
$data = $request->validate([
|
||||||
|
'package_id' => ['required', 'exists:packages,id'],
|
||||||
|
'payment_intent_id' => ['required', 'string'],
|
||||||
|
]);
|
||||||
|
|
||||||
|
$user = $request->user();
|
||||||
|
if (! $user) {
|
||||||
|
throw ValidationException::withMessages(['auth' => __('auth.login')]);
|
||||||
|
}
|
||||||
|
|
||||||
|
$package = Package::findOrFail($data['package_id']);
|
||||||
|
$tenant = $this->resolveTenant($user->id);
|
||||||
|
|
||||||
|
Stripe::setApiKey(config('services.stripe.secret'));
|
||||||
|
$intent = PaymentIntent::retrieve($data['payment_intent_id']);
|
||||||
|
|
||||||
|
if ($intent->status !== 'succeeded') {
|
||||||
|
throw ValidationException::withMessages(['payment' => 'The payment is not completed.']);
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->finalizePurchase($tenant, $package, 'stripe', [
|
||||||
|
'payment_intent' => $intent->id,
|
||||||
|
]);
|
||||||
|
|
||||||
|
return response()->json(['status' => 'completed']);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function createPaypalOrder(Request $request): JsonResponse
|
||||||
|
{
|
||||||
|
$data = $request->validate([
|
||||||
|
'package_id' => ['required', 'exists:packages,id'],
|
||||||
|
]);
|
||||||
|
|
||||||
|
$user = $request->user();
|
||||||
|
if (! $user) {
|
||||||
|
throw ValidationException::withMessages(['auth' => __('auth.login')]);
|
||||||
|
}
|
||||||
|
|
||||||
|
$tenant = $this->resolveTenant($user->id);
|
||||||
|
$package = Package::findOrFail($data['package_id']);
|
||||||
|
if ($package->price <= 0) {
|
||||||
|
throw ValidationException::withMessages(['package_id' => 'PayPal payment is not required for this package.']);
|
||||||
|
}
|
||||||
|
|
||||||
|
$client = $this->makePaypalClient();
|
||||||
|
$orders = $client->orders();
|
||||||
|
|
||||||
|
$createRequest = new OrdersCreateRequest();
|
||||||
|
$createRequest->prefer('return=representation');
|
||||||
|
$createRequest->body = [
|
||||||
|
'intent' => 'CAPTURE',
|
||||||
|
'purchase_units' => [[
|
||||||
|
'amount' => [
|
||||||
|
'currency_code' => 'EUR',
|
||||||
|
'value' => number_format($package->price, 2, '.', ''),
|
||||||
|
],
|
||||||
|
'description' => 'Package: '.$package->name,
|
||||||
|
'custom_id' => json_encode([
|
||||||
|
'user_id' => $user->id,
|
||||||
|
'tenant_id' => $tenant->id,
|
||||||
|
'package_id' => $package->id,
|
||||||
|
'package_type' => $package->type,
|
||||||
|
]),
|
||||||
|
]],
|
||||||
|
];
|
||||||
|
|
||||||
|
try {
|
||||||
|
$response = $orders->createOrder($createRequest);
|
||||||
|
$order = $response->result;
|
||||||
|
|
||||||
|
return response()->json([
|
||||||
|
'order_id' => $order->id,
|
||||||
|
'status' => $order->status ?? 'CREATED',
|
||||||
|
]);
|
||||||
|
} catch (HttpException $exception) {
|
||||||
|
Log::error('PayPal order creation failed', [
|
||||||
|
'message' => $exception->getMessage(),
|
||||||
|
'status_code' => $exception->statusCode ?? null,
|
||||||
|
]);
|
||||||
|
|
||||||
|
return response()->json(['error' => 'Unable to create PayPal order.'], 422);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public function capturePaypalOrder(Request $request): JsonResponse
|
||||||
|
{
|
||||||
|
$data = $request->validate([
|
||||||
|
'order_id' => ['required', 'string'],
|
||||||
|
'package_id' => ['required', 'exists:packages,id'],
|
||||||
|
]);
|
||||||
|
|
||||||
|
$user = $request->user();
|
||||||
|
if (! $user) {
|
||||||
|
throw ValidationException::withMessages(['auth' => __('auth.login')]);
|
||||||
|
}
|
||||||
|
|
||||||
|
$package = Package::findOrFail($data['package_id']);
|
||||||
|
$tenant = $this->resolveTenant($user->id);
|
||||||
|
|
||||||
|
$client = $this->makePaypalClient();
|
||||||
|
$orders = $client->orders();
|
||||||
|
|
||||||
|
$captureRequest = new OrdersCaptureRequest($data['order_id']);
|
||||||
|
$captureRequest->prefer('return=representation');
|
||||||
|
|
||||||
|
try {
|
||||||
|
$response = $orders->captureOrder($captureRequest);
|
||||||
|
$capture = $response->result;
|
||||||
|
|
||||||
|
if (($capture->status ?? null) !== 'COMPLETED') {
|
||||||
|
return response()->json(['error' => 'Capture incomplete.'], 422);
|
||||||
|
}
|
||||||
|
|
||||||
|
$customId = $capture->purchaseUnits[0]->customId ?? null;
|
||||||
|
if ($customId) {
|
||||||
|
$metadata = json_decode($customId, true);
|
||||||
|
|
||||||
|
if (($metadata['package_id'] ?? null) !== $package->id || ($metadata['tenant_id'] ?? null) !== $tenant->id) {
|
||||||
|
return response()->json(['error' => 'Order metadata mismatch.'], 422);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$this->finalizePurchase($tenant, $package, 'paypal', [
|
||||||
|
'order_id' => $data['order_id'],
|
||||||
|
'capture_status' => $capture->status ?? null,
|
||||||
|
]);
|
||||||
|
|
||||||
|
return response()->json([
|
||||||
|
'status' => 'captured',
|
||||||
|
]);
|
||||||
|
} catch (HttpException $exception) {
|
||||||
|
Log::error('PayPal capture failed', [
|
||||||
|
'message' => $exception->getMessage(),
|
||||||
|
'status_code' => $exception->statusCode ?? null,
|
||||||
|
]);
|
||||||
|
|
||||||
|
return response()->json(['error' => 'Unable to capture PayPal order.'], 422);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public function assignFreePackage(Request $request): JsonResponse
|
||||||
|
{
|
||||||
|
$data = $request->validate([
|
||||||
|
'package_id' => ['required', 'exists:packages,id'],
|
||||||
|
]);
|
||||||
|
|
||||||
|
$user = $request->user();
|
||||||
|
if (! $user) {
|
||||||
|
throw ValidationException::withMessages(['auth' => __('auth.login')]);
|
||||||
|
}
|
||||||
|
|
||||||
|
$package = Package::findOrFail($data['package_id']);
|
||||||
|
if ($package->price > 0) {
|
||||||
|
throw ValidationException::withMessages(['package_id' => 'Package is not free.']);
|
||||||
|
}
|
||||||
|
|
||||||
|
$tenant = $this->resolveTenant($user->id);
|
||||||
|
$this->finalizePurchase($tenant, $package, 'free_wizard');
|
||||||
|
|
||||||
|
return response()->json(['status' => 'assigned']);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function resolveTenant(int $userId): Tenant
|
||||||
|
{
|
||||||
|
$tenant = Tenant::where('user_id', $userId)->first();
|
||||||
|
|
||||||
|
if (! $tenant) {
|
||||||
|
throw ValidationException::withMessages(['tenant' => 'Tenant not found']);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $tenant;
|
||||||
|
}
|
||||||
|
|
||||||
|
private function finalizePurchase(Tenant $tenant, Package $package, string $providerId, array $metadata = []): void
|
||||||
|
{
|
||||||
|
TenantPackage::updateOrCreate(
|
||||||
|
[
|
||||||
|
'tenant_id' => $tenant->id,
|
||||||
|
'package_id' => $package->id,
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'price' => $package->price,
|
||||||
|
'active' => true,
|
||||||
|
'purchased_at' => now(),
|
||||||
|
'expires_at' => now()->addYear(),
|
||||||
|
]
|
||||||
|
);
|
||||||
|
|
||||||
|
PackagePurchase::create([
|
||||||
|
'tenant_id' => $tenant->id,
|
||||||
|
'package_id' => $package->id,
|
||||||
|
'provider_id' => $providerId,
|
||||||
|
'price' => $package->price,
|
||||||
|
'type' => $package->type === 'endcustomer' ? 'endcustomer_event' : 'reseller_subscription',
|
||||||
|
'purchased_at' => now(),
|
||||||
|
'metadata' => $metadata ? json_encode($metadata) : null,
|
||||||
|
'refunded' => false,
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function makePaypalClient(): Client
|
||||||
|
{
|
||||||
|
return Client::create([
|
||||||
|
'clientId' => config('services.paypal.client_id'),
|
||||||
|
'clientSecret' => config('services.paypal.secret'),
|
||||||
|
'environment' => config('services.paypal.sandbox', true) ? 'sandbox' : 'live',
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function transformUser(?User $user): array
|
||||||
|
{
|
||||||
|
if (! $user) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
return [
|
||||||
|
'id' => $user->id,
|
||||||
|
'email' => $user->email,
|
||||||
|
'name' => trim(($user->first_name ?? '').' '.($user->last_name ?? '')) ?: $user->username,
|
||||||
|
'pending_purchase' => (bool) $user->pending_purchase,
|
||||||
|
'email_verified' => (bool) $user->email_verified_at,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -66,5 +66,6 @@ class Kernel extends HttpKernel
|
|||||||
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
|
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
|
||||||
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
|
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
|
||||||
'locale' => \App\Http\Middleware\SetLocale::class,
|
'locale' => \App\Http\Middleware\SetLocale::class,
|
||||||
|
'stripe.csp' => \App\Http\Middleware\StripeCSP::class,
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
160
app/Http/Middleware/StripeCSP.php
Normal file
160
app/Http/Middleware/StripeCSP.php
Normal file
@@ -0,0 +1,160 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Middleware;
|
||||||
|
|
||||||
|
use Closure;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
use Symfony\Component\HttpFoundation\Response;
|
||||||
|
|
||||||
|
class StripeCSP
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Apply a CSP that allows Stripe and PayPal assets on the purchase wizard.
|
||||||
|
*/
|
||||||
|
public function handle(Request $request, Closure $next): Response
|
||||||
|
{
|
||||||
|
$response = $next($request);
|
||||||
|
|
||||||
|
$isLocal = app()->environment('local');
|
||||||
|
|
||||||
|
$scriptSrc = [
|
||||||
|
"'self'",
|
||||||
|
"'unsafe-inline'",
|
||||||
|
'https://js.stripe.com',
|
||||||
|
'https://js.stripe.network',
|
||||||
|
'https://m.stripe.network',
|
||||||
|
'https://*.stripe.com',
|
||||||
|
'https://*.stripe.network',
|
||||||
|
'https://www.paypal.com',
|
||||||
|
'https://*.paypal.com',
|
||||||
|
'https://www.paypalobjects.com',
|
||||||
|
'https://*.paypalobjects.com',
|
||||||
|
];
|
||||||
|
|
||||||
|
$styleSrc = [
|
||||||
|
"'self'",
|
||||||
|
"'unsafe-inline'",
|
||||||
|
'data:',
|
||||||
|
'https:',
|
||||||
|
'https://*.stripe.com',
|
||||||
|
'https://*.stripe.network',
|
||||||
|
'https://www.paypal.com',
|
||||||
|
'https://*.paypal.com',
|
||||||
|
'https://www.paypalobjects.com',
|
||||||
|
'https://*.paypalobjects.com',
|
||||||
|
];
|
||||||
|
|
||||||
|
$imgSrc = [
|
||||||
|
"'self'",
|
||||||
|
'data:',
|
||||||
|
'https:',
|
||||||
|
'blob:',
|
||||||
|
'https://*.stripe.com',
|
||||||
|
'https://*.stripe.network',
|
||||||
|
'https://q.stripe.com',
|
||||||
|
'https://r.stripe.com',
|
||||||
|
'https://www.paypal.com',
|
||||||
|
'https://*.paypal.com',
|
||||||
|
'https://www.paypalobjects.com',
|
||||||
|
'https://*.paypalobjects.com',
|
||||||
|
];
|
||||||
|
|
||||||
|
$fontSrc = [
|
||||||
|
"'self'",
|
||||||
|
'data:',
|
||||||
|
'https:',
|
||||||
|
'https://*.stripe.com',
|
||||||
|
'https://*.stripe.network',
|
||||||
|
'https://www.paypalobjects.com',
|
||||||
|
'https://*.paypalobjects.com',
|
||||||
|
];
|
||||||
|
|
||||||
|
$connectSrc = [
|
||||||
|
"'self'",
|
||||||
|
'https://api.stripe.com',
|
||||||
|
'https://api.stripe.network',
|
||||||
|
'https://js.stripe.com',
|
||||||
|
'https://m.stripe.com',
|
||||||
|
'https://m.stripe.network',
|
||||||
|
'https://connect.stripe.com',
|
||||||
|
'https://*.stripe.com',
|
||||||
|
'https://*.stripe.network',
|
||||||
|
'https://r.stripe.com',
|
||||||
|
'https://q.stripe.com',
|
||||||
|
'https://www.paypal.com',
|
||||||
|
'https://*.paypal.com',
|
||||||
|
'https://www.paypalobjects.com',
|
||||||
|
'https://*.paypalobjects.com',
|
||||||
|
'wss://*.stripe.network',
|
||||||
|
];
|
||||||
|
|
||||||
|
$mediaSrc = [
|
||||||
|
"'self'",
|
||||||
|
'data:',
|
||||||
|
'blob:',
|
||||||
|
'https:',
|
||||||
|
'https://js.stripe.com',
|
||||||
|
'https://*.stripe.com',
|
||||||
|
'https://*.stripe.network',
|
||||||
|
'https://m.stripe.network',
|
||||||
|
'https://www.paypal.com',
|
||||||
|
'https://*.paypal.com',
|
||||||
|
'https://www.paypalobjects.com',
|
||||||
|
'https://*.paypalobjects.com',
|
||||||
|
];
|
||||||
|
|
||||||
|
$frameSrc = [
|
||||||
|
"'self'",
|
||||||
|
'https://js.stripe.com',
|
||||||
|
'https://*.stripe.com',
|
||||||
|
'https://hooks.stripe.com',
|
||||||
|
'https://www.paypal.com',
|
||||||
|
'https://*.paypal.com',
|
||||||
|
];
|
||||||
|
|
||||||
|
$workerSrc = [
|
||||||
|
"'self'",
|
||||||
|
'blob:',
|
||||||
|
'https://js.stripe.com',
|
||||||
|
'https://*.stripe.com',
|
||||||
|
'https://*.stripe.network',
|
||||||
|
'https://m.stripe.network',
|
||||||
|
'https://www.paypal.com',
|
||||||
|
'https://*.paypal.com',
|
||||||
|
];
|
||||||
|
|
||||||
|
if ($isLocal) {
|
||||||
|
$devHost = 'http://localhost:5173';
|
||||||
|
|
||||||
|
$scriptSrc[] = $devHost;
|
||||||
|
$styleSrc[] = $devHost;
|
||||||
|
$imgSrc[] = $devHost;
|
||||||
|
$fontSrc[] = $devHost;
|
||||||
|
$connectSrc[] = $devHost;
|
||||||
|
$connectSrc[] = 'ws://localhost:5173';
|
||||||
|
$mediaSrc[] = $devHost;
|
||||||
|
$frameSrc[] = $devHost;
|
||||||
|
$workerSrc[] = $devHost;
|
||||||
|
}
|
||||||
|
|
||||||
|
$directives = [
|
||||||
|
"default-src 'self'",
|
||||||
|
'script-src ' . implode(' ', $scriptSrc),
|
||||||
|
'style-src ' . implode(' ', $styleSrc),
|
||||||
|
'img-src ' . implode(' ', $imgSrc),
|
||||||
|
'font-src ' . implode(' ', $fontSrc),
|
||||||
|
'connect-src ' . implode(' ', $connectSrc),
|
||||||
|
'media-src ' . implode(' ', $mediaSrc),
|
||||||
|
'frame-src ' . implode(' ', $frameSrc),
|
||||||
|
'worker-src ' . implode(' ', $workerSrc),
|
||||||
|
'child-src ' . implode(' ', $frameSrc),
|
||||||
|
"object-src 'none'",
|
||||||
|
"base-uri 'self'",
|
||||||
|
"form-action 'self'",
|
||||||
|
];
|
||||||
|
|
||||||
|
$response->headers->set('Content-Security-Policy', implode('; ', $directives) . ';');
|
||||||
|
|
||||||
|
return $response;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -28,3 +28,58 @@ Guest Polling (no WebSockets in v1)
|
|||||||
|
|
||||||
Webhooks
|
Webhooks
|
||||||
- Payment provider events, media pipeline status, and deletion callbacks. All signed with shared secret per provider.
|
- Payment provider events, media pipeline status, and deletion callbacks. All signed with shared secret per provider.
|
||||||
|
|
||||||
|
## Purchase Wizard Endpoints (Marketing Flow)
|
||||||
|
|
||||||
|
These endpoints support the frontend purchase wizard for package selection, authentication, and payment. They are web routes under `/purchase/` (not `/api/v1`), designed for Inertia.js integration with JSON responses for AJAX/fetch calls. No tenant middleware for auth steps (pre-tenant creation); auth required for payment.
|
||||||
|
|
||||||
|
### Flow Overview
|
||||||
|
1. **Package Selection**: User selects package via marketing page; redirects to wizard with package ID.
|
||||||
|
2. **Auth (Login/Register)**: Handle user creation/login; creates tenant if registering. Returns user data and next_step ('payment' or 'success' for free packages).
|
||||||
|
3. **Payment**: Create intent/order, complete via provider callback, finalize purchase (assign package, update tenant).
|
||||||
|
4. **Success**: Redirect to success page; email welcome if new user.
|
||||||
|
|
||||||
|
Error Handling:
|
||||||
|
- 422 Validation: `{ errors: { field: ['message'] }, message: 'Summary' }` – display in forms without reload.
|
||||||
|
- 401/403: `{ error: 'Auth required' }` – show login prompt.
|
||||||
|
- 500/Other: `{ error: 'Server error' }` – generic alert, log trace_id.
|
||||||
|
- Non-JSON (e.g., 404): Frontend catches "unexpected end of data" and shows "Endpoint not found" or retry.
|
||||||
|
|
||||||
|
All responses: JSON only for AJAX; CSRF-protected.
|
||||||
|
|
||||||
|
### Endpoints
|
||||||
|
|
||||||
|
- **POST /purchase/auth/login**
|
||||||
|
- Body: `{ login: string (email/username), password: string, remember?: boolean }`
|
||||||
|
- Response (200): `{ status: 'authenticated', user: { id, email, name, pending_purchase, email_verified }, next_step: 'payment', needs_verification: boolean }`
|
||||||
|
- Errors: 422 `{ errors: { login: ['Invalid credentials'] } }`
|
||||||
|
|
||||||
|
- **POST /purchase/auth/register**
|
||||||
|
- Body: `{ username, email, password, password_confirmation, first_name, last_name, address, phone, privacy_consent: boolean, package_id?: number }`
|
||||||
|
- Response (200): `{ status: 'registered', user: { ... }, next_step: 'payment'|'success', needs_verification: boolean, package?: { id, name, price, type } }`
|
||||||
|
- Errors: 422 `{ errors: { email: ['Taken'], password: ['Too weak'] } }`; creates tenant/user on success.
|
||||||
|
|
||||||
|
- **POST /purchase/stripe/intent** (auth required)
|
||||||
|
- Body: `{ package_id: number }`
|
||||||
|
- Response (200): `{ client_secret: string, payment_intent_id: string }`
|
||||||
|
- Errors: 422 `{ errors: { package_id: ['Invalid'] } }`
|
||||||
|
|
||||||
|
- **POST /purchase/stripe/complete** (auth required)
|
||||||
|
- Body: `{ package_id: number, payment_intent_id: string }`
|
||||||
|
- Response (200): `{ status: 'completed' }`
|
||||||
|
- Errors: 422 `{ errors: { payment: ['Not succeeded'] } }` – finalizes purchase.
|
||||||
|
|
||||||
|
- **POST /purchase/paypal/order** (auth required)
|
||||||
|
- Body: `{ package_id: number }`
|
||||||
|
- Response (200): `{ order_id: string, status: 'CREATED' }`
|
||||||
|
- Errors: 422 `{ error: 'Order creation failed' }`
|
||||||
|
|
||||||
|
- **POST /purchase/paypal/capture** (auth required)
|
||||||
|
- Body: `{ order_id: string, package_id: number }`
|
||||||
|
- Response (200): `{ status: 'captured' }`
|
||||||
|
- Errors: 422 `{ error: 'Capture incomplete' }` – finalizes purchase.
|
||||||
|
|
||||||
|
- **POST /purchase/free** (auth required)
|
||||||
|
- Body: `{ package_id: number }`
|
||||||
|
- Response (200): `{ status: 'assigned' }`
|
||||||
|
- Errors: 422 `{ errors: { package_id: ['Not free'] } }` – assigns for zero-price packages.
|
||||||
|
|||||||
31
package-lock.json
generated
31
package-lock.json
generated
@@ -25,6 +25,8 @@
|
|||||||
"@radix-ui/react-toggle": "^1.1.2",
|
"@radix-ui/react-toggle": "^1.1.2",
|
||||||
"@radix-ui/react-toggle-group": "^1.1.2",
|
"@radix-ui/react-toggle-group": "^1.1.2",
|
||||||
"@radix-ui/react-tooltip": "^1.1.8",
|
"@radix-ui/react-tooltip": "^1.1.8",
|
||||||
|
"@stripe/react-stripe-js": "^5.0.0",
|
||||||
|
"@stripe/stripe-js": "^8.0.0",
|
||||||
"@tailwindcss/vite": "^4.1.11",
|
"@tailwindcss/vite": "^4.1.11",
|
||||||
"@tanstack/react-query": "^5.90.2",
|
"@tanstack/react-query": "^5.90.2",
|
||||||
"@types/react": "^19.0.3",
|
"@types/react": "^19.0.3",
|
||||||
@@ -3297,6 +3299,29 @@
|
|||||||
"url": "https://github.com/sponsors/sindresorhus"
|
"url": "https://github.com/sponsors/sindresorhus"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@stripe/react-stripe-js": {
|
||||||
|
"version": "5.0.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@stripe/react-stripe-js/-/react-stripe-js-5.0.0.tgz",
|
||||||
|
"integrity": "sha512-SUv97BPNxV4VxTRj+QbkHsZMGVMREBTuO38wuSIPCXyKRSsy/IzzqKEkxRUympLD9TXRHIJwZNhCzhOdx0mVTw==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"prop-types": "^15.7.2"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"@stripe/stripe-js": ">=8.0.0 <9.0.0",
|
||||||
|
"react": ">=16.8.0 <20.0.0",
|
||||||
|
"react-dom": ">=16.8.0 <20.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@stripe/stripe-js": {
|
||||||
|
"version": "8.0.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@stripe/stripe-js/-/stripe-js-8.0.0.tgz",
|
||||||
|
"integrity": "sha512-dLvD55KT1cBmrqzgYRgY42qNcw6zW4HS5oRZs0xRvHw9gBWig5yDnWNop/E+/t2JK+OZO30zsnupVBN2MqW2mg==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=12.16"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@swc/helpers": {
|
"node_modules/@swc/helpers": {
|
||||||
"version": "0.5.17",
|
"version": "0.5.17",
|
||||||
"resolved": "https://registry.npmjs.org/@swc/helpers/-/helpers-0.5.17.tgz",
|
"resolved": "https://registry.npmjs.org/@swc/helpers/-/helpers-0.5.17.tgz",
|
||||||
@@ -8000,7 +8025,6 @@
|
|||||||
"version": "1.4.0",
|
"version": "1.4.0",
|
||||||
"resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz",
|
"resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz",
|
||||||
"integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==",
|
"integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==",
|
||||||
"dev": true,
|
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"js-tokens": "^3.0.0 || ^4.0.0"
|
"js-tokens": "^3.0.0 || ^4.0.0"
|
||||||
},
|
},
|
||||||
@@ -8387,7 +8411,6 @@
|
|||||||
"version": "4.1.1",
|
"version": "4.1.1",
|
||||||
"resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
|
"resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
|
||||||
"integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==",
|
"integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==",
|
||||||
"dev": true,
|
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=0.10.0"
|
"node": ">=0.10.0"
|
||||||
}
|
}
|
||||||
@@ -9086,7 +9109,6 @@
|
|||||||
"version": "15.8.1",
|
"version": "15.8.1",
|
||||||
"resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz",
|
"resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz",
|
||||||
"integrity": "sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==",
|
"integrity": "sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==",
|
||||||
"dev": true,
|
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"loose-envify": "^1.4.0",
|
"loose-envify": "^1.4.0",
|
||||||
"object-assign": "^4.1.1",
|
"object-assign": "^4.1.1",
|
||||||
@@ -9246,8 +9268,7 @@
|
|||||||
"node_modules/react-is": {
|
"node_modules/react-is": {
|
||||||
"version": "16.13.1",
|
"version": "16.13.1",
|
||||||
"resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz",
|
"resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz",
|
||||||
"integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==",
|
"integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ=="
|
||||||
"dev": true
|
|
||||||
},
|
},
|
||||||
"node_modules/react-refresh": {
|
"node_modules/react-refresh": {
|
||||||
"version": "0.17.0",
|
"version": "0.17.0",
|
||||||
|
|||||||
@@ -49,6 +49,8 @@
|
|||||||
"@radix-ui/react-toggle": "^1.1.2",
|
"@radix-ui/react-toggle": "^1.1.2",
|
||||||
"@radix-ui/react-toggle-group": "^1.1.2",
|
"@radix-ui/react-toggle-group": "^1.1.2",
|
||||||
"@radix-ui/react-tooltip": "^1.1.8",
|
"@radix-ui/react-tooltip": "^1.1.8",
|
||||||
|
"@stripe/react-stripe-js": "^5.0.0",
|
||||||
|
"@stripe/stripe-js": "^8.0.0",
|
||||||
"@tailwindcss/vite": "^4.1.11",
|
"@tailwindcss/vite": "^4.1.11",
|
||||||
"@tanstack/react-query": "^5.90.2",
|
"@tanstack/react-query": "^5.90.2",
|
||||||
"@types/react": "^19.0.3",
|
"@types/react": "^19.0.3",
|
||||||
|
|||||||
60
resources/js/components/ui/Steps.tsx
Normal file
60
resources/js/components/ui/Steps.tsx
Normal file
@@ -0,0 +1,60 @@
|
|||||||
|
import * as React from "react"
|
||||||
|
import { ChevronLeft, ChevronRight } from "lucide-react"
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
import { Button } from "@/components/ui/button"
|
||||||
|
|
||||||
|
interface Step {
|
||||||
|
id: string
|
||||||
|
title: string
|
||||||
|
description: string
|
||||||
|
}
|
||||||
|
|
||||||
|
interface StepsProps {
|
||||||
|
steps: Step[]
|
||||||
|
currentStep: number
|
||||||
|
className?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
const Steps = React.forwardRef<HTMLDivElement, StepsProps>(
|
||||||
|
({ steps, currentStep, className }, ref) => {
|
||||||
|
return (
|
||||||
|
<div ref={ref} className={cn("flex items-center justify-between w-full mb-6", className)}>
|
||||||
|
{steps.map((step, index) => (
|
||||||
|
<div key={step.id} className="flex-1 flex flex-col items-center">
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
"w-10 h-10 rounded-full flex items-center justify-center text-sm font-medium border-2 transition-colors",
|
||||||
|
index <= currentStep
|
||||||
|
? "bg-blue-500 text-white border-blue-500"
|
||||||
|
: "bg-gray-200 text-gray-500 border-gray-200 dark:bg-gray-700 dark:text-gray-400 dark:border-gray-700"
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{index + 1}
|
||||||
|
</div>
|
||||||
|
<div className="mt-2 text-xs font-medium text-center">
|
||||||
|
<p className={cn(index === currentStep ? "text-blue-600" : "text-gray-500")}>
|
||||||
|
{step.title}
|
||||||
|
</p>
|
||||||
|
<p className="text-xs text-gray-400">{step.description}</p>
|
||||||
|
</div>
|
||||||
|
{index < steps.length - 1 && (
|
||||||
|
<div className="flex-1 h-px bg-gray-200 dark:bg-gray-700 mx-2">
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
"h-full transition-all duration-300",
|
||||||
|
index < currentStep ? "bg-blue-500" : "bg-transparent"
|
||||||
|
)}
|
||||||
|
style={{ width: index < currentStep ? '100%' : '0%' }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
)
|
||||||
|
Steps.displayName = "Steps"
|
||||||
|
|
||||||
|
export { Steps }
|
||||||
203
resources/js/pages/auth/LoginForm.tsx
Normal file
203
resources/js/pages/auth/LoginForm.tsx
Normal file
@@ -0,0 +1,203 @@
|
|||||||
|
|
||||||
|
import React, { useEffect, useMemo, useState } from 'react';
|
||||||
|
import { useForm } from '@inertiajs/react';
|
||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
import { LoaderCircle } from 'lucide-react';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { Checkbox } from '@/components/ui/checkbox';
|
||||||
|
import { Input } from '@/components/ui/input';
|
||||||
|
import { Label } from '@/components/ui/label';
|
||||||
|
import InputError from '@/components/input-error';
|
||||||
|
import TextLink from '@/components/text-link';
|
||||||
|
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||||
|
|
||||||
|
interface LoginFormProps {
|
||||||
|
onSuccess?: (payload: any) => void;
|
||||||
|
canResetPassword?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
const getCsrfToken = () =>
|
||||||
|
(document.querySelector('meta[name="csrf-token"]') as HTMLMetaElement | null)?.content ?? '';
|
||||||
|
|
||||||
|
const parseJson = async (response: Response) => {
|
||||||
|
if (response.headers.get('Content-Type')?.includes('application/json')) {
|
||||||
|
const json = await response.json().catch(() => null);
|
||||||
|
if (json) return json;
|
||||||
|
}
|
||||||
|
|
||||||
|
const text = await response.text();
|
||||||
|
throw new Error(text || 'Invalid server response (unexpected end of data or non-JSON).');
|
||||||
|
};
|
||||||
|
|
||||||
|
export default function LoginForm({ onSuccess, canResetPassword = true }: LoginFormProps) {
|
||||||
|
const { t } = useTranslation('auth');
|
||||||
|
const csrfToken = useMemo(getCsrfToken, []);
|
||||||
|
|
||||||
|
const { data, setData, errors, setError, clearErrors, reset } = useForm({
|
||||||
|
login: '',
|
||||||
|
password: '',
|
||||||
|
remember: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
const [hasTriedSubmit, setHasTriedSubmit] = useState(false);
|
||||||
|
const [submitting, setSubmitting] = useState(false);
|
||||||
|
const [formError, setFormError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
|
||||||
|
event.preventDefault();
|
||||||
|
setHasTriedSubmit(true);
|
||||||
|
setSubmitting(true);
|
||||||
|
setFormError(null);
|
||||||
|
clearErrors();
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch('/purchase/auth/login', {
|
||||||
|
method: 'POST',
|
||||||
|
credentials: 'same-origin',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
Accept: 'application/json',
|
||||||
|
'X-CSRF-TOKEN': csrfToken,
|
||||||
|
'X-Requested-With': 'XMLHttpRequest',
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
login: data.login,
|
||||||
|
password: data.password,
|
||||||
|
remember: data.remember,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (response.ok) {
|
||||||
|
const payload = await parseJson(response);
|
||||||
|
reset({ login: payload?.user?.email ?? data.login, password: '', remember: false });
|
||||||
|
setHasTriedSubmit(false);
|
||||||
|
if (onSuccess) {
|
||||||
|
onSuccess(payload);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (response.status === 422) {
|
||||||
|
const body = await parseJson(response);
|
||||||
|
const validationErrors = body.errors ?? {};
|
||||||
|
let fallbackMessage: string | null = body.message ?? null;
|
||||||
|
|
||||||
|
Object.entries(validationErrors as Record<string, string | string[]>).forEach(([key, value]) => {
|
||||||
|
const message = Array.isArray(value) ? value[0] : value;
|
||||||
|
if (typeof message === 'string') {
|
||||||
|
setError(key as keyof typeof data, message);
|
||||||
|
if (!fallbackMessage) {
|
||||||
|
fallbackMessage = message;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
if (fallbackMessage) {
|
||||||
|
setFormError(fallbackMessage);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setFormError(t('login.generic_error', { defaultValue: 'Login failed. Please try again.' }));
|
||||||
|
} catch (error) {
|
||||||
|
setFormError(t('login.generic_error', { defaultValue: 'Login failed. Please try again.' }));
|
||||||
|
} finally {
|
||||||
|
setSubmitting(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!hasTriedSubmit) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const errorKeys = Object.keys(errors);
|
||||||
|
if (errorKeys.length === 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const field = document.querySelector<HTMLInputElement>(`[name="${errorKeys[0]}"]`);
|
||||||
|
|
||||||
|
if (field) {
|
||||||
|
field.scrollIntoView({ behavior: 'smooth', block: 'center' });
|
||||||
|
field.focus();
|
||||||
|
}
|
||||||
|
}, [errors, hasTriedSubmit]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<form className="flex flex-col gap-6" onSubmit={handleSubmit} noValidate>
|
||||||
|
<div className="grid gap-6">
|
||||||
|
<div className="grid gap-2">
|
||||||
|
<Label htmlFor="login">{t('login.email')}</Label>
|
||||||
|
<Input
|
||||||
|
id="login"
|
||||||
|
type="text"
|
||||||
|
name="login"
|
||||||
|
autoComplete="username"
|
||||||
|
required
|
||||||
|
autoFocus
|
||||||
|
placeholder={t('login.email_placeholder')}
|
||||||
|
value={data.login}
|
||||||
|
onChange={(event) => {
|
||||||
|
setData('login', event.target.value);
|
||||||
|
if (errors.login) {
|
||||||
|
clearErrors('login');
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<InputError message={errors.login} />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid gap-2">
|
||||||
|
<div className="flex items-center">
|
||||||
|
<Label htmlFor="password">{t('login.password')}</Label>
|
||||||
|
{canResetPassword && (
|
||||||
|
<TextLink href="/forgot-password" className="ml-auto text-sm">
|
||||||
|
{t('login.forgot')}
|
||||||
|
</TextLink>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<Input
|
||||||
|
id="password"
|
||||||
|
type="password"
|
||||||
|
name="password"
|
||||||
|
autoComplete="current-password"
|
||||||
|
required
|
||||||
|
placeholder={t('login.password_placeholder')}
|
||||||
|
value={data.password}
|
||||||
|
onChange={(event) => {
|
||||||
|
setData('password', event.target.value);
|
||||||
|
if (errors.password) {
|
||||||
|
clearErrors('password');
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<InputError message={errors.password} />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center space-x-3">
|
||||||
|
<Checkbox
|
||||||
|
id="remember"
|
||||||
|
name="remember"
|
||||||
|
checked={data.remember}
|
||||||
|
onCheckedChange={(checked) => setData('remember', Boolean(checked))}
|
||||||
|
/>
|
||||||
|
<Label htmlFor="remember">{t('login.remember')}</Label>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Button type="submit" className="w-full" disabled={submitting}>
|
||||||
|
{submitting && <LoaderCircle className="h-4 w-4 animate-spin mr-2" />}
|
||||||
|
{t('login.submit')}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{(formError || Object.keys(errors).length > 0) && (
|
||||||
|
<Alert variant="destructive">
|
||||||
|
<AlertDescription>
|
||||||
|
{formError || Object.values(errors).join(' ')}
|
||||||
|
</AlertDescription>
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
</form>
|
||||||
|
);
|
||||||
|
}
|
||||||
412
resources/js/pages/auth/RegisterForm.tsx
Normal file
412
resources/js/pages/auth/RegisterForm.tsx
Normal file
@@ -0,0 +1,412 @@
|
|||||||
|
|
||||||
|
import React, { useEffect, useMemo, useState } from 'react';
|
||||||
|
import { useForm } from '@inertiajs/react';
|
||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
import { LoaderCircle, User, Mail, Phone, Lock, MapPin } from 'lucide-react';
|
||||||
|
import { Dialog, DialogContent, DialogDescription, DialogTitle } from '@/components/ui/dialog';
|
||||||
|
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||||
|
|
||||||
|
interface RegisterFormProps {
|
||||||
|
packageId?: number;
|
||||||
|
onSuccess?: (payload: any) => void;
|
||||||
|
privacyHtml: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const getCsrfToken = () =>
|
||||||
|
(document.querySelector('meta[name="csrf-token"]') as HTMLMetaElement | null)?.content ?? '';
|
||||||
|
|
||||||
|
export default function RegisterForm({ packageId, onSuccess, privacyHtml }: RegisterFormProps) {
|
||||||
|
const { t } = useTranslation(['auth', 'common']);
|
||||||
|
const csrfToken = useMemo(getCsrfToken, []);
|
||||||
|
|
||||||
|
const { data, setData, errors, setError, clearErrors, reset } = useForm({
|
||||||
|
username: '',
|
||||||
|
email: '',
|
||||||
|
password: '',
|
||||||
|
password_confirmation: '',
|
||||||
|
first_name: '',
|
||||||
|
last_name: '',
|
||||||
|
address: '',
|
||||||
|
phone: '',
|
||||||
|
privacy_consent: false,
|
||||||
|
package_id: packageId ?? null,
|
||||||
|
});
|
||||||
|
|
||||||
|
const [privacyOpen, setPrivacyOpen] = useState(false);
|
||||||
|
const [hasTriedSubmit, setHasTriedSubmit] = useState(false);
|
||||||
|
const [submitting, setSubmitting] = useState(false);
|
||||||
|
const [formError, setFormError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setData('package_id', packageId ?? null);
|
||||||
|
}, [packageId]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!hasTriedSubmit) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const errorKeys = Object.keys(errors);
|
||||||
|
if (errorKeys.length === 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const firstError = errorKeys[0];
|
||||||
|
const field = document.querySelector<HTMLInputElement | HTMLTextAreaElement>(`[name="${firstError}"]`);
|
||||||
|
|
||||||
|
if (field) {
|
||||||
|
field.scrollIntoView({ behavior: 'smooth', block: 'center' });
|
||||||
|
field.focus();
|
||||||
|
}
|
||||||
|
}, [errors, hasTriedSubmit]);
|
||||||
|
|
||||||
|
const parseJson = async (response: Response) => {
|
||||||
|
if (response.headers.get('Content-Type')?.includes('application/json')) {
|
||||||
|
const json = await response.json().catch(() => null);
|
||||||
|
if (json) return json;
|
||||||
|
}
|
||||||
|
|
||||||
|
const text = await response.text();
|
||||||
|
throw new Error(text || 'Invalid server response (unexpected end of data or non-JSON).');
|
||||||
|
};
|
||||||
|
|
||||||
|
const submit = async (event: React.FormEvent<HTMLFormElement>) => {
|
||||||
|
event.preventDefault();
|
||||||
|
setHasTriedSubmit(true);
|
||||||
|
setSubmitting(true);
|
||||||
|
setFormError(null);
|
||||||
|
clearErrors();
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch('/purchase/auth/register', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
Accept: 'application/json',
|
||||||
|
'X-CSRF-TOKEN': csrfToken,
|
||||||
|
'X-Requested-With': 'XMLHttpRequest',
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
...data,
|
||||||
|
privacy_consent: Boolean(data.privacy_consent),
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (response.ok) {
|
||||||
|
const payload = await parseJson(response);
|
||||||
|
reset({
|
||||||
|
username: '',
|
||||||
|
email: '',
|
||||||
|
password: '',
|
||||||
|
password_confirmation: '',
|
||||||
|
first_name: '',
|
||||||
|
last_name: '',
|
||||||
|
address: '',
|
||||||
|
phone: '',
|
||||||
|
privacy_consent: false,
|
||||||
|
package_id: packageId ?? null,
|
||||||
|
});
|
||||||
|
setHasTriedSubmit(false);
|
||||||
|
if (onSuccess) {
|
||||||
|
onSuccess(payload);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (response.status === 422) {
|
||||||
|
const body = await parseJson(response);
|
||||||
|
const validationErrors = body.errors ?? {};
|
||||||
|
let fallbackMessage: string | null = body.message ?? null;
|
||||||
|
|
||||||
|
Object.entries(validationErrors).forEach(([key, value]) => {
|
||||||
|
const message = Array.isArray(value) ? value[0] : value;
|
||||||
|
if (typeof message === 'string') {
|
||||||
|
setError(key, message);
|
||||||
|
if (!fallbackMessage) {
|
||||||
|
fallbackMessage = message;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
if (fallbackMessage) {
|
||||||
|
setFormError(fallbackMessage);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setFormError(t('register.generic_error', { defaultValue: 'Registrierung fehlgeschlagen. Bitte versuche es erneut.' }));
|
||||||
|
} catch (error) {
|
||||||
|
const message = (error as Error).message || t('register.generic_error', { defaultValue: 'Registrierung fehlgeschlagen. Bitte versuche es erneut.' });
|
||||||
|
setFormError(message);
|
||||||
|
} finally {
|
||||||
|
setSubmitting(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<form className="space-y-6" onSubmit={submit} noValidate>
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||||
|
<div className="md:col-span-1">
|
||||||
|
<label htmlFor="first_name" className="block text-sm font-medium text-gray-700 mb-1">
|
||||||
|
{t('register.first_name')} {t('common:required')}
|
||||||
|
</label>
|
||||||
|
<div className="relative">
|
||||||
|
<User className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 w-5 h-5" />
|
||||||
|
<input
|
||||||
|
id="first_name"
|
||||||
|
name="first_name"
|
||||||
|
type="text"
|
||||||
|
required
|
||||||
|
value={data.first_name}
|
||||||
|
onChange={(event) => {
|
||||||
|
setData('first_name', event.target.value);
|
||||||
|
if (errors.first_name) {
|
||||||
|
clearErrors('first_name');
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
className={`block w-full pl-10 pr-3 py-3 border rounded-md shadow-sm placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-[#FFB6C1] focus:border-[#FFB6C1] sm:text-sm ${errors.first_name ? 'border-red-500' : 'border-gray-300'}`}
|
||||||
|
placeholder={t('register.first_name_placeholder')}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
{errors.first_name && <p className="text-sm text-red-600 mt-1">{errors.first_name}</p>}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="md:col-span-1">
|
||||||
|
<label htmlFor="last_name" className="block text-sm font-medium text-gray-700 mb-1">
|
||||||
|
{t('register.last_name')} {t('common:required')}
|
||||||
|
</label>
|
||||||
|
<div className="relative">
|
||||||
|
<User className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 w-5 h-5" />
|
||||||
|
<input
|
||||||
|
id="last_name"
|
||||||
|
name="last_name"
|
||||||
|
type="text"
|
||||||
|
required
|
||||||
|
value={data.last_name}
|
||||||
|
onChange={(event) => {
|
||||||
|
setData('last_name', event.target.value);
|
||||||
|
if (errors.last_name) {
|
||||||
|
clearErrors('last_name');
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
className={`block w-full pl-10 pr-3 py-3 border rounded-md shadow-sm placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-[#FFB6C1] focus:border-[#FFB6C1] sm:text-sm ${errors.last_name ? 'border-red-500' : 'border-gray-300'}`}
|
||||||
|
placeholder={t('register.last_name_placeholder')}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
{errors.last_name && <p className="text-sm text-red-600 mt-1">{errors.last_name}</p>}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="md:col-span-2">
|
||||||
|
<label htmlFor="email" className="block text-sm font-medium text-gray-700 mb-1">
|
||||||
|
{t('register.email')} {t('common:required')}
|
||||||
|
</label>
|
||||||
|
<div className="relative">
|
||||||
|
<Mail className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 w-5 h-5" />
|
||||||
|
<input
|
||||||
|
id="email"
|
||||||
|
name="email"
|
||||||
|
type="email"
|
||||||
|
required
|
||||||
|
value={data.email}
|
||||||
|
onChange={(event) => {
|
||||||
|
setData('email', event.target.value);
|
||||||
|
if (errors.email) {
|
||||||
|
clearErrors('email');
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
className={`block w-full pl-10 pr-3 py-3 border rounded-md shadow-sm placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-[#FFB6C1] focus:border-[#FFB6C1] sm:text-sm ${errors.email ? 'border-red-500' : 'border-gray-300'}`}
|
||||||
|
placeholder={t('register.email_placeholder')}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
{errors.email && <p className="text-sm text-red-600 mt-1">{errors.email}</p>}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="md:col-span-1">
|
||||||
|
<label htmlFor="username" className="block text-sm font-medium text-gray-700 mb-1">
|
||||||
|
{t('register.username')} {t('common:required')}
|
||||||
|
</label>
|
||||||
|
<div className="relative">
|
||||||
|
<User className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 w-5 h-5" />
|
||||||
|
<input
|
||||||
|
id="username"
|
||||||
|
name="username"
|
||||||
|
type="text"
|
||||||
|
required
|
||||||
|
value={data.username}
|
||||||
|
onChange={(event) => {
|
||||||
|
setData('username', event.target.value);
|
||||||
|
if (errors.username) {
|
||||||
|
clearErrors('username');
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
className={`block w-full pl-10 pr-3 py-3 border rounded-md shadow-sm placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-[#FFB6C1] focus:border-[#FFB6C1] sm:text-sm ${errors.username ? 'border-red-500' : 'border-gray-300'}`}
|
||||||
|
placeholder={t('register.username_placeholder')}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
{errors.username && <p className="text-sm text-red-600 mt-1">{errors.username}</p>}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="md:col-span-1">
|
||||||
|
<label htmlFor="phone" className="block text-sm font-medium text-gray-700 mb-1">
|
||||||
|
{t('register.phone')} {t('common:required')}
|
||||||
|
</label>
|
||||||
|
<div className="relative">
|
||||||
|
<Phone className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 w-5 h-5" />
|
||||||
|
<input
|
||||||
|
id="phone"
|
||||||
|
name="phone"
|
||||||
|
type="tel"
|
||||||
|
required
|
||||||
|
value={data.phone}
|
||||||
|
onChange={(event) => {
|
||||||
|
setData('phone', event.target.value);
|
||||||
|
if (errors.phone) {
|
||||||
|
clearErrors('phone');
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
className={`block w-full pl-10 pr-3 py-3 border rounded-md shadow-sm placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-[#FFB6C1] focus:border-[#FFB6C1] sm:text-sm ${errors.phone ? 'border-red-500' : 'border-gray-300'}`}
|
||||||
|
placeholder={t('register.phone_placeholder')}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
{errors.phone && <p className="text-sm text-red-600 mt-1">{errors.phone}</p>}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="md:col-span-2">
|
||||||
|
<label htmlFor="address" className="block text-sm font-medium text-gray-700 mb-1">
|
||||||
|
{t('register.address')} {t('common:required')}
|
||||||
|
</label>
|
||||||
|
<div className="relative">
|
||||||
|
<MapPin className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 w-5 h-5" />
|
||||||
|
<textarea
|
||||||
|
id="address"
|
||||||
|
name="address"
|
||||||
|
required
|
||||||
|
value={data.address}
|
||||||
|
onChange={(event) => {
|
||||||
|
setData('address', event.target.value);
|
||||||
|
if (errors.address) {
|
||||||
|
clearErrors('address');
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
className={`block w-full pl-10 pr-3 py-3 border rounded-md shadow-sm placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-[#FFB6C1] focus:border-[#FFB6C1] sm:text-sm ${errors.address ? 'border-red-500' : 'border-gray-300'}`}
|
||||||
|
placeholder={t('register.address_placeholder')}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
{errors.address && <p className="text-sm text-red-600 mt-1">{errors.address}</p>}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="md:col-span-1">
|
||||||
|
<label htmlFor="password" className="block text-sm font-medium text-gray-700 mb-1">
|
||||||
|
{t('register.password')} {t('common:required')}
|
||||||
|
</label>
|
||||||
|
<div className="relative">
|
||||||
|
<Lock className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 w-5 h-5" />
|
||||||
|
<input
|
||||||
|
id="password"
|
||||||
|
name="password"
|
||||||
|
type="password"
|
||||||
|
required
|
||||||
|
value={data.password}
|
||||||
|
onChange={(event) => {
|
||||||
|
setData('password', event.target.value);
|
||||||
|
if (errors.password) {
|
||||||
|
clearErrors('password');
|
||||||
|
}
|
||||||
|
if (data.password_confirmation && event.target.value === data.password_confirmation) {
|
||||||
|
clearErrors('password_confirmation');
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
className={`block w-full pl-10 pr-3 py-3 border rounded-md shadow-sm placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-[#FFB6C1] focus:border-[#FFB6C1] sm:text-sm ${errors.password ? 'border-red-500' : 'border-gray-300'}`}
|
||||||
|
placeholder={t('register.password_placeholder')}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
{errors.password && <p className="text-sm text-red-600 mt-1">{errors.password}</p>}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="md:col-span-1">
|
||||||
|
<label htmlFor="password_confirmation" className="block text-sm font-medium text-gray-700 mb-1">
|
||||||
|
{t('register.confirm_password')} {t('common:required')}
|
||||||
|
</label>
|
||||||
|
<div className="relative">
|
||||||
|
<Lock className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 w-5 h-5" />
|
||||||
|
<input
|
||||||
|
id="password_confirmation"
|
||||||
|
name="password_confirmation"
|
||||||
|
type="password"
|
||||||
|
required
|
||||||
|
value={data.password_confirmation}
|
||||||
|
onChange={(event) => {
|
||||||
|
setData('password_confirmation', event.target.value);
|
||||||
|
if (errors.password_confirmation) {
|
||||||
|
clearErrors('password_confirmation');
|
||||||
|
}
|
||||||
|
if (data.password && event.target.value === data.password) {
|
||||||
|
clearErrors('password_confirmation');
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
className={`block w-full pl-10 pr-3 py-3 border rounded-md shadow-sm placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-[#FFB6C1] focus:border-[#FFB6C1] sm:text-sm ${errors.password_confirmation ? 'border-red-500' : 'border-gray-300'}`}
|
||||||
|
placeholder={t('register.confirm_password_placeholder')}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
{errors.password_confirmation && <p className="text-sm text-red-600 mt-1">{errors.password_confirmation}</p>}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="md:col-span-2 flex items-start">
|
||||||
|
<input
|
||||||
|
id="privacy_consent"
|
||||||
|
name="privacy_consent"
|
||||||
|
type="checkbox"
|
||||||
|
required
|
||||||
|
checked={data.privacy_consent}
|
||||||
|
onChange={(event) => {
|
||||||
|
setData('privacy_consent', event.target.checked);
|
||||||
|
if (event.target.checked && errors.privacy_consent) {
|
||||||
|
clearErrors('privacy_consent');
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
className="h-4 w-4 text-[#FFB6C1] focus:ring-[#FFB6C1] border-gray-300 rounded"
|
||||||
|
/>
|
||||||
|
<label htmlFor="privacy_consent" className="ml-2 block text-sm text-gray-900">
|
||||||
|
{t('register.privacy_consent')}{' '}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setPrivacyOpen(true)}
|
||||||
|
className="text-[#FFB6C1] hover:underline inline bg-transparent border-none cursor-pointer p-0 font-medium"
|
||||||
|
>
|
||||||
|
{t('register.privacy_policy')}
|
||||||
|
</button>.
|
||||||
|
</label>
|
||||||
|
{errors.privacy_consent && <p className="mt-2 text-sm text-red-600">{errors.privacy_consent}</p>}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{(formError || Object.keys(errors).length > 0) && (
|
||||||
|
<Alert>
|
||||||
|
{formError && <AlertDescription>{formError}</AlertDescription>}
|
||||||
|
{Object.keys(errors).length > 0 && !formError && (
|
||||||
|
<AlertDescription>{Object.values(errors).join(' ')}</AlertDescription>
|
||||||
|
)}
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
disabled={submitting}
|
||||||
|
className="group relative w-full flex justify-center py-2 px-4 border border-transparent text-sm font-medium rounded-md text-white bg-[#FFB6C1] hover:bg-[#FF69B4] focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-[#FFB6C1] transition duration-300 disabled:opacity-50"
|
||||||
|
>
|
||||||
|
{submitting && <LoaderCircle className="h-4 w-4 animate-spin mr-2" />}
|
||||||
|
{t('register.submit')}
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<Dialog open={privacyOpen} onOpenChange={setPrivacyOpen}>
|
||||||
|
<DialogContent className="max-w-4xl max-h-[80vh] overflow-y-auto p-0">
|
||||||
|
<DialogTitle className="sr-only">Datenschutzerkl<EFBFBD>rung</DialogTitle>
|
||||||
|
<DialogDescription className="sr-only">Lesen Sie unsere Datenschutzerkl<EFBFBD>rung.</DialogDescription>
|
||||||
|
<div className="p-6">
|
||||||
|
<div dangerouslySetInnerHTML={{ __html: privacyHtml }} />
|
||||||
|
</div>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
</form>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -2,7 +2,7 @@ import React, { useEffect, useState } from 'react';
|
|||||||
import { useForm } from '@inertiajs/react';
|
import { useForm } from '@inertiajs/react';
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
import { LoaderCircle, User, Mail, Phone, Lock, Home, MapPin } from 'lucide-react';
|
import { LoaderCircle, User, Mail, Phone, Lock, Home, MapPin } from 'lucide-react';
|
||||||
import { Dialog, DialogContent } from '@/components/ui/dialog';
|
import { Dialog, DialogContent, DialogTitle, DialogDescription } from '@/components/ui/dialog';
|
||||||
|
|
||||||
interface RegisterProps {
|
interface RegisterProps {
|
||||||
package?: {
|
package?: {
|
||||||
@@ -11,7 +11,7 @@ interface RegisterProps {
|
|||||||
description: string;
|
description: string;
|
||||||
price: number;
|
price: number;
|
||||||
} | null;
|
} | null;
|
||||||
privacyHtml: string;
|
privacyHtml?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
import MarketingLayout from '@/layouts/marketing/MarketingLayout';
|
import MarketingLayout from '@/layouts/marketing/MarketingLayout';
|
||||||
@@ -356,8 +356,14 @@ export default function Register({ package: initialPackage, privacyHtml }: Regis
|
|||||||
|
|
||||||
<Dialog open={privacyOpen} onOpenChange={setPrivacyOpen}>
|
<Dialog open={privacyOpen} onOpenChange={setPrivacyOpen}>
|
||||||
<DialogContent className="max-w-4xl max-h-[80vh] overflow-y-auto p-0">
|
<DialogContent className="max-w-4xl max-h-[80vh] overflow-y-auto p-0">
|
||||||
|
<DialogTitle className="sr-only">Datenschutzerklärung</DialogTitle>
|
||||||
|
<DialogDescription className="sr-only">Lesen Sie unsere Datenschutzerklärung.</DialogDescription>
|
||||||
<div className="p-6">
|
<div className="p-6">
|
||||||
<div dangerouslySetInnerHTML={{ __html: privacyHtml }} />
|
{privacyHtml ? (
|
||||||
|
<div dangerouslySetInnerHTML={{ __html: privacyHtml }} />
|
||||||
|
) : (
|
||||||
|
<p>Datenschutzerklärung wird geladen...</p>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
</DialogContent>
|
</DialogContent>
|
||||||
</Dialog>
|
</Dialog>
|
||||||
|
|||||||
@@ -489,24 +489,15 @@ const Packages: React.FC<PackagesProps> = ({ endcustomerPackages, resellerPackag
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
<div className="text-center">
|
<div className="text-center">
|
||||||
{auth.user ? (
|
<Link
|
||||||
<Link
|
href={`/purchase-wizard/${selectedPackage.id}`}
|
||||||
href={`/buy-packages/${selectedPackage.id}`}
|
className="w-full block bg-[#FFB6C1] text-white py-3 rounded-md font-semibold font-sans-marketing hover:bg-[#FF69B4] transition text-center"
|
||||||
className="w-full block bg-[#FFB6C1] text-white py-3 rounded-md font-semibold font-sans-marketing hover:bg-[#FF69B4] transition text-center"
|
onClick={() => {
|
||||||
>
|
localStorage.setItem('preferred_package', JSON.stringify(selectedPackage));
|
||||||
{t('packages.to_order')}
|
}}
|
||||||
</Link>
|
>
|
||||||
) : (
|
{t('packages.to_order')}
|
||||||
<Link
|
</Link>
|
||||||
href={`/register?package_id=${selectedPackage.id}`}
|
|
||||||
className="w-full block bg-[#FFB6C1] text-white py-3 rounded-md font-semibold font-sans-marketing hover:bg-[#FF69B4] transition text-center"
|
|
||||||
onClick={() => {
|
|
||||||
localStorage.setItem('preferred_package', JSON.stringify(selectedPackage));
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{t('packages.to_order')}
|
|
||||||
</Link>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</TabsContent>
|
</TabsContent>
|
||||||
|
|||||||
450
resources/js/pages/marketing/PaymentForm.tsx
Normal file
450
resources/js/pages/marketing/PaymentForm.tsx
Normal file
@@ -0,0 +1,450 @@
|
|||||||
|
import React, { useEffect, useMemo, useRef, useState } from 'react';
|
||||||
|
import { Elements, CardElement, useElements, useStripe } from '@stripe/react-stripe-js';
|
||||||
|
import type { Stripe as StripeInstance } from '@stripe/stripe-js';
|
||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||||
|
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||||
|
import { Loader2 } from 'lucide-react';
|
||||||
|
|
||||||
|
type StripePromise = Promise<StripeInstance | null>;
|
||||||
|
|
||||||
|
interface PaymentFormProps {
|
||||||
|
packageId: number;
|
||||||
|
packageName: string;
|
||||||
|
price: number;
|
||||||
|
currency?: string;
|
||||||
|
stripePromise: StripePromise;
|
||||||
|
paypalClientId?: string | null;
|
||||||
|
onSuccess: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
declare global {
|
||||||
|
interface Window {
|
||||||
|
paypal?: any;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const formatCurrency = (value: number, currency = 'EUR') =>
|
||||||
|
new Intl.NumberFormat('de-DE', {
|
||||||
|
style: 'currency',
|
||||||
|
currency,
|
||||||
|
}).format(value);
|
||||||
|
|
||||||
|
const getCsrfToken = () =>
|
||||||
|
(document.querySelector('meta[name="csrf-token"]') as HTMLMetaElement | null)?.content ?? '';
|
||||||
|
|
||||||
|
async function postJson<T>(url: string, body: unknown, csrfToken: string): Promise<T> {
|
||||||
|
const response = await fetch(url, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'Accept': 'application/json',
|
||||||
|
'X-CSRF-TOKEN': csrfToken,
|
||||||
|
},
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (response.status === 204) {
|
||||||
|
return {} as T;
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = await response.json().catch(() => ({}));
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
const message = (data as { message?: string; error?: string }).message ?? (data as { message?: string; error?: string }).error ?? 'Request failed.';
|
||||||
|
throw new Error(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
return data as T;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function PaymentForm({
|
||||||
|
packageId,
|
||||||
|
packageName,
|
||||||
|
price,
|
||||||
|
currency = 'EUR',
|
||||||
|
stripePromise,
|
||||||
|
paypalClientId,
|
||||||
|
onSuccess,
|
||||||
|
}: PaymentFormProps) {
|
||||||
|
const { t } = useTranslation('marketing');
|
||||||
|
const csrfToken = useMemo(getCsrfToken, []);
|
||||||
|
const [provider, setProvider] = useState<'stripe' | 'paypal'>('stripe');
|
||||||
|
const [statusMessage, setStatusMessage] = useState<string | null>(null);
|
||||||
|
const [errorMessage, setErrorMessage] = useState<string | null>(null);
|
||||||
|
const [freeStatus, setFreeStatus] = useState<'idle' | 'loading' | 'done' | 'error'>('idle');
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setErrorMessage(null);
|
||||||
|
setStatusMessage(null);
|
||||||
|
}, [provider]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (price === 0 && freeStatus === 'idle') {
|
||||||
|
const assignFree = async () => {
|
||||||
|
try {
|
||||||
|
setFreeStatus('loading');
|
||||||
|
await postJson<{ status: string }>('/purchase/free', { package_id: packageId }, csrfToken);
|
||||||
|
setFreeStatus('done');
|
||||||
|
setStatusMessage(
|
||||||
|
t('payment.free_assigned', {
|
||||||
|
defaultValue: 'Kostenloses Paket wurde zugewiesen.',
|
||||||
|
package: packageName,
|
||||||
|
})
|
||||||
|
);
|
||||||
|
onSuccess();
|
||||||
|
} catch (error) {
|
||||||
|
setFreeStatus('error');
|
||||||
|
setErrorMessage((error as Error).message ?? 'Free package assignment failed.');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
assignFree();
|
||||||
|
}
|
||||||
|
}, [csrfToken, freeStatus, onSuccess, packageId, packageName, price, t]);
|
||||||
|
|
||||||
|
if (price === 0) {
|
||||||
|
return (
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle>{t('payment.title', { defaultValue: 'Zahlung' })}</CardTitle>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="space-y-4">
|
||||||
|
{freeStatus === 'loading' && (
|
||||||
|
<div className="flex items-center space-x-2 text-sm text-gray-600">
|
||||||
|
<Loader2 className="h-4 w-4 animate-spin" />
|
||||||
|
<span>{t('payment.processing_free', { defaultValue: 'Paket wird freigeschaltet <20>' })}</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{statusMessage && (
|
||||||
|
<Alert variant="success">
|
||||||
|
<AlertDescription>{statusMessage}</AlertDescription>
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
{errorMessage && (
|
||||||
|
<Alert variant="destructive">
|
||||||
|
<AlertDescription>{errorMessage}</AlertDescription>
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle>{t('payment.title', { defaultValue: 'Zahlung' })}</CardTitle>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="space-y-6">
|
||||||
|
<div className="flex items-center justify-between flex-wrap gap-3">
|
||||||
|
<div>
|
||||||
|
<p className="text-sm text-gray-500">{t('payment.total_due', { defaultValue: 'Gesamtbetrag' })}</p>
|
||||||
|
<p className="text-lg font-semibold">{formatCurrency(price, currency)}</p>
|
||||||
|
</div>
|
||||||
|
<div className="inline-flex rounded-md shadow-sm" role="group">
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant={provider === 'stripe' ? 'default' : 'outline'}
|
||||||
|
onClick={() => setProvider('stripe')}
|
||||||
|
>
|
||||||
|
Stripe
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant={provider === 'paypal' ? 'default' : 'outline'}
|
||||||
|
onClick={() => setProvider('paypal')}
|
||||||
|
>
|
||||||
|
PayPal
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{provider === 'stripe' ? (
|
||||||
|
<Elements stripe={stripePromise} options={{ appearance: { theme: 'stripe' } }}>
|
||||||
|
<StripeCardForm
|
||||||
|
packageId={packageId}
|
||||||
|
csrfToken={csrfToken}
|
||||||
|
amountLabel={formatCurrency(price, currency)}
|
||||||
|
onSuccess={() => {
|
||||||
|
setStatusMessage(t('payment.success_stripe', { defaultValue: 'Stripe-Zahlung erfolgreich.' }));
|
||||||
|
onSuccess();
|
||||||
|
}}
|
||||||
|
onError={(message) => setErrorMessage(message)}
|
||||||
|
/>
|
||||||
|
</Elements>
|
||||||
|
) : (
|
||||||
|
<PayPalSection
|
||||||
|
packageId={packageId}
|
||||||
|
amount={price}
|
||||||
|
currency={currency}
|
||||||
|
clientId={paypalClientId}
|
||||||
|
csrfToken={csrfToken}
|
||||||
|
onSuccess={() => {
|
||||||
|
setStatusMessage(t('payment.success_paypal', { defaultValue: 'PayPal-Zahlung erfolgreich.' }));
|
||||||
|
onSuccess();
|
||||||
|
}}
|
||||||
|
onError={(message) => setErrorMessage(message)}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{statusMessage && (
|
||||||
|
<Alert variant="success">
|
||||||
|
<AlertDescription>{statusMessage}</AlertDescription>
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{errorMessage && (
|
||||||
|
<Alert variant="destructive">
|
||||||
|
<AlertDescription>{errorMessage}</AlertDescription>
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
interface StripeCardFormProps {
|
||||||
|
packageId: number;
|
||||||
|
csrfToken: string;
|
||||||
|
amountLabel: string;
|
||||||
|
onSuccess: () => void;
|
||||||
|
onError: (message: string) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
const StripeCardForm: React.FC<StripeCardFormProps> = ({ packageId, csrfToken, amountLabel, onSuccess, onError }) => {
|
||||||
|
const { t } = useTranslation('marketing');
|
||||||
|
const stripe = useStripe();
|
||||||
|
const elements = useElements();
|
||||||
|
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||||
|
const [localError, setLocalError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
|
||||||
|
event.preventDefault();
|
||||||
|
|
||||||
|
if (!stripe || !elements) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const cardElement = elements.getElement(CardElement);
|
||||||
|
if (!cardElement) {
|
||||||
|
setLocalError('Card element not found.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
setIsSubmitting(true);
|
||||||
|
setLocalError(null);
|
||||||
|
|
||||||
|
const { client_secret: clientSecret, payment_intent_id: paymentIntentId } = await postJson<{
|
||||||
|
client_secret: string;
|
||||||
|
payment_intent_id: string;
|
||||||
|
}>('/purchase/stripe/intent', { package_id: packageId }, csrfToken);
|
||||||
|
|
||||||
|
const confirmation = await stripe.confirmCardPayment(clientSecret, {
|
||||||
|
payment_method: {
|
||||||
|
card: cardElement,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (confirmation.error) {
|
||||||
|
throw new Error(confirmation.error.message || 'Card confirmation failed.');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (confirmation.paymentIntent?.status !== 'succeeded') {
|
||||||
|
throw new Error('Stripe did not confirm the payment.');
|
||||||
|
}
|
||||||
|
|
||||||
|
await postJson('/purchase/stripe/complete', {
|
||||||
|
package_id: packageId,
|
||||||
|
payment_intent_id: confirmation.paymentIntent.id || paymentIntentId,
|
||||||
|
}, csrfToken);
|
||||||
|
|
||||||
|
onSuccess();
|
||||||
|
} catch (error) {
|
||||||
|
const message = (error as Error).message || 'Stripe payment failed.';
|
||||||
|
setLocalError(message);
|
||||||
|
onError(message);
|
||||||
|
} finally {
|
||||||
|
setIsSubmitting(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<form onSubmit={handleSubmit} className="space-y-4">
|
||||||
|
<div className="space-y-2">
|
||||||
|
<label htmlFor="card-element" className="text-sm font-medium">
|
||||||
|
{t('payment.card_details', { defaultValue: 'Kartendaten' })}
|
||||||
|
</label>
|
||||||
|
<div className="p-3 border border-gray-300 rounded-md">
|
||||||
|
<CardElement
|
||||||
|
options={{
|
||||||
|
hidePostalCode: true,
|
||||||
|
style: {
|
||||||
|
base: {
|
||||||
|
fontSize: '16px',
|
||||||
|
color: '#424770',
|
||||||
|
'::placeholder': {
|
||||||
|
color: '#aab7c4',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
{localError && (
|
||||||
|
<Alert variant="destructive">
|
||||||
|
<AlertDescription>{localError}</AlertDescription>
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<Button type="submit" className="w-full" disabled={!stripe || isSubmitting}>
|
||||||
|
{isSubmitting && <Loader2 className="h-4 w-4 animate-spin mr-2" />}
|
||||||
|
{t('payment.submit', {
|
||||||
|
defaultValue: 'Jetzt bezahlen',
|
||||||
|
price: amountLabel,
|
||||||
|
})}
|
||||||
|
</Button>
|
||||||
|
</form>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
interface PayPalSectionProps {
|
||||||
|
packageId: number;
|
||||||
|
amount: number;
|
||||||
|
currency: string;
|
||||||
|
clientId?: string | null;
|
||||||
|
csrfToken: string;
|
||||||
|
onSuccess: () => void;
|
||||||
|
onError: (message: string) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
const PayPalSection: React.FC<PayPalSectionProps> = ({
|
||||||
|
packageId,
|
||||||
|
amount,
|
||||||
|
currency,
|
||||||
|
clientId,
|
||||||
|
csrfToken,
|
||||||
|
onSuccess,
|
||||||
|
onError,
|
||||||
|
}) => {
|
||||||
|
const { t } = useTranslation('marketing');
|
||||||
|
const containerRef = useRef<HTMLDivElement | null>(null);
|
||||||
|
const [isSdkReady, setIsSdkReady] = useState(false);
|
||||||
|
const [isProcessing, setIsProcessing] = useState(false);
|
||||||
|
const [localError, setLocalError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!clientId) {
|
||||||
|
const message = t('payment.paypal_missing_key', { defaultValue: 'PayPal ist derzeit nicht konfiguriert.' });
|
||||||
|
setLocalError(message);
|
||||||
|
onError(message);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (window.paypal) {
|
||||||
|
setIsSdkReady(true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const script = document.createElement('script');
|
||||||
|
script.src = `https://www.paypal.com/sdk/js?client-id=${clientId}¤cy=${currency}&intent=capture&components=buttons`;
|
||||||
|
script.async = true;
|
||||||
|
script.onload = () => setIsSdkReady(true);
|
||||||
|
script.onerror = () => {
|
||||||
|
const message = t('payment.paypal_sdk_failed', { defaultValue: 'PayPal-SDK konnte nicht geladen werden.' });
|
||||||
|
setLocalError(message);
|
||||||
|
onError(message);
|
||||||
|
};
|
||||||
|
document.body.appendChild(script);
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
script.remove();
|
||||||
|
};
|
||||||
|
}, [clientId, currency, onError, t]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!isSdkReady || !window.paypal || !containerRef.current) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const buttons = window.paypal.Buttons({
|
||||||
|
style: {
|
||||||
|
layout: 'vertical',
|
||||||
|
color: 'gold',
|
||||||
|
shape: 'rect',
|
||||||
|
},
|
||||||
|
createOrder: async () => {
|
||||||
|
try {
|
||||||
|
setIsProcessing(true);
|
||||||
|
const { order_id: orderId } = await postJson<{ order_id: string }>('/purchase/paypal/order', {
|
||||||
|
package_id: packageId,
|
||||||
|
}, csrfToken);
|
||||||
|
return orderId;
|
||||||
|
} catch (error) {
|
||||||
|
const message = (error as Error).message || 'PayPal order creation failed.';
|
||||||
|
setLocalError(message);
|
||||||
|
onError(message);
|
||||||
|
setIsProcessing(false);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
onApprove: async (data: { orderID: string }) => {
|
||||||
|
try {
|
||||||
|
await postJson('/purchase/paypal/capture', {
|
||||||
|
order_id: data.orderID,
|
||||||
|
package_id: packageId,
|
||||||
|
}, csrfToken);
|
||||||
|
setIsProcessing(false);
|
||||||
|
setLocalError(null);
|
||||||
|
onSuccess();
|
||||||
|
} catch (error) {
|
||||||
|
const message = (error as Error).message || 'PayPal capture failed.';
|
||||||
|
setLocalError(message);
|
||||||
|
onError(message);
|
||||||
|
setIsProcessing(false);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
onError: (error: Error) => {
|
||||||
|
const message = error?.message || 'PayPal payment failed.';
|
||||||
|
setLocalError(message);
|
||||||
|
onError(message);
|
||||||
|
setIsProcessing(false);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
buttons.render(containerRef.current);
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
try {
|
||||||
|
buttons.close();
|
||||||
|
} catch (error) {
|
||||||
|
// ignore close errors
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}, [csrfToken, isSdkReady, onError, onSuccess, packageId]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div ref={containerRef} />
|
||||||
|
{isProcessing && (
|
||||||
|
<div className="flex items-center space-x-2 text-sm text-gray-600">
|
||||||
|
<Loader2 className="h-4 w-4 animate-spin" />
|
||||||
|
<span>{t('payment.processing_paypal', { defaultValue: 'PayPal-Zahlung wird verarbeitet <20>' })}</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{localError && (
|
||||||
|
<Alert variant="destructive">
|
||||||
|
<AlertDescription>{localError}</AlertDescription>
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
<p className="text-xs text-gray-500">
|
||||||
|
{t('payment.paypal_hint', {
|
||||||
|
defaultValue: 'Der Betrag von {{amount}} wird bei PayPal angezeigt.',
|
||||||
|
amount: formatCurrency(amount, currency),
|
||||||
|
})}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
297
resources/js/pages/marketing/PurchaseWizard.tsx
Normal file
297
resources/js/pages/marketing/PurchaseWizard.tsx
Normal file
@@ -0,0 +1,297 @@
|
|||||||
|
import React, { useCallback, useEffect, useMemo, useState } from 'react';
|
||||||
|
import { Head, usePage } from '@inertiajs/react';
|
||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
import { loadStripe } from '@stripe/stripe-js';
|
||||||
|
import { Steps } from '@/components/ui/steps';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||||
|
import { Progress } from '@/components/ui/progress';
|
||||||
|
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||||
|
import MarketingLayout from '@/layouts/marketing/MarketingLayout';
|
||||||
|
import RegisterForm from '../auth/RegisterForm';
|
||||||
|
import LoginForm from '../auth/LoginForm';
|
||||||
|
import PaymentForm from './PaymentForm';
|
||||||
|
import SuccessStep from './SuccessStep';
|
||||||
|
|
||||||
|
interface Package {
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
description: string;
|
||||||
|
price: number;
|
||||||
|
features: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
interface PurchaseWizardProps {
|
||||||
|
package: Package;
|
||||||
|
stripePublishableKey: string;
|
||||||
|
paypalClientId?: string | null;
|
||||||
|
privacyHtml: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
type StepId = 'package' | 'auth' | 'payment' | 'success';
|
||||||
|
|
||||||
|
interface WizardUser {
|
||||||
|
id: number;
|
||||||
|
email: string;
|
||||||
|
name?: string;
|
||||||
|
pending_purchase?: boolean;
|
||||||
|
email_verified?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface AuthSuccessPayload {
|
||||||
|
status: 'authenticated' | 'registered';
|
||||||
|
user?: WizardUser;
|
||||||
|
next_step?: StepId | 'verification';
|
||||||
|
needs_verification?: boolean;
|
||||||
|
package?: {
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
price: number;
|
||||||
|
type: string;
|
||||||
|
} | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const steps: Array<{ id: StepId; title: string; description: string }> = [
|
||||||
|
{ id: 'package', title: 'Paket ausw<73>hlen', description: 'Best<73>tigen Sie Ihr gew<65>hltes Paket' },
|
||||||
|
{ id: 'auth', title: 'Anmelden oder Registrieren', description: 'Erstellen oder melden Sie sich an' },
|
||||||
|
{ id: 'payment', title: 'Zahlung', description: 'Sichern Sie Ihr Paket ab' },
|
||||||
|
{ id: 'success', title: 'Erfolg', description: 'Willkommen!' },
|
||||||
|
];
|
||||||
|
|
||||||
|
export default function PurchaseWizard({
|
||||||
|
package: initialPackage,
|
||||||
|
stripePublishableKey,
|
||||||
|
paypalClientId,
|
||||||
|
privacyHtml,
|
||||||
|
}: PurchaseWizardProps) {
|
||||||
|
const { t } = useTranslation(['marketing', 'auth']);
|
||||||
|
const { props } = usePage();
|
||||||
|
const serverUser = (props as any)?.auth?.user ?? null;
|
||||||
|
|
||||||
|
const [currentStepIndex, setCurrentStepIndex] = useState(0);
|
||||||
|
const [authType, setAuthType] = useState<'register' | 'login'>('register');
|
||||||
|
const [wizardUser, setWizardUser] = useState<WizardUser | null>(serverUser);
|
||||||
|
const [authNotice, setAuthNotice] = useState<string | null>(null);
|
||||||
|
|
||||||
|
const isAuthenticated = Boolean(wizardUser);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (serverUser) {
|
||||||
|
setWizardUser(serverUser);
|
||||||
|
}
|
||||||
|
}, [serverUser ? serverUser.id : null]);
|
||||||
|
|
||||||
|
const stripePromise = useMemo(() => loadStripe(stripePublishableKey), [stripePublishableKey]);
|
||||||
|
|
||||||
|
const goToStep = useCallback((stepId: StepId) => {
|
||||||
|
const idx = steps.findIndex((step) => step.id === stepId);
|
||||||
|
if (idx >= 0) {
|
||||||
|
setCurrentStepIndex(idx);
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleContinue = useCallback(() => {
|
||||||
|
let nextIndex = Math.min(currentStepIndex + 1, steps.length - 1);
|
||||||
|
if (steps[nextIndex]?.id === 'auth' && isAuthenticated) {
|
||||||
|
nextIndex = Math.min(nextIndex + 1, steps.length - 1);
|
||||||
|
}
|
||||||
|
setCurrentStepIndex(nextIndex);
|
||||||
|
}, [currentStepIndex, isAuthenticated]);
|
||||||
|
|
||||||
|
const handleBack = useCallback(() => {
|
||||||
|
let nextIndex = Math.max(currentStepIndex - 1, 0);
|
||||||
|
if (steps[nextIndex]?.id === 'auth' && isAuthenticated) {
|
||||||
|
nextIndex = Math.max(nextIndex - 1, 0);
|
||||||
|
}
|
||||||
|
setCurrentStepIndex(nextIndex);
|
||||||
|
}, [currentStepIndex, isAuthenticated]);
|
||||||
|
|
||||||
|
const handleAuthSuccess = useCallback(
|
||||||
|
(payload: AuthSuccessPayload) => {
|
||||||
|
if (payload?.user) {
|
||||||
|
setWizardUser(payload.user);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (payload?.needs_verification) {
|
||||||
|
setAuthNotice(t('auth:verify_notice', { defaultValue: 'Bitte best<73>tige deine E-Mail-Adresse, um fortzufahren.' }));
|
||||||
|
} else {
|
||||||
|
setAuthNotice(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
const next = payload?.next_step;
|
||||||
|
if (next === 'success') {
|
||||||
|
goToStep('success');
|
||||||
|
} else {
|
||||||
|
goToStep('payment');
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[goToStep, t],
|
||||||
|
);
|
||||||
|
|
||||||
|
const handlePaymentSuccess = useCallback(() => {
|
||||||
|
goToStep('success');
|
||||||
|
}, [goToStep]);
|
||||||
|
|
||||||
|
const renderPackageStep = () => (
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle>{initialPackage.name}</CardTitle>
|
||||||
|
<CardDescription>{initialPackage.description}</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent>
|
||||||
|
<p>
|
||||||
|
{t('marketing:payment.price_label', { defaultValue: 'Preis' })}:
|
||||||
|
{' '}
|
||||||
|
{initialPackage.price === 0
|
||||||
|
? t('marketing:payment.free', { defaultValue: 'Kostenlos' })
|
||||||
|
: new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(initialPackage.price)}
|
||||||
|
</p>
|
||||||
|
<ul className="list-disc pl-5 mt-4 space-y-1">
|
||||||
|
{initialPackage.features.map((feature, index) => (
|
||||||
|
<li key={index}>{feature}</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
<Button onClick={handleContinue} className="w-full mt-6">
|
||||||
|
{t('marketing:payment.continue', { defaultValue: 'Weiter' })}
|
||||||
|
</Button>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
|
||||||
|
const renderAuthStep = () => {
|
||||||
|
if (isAuthenticated) {
|
||||||
|
return (
|
||||||
|
<Card>
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle>{t('auth:already_authenticated', { defaultValue: 'Bereits angemeldet' })}</CardTitle>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="space-y-4">
|
||||||
|
<Alert>
|
||||||
|
<AlertDescription>
|
||||||
|
{t('auth:logged_in_as', {
|
||||||
|
defaultValue: 'Du bist angemeldet als {{email}}.',
|
||||||
|
email: wizardUser?.email ?? wizardUser?.name ?? t('auth:user', { defaultValue: 'aktueller Nutzer' }),
|
||||||
|
})}
|
||||||
|
</AlertDescription>
|
||||||
|
</Alert>
|
||||||
|
{authNotice && (
|
||||||
|
<Alert>
|
||||||
|
<AlertDescription>{authNotice}</AlertDescription>
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
<Button onClick={() => goToStep('payment')} className="w-full">
|
||||||
|
{t('auth:skip_to_payment', { defaultValue: 'Weiter zur Zahlung' })}
|
||||||
|
</Button>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-6">
|
||||||
|
<div className="flex justify-center gap-3">
|
||||||
|
<Button
|
||||||
|
variant={authType === 'register' ? 'default' : 'outline'}
|
||||||
|
onClick={() => {
|
||||||
|
setAuthType('register');
|
||||||
|
setAuthNotice(null);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{t('auth:register.title', { defaultValue: 'Registrieren' })}
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant={authType === 'login' ? 'default' : 'outline'}
|
||||||
|
onClick={() => {
|
||||||
|
setAuthType('login');
|
||||||
|
setAuthNotice(null);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{t('auth:login.title', { defaultValue: 'Anmelden' })}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
{authNotice && (
|
||||||
|
<Alert>
|
||||||
|
<AlertDescription>{authNotice}</AlertDescription>
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
{authType === 'register' ? (
|
||||||
|
<RegisterForm
|
||||||
|
packageId={initialPackage.id}
|
||||||
|
privacyHtml={privacyHtml}
|
||||||
|
onSuccess={handleAuthSuccess}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<LoginForm onSuccess={handleAuthSuccess} />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const renderPaymentStep = () => (
|
||||||
|
<div className="space-y-4">
|
||||||
|
{isAuthenticated && (
|
||||||
|
<Alert>
|
||||||
|
<AlertDescription>
|
||||||
|
{t('marketing:payment.authenticated_notice', {
|
||||||
|
defaultValue: 'Angemeldet als {{email}}. Zahlungsmethode ausw<73>hlen.',
|
||||||
|
email: wizardUser?.email ?? wizardUser?.name ?? t('auth:user', { defaultValue: 'aktueller Nutzer' }),
|
||||||
|
})}
|
||||||
|
</AlertDescription>
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
{authNotice && (
|
||||||
|
<Alert>
|
||||||
|
<AlertDescription>{authNotice}</AlertDescription>
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
<PaymentForm
|
||||||
|
packageId={initialPackage.id}
|
||||||
|
packageName={initialPackage.name}
|
||||||
|
price={initialPackage.price}
|
||||||
|
currency="EUR"
|
||||||
|
stripePromise={stripePromise}
|
||||||
|
paypalClientId={paypalClientId}
|
||||||
|
onSuccess={handlePaymentSuccess}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
|
||||||
|
const renderSuccessStep = () => <SuccessStep package={initialPackage} />;
|
||||||
|
|
||||||
|
const currentStep = steps[currentStepIndex];
|
||||||
|
|
||||||
|
const renderStepContent = () => {
|
||||||
|
switch (currentStep.id) {
|
||||||
|
case 'package':
|
||||||
|
return renderPackageStep();
|
||||||
|
case 'auth':
|
||||||
|
return renderAuthStep();
|
||||||
|
case 'payment':
|
||||||
|
return renderPaymentStep();
|
||||||
|
case 'success':
|
||||||
|
return renderSuccessStep();
|
||||||
|
default:
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<MarketingLayout title={t('marketing:payment.wizard_title', { defaultValue: 'Kauf-Wizard' })}>
|
||||||
|
<Head title={t('marketing:payment.wizard_title', { defaultValue: 'Kauf-Wizard' })} />
|
||||||
|
<div className="min-h-screen bg-gray-50 py-12">
|
||||||
|
<div className="max-w-2xl mx-auto px-4">
|
||||||
|
<Progress value={(currentStepIndex / (steps.length - 1)) * 100} className="mb-6" />
|
||||||
|
<Steps steps={steps} currentStep={currentStepIndex} />
|
||||||
|
{renderStepContent()}
|
||||||
|
{currentStep.id !== 'success' && currentStep.id !== 'package' && (
|
||||||
|
<div className="mt-6">
|
||||||
|
<Button variant="outline" onClick={handleBack}>
|
||||||
|
{t('marketing:payment.back', { defaultValue: 'Zur<75>ck' })}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</MarketingLayout>
|
||||||
|
);
|
||||||
|
}
|
||||||
43
resources/js/pages/marketing/SuccessStep.tsx
Normal file
43
resources/js/pages/marketing/SuccessStep.tsx
Normal file
@@ -0,0 +1,43 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import { useTranslation } from 'react-i18next';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||||
|
import { CheckCircle } from 'lucide-react';
|
||||||
|
import { router } from '@inertiajs/react';
|
||||||
|
|
||||||
|
interface Package {
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
description: string;
|
||||||
|
price: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface SuccessStepProps {
|
||||||
|
package: Package;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function SuccessStep({ package: pkg }: SuccessStepProps) {
|
||||||
|
const { t } = useTranslation('marketing');
|
||||||
|
|
||||||
|
const handleDashboard = () => {
|
||||||
|
router.visit('/admin');
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Card>
|
||||||
|
<CardHeader className="text-center">
|
||||||
|
<CheckCircle className="h-16 w-16 text-green-500 mx-auto mb-4" />
|
||||||
|
<CardTitle className="text-2xl">{t('success.title')}</CardTitle>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="space-y-4 text-center">
|
||||||
|
<p>{t('success.message', { package: pkg.name })}</p>
|
||||||
|
<p className="text-lg font-semibold">
|
||||||
|
{pkg.price === 0 ? t('success.free_assigned') : t('success.paid_assigned')}
|
||||||
|
</p>
|
||||||
|
<Button onClick={handleDashboard} className="w-full">
|
||||||
|
{t('success.go_to_dashboard')}
|
||||||
|
</Button>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -11,8 +11,15 @@ return [
|
|||||||
'password' => 'Passwort',
|
'password' => 'Passwort',
|
||||||
'remember' => 'Angemeldet bleiben',
|
'remember' => 'Angemeldet bleiben',
|
||||||
'submit' => 'Anmelden',
|
'submit' => 'Anmelden',
|
||||||
|
'generic_error' => 'Anmeldung fehlgeschlagen. Bitte versuche es erneut.',
|
||||||
],
|
],
|
||||||
|
|
||||||
|
'already_authenticated' => 'Bereits angemeldet',
|
||||||
|
'logged_in_as' => 'Du bist angemeldet als :email.',
|
||||||
|
'skip_to_payment' => 'Weiter zur Zahlung',
|
||||||
|
'verify_notice' => 'Bitte bestätige deine E-Mail-Adresse, um fortzufahren.',
|
||||||
|
'user' => 'aktueller Nutzer',
|
||||||
|
|
||||||
'register' => [
|
'register' => [
|
||||||
'title' => 'Registrieren',
|
'title' => 'Registrieren',
|
||||||
'name' => 'Vollständiger Name',
|
'name' => 'Vollständiger Name',
|
||||||
@@ -26,6 +33,7 @@ return [
|
|||||||
'phone' => 'Telefonnummer',
|
'phone' => 'Telefonnummer',
|
||||||
'privacy_consent' => 'Ich stimme der Datenschutzerklärung zu und akzeptiere die Verarbeitung meiner persönlichen Daten.',
|
'privacy_consent' => 'Ich stimme der Datenschutzerklärung zu und akzeptiere die Verarbeitung meiner persönlichen Daten.',
|
||||||
'submit' => 'Registrieren',
|
'submit' => 'Registrieren',
|
||||||
|
'generic_error' => 'Registrierung fehlgeschlagen. Bitte versuche es erneut.',
|
||||||
],
|
],
|
||||||
|
|
||||||
'verification' => [
|
'verification' => [
|
||||||
|
|||||||
@@ -51,6 +51,24 @@ return [
|
|||||||
'feature_custom_branding' => 'Benutzerdefiniertes Branding',
|
'feature_custom_branding' => 'Benutzerdefiniertes Branding',
|
||||||
'feature_advanced_reporting' => 'Erweiterte Berichterstattung',
|
'feature_advanced_reporting' => 'Erweiterte Berichterstattung',
|
||||||
],
|
],
|
||||||
|
'payment' => [
|
||||||
|
'wizard_title' => 'Kauf-Wizard',
|
||||||
|
'title' => 'Zahlung',
|
||||||
|
'price_label' => 'Preis',
|
||||||
|
'free' => 'Kostenlos',
|
||||||
|
'continue' => 'Weiter',
|
||||||
|
'back' => 'Zurück',
|
||||||
|
'total_due' => 'Gesamtbetrag',
|
||||||
|
'success_stripe' => 'Stripe-Zahlung erfolgreich.',
|
||||||
|
'success_paypal' => 'PayPal-Zahlung erfolgreich.',
|
||||||
|
'free_assigned' => 'Kostenloses Paket wurde zugewiesen.',
|
||||||
|
'processing_free' => 'Paket wird freigeschaltet ...',
|
||||||
|
'processing_paypal' => 'PayPal-Zahlung wird verarbeitet ...',
|
||||||
|
'paypal_hint' => 'Der Betrag von {{amount}} wird bei PayPal angezeigt.',
|
||||||
|
'paypal_missing_key' => 'PayPal ist derzeit nicht konfiguriert.',
|
||||||
|
'paypal_sdk_failed' => 'PayPal-SDK konnte nicht geladen werden.',
|
||||||
|
'authenticated_notice' => 'Angemeldet als {{email}}. Zahlungsmethode auswählen.',
|
||||||
|
],
|
||||||
'nav' => [
|
'nav' => [
|
||||||
'home' => 'Startseite',
|
'home' => 'Startseite',
|
||||||
'how_it_works' => 'So funktioniert\'s',
|
'how_it_works' => 'So funktioniert\'s',
|
||||||
@@ -139,6 +157,10 @@ return [
|
|||||||
'complete_purchase' => 'Kauf abschließen',
|
'complete_purchase' => 'Kauf abschließen',
|
||||||
'login_to_continue' => 'Melden Sie sich an, um fortzufahren.',
|
'login_to_continue' => 'Melden Sie sich an, um fortzufahren.',
|
||||||
'loading' => 'Laden...',
|
'loading' => 'Laden...',
|
||||||
|
'message' => 'Danke! Paket :package ist bereit.',
|
||||||
|
'free_assigned' => 'Kostenloses Paket wurde aktiviert.',
|
||||||
|
'paid_assigned' => 'Zahlung erfolgreich verarbeitet.',
|
||||||
|
'go_to_dashboard' => 'Zum Dashboard',
|
||||||
],
|
],
|
||||||
'register' => [
|
'register' => [
|
||||||
'free' => 'Kostenlos',
|
'free' => 'Kostenlos',
|
||||||
|
|||||||
43
resources/lang/en/auth.php
Normal file
43
resources/lang/en/auth.php
Normal file
@@ -0,0 +1,43 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
return [
|
||||||
|
'failed' => 'These credentials do not match our records.',
|
||||||
|
'password' => 'The provided password is incorrect.',
|
||||||
|
'throttle' => 'Too many login attempts. Please try again in :seconds seconds.',
|
||||||
|
|
||||||
|
'login' => [
|
||||||
|
'title' => 'Log in',
|
||||||
|
'username_or_email' => 'Username or email',
|
||||||
|
'password' => 'Password',
|
||||||
|
'remember' => 'Remember me',
|
||||||
|
'submit' => 'Log in',
|
||||||
|
'generic_error' => 'Login failed. Please try again.',
|
||||||
|
],
|
||||||
|
|
||||||
|
'already_authenticated' => 'Already signed in',
|
||||||
|
'logged_in_as' => 'You are signed in as :email.',
|
||||||
|
'skip_to_payment' => 'Continue to payment',
|
||||||
|
'verify_notice' => 'Please verify your email address to continue.',
|
||||||
|
'user' => 'current user',
|
||||||
|
|
||||||
|
'register' => [
|
||||||
|
'title' => 'Register',
|
||||||
|
'name' => 'Full name',
|
||||||
|
'username' => 'Username',
|
||||||
|
'email' => 'Email address',
|
||||||
|
'password' => 'Password',
|
||||||
|
'password_confirmation' => 'Confirm password',
|
||||||
|
'first_name' => 'First name',
|
||||||
|
'last_name' => 'Last name',
|
||||||
|
'address' => 'Address',
|
||||||
|
'phone' => 'Phone number',
|
||||||
|
'privacy_consent' => 'I agree to the privacy policy and consent to the processing of my personal data.',
|
||||||
|
'submit' => 'Sign up',
|
||||||
|
'generic_error' => 'Registration failed. Please try again.',
|
||||||
|
],
|
||||||
|
|
||||||
|
'verification' => [
|
||||||
|
'notice' => 'Please verify your email address.',
|
||||||
|
'resend' => 'Resend email',
|
||||||
|
],
|
||||||
|
];
|
||||||
@@ -51,6 +51,24 @@ return [
|
|||||||
'feature_custom_branding' => 'Custom Branding',
|
'feature_custom_branding' => 'Custom Branding',
|
||||||
'feature_advanced_reporting' => 'Advanced Reporting',
|
'feature_advanced_reporting' => 'Advanced Reporting',
|
||||||
],
|
],
|
||||||
|
'payment' => [
|
||||||
|
'wizard_title' => 'Purchase Wizard',
|
||||||
|
'title' => 'Payment',
|
||||||
|
'price_label' => 'Price',
|
||||||
|
'free' => 'Free',
|
||||||
|
'continue' => 'Continue',
|
||||||
|
'back' => 'Back',
|
||||||
|
'total_due' => 'Total due',
|
||||||
|
'success_stripe' => 'Stripe payment successful.',
|
||||||
|
'success_paypal' => 'PayPal payment successful.',
|
||||||
|
'free_assigned' => 'Free package has been assigned.',
|
||||||
|
'processing_free' => 'Assigning free package ...',
|
||||||
|
'processing_paypal' => 'Processing PayPal payment ...',
|
||||||
|
'paypal_hint' => 'The amount of {{amount}} will be shown in PayPal.',
|
||||||
|
'paypal_missing_key' => 'PayPal is not configured right now.',
|
||||||
|
'paypal_sdk_failed' => 'Failed to load the PayPal SDK.',
|
||||||
|
'authenticated_notice' => 'Signed in as {{email}}. Choose your payment method.',
|
||||||
|
],
|
||||||
'nav' => [
|
'nav' => [
|
||||||
'home' => 'Home',
|
'home' => 'Home',
|
||||||
'how_it_works' => 'How it works',
|
'how_it_works' => 'How it works',
|
||||||
@@ -133,12 +151,16 @@ return [
|
|||||||
],
|
],
|
||||||
'success' => [
|
'success' => [
|
||||||
'title' => 'Success',
|
'title' => 'Success',
|
||||||
'verify_email' => 'Verify Email',
|
'verify_email' => 'Verify email',
|
||||||
'check_email' => 'Check your email for the verification link.',
|
'check_email' => 'Check your inbox for the verification link.',
|
||||||
'redirecting' => 'Redirecting to admin area...',
|
'redirecting' => 'Redirecting to the admin area...',
|
||||||
'complete_purchase' => 'Complete Purchase',
|
'complete_purchase' => 'Complete purchase',
|
||||||
'login_to_continue' => 'Log in to continue.',
|
'login_to_continue' => 'Please sign in to continue.',
|
||||||
'loading' => 'Loading...',
|
'loading' => 'Loading...',
|
||||||
|
'message' => 'Thank you! Package :package is ready.',
|
||||||
|
'free_assigned' => 'Free package has been activated.',
|
||||||
|
'paid_assigned' => 'Payment processed successfully.',
|
||||||
|
'go_to_dashboard' => 'Go to dashboard',
|
||||||
],
|
],
|
||||||
'register' => [
|
'register' => [
|
||||||
'free' => 'Free',
|
'free' => 'Free',
|
||||||
|
|||||||
@@ -92,6 +92,9 @@ Route::prefix('v1')->name('api.v1.')->group(function () {
|
|||||||
Route::prefix('packages')->group(function () {
|
Route::prefix('packages')->group(function () {
|
||||||
Route::get('/', [PackageController::class, 'index'])->name('packages.index');
|
Route::get('/', [PackageController::class, 'index'])->name('packages.index');
|
||||||
Route::post('/purchase', [PackageController::class, 'purchase'])->name('packages.purchase');
|
Route::post('/purchase', [PackageController::class, 'purchase'])->name('packages.purchase');
|
||||||
|
Route::post('/payment-intent', [PackageController::class, 'createPaymentIntent'])->name('packages.payment-intent');
|
||||||
|
Route::post('/complete', [PackageController::class, 'completePurchase'])->name('packages.complete');
|
||||||
|
Route::post('/free', [PackageController::class, 'assignFree'])->name('packages.free');
|
||||||
});
|
});
|
||||||
|
|
||||||
Route::prefix('stripe')->group(function () {
|
Route::prefix('stripe')->group(function () {
|
||||||
|
|||||||
@@ -143,7 +143,14 @@ Route::get('/super-admin/templates/tasks.csv', function () {
|
|||||||
return response()->stream($callback, 200, $headers);
|
return response()->stream($callback, 200, $headers);
|
||||||
});
|
});
|
||||||
|
|
||||||
Route::get('/buy-packages/{package_id}', [\App\Http\Controllers\MarketingController::class, 'buyPackages'])->name('buy.packages');
|
Route::get('/purchase-wizard/{package_id}', function ($package_id) {
|
||||||
|
return redirect("/de/purchase-wizard/{$package_id}");
|
||||||
|
})->name('purchase.wizard.fallback');
|
||||||
|
|
||||||
|
Route::prefix('{locale?}')->where(['locale' => 'de|en'])->middleware('locale')->group(function () {
|
||||||
|
Route::get('/purchase-wizard/{package_id}', [\App\Http\Controllers\MarketingController::class, 'purchaseWizard'])->middleware(\App\Http\Middleware\StripeCSP::class)->name('purchase.wizard');
|
||||||
|
Route::get('/buy-packages/{package_id}', [\App\Http\Controllers\MarketingController::class, 'buyPackages'])->name('buy.packages');
|
||||||
|
});
|
||||||
Route::middleware('auth')->group(function () {
|
Route::middleware('auth')->group(function () {
|
||||||
Route::get('/profile', [\App\Http\Controllers\ProfileController::class, 'index'])->name('profile');
|
Route::get('/profile', [\App\Http\Controllers\ProfileController::class, 'index'])->name('profile');
|
||||||
Route::get('/profile/account', [\App\Http\Controllers\ProfileController::class, 'account'])->name('profile.account');
|
Route::get('/profile/account', [\App\Http\Controllers\ProfileController::class, 'account'])->name('profile.account');
|
||||||
@@ -160,3 +167,17 @@ Route::prefix('{locale?}')->where(['locale' => 'de|en'])->middleware('locale')->
|
|||||||
])
|
])
|
||||||
->name('anlaesse.type');
|
->name('anlaesse.type');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
|
Route::prefix('purchase')->group(function () {
|
||||||
|
Route::post('/auth/login', [\App\Http\Controllers\PurchaseWizardController::class, 'login'])->name('purchase.auth.login');
|
||||||
|
Route::post('/auth/register', [\App\Http\Controllers\PurchaseWizardController::class, 'register'])->name('purchase.auth.register');
|
||||||
|
});
|
||||||
|
|
||||||
|
Route::middleware(['auth', 'verified'])->prefix('purchase')->group(function () {
|
||||||
|
Route::post('/stripe/intent', [\App\Http\Controllers\PurchaseWizardController::class, 'createStripeIntent'])->name('purchase.stripe.intent');
|
||||||
|
Route::post('/stripe/complete', [\App\Http\Controllers\PurchaseWizardController::class, 'completeStripe'])->name('purchase.stripe.complete');
|
||||||
|
Route::post('/paypal/order', [\App\Http\Controllers\PurchaseWizardController::class, 'createPaypalOrder'])->name('purchase.paypal.order');
|
||||||
|
Route::post('/paypal/capture', [\App\Http\Controllers\PurchaseWizardController::class, 'capturePaypalOrder'])->name('purchase.paypal.capture');
|
||||||
|
Route::post('/free', [\App\Http\Controllers\PurchaseWizardController::class, 'assignFreePackage'])->name('purchase.free');
|
||||||
|
});
|
||||||
|
|||||||
@@ -1,69 +1,153 @@
|
|||||||
import { test, expect } from '@playwright/test';
|
import { test, expect } from '@playwright/test';
|
||||||
import { execSync } from 'child_process'; // Für artisan seed
|
import { execSync } from 'child_process';
|
||||||
|
|
||||||
test.describe('Marketing Package Flow: Auswahl → Registrierung → Kauf (Free & Paid)', () => {
|
const BASE_URL = process.env.PLAYWRIGHT_BASE_URL || 'http://localhost:8000';
|
||||||
test.beforeAll(async () => {
|
|
||||||
// Seed Test-Tenant (einmalig)
|
function seedTestUser() {
|
||||||
execSync('php artisan tenant:add-dummy --email=test@example.com --password=password123 --first_name=Test --last_name=User --address="Teststr. 1" --phone="+49123"');
|
execSync('php artisan tenant:add-dummy --email=test@example.com --password=password123 --first_name=Test --last_name=User --address="Teststr. 1" --phone="+49123"', { stdio: 'ignore' });
|
||||||
// Mock Verifizierung: Update DB (in Test-Env)
|
execSync('php artisan tinker --execute="App\\Models\\User::where(\'email\', \'test@example.com\')->update([\'email_verified_at\' => now()]);"', { stdio: 'ignore' });
|
||||||
execSync('php artisan tinker --execute="App\\Models\\User::where(\'email\', \'test@example.com\')->update([\'email_verified_at\' => now()]);"');
|
}
|
||||||
|
|
||||||
|
test.describe('Marketing Purchase Wizard', () => {
|
||||||
|
test.beforeAll(() => {
|
||||||
|
seedTestUser();
|
||||||
});
|
});
|
||||||
|
|
||||||
test('Free-Paket-Flow (ID=1, Starter)', async ({ page }) => {
|
test('guest users see registration step after package selection', async ({ page }) => {
|
||||||
await page.goto('http://localhost:8000/de'); // Lokaler Server (vite dev)
|
await page.goto(`${BASE_URL}/purchase-wizard/1`);
|
||||||
await expect(page).toHaveTitle(/Fotospiel/);
|
|
||||||
await page.screenshot({ path: 'free-step1-home.png', fullPage: true });
|
|
||||||
|
|
||||||
// Paketauswahl
|
await page.getByRole('button', { name: /Weiter/i }).click();
|
||||||
await page.getByRole('link', { name: 'Alle Packages ansehen' }).click();
|
|
||||||
await expect(page).toHaveURL(/\/de\/packages/);
|
|
||||||
await page.screenshot({ path: 'free-step2-packages.png', fullPage: true });
|
|
||||||
await page.getByRole('button', { name: 'Details anzeigen' }).first().click(); // Erstes Paket (Free)
|
|
||||||
await expect(page.locator('dialog')).toBeVisible();
|
|
||||||
await page.screenshot({ path: 'free-step3-modal.png', fullPage: true });
|
|
||||||
await page.getByRole('tab', { name: 'Kaufen' }).click();
|
|
||||||
await page.getByRole('link', { name: 'Registrieren & Kaufen' }).click();
|
|
||||||
await expect(page).toHaveURL(/\/de\/register\?package_id=1/);
|
|
||||||
await page.screenshot({ path: 'free-step4-register.png', fullPage: true });
|
|
||||||
|
|
||||||
// Registrierung (Test-Daten, aber seedet vorab – hier Login simulieren falls nötig)
|
await expect(page.getByText(/Registrieren/i)).toBeVisible();
|
||||||
// Da seeded: Verwende Login statt neuer Registrierung für Test
|
await expect(page.getByText(/Anmelden/i)).toBeVisible();
|
||||||
await page.fill('[name="email"]', 'test@example.com');
|
|
||||||
await page.fill('[name="password"]', 'password123');
|
|
||||||
await page.getByRole('button', { name: 'Anmelden' }).click(); // Falls Login-Form nach Redirect
|
|
||||||
await expect(page).toHaveURL(/\/buy-packages\/1/);
|
|
||||||
await page.screenshot({ path: 'free-step5-buy.png', fullPage: true });
|
|
||||||
|
|
||||||
// Kauf (Free: Direkte Success)
|
|
||||||
await expect(page.locator('text=Free package assigned')).toContainText('success'); // API-Response oder Page-Text
|
|
||||||
await page.goto('/marketing/success');
|
|
||||||
await expect(page).toHaveURL(/\/marketing\/success/);
|
|
||||||
await page.screenshot({ path: 'free-step6-success.png', fullPage: true });
|
|
||||||
await expect(page).toHaveURL(/\/admin/); // Redirect
|
|
||||||
await page.screenshot({ path: 'free-step7-admin.png', fullPage: true });
|
|
||||||
await expect(page.locator('text=Remaining Photos')).toContainText('300'); // Limits aus package-flow.test.ts integriert
|
|
||||||
});
|
});
|
||||||
|
|
||||||
test('Paid-Paket-Flow (ID=2, Pro mit Stripe-Test)', async ({ page }) => {
|
test('authenticated users skip auth and can finish PayPal flow', async ({ page }) => {
|
||||||
// Ähnlich wie Free, aber package_id=2
|
await page.route('https://js.stripe.com/v3', async (route) => {
|
||||||
await page.goto('http://localhost:8000/de/packages');
|
await route.fulfill({
|
||||||
await page.getByRole('button', { name: 'Details anzeigen' }).nth(1).click(); // Zweites Paket (Paid)
|
status: 200,
|
||||||
// ... (Modal, Register/Login wie oben)
|
contentType: 'application/javascript',
|
||||||
await expect(page).toHaveURL(/\/buy-packages\/2/);
|
body: `window.Stripe = function(){
|
||||||
|
return {
|
||||||
// Mock Stripe
|
elements: function(){
|
||||||
await page.route('https://checkout.stripe.com/**', async route => {
|
return {
|
||||||
await route.fulfill({ status: 200, body: '<html>Mock Stripe Success</html>' });
|
create: function(){
|
||||||
|
return {
|
||||||
|
mount: function(){},
|
||||||
|
destroy: function(){},
|
||||||
|
on: function(){},
|
||||||
|
update: function(){},
|
||||||
|
unmount: function(){},
|
||||||
|
};
|
||||||
|
},
|
||||||
|
getElement: function(){
|
||||||
|
return {
|
||||||
|
clear: function(){},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
};
|
||||||
|
},
|
||||||
|
confirmCardPayment: async function(){
|
||||||
|
return { paymentIntent: { id: 'pi_test', status: 'succeeded' } };
|
||||||
|
}
|
||||||
|
};
|
||||||
|
};`
|
||||||
|
});
|
||||||
});
|
});
|
||||||
// Simuliere Checkout: Fill Test-Karte
|
|
||||||
await page.fill('[name="cardNumber"]', '4242424242424242');
|
|
||||||
await page.fill('[name="cardExpiry"]', '12/25');
|
|
||||||
await page.fill('[name="cardCvc"]', '123');
|
|
||||||
await page.click('[name="submit"]');
|
|
||||||
await page.waitForURL(/\/marketing\/success/); // Nach Webhook
|
|
||||||
await page.screenshot({ path: 'paid-step6-success.png', fullPage: true });
|
|
||||||
|
|
||||||
// Integration: Limits-Check wie in package-flow.test.ts
|
await page.route('https://www.paypal.com/sdk/js?**', async (route) => {
|
||||||
await expect(page.locator('text=Remaining Photos')).toContainText('Unbegrenzt'); // Pro-Limit
|
await route.fulfill({
|
||||||
|
status: 200,
|
||||||
|
contentType: 'application/javascript',
|
||||||
|
body: `window.paypal = {
|
||||||
|
Buttons: function(options){
|
||||||
|
return {
|
||||||
|
render: function(container){
|
||||||
|
const target = typeof container === 'string' ? document.querySelector(container) : container;
|
||||||
|
if (!target) return;
|
||||||
|
const btn = document.createElement('button');
|
||||||
|
btn.type = 'button';
|
||||||
|
btn.textContent = 'PayPal Test Button';
|
||||||
|
btn.addEventListener('click', async () => {
|
||||||
|
try {
|
||||||
|
const orderId = await options.createOrder();
|
||||||
|
await options.onApprove({ orderID: orderId });
|
||||||
|
} catch (error) {
|
||||||
|
if (options.onError) options.onError(error);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
target.innerHTML = '';
|
||||||
|
target.appendChild(btn);
|
||||||
|
},
|
||||||
|
close: function(){}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
};`
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
await page.route('**/purchase/auth/login', (route) => route.fulfill({
|
||||||
|
status: 200,
|
||||||
|
contentType: 'application/json',
|
||||||
|
body: JSON.stringify({
|
||||||
|
status: 'authenticated',
|
||||||
|
user: { id: 1, email: 'test@example.com', name: 'Test User', pending_purchase: false, email_verified: true },
|
||||||
|
next_step: 'payment',
|
||||||
|
needs_verification: false,
|
||||||
|
}),
|
||||||
|
}));
|
||||||
|
|
||||||
|
await page.route('**/purchase/auth/register', (route) => route.fulfill({
|
||||||
|
status: 200,
|
||||||
|
contentType: 'application/json',
|
||||||
|
body: JSON.stringify({
|
||||||
|
status: 'registered',
|
||||||
|
user: { id: 2, email: 'new@example.com', name: 'New User', pending_purchase: true, email_verified: false },
|
||||||
|
next_step: 'payment',
|
||||||
|
}),
|
||||||
|
}));
|
||||||
|
|
||||||
|
await page.route('**/purchase/stripe/intent', (route) => route.fulfill({
|
||||||
|
status: 200,
|
||||||
|
contentType: 'application/json',
|
||||||
|
body: JSON.stringify({ client_secret: 'pi_secret', payment_intent_id: 'pi_test' }),
|
||||||
|
}));
|
||||||
|
|
||||||
|
await page.route('**/purchase/stripe/complete', (route) => route.fulfill({
|
||||||
|
status: 200,
|
||||||
|
contentType: 'application/json',
|
||||||
|
body: JSON.stringify({ status: 'completed' }),
|
||||||
|
}));
|
||||||
|
|
||||||
|
await page.route('**/purchase/paypal/order', (route) => route.fulfill({
|
||||||
|
status: 200,
|
||||||
|
contentType: 'application/json',
|
||||||
|
body: JSON.stringify({ order_id: 'ORDER-TEST', status: 'CREATED' }),
|
||||||
|
}));
|
||||||
|
|
||||||
|
await page.route('**/purchase/paypal/capture', (route) => route.fulfill({
|
||||||
|
status: 200,
|
||||||
|
contentType: 'application/json',
|
||||||
|
body: JSON.stringify({ status: 'captured' }),
|
||||||
|
}));
|
||||||
|
|
||||||
|
await page.goto(`${BASE_URL}/de/login`);
|
||||||
|
await page.fill('input[name="login"]', 'test@example.com');
|
||||||
|
await page.fill('input[name="password"]', 'password123');
|
||||||
|
await page.getByRole('button', { name: /Anmelden/i }).click();
|
||||||
|
await expect(page).toHaveURL(/dashboard|admin/i, { timeout: 10000 });
|
||||||
|
|
||||||
|
await page.goto(`${BASE_URL}/purchase-wizard/2`);
|
||||||
|
|
||||||
|
await page.getByRole('button', { name: /Weiter/i }).click();
|
||||||
|
|
||||||
|
await expect(page.getByRole('button', { name: 'Stripe' })).toBeVisible();
|
||||||
|
await expect(page.getByRole('button', { name: 'PayPal' })).toBeVisible();
|
||||||
|
|
||||||
|
await page.getByRole('button', { name: 'PayPal' }).click();
|
||||||
|
await page.getByRole('button', { name: 'PayPal Test Button' }).click();
|
||||||
|
|
||||||
|
await expect(page.getByText(/Willkommen/i)).toBeVisible();
|
||||||
|
await expect(page.getByRole('button', { name: /Dashboard/i })).toBeVisible();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
Reference in New Issue
Block a user