removed all references to credits. now credits are completely replaced by addons.
This commit is contained in:
@@ -1,120 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Models\Tenant;
|
||||
use App\Models\User;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Console\Attributes\AsCommand;
|
||||
|
||||
#[AsCommand(name: 'tenant:add-dummy')]
|
||||
class AddDummyTenantUser extends Command
|
||||
{
|
||||
protected $signature = 'tenant:add-dummy
|
||||
{--email=demo@example.com}
|
||||
{--password=secret123!}
|
||||
{--tenant="Demo Tenant"}
|
||||
{--name="Demo Admin"}
|
||||
{--first_name="Demo"}
|
||||
{--last_name="Admin"}
|
||||
{--address="Demo Str. 1, 12345 Demo City"}
|
||||
{--phone="+49 123 4567890"}
|
||||
{--update-password : Overwrite password if user already exists}
|
||||
';
|
||||
protected $description = 'Create a demo tenant and a tenant user with given credentials.';
|
||||
|
||||
public function handle(): int
|
||||
{
|
||||
$email = (string) $this->option('email');
|
||||
$password = (string) $this->option('password');
|
||||
$tenantName = (string) $this->option('tenant');
|
||||
$userName = (string) $this->option('name');
|
||||
$firstName = (string) $this->option('first_name');
|
||||
$lastName = (string) $this->option('last_name');
|
||||
$address = (string) $this->option('address');
|
||||
$phone = (string) $this->option('phone');
|
||||
|
||||
$this->info('Starting dummy tenant creation with email: ' . $email);
|
||||
|
||||
// Pre-flight checks for common failures
|
||||
if (! Schema::hasTable('users')) {
|
||||
$this->error("Table 'users' does not exist. Run: php artisan migrate");
|
||||
return self::FAILURE;
|
||||
}
|
||||
if (! Schema::hasTable('tenants')) {
|
||||
$this->error("Table 'tenants' does not exist. Run: php artisan migrate");
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
DB::beginTransaction();
|
||||
try {
|
||||
// Create or fetch tenant
|
||||
$slug = Str::slug($tenantName ?: 'demo-tenant');
|
||||
/** @var Tenant $tenant */
|
||||
$tenant = Tenant::query()->where('slug', $slug)->first();
|
||||
if (! $tenant) {
|
||||
$tenant = new Tenant();
|
||||
$tenant->name = $tenantName;
|
||||
$tenant->slug = $slug;
|
||||
$tenant->domain = null;
|
||||
$tenant->contact_name = $userName;
|
||||
$tenant->contact_email = $email;
|
||||
$tenant->contact_phone = $phone ?: null;
|
||||
$tenant->event_credits_balance = 1;
|
||||
$tenant->max_photos_per_event = 500;
|
||||
$tenant->max_storage_mb = 1024;
|
||||
$tenant->features = ['custom_branding' => false];
|
||||
$tenant->is_active = true;
|
||||
$tenant->is_suspended = false;
|
||||
$tenant->save();
|
||||
$this->info('Created new tenant: ' . $tenant->name);
|
||||
} else {
|
||||
$this->info('Using existing tenant: ' . $tenant->name);
|
||||
}
|
||||
|
||||
// Create or fetch user
|
||||
/** @var User $user */
|
||||
$user = User::query()->where('email', $email)->first();
|
||||
$updatePassword = (bool) $this->option('update-password');
|
||||
if (! $user) {
|
||||
$user = new User();
|
||||
if (Schema::hasColumn($user->getTable(), 'name')) $user->name = $userName;
|
||||
$user->email = $email;
|
||||
$user->password = Hash::make($password);
|
||||
$this->info('Creating new user: ' . $email);
|
||||
} else if ($updatePassword) {
|
||||
$user->password = Hash::make($password);
|
||||
$this->info('Updating password for existing user: ' . $email);
|
||||
}
|
||||
if (Schema::hasColumn($user->getTable(), 'first_name')) $user->first_name = $firstName;
|
||||
if (Schema::hasColumn($user->getTable(), 'last_name')) $user->last_name = $lastName;
|
||||
if (Schema::hasColumn($user->getTable(), 'address')) $user->address = $address;
|
||||
if (Schema::hasColumn($user->getTable(), 'phone')) $user->phone = $phone;
|
||||
if (Schema::hasColumn($user->getTable(), 'tenant_id')) {
|
||||
$user->tenant_id = $tenant->id;
|
||||
}
|
||||
if (Schema::hasColumn($user->getTable(), 'role')) {
|
||||
$user->role = 'tenant_admin';
|
||||
}
|
||||
$user->save();
|
||||
$this->info('User saved successfully.');
|
||||
|
||||
DB::commit();
|
||||
} catch (\Throwable $e) {
|
||||
DB::rollBack();
|
||||
$this->error('Failed: '.$e->getMessage());
|
||||
$this->error('Stack trace: ' . $e->getTraceAsString());
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$this->info('Dummy tenant user created/updated.');
|
||||
$this->line('Tenant: '.$tenant->name.' (#'.$tenant->id.')');
|
||||
$this->line('Email: '.$email);
|
||||
$this->line('Password: '.$password);
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -30,56 +30,8 @@ class CheckEventPackages extends Command
|
||||
->sortDesc()
|
||||
->values();
|
||||
|
||||
$creditThresholds = collect(config('package-limits.credit_thresholds', []))
|
||||
->filter(fn ($value) => is_numeric($value) && $value >= 0)
|
||||
->map(fn ($value) => (int) $value)
|
||||
->unique()
|
||||
->sortDesc()
|
||||
->values();
|
||||
|
||||
$maxCreditThreshold = $creditThresholds->max();
|
||||
|
||||
$now = now();
|
||||
|
||||
if ($maxCreditThreshold !== null) {
|
||||
\App\Models\Tenant::query()
|
||||
->select(['id', 'event_credits_balance', 'credit_warning_sent_at', 'credit_warning_threshold', 'contact_email'])
|
||||
->chunkById(100, function ($tenants) use ($creditThresholds, $maxCreditThreshold, $now) {
|
||||
foreach ($tenants as $tenant) {
|
||||
$balance = (int) ($tenant->event_credits_balance ?? 0);
|
||||
|
||||
if ($balance > $maxCreditThreshold && $tenant->credit_warning_sent_at) {
|
||||
$tenant->forceFill([
|
||||
'credit_warning_sent_at' => null,
|
||||
'credit_warning_threshold' => null,
|
||||
])->save();
|
||||
|
||||
PackageLimitMetrics::recordCreditRecovery($balance);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach ($creditThresholds as $threshold) {
|
||||
if (
|
||||
$balance <= $threshold
|
||||
&& (
|
||||
$tenant->credit_warning_sent_at === null
|
||||
|| $threshold < ($tenant->credit_warning_threshold ?? PHP_INT_MAX)
|
||||
)
|
||||
) {
|
||||
event(new \App\Events\Packages\TenantCreditsLow($tenant, $balance, $threshold));
|
||||
PackageLimitMetrics::recordCreditWarning($threshold, $balance);
|
||||
$tenant->forceFill([
|
||||
'credit_warning_sent_at' => $now,
|
||||
'credit_warning_threshold' => $threshold,
|
||||
])->save();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
EventPackage::query()
|
||||
->whereNotNull('gallery_expires_at')
|
||||
->chunkById(100, function ($packages) use ($warningDays, $now) {
|
||||
|
||||
@@ -1,93 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\Event;
|
||||
use App\Models\Package;
|
||||
use App\Models\TenantPackage;
|
||||
use App\Models\EventPackage;
|
||||
use App\Models\PackagePurchase;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class MigrateToPackages extends Command
|
||||
{
|
||||
protected $signature = 'packages:migrate';
|
||||
protected $description = 'Migrate existing credits data to packages';
|
||||
|
||||
public function handle()
|
||||
{
|
||||
DB::transaction(function () {
|
||||
// Find Free package for endcustomer
|
||||
$freePackage = Package::where('name', 'Free / Test')->where('type', 'endcustomer')->first();
|
||||
if (!$freePackage) {
|
||||
$this->error('Free package not found. Run seeder first.');
|
||||
return 1;
|
||||
}
|
||||
|
||||
$resellerPackage = Package::where('name', 'Reseller S')->where('type', 'reseller')->first();
|
||||
if (!$resellerPackage) {
|
||||
$this->error('Reseller package not found. Run seeder first.');
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Migrate tenants with credits to tenant_packages (reseller free)
|
||||
$tenants = Tenant::where('event_credits_balance', '>', 0)->get();
|
||||
foreach ($tenants as $tenant) {
|
||||
$initialEvents = floor($tenant->event_credits_balance / 100); // Arbitrary conversion
|
||||
TenantPackage::create([
|
||||
'tenant_id' => $tenant->id,
|
||||
'package_id' => $resellerPackage->id,
|
||||
'price' => 0,
|
||||
'purchased_at' => now(),
|
||||
'expires_at' => now()->addYear(),
|
||||
'used_events' => 0,
|
||||
'active' => true,
|
||||
]);
|
||||
|
||||
PackagePurchase::create([
|
||||
'tenant_id' => $tenant->id,
|
||||
'package_id' => $resellerPackage->id,
|
||||
'type' => 'reseller_subscription',
|
||||
'provider_id' => 'migration',
|
||||
'price' => 0,
|
||||
'metadata' => ['migrated_credits' => $tenant->event_credits_balance],
|
||||
]);
|
||||
|
||||
$this->info("Migrated tenant {$tenant->name} with {$tenant->event_credits_balance} credits to Reseller S package.");
|
||||
}
|
||||
|
||||
// Migrate events to event_packages (free)
|
||||
$events = Event::all();
|
||||
foreach ($events as $event) {
|
||||
EventPackage::create([
|
||||
'event_id' => $event->id,
|
||||
'package_id' => $freePackage->id,
|
||||
'price' => 0,
|
||||
'purchased_at' => $event->created_at,
|
||||
'used_photos' => 0,
|
||||
]);
|
||||
|
||||
PackagePurchase::create([
|
||||
'tenant_id' => $event->tenant_id,
|
||||
'event_id' => $event->id,
|
||||
'package_id' => $freePackage->id,
|
||||
'type' => 'endcustomer',
|
||||
'provider_id' => 'migration',
|
||||
'price' => 0,
|
||||
'metadata' => ['migrated_from_credits' => true],
|
||||
]);
|
||||
|
||||
$this->info("Migrated event {$event->name} to Free package.");
|
||||
}
|
||||
|
||||
// Clear old credits data (assume drop migration already run)
|
||||
Tenant::where('event_credits_balance', '>', 0)->update(['event_credits_balance' => 0]);
|
||||
|
||||
$this->info('Migration completed successfully.');
|
||||
});
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,6 @@ use App\Jobs\Packages\SendEventPackageGuestLimitNotification;
|
||||
use App\Jobs\Packages\SendEventPackageGuestThresholdWarning;
|
||||
use App\Jobs\Packages\SendEventPackagePhotoLimitNotification;
|
||||
use App\Jobs\Packages\SendEventPackagePhotoThresholdWarning;
|
||||
use App\Jobs\Packages\SendTenantCreditsLowNotification;
|
||||
use App\Jobs\Packages\SendTenantPackageEventLimitNotification;
|
||||
use App\Jobs\Packages\SendTenantPackageEventThresholdWarning;
|
||||
use App\Jobs\Packages\SendTenantPackageExpiredNotification;
|
||||
@@ -16,7 +15,6 @@ use App\Jobs\Packages\SendTenantPackageExpiringNotification;
|
||||
use App\Models\TenantNotificationLog;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Arr;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
class RetryTenantNotification extends Command
|
||||
{
|
||||
@@ -78,7 +76,6 @@ class RetryTenantNotification extends Command
|
||||
'guest_limit' => $this->dispatchGuestLimit($context),
|
||||
'gallery_warning' => $this->dispatchGalleryWarning($context),
|
||||
'gallery_expired' => $this->dispatchGalleryExpired($context),
|
||||
'credits_low' => $this->dispatchCreditsLow($log->tenant_id, $context),
|
||||
'event_threshold' => $this->dispatchEventThreshold($context),
|
||||
'event_limit' => $this->dispatchEventLimit($context),
|
||||
'package_expiring' => $this->dispatchPackageExpiring($context),
|
||||
@@ -174,23 +171,6 @@ class RetryTenantNotification extends Command
|
||||
return true;
|
||||
}
|
||||
|
||||
private function dispatchCreditsLow(int $tenantId, array $context): bool
|
||||
{
|
||||
$balance = Arr::get($context, 'balance');
|
||||
$threshold = Arr::get($context, 'threshold');
|
||||
|
||||
if ($balance === null || $threshold === null) {
|
||||
Log::warning('credits_low retry missing balance or threshold', compact('tenantId', 'context'));
|
||||
}
|
||||
|
||||
$balance = $balance !== null ? (int) $balance : 0;
|
||||
$threshold = $threshold !== null ? (int) $threshold : 0;
|
||||
|
||||
SendTenantCreditsLowNotification::dispatch($tenantId, $balance, $threshold);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private function dispatchEventThreshold(array $context): bool
|
||||
{
|
||||
$tenantPackageId = Arr::get($context, 'tenant_package_id');
|
||||
|
||||
@@ -1,613 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Models\Event;
|
||||
use App\Models\EventPackage;
|
||||
use App\Models\EventType;
|
||||
use App\Models\Package;
|
||||
use App\Models\Photo;
|
||||
use App\Models\TaskCollection;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\TenantPackage;
|
||||
use App\Models\User;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Arr;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class SeedDemoSwitcherTenants extends Command
|
||||
{
|
||||
protected $signature = 'demo:seed-switcher {--with-photos : Download sample photos from Pexels} {--photos-per-event=18 : Target photos per event when downloading} {--cleanup : Remove demo switcher tenants/events/photos instead of seeding}';
|
||||
|
||||
protected $description = 'Seeds demo tenants used by the DevTenantSwitcher (endcustomer + reseller profiles)';
|
||||
|
||||
public function handle(): int
|
||||
{
|
||||
if (! app()->environment(['local', 'development', 'demo'])) {
|
||||
$this->error('Cleanup/Seeding is restricted to local/development/demo environments.');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
if ($this->option('cleanup')) {
|
||||
return $this->cleanup();
|
||||
}
|
||||
|
||||
$this->info('Seeding demo tenants for switcher...');
|
||||
|
||||
$packages = $this->loadPackages();
|
||||
$eventTypes = $this->loadEventTypes();
|
||||
|
||||
DB::transaction(function () use ($packages, $eventTypes) {
|
||||
$this->seedCustomerStandardEmpty($packages, $eventTypes);
|
||||
$this->seedCustomerStarterWedding($packages, $eventTypes);
|
||||
$this->seedResellerActive($packages, $eventTypes);
|
||||
$this->seedResellerFull($packages, $eventTypes);
|
||||
});
|
||||
|
||||
if ($this->option('with-photos')) {
|
||||
$this->seedPhotosFromPexels((int) $this->option('photos-per-event'));
|
||||
}
|
||||
|
||||
$this->info('Done.');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
private function cleanup(): int
|
||||
{
|
||||
$slugs = [
|
||||
'demo-standard-empty',
|
||||
'demo-starter-wedding',
|
||||
'demo-reseller-active',
|
||||
'demo-reseller-full',
|
||||
];
|
||||
|
||||
$eventsDeleted = 0;
|
||||
$photosDeleted = 0;
|
||||
$photoLikesDeleted = 0;
|
||||
$usersDeleted = 0;
|
||||
|
||||
foreach ($slugs as $slug) {
|
||||
$tenant = Tenant::where('slug', $slug)->first();
|
||||
|
||||
if (! $tenant) {
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach ($tenant->events as $event) {
|
||||
$eventsDeleted++;
|
||||
$photos = Photo::where('event_id', $event->id)->get();
|
||||
foreach ($photos as $photo) {
|
||||
$deletedLikes = $photo->likes()->count();
|
||||
$photo->likes()->delete();
|
||||
$photoLikesDeleted += $deletedLikes;
|
||||
|
||||
if ($photo->thumbnail_path) {
|
||||
Storage::disk('public')->delete($photo->thumbnail_path);
|
||||
}
|
||||
|
||||
if ($photo->file_path) {
|
||||
Storage::disk('public')->delete($photo->file_path);
|
||||
}
|
||||
|
||||
$photo->delete();
|
||||
$photosDeleted++;
|
||||
}
|
||||
|
||||
Storage::disk('public')->deleteDirectory("events/{$event->id}/gallery");
|
||||
Storage::disk('public')->deleteDirectory("events/{$event->id}/gallery/thumbs");
|
||||
|
||||
$event->taskCollections()->detach();
|
||||
$event->tasks()->detach();
|
||||
$event->eventPackages()->delete();
|
||||
$event->delete();
|
||||
}
|
||||
|
||||
TenantPackage::where('tenant_id', $tenant->id)->delete();
|
||||
$usersDeleted += User::where('tenant_id', $tenant->id)->count();
|
||||
User::where('tenant_id', $tenant->id)->delete();
|
||||
$tenant->delete();
|
||||
}
|
||||
|
||||
$this->info(
|
||||
'Cleanup completed. Tenants deleted: '.count($slugs)
|
||||
.", Users deleted: {$usersDeleted}, Events deleted: {$eventsDeleted}, Photos deleted: {$photosDeleted}, Photo likes deleted: {$photoLikesDeleted}"
|
||||
);
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
private function loadPackages(): array
|
||||
{
|
||||
$slugs = [
|
||||
'starter' => 'Starter',
|
||||
'standard' => 'Standard',
|
||||
's-small-reseller' => 'Reseller S',
|
||||
];
|
||||
|
||||
$packages = [];
|
||||
foreach ($slugs as $slug => $label) {
|
||||
$package = Package::where('slug', $slug)->first();
|
||||
if (! $package) {
|
||||
$this->error("Package {$label} ({$slug}) not found. Run PackageSeeder first.");
|
||||
abort(1);
|
||||
}
|
||||
|
||||
$packages[$slug] = $package;
|
||||
}
|
||||
|
||||
return $packages;
|
||||
}
|
||||
|
||||
private function loadEventTypes(): array
|
||||
{
|
||||
$slugs = ['wedding', 'corporate', 'birthday', 'festival'];
|
||||
$types = [];
|
||||
|
||||
foreach ($slugs as $slug) {
|
||||
$eventType = EventType::where('slug', $slug)->first();
|
||||
if ($eventType) {
|
||||
$types[$slug] = $eventType;
|
||||
}
|
||||
}
|
||||
|
||||
return $types;
|
||||
}
|
||||
|
||||
private function seedCustomerStandardEmpty(array $packages, array $eventTypes): void
|
||||
{
|
||||
$tenant = $this->upsertTenant(
|
||||
slug: 'demo-standard-empty',
|
||||
name: 'Demo Standard (ohne Event)',
|
||||
contactEmail: 'standard-empty@demo.fotospiel',
|
||||
attributes: [
|
||||
'subscription_tier' => 'standard',
|
||||
'subscription_status' => 'active',
|
||||
'event_credits_balance' => 1,
|
||||
],
|
||||
);
|
||||
|
||||
$this->upsertAdmin($tenant, 'standard-empty@demo.fotospiel');
|
||||
|
||||
TenantPackage::updateOrCreate(
|
||||
['tenant_id' => $tenant->id, 'package_id' => $packages['standard']->id],
|
||||
[
|
||||
'price' => $packages['standard']->price,
|
||||
'purchased_at' => Carbon::now()->subDays(1),
|
||||
'expires_at' => Carbon::now()->addMonths(12),
|
||||
'used_events' => 0,
|
||||
'active' => true,
|
||||
]
|
||||
);
|
||||
|
||||
$this->comment('Seeded Standard tenant without events.');
|
||||
}
|
||||
|
||||
private function seedCustomerStarterWedding(array $packages, array $eventTypes): void
|
||||
{
|
||||
$tenant = $this->upsertTenant(
|
||||
slug: 'demo-starter-wedding',
|
||||
name: 'Demo Starter Wedding',
|
||||
contactEmail: 'starter-wedding@demo.fotospiel',
|
||||
attributes: [
|
||||
'subscription_tier' => 'starter',
|
||||
'subscription_status' => 'active',
|
||||
'event_credits_balance' => 0,
|
||||
],
|
||||
);
|
||||
|
||||
$this->upsertAdmin($tenant, 'starter-wedding@demo.fotospiel');
|
||||
|
||||
$event = $this->upsertEvent(
|
||||
tenant: $tenant,
|
||||
package: $packages['starter'],
|
||||
eventType: $eventTypes['wedding'] ?? null,
|
||||
attributes: [
|
||||
'name' => ['de' => 'Hochzeit Mia & Jonas', 'en' => 'Wedding Mia & Jonas'],
|
||||
'slug' => 'demo-starter-wedding',
|
||||
'status' => 'published',
|
||||
'is_active' => true,
|
||||
'date' => Carbon::now()->addWeeks(5),
|
||||
],
|
||||
);
|
||||
|
||||
$this->attachDefaultCollections($event);
|
||||
}
|
||||
|
||||
private function seedResellerActive(array $packages, array $eventTypes): void
|
||||
{
|
||||
$tenant = $this->upsertTenant(
|
||||
slug: 'demo-reseller-active',
|
||||
name: 'Demo Reseller Active',
|
||||
contactEmail: 'reseller-active@demo.fotospiel',
|
||||
attributes: [
|
||||
'subscription_tier' => 'reseller',
|
||||
'subscription_status' => 'active',
|
||||
'event_credits_balance' => 2,
|
||||
],
|
||||
);
|
||||
|
||||
$this->upsertAdmin($tenant, 'reseller-active@demo.fotospiel');
|
||||
|
||||
TenantPackage::updateOrCreate(
|
||||
['tenant_id' => $tenant->id, 'package_id' => $packages['s-small-reseller']->id],
|
||||
[
|
||||
'price' => $packages['s-small-reseller']->price,
|
||||
'purchased_at' => Carbon::now()->subMonths(1),
|
||||
'expires_at' => Carbon::now()->addMonths(11),
|
||||
'used_events' => 3,
|
||||
'active' => true,
|
||||
]
|
||||
);
|
||||
|
||||
$events = [
|
||||
[
|
||||
'name' => ['de' => 'Corporate Summit', 'en' => 'Corporate Summit'],
|
||||
'slug' => 'demo-reseller-corporate',
|
||||
'type' => $eventTypes['corporate'] ?? null,
|
||||
'date' => Carbon::now()->addWeeks(3),
|
||||
],
|
||||
[
|
||||
'name' => ['de' => 'Sommerfestival', 'en' => 'Summer Festival'],
|
||||
'slug' => 'demo-reseller-festival',
|
||||
'type' => $eventTypes['festival'] ?? ($eventTypes['birthday'] ?? null),
|
||||
'date' => Carbon::now()->addWeeks(6),
|
||||
],
|
||||
[
|
||||
'name' => ['de' => 'Geburtstag Lisa', 'en' => 'Lisa Birthday'],
|
||||
'slug' => 'demo-reseller-birthday',
|
||||
'type' => $eventTypes['birthday'] ?? null,
|
||||
'date' => Carbon::now()->addWeeks(9),
|
||||
],
|
||||
];
|
||||
|
||||
foreach ($events as $index => $config) {
|
||||
$event = $this->upsertEvent(
|
||||
tenant: $tenant,
|
||||
package: $packages['standard'],
|
||||
eventType: $config['type'],
|
||||
attributes: [
|
||||
'name' => $config['name'],
|
||||
'slug' => $config['slug'],
|
||||
'status' => 'published',
|
||||
'is_active' => true,
|
||||
'date' => $config['date'],
|
||||
],
|
||||
);
|
||||
|
||||
$this->attachDefaultCollections($event);
|
||||
}
|
||||
}
|
||||
|
||||
private function seedResellerFull(array $packages, array $eventTypes): void
|
||||
{
|
||||
$tenant = $this->upsertTenant(
|
||||
slug: 'demo-reseller-full',
|
||||
name: 'Demo Reseller Voll',
|
||||
contactEmail: 'reseller-full@demo.fotospiel',
|
||||
attributes: [
|
||||
'subscription_tier' => 'reseller',
|
||||
'subscription_status' => 'active',
|
||||
'event_credits_balance' => 0,
|
||||
],
|
||||
);
|
||||
|
||||
$this->upsertAdmin($tenant, 'reseller-full@demo.fotospiel');
|
||||
|
||||
TenantPackage::updateOrCreate(
|
||||
['tenant_id' => $tenant->id, 'package_id' => $packages['s-small-reseller']->id],
|
||||
[
|
||||
'price' => $packages['s-small-reseller']->price,
|
||||
'purchased_at' => Carbon::now()->subMonths(6),
|
||||
'expires_at' => Carbon::now()->addMonths(6),
|
||||
'used_events' => 5,
|
||||
'active' => true,
|
||||
]
|
||||
);
|
||||
|
||||
$eventConfigs = [
|
||||
['slug' => 'demo-full-wedding', 'name' => ['de' => 'Hochzeit Clara & Ben', 'en' => 'Wedding Clara & Ben'], 'type' => $eventTypes['wedding'] ?? null],
|
||||
['slug' => 'demo-full-corporate', 'name' => ['de' => 'Jahrestagung', 'en' => 'Annual Summit'], 'type' => $eventTypes['corporate'] ?? null],
|
||||
['slug' => 'demo-full-birthday', 'name' => ['de' => 'Geburtstag Jonas', 'en' => 'Birthday Jonas'], 'type' => $eventTypes['birthday'] ?? null],
|
||||
['slug' => 'demo-full-festival', 'name' => ['de' => 'Stadtfest', 'en' => 'City Festival'], 'type' => $eventTypes['festival'] ?? null],
|
||||
['slug' => 'demo-full-christmas', 'name' => ['de' => 'Weihnachtsfeier', 'en' => 'Christmas Party'], 'type' => $eventTypes['corporate'] ?? null],
|
||||
];
|
||||
|
||||
foreach ($eventConfigs as $index => $config) {
|
||||
$event = $this->upsertEvent(
|
||||
tenant: $tenant,
|
||||
package: $packages['standard'],
|
||||
eventType: $config['type'],
|
||||
attributes: [
|
||||
'name' => $config['name'],
|
||||
'slug' => $config['slug'],
|
||||
'status' => 'archived',
|
||||
'is_active' => false,
|
||||
'date' => Carbon::now()->subWeeks(5 - $index),
|
||||
],
|
||||
);
|
||||
|
||||
$this->attachDefaultCollections($event);
|
||||
}
|
||||
}
|
||||
|
||||
private function upsertTenant(string $slug, string $name, string $contactEmail, array $attributes = []): Tenant
|
||||
{
|
||||
$defaults = [
|
||||
'name' => $name,
|
||||
'contact_email' => $contactEmail,
|
||||
'subscription_expires_at' => Carbon::now()->addMonths(12),
|
||||
'is_active' => true,
|
||||
'is_suspended' => false,
|
||||
'settings_updated_at' => Carbon::now(),
|
||||
'settings' => [
|
||||
'branding' => [
|
||||
'logo_url' => null,
|
||||
'primary_color' => '#1D4ED8',
|
||||
'secondary_color' => '#0F172A',
|
||||
'font_family' => 'Inter, sans-serif',
|
||||
],
|
||||
'features' => [
|
||||
'photo_likes_enabled' => true,
|
||||
'event_checklist' => true,
|
||||
],
|
||||
'contact_email' => $contactEmail,
|
||||
],
|
||||
];
|
||||
|
||||
return Tenant::updateOrCreate(
|
||||
['slug' => $slug],
|
||||
array_merge($defaults, $attributes, ['slug' => $slug])
|
||||
);
|
||||
}
|
||||
|
||||
private function upsertAdmin(Tenant $tenant, string $email): User
|
||||
{
|
||||
$password = config('seeding.demo_tenant_password', 'Demo1234!');
|
||||
|
||||
$user = User::updateOrCreate(
|
||||
['email' => $email],
|
||||
[
|
||||
'tenant_id' => $tenant->id,
|
||||
'role' => 'tenant_admin',
|
||||
'password' => Hash::make($password),
|
||||
'first_name' => Str::headline(Str::before($tenant->slug, '-')),
|
||||
'last_name' => 'Demo',
|
||||
]
|
||||
);
|
||||
|
||||
if (! $user->email_verified_at) {
|
||||
$user->forceFill(['email_verified_at' => now()])->save();
|
||||
}
|
||||
|
||||
return $user;
|
||||
}
|
||||
|
||||
private function upsertEvent(Tenant $tenant, Package $package, ?EventType $eventType, array $attributes): Event
|
||||
{
|
||||
$resolvedEventType = $eventType ?? $this->fallbackEventType();
|
||||
|
||||
$payload = array_merge([
|
||||
'tenant_id' => $tenant->id,
|
||||
'event_type_id' => $resolvedEventType?->id,
|
||||
'settings' => [
|
||||
'features' => [
|
||||
'photo_likes_enabled' => true,
|
||||
'event_checklist' => true,
|
||||
],
|
||||
],
|
||||
], $attributes);
|
||||
|
||||
/** @var Event $event */
|
||||
$event = Event::updateOrCreate(
|
||||
['slug' => $attributes['slug']],
|
||||
$payload
|
||||
);
|
||||
|
||||
EventPackage::updateOrCreate(
|
||||
[
|
||||
'event_id' => $event->id,
|
||||
'package_id' => $package->id,
|
||||
],
|
||||
[
|
||||
'purchased_price' => $package->price,
|
||||
'purchased_at' => Carbon::now()->subDays(2),
|
||||
'used_photos' => 0,
|
||||
'used_guests' => 0,
|
||||
'gallery_expires_at' => Carbon::now()->addDays($package->gallery_days ?? 30),
|
||||
]
|
||||
);
|
||||
|
||||
return $event;
|
||||
}
|
||||
|
||||
private function fallbackEventType(): ?EventType
|
||||
{
|
||||
$fallback = EventType::first();
|
||||
|
||||
if (! $fallback) {
|
||||
$this->warn('No EventType available, events will miss type. Please run EventTypesSeeder.');
|
||||
}
|
||||
|
||||
return $fallback;
|
||||
}
|
||||
|
||||
private function attachDefaultCollections(Event $event): void
|
||||
{
|
||||
if (! $event->event_type_id) {
|
||||
return;
|
||||
}
|
||||
|
||||
$collection = TaskCollection::where('event_type_id', $event->event_type_id)
|
||||
->where('is_default', true)
|
||||
->orderBy('position')
|
||||
->first();
|
||||
|
||||
if (! $collection) {
|
||||
return;
|
||||
}
|
||||
|
||||
$event->taskCollections()->syncWithoutDetaching([$collection->id]);
|
||||
|
||||
$taskIds = $collection->tasks()->pluck('tasks.id')->all();
|
||||
if ($taskIds !== []) {
|
||||
$event->tasks()->syncWithoutDetaching($taskIds);
|
||||
}
|
||||
}
|
||||
|
||||
private function seedPhotosFromPexels(int $targetPerEvent): void
|
||||
{
|
||||
$apiKey = config('services.pexels.key') ?? env('PEXELS_API_KEY');
|
||||
if (! $apiKey) {
|
||||
$this->warn('PEXELS_API_KEY missing, skipping photo download.');
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$events = Event::whereIn('slug', [
|
||||
'demo-starter-wedding',
|
||||
'demo-reseller-corporate',
|
||||
'demo-reseller-festival',
|
||||
'demo-reseller-birthday',
|
||||
'demo-full-wedding',
|
||||
'demo-full-corporate',
|
||||
'demo-full-birthday',
|
||||
'demo-full-festival',
|
||||
'demo-full-christmas',
|
||||
])->get();
|
||||
|
||||
foreach ($events as $event) {
|
||||
$query = $this->guessQueryForEvent($event);
|
||||
$this->info("Downloading photos for {$event->slug} ({$query})...");
|
||||
|
||||
$photos = $this->fetchPexels($apiKey, $query, $targetPerEvent);
|
||||
if ($photos === []) {
|
||||
$this->warn('No photos returned from Pexels.');
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$this->storePhotos($event, $photos);
|
||||
}
|
||||
}
|
||||
|
||||
private function guessQueryForEvent(Event $event): string
|
||||
{
|
||||
$typeSlug = optional($event->eventType)->slug;
|
||||
|
||||
return match ($typeSlug) {
|
||||
'wedding' => 'wedding photography couple',
|
||||
'corporate' => 'corporate event people',
|
||||
'birthday' => 'birthday party friends',
|
||||
default => 'event celebration crowd',
|
||||
};
|
||||
}
|
||||
|
||||
private function fetchPexels(string $apiKey, string $query, int $count): array
|
||||
{
|
||||
$perPage = min(40, max(5, $count));
|
||||
|
||||
$response = Http::withHeaders([
|
||||
'Authorization' => $apiKey,
|
||||
])->get('https://api.pexels.com/v1/search', [
|
||||
'query' => $query,
|
||||
'per_page' => $perPage,
|
||||
'orientation' => 'landscape',
|
||||
]);
|
||||
|
||||
if (! $response->ok()) {
|
||||
$this->warn('Pexels request failed: '.$response->status());
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
$data = $response->json();
|
||||
|
||||
return Arr::get($data, 'photos', []);
|
||||
}
|
||||
|
||||
private function storePhotos(Event $event, array $photos): void
|
||||
{
|
||||
$tenantId = $event->tenant_id;
|
||||
$storage = Storage::disk('public');
|
||||
$storage->makeDirectory("events/{$event->id}/gallery");
|
||||
$storage->makeDirectory("events/{$event->id}/gallery/thumbs");
|
||||
|
||||
$demoPhotos = Photo::where('event_id', $event->id)
|
||||
->where('metadata->demo', true)
|
||||
->get();
|
||||
|
||||
foreach ($demoPhotos as $photo) {
|
||||
$storage->delete([$photo->file_path, $photo->thumbnail_path]);
|
||||
$photo->delete();
|
||||
}
|
||||
|
||||
$limit = min(count($photos), (int) $this->option('photos-per-event'));
|
||||
for ($i = 0; $i < $limit; $i++) {
|
||||
$photo = $photos[$i];
|
||||
$src = $photo['src'] ?? [];
|
||||
$originalUrl = $src['large2x'] ?? $src['large'] ?? null;
|
||||
$thumbUrl = $src['medium'] ?? $src['small'] ?? $originalUrl;
|
||||
|
||||
if (! $originalUrl) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$filename = sprintf('%s-demo-%02d.jpg', $event->slug, $i + 1);
|
||||
$thumbFilename = sprintf('%s-demo-%02d_thumb.jpg', $event->slug, $i + 1);
|
||||
|
||||
$filePath = "events/{$event->id}/gallery/{$filename}";
|
||||
$thumbPath = "events/{$event->id}/gallery/thumbs/{$thumbFilename}";
|
||||
|
||||
try {
|
||||
$imageResponse = Http::get($originalUrl);
|
||||
if ($imageResponse->ok()) {
|
||||
$storage->put($filePath, $imageResponse->body());
|
||||
}
|
||||
|
||||
if ($thumbUrl) {
|
||||
$thumbResponse = Http::get($thumbUrl);
|
||||
if ($thumbResponse->ok()) {
|
||||
$storage->put($thumbPath, $thumbResponse->body());
|
||||
}
|
||||
}
|
||||
} catch (\Throwable $exception) {
|
||||
$this->warn('Failed to download image: '.$exception->getMessage());
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$timestamp = Carbon::parse($event->date ?? Carbon::now())->addHours($i);
|
||||
|
||||
Photo::updateOrCreate(
|
||||
[
|
||||
'tenant_id' => $tenantId,
|
||||
'event_id' => $event->id,
|
||||
'file_path' => $filePath,
|
||||
],
|
||||
[
|
||||
'thumbnail_path' => $thumbPath,
|
||||
'guest_name' => 'Demo Guest '.($i + 1),
|
||||
'likes_count' => rand(1, 25),
|
||||
'is_featured' => $i === 0,
|
||||
'metadata' => ['demo' => true, 'source' => 'pexels'],
|
||||
'created_at' => $timestamp,
|
||||
'updated_at' => $timestamp,
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
EventPackage::where('event_id', $event->id)->update([
|
||||
'used_photos' => max($limit, 0),
|
||||
'used_guests' => max(15, $event->eventPackage?->used_guests ?? 0),
|
||||
]);
|
||||
|
||||
$this->info("Seeded {$limit} photos for {$event->slug}");
|
||||
}
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Events\Packages;
|
||||
|
||||
use App\Models\Tenant;
|
||||
use Illuminate\Foundation\Events\Dispatchable;
|
||||
use Illuminate\Queue\SerializesModels;
|
||||
|
||||
class TenantCreditsLow
|
||||
{
|
||||
use Dispatchable;
|
||||
use SerializesModels;
|
||||
|
||||
public function __construct(
|
||||
public Tenant $tenant,
|
||||
public int $balance,
|
||||
public int $threshold,
|
||||
) {}
|
||||
}
|
||||
@@ -62,11 +62,6 @@ class EventPurchaseResource extends Resource
|
||||
'monthly_agency' => 'Agency Subscription',
|
||||
])
|
||||
->required(),
|
||||
TextInput::make('credits_added')
|
||||
->label('Credits hinzugefügt')
|
||||
->numeric()
|
||||
->required()
|
||||
->minValue(0),
|
||||
TextInput::make('price')
|
||||
->label('Preis')
|
||||
->numeric()
|
||||
@@ -111,10 +106,6 @@ class EventPurchaseResource extends Resource
|
||||
'monthly_pro' => 'warning',
|
||||
default => 'gray',
|
||||
}),
|
||||
TextColumn::make('credits_added')
|
||||
->label('Credits')
|
||||
->badge()
|
||||
->color('success'),
|
||||
TextColumn::make('price')
|
||||
->label('Preis')
|
||||
->money('EUR')
|
||||
@@ -183,7 +174,6 @@ class EventPurchaseResource extends Resource
|
||||
->visible(fn (EventPurchase $record): bool => $record->transaction_id && is_null($record->refunded_at))
|
||||
->action(function (EventPurchase $record) {
|
||||
$record->update(['refunded_at' => now()]);
|
||||
$record->tenant->decrement('event_credits_balance', $record->credits_added);
|
||||
Log::info('Refund processed for purchase ID: ' . $record->id);
|
||||
}),
|
||||
])
|
||||
|
||||
@@ -43,10 +43,6 @@ class PurchaseHistoryResource extends Resource
|
||||
->label(__('admin.purchase_history.fields.package'))
|
||||
->required()
|
||||
->maxLength(255),
|
||||
Forms\Components\TextInput::make('credits_added')
|
||||
->label(__('admin.purchase_history.fields.credits'))
|
||||
->numeric()
|
||||
->required(),
|
||||
Forms\Components\TextInput::make('price')
|
||||
->label(__('admin.purchase_history.fields.price'))
|
||||
->numeric()
|
||||
@@ -81,11 +77,6 @@ class PurchaseHistoryResource extends Resource
|
||||
->badge()
|
||||
->sortable()
|
||||
->searchable(),
|
||||
Tables\Columns\TextColumn::make('credits_added')
|
||||
->label(__('admin.purchase_history.fields.credits'))
|
||||
->badge()
|
||||
->color(fn (int $state): string => $state > 0 ? 'success' : ($state < 0 ? 'danger' : 'gray'))
|
||||
->sortable(),
|
||||
Tables\Columns\TextColumn::make('price')
|
||||
->label(__('admin.purchase_history.fields.price'))
|
||||
->formatStateUsing(fn ($state, PurchaseHistory $record): string => number_format((float) $state, 2).' '.($record->currency ?? 'EUR'))
|
||||
|
||||
@@ -56,10 +56,6 @@ class TenantResource extends Resource
|
||||
->email()
|
||||
->required()
|
||||
->maxLength(255),
|
||||
TextInput::make('event_credits_balance')
|
||||
->label(__('admin.tenants.fields.event_credits_balance'))
|
||||
->numeric()
|
||||
->readOnly(),
|
||||
TextInput::make('paddle_customer_id')
|
||||
->label('Paddle Customer ID')
|
||||
->maxLength(191)
|
||||
@@ -112,10 +108,6 @@ class TenantResource extends Resource
|
||||
->label('Paddle Customer')
|
||||
->toggleable(isToggledHiddenByDefault: true)
|
||||
->formatStateUsing(fn ($state) => $state ?: '-'),
|
||||
Tables\Columns\TextColumn::make('event_credits_balance')
|
||||
->label(__('admin.tenants.fields.event_credits_balance'))
|
||||
->badge()
|
||||
->color(fn (int $state): string => $state <= 0 ? 'danger' : ($state < 5 ? 'warning' : 'success')),
|
||||
Tables\Columns\TextColumn::make('active_reseller_package_id')
|
||||
->label(__('admin.tenants.fields.active_package'))
|
||||
->badge()
|
||||
@@ -177,44 +169,6 @@ class TenantResource extends Resource
|
||||
'metadata' => ['reason' => $data['reason'] ?? 'manual assignment'],
|
||||
]);
|
||||
}),
|
||||
Actions\Action::make('adjust_credits')
|
||||
->label(__('admin.tenants.actions.adjust_credits'))
|
||||
->icon('heroicon-o-banknotes')
|
||||
->authorize(fn (Tenant $record): bool => auth()->user()?->can('adjustCredits', $record) ?? false)
|
||||
->form([
|
||||
Forms\Components\TextInput::make('delta')
|
||||
->label(__('admin.tenants.actions.adjust_credits_delta'))
|
||||
->numeric()
|
||||
->required()
|
||||
->rule('integer')
|
||||
->helperText(__('admin.tenants.actions.adjust_credits_delta_hint')),
|
||||
Forms\Components\Textarea::make('reason')
|
||||
->label(__('admin.tenants.actions.adjust_credits_reason'))
|
||||
->rows(3)
|
||||
->maxLength(500),
|
||||
])
|
||||
->action(function (Tenant $record, array $data): void {
|
||||
$delta = (int) ($data['delta'] ?? 0);
|
||||
|
||||
if ($delta === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
$newBalance = max(0, $record->event_credits_balance + $delta);
|
||||
|
||||
$record->forceFill([
|
||||
'event_credits_balance' => $newBalance,
|
||||
])->save();
|
||||
|
||||
Notification::make()
|
||||
->title(__('admin.tenants.actions.adjust_credits_success_title'))
|
||||
->body(__('admin.tenants.actions.adjust_credits_success_body', [
|
||||
'delta' => $delta,
|
||||
'balance' => $newBalance,
|
||||
]))
|
||||
->success()
|
||||
->send();
|
||||
}),
|
||||
Actions\Action::make('suspend')
|
||||
->label('Suspendieren')
|
||||
->color('danger')
|
||||
|
||||
@@ -1,60 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Widgets;
|
||||
|
||||
use App\Models\PurchaseHistory;
|
||||
use App\Models\Tenant;
|
||||
use Filament\Widgets\StatsOverviewWidget;
|
||||
use Filament\Widgets\StatsOverviewWidget\Stat;
|
||||
|
||||
class CreditAlertsWidget extends StatsOverviewWidget
|
||||
{
|
||||
protected static ?int $sort = 0;
|
||||
|
||||
protected int|string|array $columnSpan = 'full';
|
||||
|
||||
protected function getStats(): array
|
||||
{
|
||||
$lowBalanceCount = Tenant::query()
|
||||
->where('is_active', true)
|
||||
->where('event_credits_balance', '<', 5)
|
||||
->count();
|
||||
|
||||
$monthStart = now()->startOfMonth();
|
||||
$monthlyRevenue = PurchaseHistory::query()
|
||||
->where('purchased_at', '>=', $monthStart)
|
||||
->sum('price');
|
||||
|
||||
$activeSubscriptions = Tenant::query()
|
||||
->whereNotNull('subscription_expires_at')
|
||||
->where('subscription_expires_at', '>', now())
|
||||
->count();
|
||||
|
||||
return [
|
||||
Stat::make(
|
||||
__('admin.widgets.credit_alerts.low_balance_label'),
|
||||
$lowBalanceCount
|
||||
)
|
||||
->description(__('admin.widgets.credit_alerts.low_balance_desc'))
|
||||
->descriptionIcon('heroicon-m-exclamation-triangle')
|
||||
->color('warning')
|
||||
->url(route('filament.superadmin.resources.tenants.index')),
|
||||
Stat::make(
|
||||
__('admin.widgets.credit_alerts.monthly_revenue_label'),
|
||||
number_format((float) $monthlyRevenue, 2).' €'
|
||||
)
|
||||
->description(__('admin.widgets.credit_alerts.monthly_revenue_desc', [
|
||||
'month' => $monthStart->translatedFormat('F'),
|
||||
]))
|
||||
->descriptionIcon('heroicon-m-currency-euro')
|
||||
->color('success'),
|
||||
Stat::make(
|
||||
__('admin.widgets.credit_alerts.active_subscriptions_label'),
|
||||
$activeSubscriptions
|
||||
)
|
||||
->description(__('admin.widgets.credit_alerts.active_subscriptions_desc'))
|
||||
->descriptionIcon('heroicon-m-arrow-trending-up')
|
||||
->color('info'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -42,12 +42,7 @@ class TopTenantsByRevenue extends BaseWidget
|
||||
->label(__('admin.widgets.top_tenants_by_revenue.count'))
|
||||
->badge()
|
||||
->sortable(),
|
||||
Tables\Columns\TextColumn::make('event_credits_balance')
|
||||
->label(__('admin.common.credits'))
|
||||
->badge()
|
||||
->sortable(),
|
||||
])
|
||||
->paginated(false);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -180,12 +180,10 @@ class EventController extends Controller
|
||||
'gallery_expires_at' => $package->gallery_days ? now()->addDays($package->gallery_days) : null,
|
||||
]);
|
||||
|
||||
if ($package->isReseller()) {
|
||||
$note = sprintf('Event #%d created (%s)', $event->id, $event->name);
|
||||
$note = sprintf('Event #%d created (%s)', $event->id, $event->name);
|
||||
|
||||
if (! $tenant->consumeEventAllowance(1, 'event.create', $note)) {
|
||||
throw new HttpException(402, 'Insufficient credits or package allowance.');
|
||||
}
|
||||
if (! $tenant->consumeEventAllowance(1, 'event.create', $note)) {
|
||||
throw new HttpException(402, 'Insufficient package allowance.');
|
||||
}
|
||||
|
||||
return $event;
|
||||
@@ -220,7 +218,7 @@ class EventController extends Controller
|
||||
'eventType',
|
||||
'photos' => fn ($query) => $query->with('likes')->latest(),
|
||||
'tasks',
|
||||
'tenant' => fn ($query) => $query->select('id', 'name', 'event_credits_balance'),
|
||||
'tenant' => fn ($query) => $query->select('id', 'name'),
|
||||
'eventPackages' => fn ($query) => $query
|
||||
->with(['package', 'addons'])
|
||||
->orderByDesc('purchased_at')
|
||||
|
||||
@@ -49,10 +49,6 @@ class SettingsController extends Controller
|
||||
'defaults' => $defaults,
|
||||
'preferences' => $resolved,
|
||||
'overrides' => $tenant->notification_preferences ?? null,
|
||||
'meta' => [
|
||||
'credit_warning_sent_at' => $tenant->credit_warning_sent_at?->toIso8601String(),
|
||||
'credit_warning_threshold' => $tenant->credit_warning_threshold,
|
||||
],
|
||||
],
|
||||
]);
|
||||
}
|
||||
@@ -80,10 +76,6 @@ class SettingsController extends Controller
|
||||
'data' => [
|
||||
'preferences' => $resolved,
|
||||
'overrides' => $tenant->notification_preferences,
|
||||
'meta' => [
|
||||
'credit_warning_sent_at' => $tenant->credit_warning_sent_at?->toIso8601String(),
|
||||
'credit_warning_threshold' => $tenant->credit_warning_threshold,
|
||||
],
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -89,7 +89,6 @@ class TenantAdminTokenController extends Controller
|
||||
'tenant_id' => $tenant->id,
|
||||
'name' => $tenant->name,
|
||||
'slug' => $tenant->slug,
|
||||
'event_credits_balance' => $tenant->event_credits_balance,
|
||||
'features' => $tenant->features,
|
||||
];
|
||||
}
|
||||
@@ -141,7 +140,6 @@ class TenantAdminTokenController extends Controller
|
||||
'slug' => $tenant->slug,
|
||||
'email' => $tenant->contact_email,
|
||||
'fullName' => $fullName,
|
||||
'event_credits_balance' => $tenant->event_credits_balance,
|
||||
'active_reseller_package_id' => $activePackage?->id,
|
||||
'remaining_events' => $activePackage?->remaining_events ?? 0,
|
||||
'package_expires_at' => $activePackage?->expires_at,
|
||||
|
||||
@@ -77,7 +77,6 @@ class RegisteredUserController extends Controller
|
||||
'email' => $request->email,
|
||||
'is_active' => true,
|
||||
'is_suspended' => false,
|
||||
'event_credits_balance' => 0,
|
||||
'subscription_tier' => 'free',
|
||||
'subscription_expires_at' => null,
|
||||
'settings' => json_encode([
|
||||
|
||||
@@ -100,7 +100,6 @@ class CheckoutController extends Controller
|
||||
'email' => $validated['email'],
|
||||
'is_active' => true,
|
||||
'is_suspended' => false,
|
||||
'event_credits_balance' => 0,
|
||||
'subscription_tier' => 'free',
|
||||
'subscription_expires_at' => null,
|
||||
'settings' => json_encode([
|
||||
|
||||
@@ -137,7 +137,6 @@ class CheckoutGoogleController extends Controller
|
||||
'contact_email' => $email,
|
||||
'is_active' => true,
|
||||
'is_suspended' => false,
|
||||
'event_credits_balance' => 0,
|
||||
'subscription_tier' => 'free',
|
||||
'subscription_status' => 'free',
|
||||
'subscription_expires_at' => null,
|
||||
|
||||
@@ -1,136 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers\Tenant;
|
||||
|
||||
use App\Http\Controllers\Controller;
|
||||
use App\Http\Resources\Tenant\CreditLedgerResource;
|
||||
use App\Http\Resources\Tenant\EventPurchaseResource;
|
||||
use App\Models\EventCreditsLedger;
|
||||
use App\Models\EventPurchase;
|
||||
use App\Models\Tenant;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Symfony\Component\HttpKernel\Exception\HttpException;
|
||||
|
||||
class CreditController extends Controller
|
||||
{
|
||||
public function balance(Request $request): JsonResponse
|
||||
{
|
||||
$tenant = $this->resolveTenant($request);
|
||||
|
||||
return response()->json([
|
||||
'balance' => $tenant->event_credits_balance,
|
||||
'free_event_granted_at' => $tenant->free_event_granted_at,
|
||||
]);
|
||||
}
|
||||
|
||||
public function ledger(Request $request)
|
||||
{
|
||||
$tenant = $this->resolveTenant($request);
|
||||
|
||||
$ledgers = EventCreditsLedger::where('tenant_id', $tenant->id)
|
||||
->orderByDesc('created_at')
|
||||
->paginate(20);
|
||||
|
||||
return CreditLedgerResource::collection($ledgers);
|
||||
}
|
||||
|
||||
public function history(Request $request)
|
||||
{
|
||||
$tenant = $this->resolveTenant($request);
|
||||
|
||||
$purchases = EventPurchase::where('tenant_id', $tenant->id)
|
||||
->orderByDesc('purchased_at')
|
||||
->paginate(20);
|
||||
|
||||
return EventPurchaseResource::collection($purchases);
|
||||
}
|
||||
|
||||
public function purchase(Request $request): JsonResponse
|
||||
{
|
||||
$tenant = $this->resolveTenant($request);
|
||||
|
||||
$data = $request->validate([
|
||||
'package_id' => ['required', 'string', 'max:255'],
|
||||
'credits_added' => ['required', 'integer', 'min:1'],
|
||||
'platform' => ['nullable', 'string', 'max:32'],
|
||||
'transaction_id' => ['nullable', 'string', 'max:255'],
|
||||
'subscription_active' => ['sometimes', 'boolean'],
|
||||
]);
|
||||
|
||||
$purchase = EventPurchase::create([
|
||||
'tenant_id' => $tenant->id,
|
||||
'events_purchased' => $data['credits_added'],
|
||||
'amount' => 0,
|
||||
'currency' => 'EUR',
|
||||
'provider' => $data['platform'] ?? 'tenant-app',
|
||||
'external_receipt_id' => $data['transaction_id'] ?? null,
|
||||
'status' => 'completed',
|
||||
'purchased_at' => now(),
|
||||
]);
|
||||
|
||||
$note = 'Package: '.$data['package_id'];
|
||||
$incremented = $tenant->incrementCredits($data['credits_added'], 'purchase', $note, $purchase->id);
|
||||
|
||||
if (! $incremented) {
|
||||
throw new HttpException(500, 'Unable to record credit purchase');
|
||||
}
|
||||
|
||||
if (array_key_exists('subscription_active', $data)) {
|
||||
$tenant->update([
|
||||
'subscription_tier' => $data['subscription_active'] ? 'pro' : $tenant->subscription_tier,
|
||||
]);
|
||||
}
|
||||
|
||||
$tenant->refresh();
|
||||
|
||||
return response()->json([
|
||||
'message' => 'Purchase recorded',
|
||||
'balance' => $tenant->event_credits_balance,
|
||||
'subscription_active' => (bool) ($data['subscription_active'] ?? false),
|
||||
], 201);
|
||||
}
|
||||
|
||||
public function sync(Request $request): JsonResponse
|
||||
{
|
||||
$tenant = $this->resolveTenant($request);
|
||||
|
||||
$data = $request->validate([
|
||||
'balance' => ['nullable', 'integer', 'min:0'],
|
||||
'subscription_active' => ['sometimes', 'boolean'],
|
||||
'last_sync' => ['nullable', 'date'],
|
||||
]);
|
||||
|
||||
if (array_key_exists('subscription_active', $data)) {
|
||||
$tenant->update([
|
||||
'subscription_tier' => $data['subscription_active'] ? 'pro' : ($tenant->subscription_tier ?? 'free'),
|
||||
]);
|
||||
}
|
||||
|
||||
// Server remains source of truth for balance; echo current state back to client
|
||||
return response()->json([
|
||||
'balance' => $tenant->event_credits_balance,
|
||||
'subscription_active' => (bool) ($tenant->active_subscription ?? false),
|
||||
'server_time' => now()->toIso8601String(),
|
||||
]);
|
||||
}
|
||||
|
||||
private function resolveTenant(Request $request): Tenant
|
||||
{
|
||||
$user = $request->user();
|
||||
if ($user && isset($user->tenant) && $user->tenant instanceof Tenant) {
|
||||
return $user->tenant;
|
||||
}
|
||||
|
||||
$tenantId = $request->attributes->get('tenant_id');
|
||||
if (! $tenantId && $user && isset($user->tenant_id)) {
|
||||
$tenantId = $user->tenant_id;
|
||||
}
|
||||
|
||||
if (! $tenantId) {
|
||||
throw new HttpException(401, 'Unauthenticated');
|
||||
}
|
||||
|
||||
return Tenant::findOrFail($tenantId);
|
||||
}
|
||||
}
|
||||
@@ -1,100 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Jobs\Packages;
|
||||
|
||||
use App\Jobs\Concerns\LogsTenantNotifications;
|
||||
use App\Models\Tenant;
|
||||
use App\Notifications\Packages\TenantCreditsLowNotification;
|
||||
use Illuminate\Bus\Queueable;
|
||||
use Illuminate\Contracts\Queue\ShouldQueue;
|
||||
use Illuminate\Foundation\Bus\Dispatchable;
|
||||
use Illuminate\Queue\InteractsWithQueue;
|
||||
use Illuminate\Queue\SerializesModels;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Facades\Notification;
|
||||
|
||||
class SendTenantCreditsLowNotification implements ShouldQueue
|
||||
{
|
||||
use Dispatchable;
|
||||
use InteractsWithQueue;
|
||||
use LogsTenantNotifications;
|
||||
use Queueable;
|
||||
use SerializesModels;
|
||||
|
||||
public function __construct(
|
||||
public int $tenantId,
|
||||
public int $balance,
|
||||
public int $threshold,
|
||||
) {}
|
||||
|
||||
public function handle(): void
|
||||
{
|
||||
$tenant = Tenant::find($this->tenantId);
|
||||
|
||||
if (! $tenant) {
|
||||
Log::warning('Tenant credits low job skipped; tenant missing', [
|
||||
'tenant_id' => $this->tenantId,
|
||||
]);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$preferences = app(\App\Services\Packages\TenantNotificationPreferences::class);
|
||||
if (! $preferences->shouldNotify($tenant, 'credits_low')) {
|
||||
$this->logNotification($tenant, [
|
||||
'type' => 'credits_low',
|
||||
'status' => 'skipped',
|
||||
'context' => [
|
||||
'balance' => $this->balance,
|
||||
'threshold' => $this->threshold,
|
||||
'reason' => 'opt_out',
|
||||
],
|
||||
]);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$emails = collect([
|
||||
$tenant->contact_email,
|
||||
$tenant->user?->email,
|
||||
])->filter(fn ($email) => is_string($email) && filter_var($email, FILTER_VALIDATE_EMAIL))
|
||||
->unique();
|
||||
|
||||
if ($emails->isEmpty()) {
|
||||
Log::info('Tenant credits low notification skipped due to missing recipients', [
|
||||
'tenant_id' => $tenant->id,
|
||||
]);
|
||||
|
||||
$this->logNotification($tenant, [
|
||||
'type' => 'credits_low',
|
||||
'status' => 'skipped',
|
||||
'context' => [
|
||||
'balance' => $this->balance,
|
||||
'threshold' => $this->threshold,
|
||||
'reason' => 'no_recipient',
|
||||
],
|
||||
]);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$context = [
|
||||
'balance' => $this->balance,
|
||||
'threshold' => $this->threshold,
|
||||
];
|
||||
|
||||
$this->dispatchToRecipients(
|
||||
$tenant,
|
||||
$emails,
|
||||
'credits_low',
|
||||
function (string $email) use ($tenant) {
|
||||
Notification::route('mail', $email)->notify(new TenantCreditsLowNotification(
|
||||
$tenant,
|
||||
$this->balance,
|
||||
$this->threshold,
|
||||
));
|
||||
},
|
||||
$context
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -66,14 +66,6 @@ class ProcessRevenueCatWebhook implements ShouldQueue
|
||||
?? $this->value('event.entitlement_id');
|
||||
$credits = $this->mapCreditsFromProduct($productId);
|
||||
|
||||
if ($credits <= 0) {
|
||||
Log::info('RevenueCat webhook ignored due to unmapped product', [
|
||||
'event_id' => $this->eventId,
|
||||
'product_id' => $productId,
|
||||
]);
|
||||
return;
|
||||
}
|
||||
|
||||
$transactionId = $this->value('event.transaction_id')
|
||||
?? $this->value('event.id')
|
||||
?? $this->eventId
|
||||
@@ -101,9 +93,6 @@ class ProcessRevenueCatWebhook implements ShouldQueue
|
||||
'status' => 'completed',
|
||||
'purchased_at' => now(),
|
||||
]);
|
||||
|
||||
$note = sprintf('RevenueCat product: %s', $productId ?? 'unknown');
|
||||
$tenant->incrementCredits($credits, 'purchase', $note, $purchase->id);
|
||||
});
|
||||
|
||||
$tenant->refresh();
|
||||
|
||||
@@ -88,7 +88,6 @@ class ValidateStripeWebhookJob implements ShouldQueue
|
||||
'purchased_at' => now(),
|
||||
]);
|
||||
|
||||
$tenant->incrementCredits($eventsPurchased, 'purchase', null, $purchase->id);
|
||||
});
|
||||
|
||||
Log::info('Processed Stripe purchase via job', ['receipt_id' => $receiptId, 'tenant_id' => $tenantId]);
|
||||
@@ -96,4 +95,4 @@ class ValidateStripeWebhookJob implements ShouldQueue
|
||||
Log::info('Unhandled Stripe event in job', ['type' => $event['type']]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Listeners\Packages;
|
||||
|
||||
use App\Events\Packages\TenantCreditsLow;
|
||||
use App\Jobs\Packages\SendTenantCreditsLowNotification;
|
||||
|
||||
class QueueTenantCreditsLowNotification
|
||||
{
|
||||
public function handle(TenantCreditsLow $event): void
|
||||
{
|
||||
SendTenantCreditsLowNotification::dispatch(
|
||||
$event->tenant->id,
|
||||
$event->balance,
|
||||
$event->threshold
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
class EventCreditsLedger extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
|
||||
protected $table = 'event_credits_ledger';
|
||||
protected $guarded = [];
|
||||
protected $casts = [
|
||||
'created_at' => 'datetime',
|
||||
'delta' => 'integer',
|
||||
];
|
||||
|
||||
public function tenant(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Tenant::class);
|
||||
}
|
||||
|
||||
public function relatedPurchase(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(EventPurchase::class, 'related_purchase_id');
|
||||
}
|
||||
}
|
||||
@@ -18,7 +18,6 @@ class PurchaseHistory extends Model
|
||||
protected $guarded = [];
|
||||
|
||||
protected $casts = [
|
||||
'credits_added' => 'integer',
|
||||
'price' => 'decimal:2',
|
||||
'purchased_at' => 'datetime',
|
||||
'created_at' => 'datetime',
|
||||
|
||||
@@ -109,84 +109,6 @@ class Tenant extends Model
|
||||
$this->attributes['settings'] = json_encode($value ?? []);
|
||||
}
|
||||
|
||||
public function incrementCredits(int $amount, string $reason = 'manual', ?string $note = null, ?int $purchaseId = null): bool
|
||||
{
|
||||
if ($amount <= 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$balance = (int) ($this->event_credits_balance ?? 0) + $amount;
|
||||
$this->forceFill(['event_credits_balance' => $balance])->save();
|
||||
|
||||
$maxThreshold = collect(config('package-limits.credit_thresholds', []))
|
||||
->filter(fn ($value) => is_numeric($value) && $value >= 0)
|
||||
->map(fn ($value) => (int) $value)
|
||||
->max();
|
||||
|
||||
if (
|
||||
$maxThreshold !== null
|
||||
&& $balance > $maxThreshold
|
||||
&& ($this->credit_warning_sent_at !== null || $this->credit_warning_threshold !== null)
|
||||
) {
|
||||
$this->forceFill([
|
||||
'credit_warning_sent_at' => null,
|
||||
'credit_warning_threshold' => null,
|
||||
])->save();
|
||||
}
|
||||
|
||||
EventCreditsLedger::create([
|
||||
'tenant_id' => $this->id,
|
||||
'delta' => $amount,
|
||||
'reason' => $reason,
|
||||
'related_purchase_id' => $purchaseId,
|
||||
'note' => $note,
|
||||
]);
|
||||
|
||||
Log::info('Tenant credits incremented', [
|
||||
'tenant_id' => $this->id,
|
||||
'delta' => $amount,
|
||||
'reason' => $reason,
|
||||
'purchase_id' => $purchaseId,
|
||||
]);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public function decrementCredits(int $amount, string $reason = 'usage', ?string $note = null, ?int $purchaseId = null): bool
|
||||
{
|
||||
$current = (int) ($this->event_credits_balance ?? 0);
|
||||
|
||||
if ($amount <= 0 || $amount > $current) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$balance = $current - $amount;
|
||||
$this->forceFill(['event_credits_balance' => $balance])->save();
|
||||
|
||||
app(\App\Services\Packages\TenantUsageTracker::class)->recordCreditBalance(
|
||||
$this,
|
||||
$current,
|
||||
$balance
|
||||
);
|
||||
|
||||
EventCreditsLedger::create([
|
||||
'tenant_id' => $this->id,
|
||||
'delta' => -$amount,
|
||||
'reason' => $reason,
|
||||
'related_purchase_id' => $purchaseId,
|
||||
'note' => $note,
|
||||
]);
|
||||
|
||||
Log::info('Tenant credits decremented', [
|
||||
'tenant_id' => $this->id,
|
||||
'delta' => -$amount,
|
||||
'reason' => $reason,
|
||||
'purchase_id' => $purchaseId,
|
||||
]);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public function hasEventAllowance(): bool
|
||||
{
|
||||
$package = $this->getActiveResellerPackage();
|
||||
@@ -194,7 +116,7 @@ class Tenant extends Model
|
||||
return true;
|
||||
}
|
||||
|
||||
return (int) ($this->event_credits_balance ?? 0) > 0;
|
||||
return false;
|
||||
}
|
||||
|
||||
public function consumeEventAllowance(int $amount = 1, string $reason = 'event.create', ?string $note = null): bool
|
||||
@@ -221,7 +143,12 @@ class Tenant extends Model
|
||||
return true;
|
||||
}
|
||||
|
||||
return $this->decrementCredits($amount, $reason, $note);
|
||||
Log::warning('Event allowance missing for tenant', [
|
||||
'tenant_id' => $this->id,
|
||||
'reason' => $reason,
|
||||
]);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public function getActiveResellerPackage(): ?TenantPackage
|
||||
|
||||
@@ -1,42 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Notifications\Packages;
|
||||
|
||||
use App\Models\Tenant;
|
||||
use Illuminate\Bus\Queueable;
|
||||
use Illuminate\Contracts\Queue\ShouldQueue;
|
||||
use Illuminate\Notifications\Messages\MailMessage;
|
||||
use Illuminate\Notifications\Notification;
|
||||
|
||||
class TenantCreditsLowNotification extends Notification implements ShouldQueue
|
||||
{
|
||||
use Queueable;
|
||||
|
||||
public function __construct(
|
||||
private readonly Tenant $tenant,
|
||||
private readonly int $balance,
|
||||
private readonly int $threshold,
|
||||
) {}
|
||||
|
||||
public function via(object $notifiable): array
|
||||
{
|
||||
return ['mail'];
|
||||
}
|
||||
|
||||
public function toMail(object $notifiable): MailMessage
|
||||
{
|
||||
$url = url('/tenant/billing');
|
||||
|
||||
return (new MailMessage)
|
||||
->subject(__('emails.package_limits.credits_low.subject'))
|
||||
->greeting(__('emails.package_limits.credits_low.greeting', [
|
||||
'name' => $this->tenant->name ?? __('emails.package_limits.team_fallback'),
|
||||
]))
|
||||
->line(__('emails.package_limits.credits_low.body', [
|
||||
'balance' => $this->balance,
|
||||
'threshold' => $this->threshold,
|
||||
]))
|
||||
->action(__('emails.package_limits.credits_low.action'), $url)
|
||||
->line(__('emails.package_limits.footer'));
|
||||
}
|
||||
}
|
||||
@@ -54,14 +54,6 @@ class TenantPolicy
|
||||
return $user->role === 'super_admin';
|
||||
}
|
||||
|
||||
/**
|
||||
* Custom ability for adjusting credits.
|
||||
*/
|
||||
public function adjustCredits(User $user, Tenant $tenant): bool
|
||||
{
|
||||
return $user->role === 'super_admin';
|
||||
}
|
||||
|
||||
/**
|
||||
* Custom ability for suspending a tenant.
|
||||
*/
|
||||
@@ -70,4 +62,3 @@ class TenantPolicy
|
||||
return $user->role === 'super_admin';
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -10,7 +10,6 @@ use App\Events\Packages\EventPackageGuestLimitReached;
|
||||
use App\Events\Packages\EventPackageGuestThresholdReached;
|
||||
use App\Events\Packages\EventPackagePhotoLimitReached;
|
||||
use App\Events\Packages\EventPackagePhotoThresholdReached;
|
||||
use App\Events\Packages\TenantCreditsLow;
|
||||
use App\Events\Packages\TenantPackageEventLimitReached;
|
||||
use App\Events\Packages\TenantPackageEventThresholdReached;
|
||||
use App\Events\Packages\TenantPackageExpired;
|
||||
@@ -23,7 +22,6 @@ use App\Listeners\Packages\QueueGuestLimitNotification;
|
||||
use App\Listeners\Packages\QueueGuestThresholdNotification;
|
||||
use App\Listeners\Packages\QueuePhotoLimitNotification;
|
||||
use App\Listeners\Packages\QueuePhotoThresholdNotification;
|
||||
use App\Listeners\Packages\QueueTenantCreditsLowNotification;
|
||||
use App\Listeners\Packages\QueueTenantEventLimitNotification;
|
||||
use App\Listeners\Packages\QueueTenantEventThresholdNotification;
|
||||
use App\Listeners\Packages\QueueTenantPackageExpiredNotification;
|
||||
@@ -133,11 +131,6 @@ class AppServiceProvider extends ServiceProvider
|
||||
[QueueTenantPackageExpiredNotification::class, 'handle']
|
||||
);
|
||||
|
||||
EventFacade::listen(
|
||||
TenantCreditsLow::class,
|
||||
[QueueTenantCreditsLowNotification::class, 'handle']
|
||||
);
|
||||
|
||||
EventFacade::listen(
|
||||
GuestPhotoUploaded::class,
|
||||
[SendPhotoUploadedNotification::class, 'handle']
|
||||
|
||||
@@ -6,7 +6,6 @@ use App\Filament\Blog\Resources\CategoryResource;
|
||||
use App\Filament\Blog\Resources\PostResource;
|
||||
use App\Filament\Resources\InfrastructureActionLogs\InfrastructureActionLogResource;
|
||||
use App\Filament\Resources\LegalPageResource;
|
||||
use App\Filament\Widgets\CreditAlertsWidget;
|
||||
use App\Filament\Widgets\DokployPlatformHealth;
|
||||
use App\Filament\Widgets\PlatformStatsWidget;
|
||||
use App\Filament\Widgets\RevenueTrendWidget;
|
||||
@@ -54,7 +53,6 @@ class SuperAdminPanelProvider extends PanelProvider
|
||||
->widgets([
|
||||
Widgets\AccountWidget::class,
|
||||
Widgets\FilamentInfoWidget::class,
|
||||
CreditAlertsWidget::class,
|
||||
RevenueTrendWidget::class,
|
||||
PlatformStatsWidget::class,
|
||||
\App\Filament\Widgets\CouponUsageWidget::class,
|
||||
|
||||
@@ -142,7 +142,6 @@ class CheckoutAssignmentService
|
||||
'email' => $user->email,
|
||||
'is_active' => true,
|
||||
'is_suspended' => false,
|
||||
'event_credits_balance' => 0,
|
||||
'subscription_tier' => 'free',
|
||||
'subscription_status' => 'active',
|
||||
'settings' => [
|
||||
|
||||
@@ -16,33 +16,37 @@ class PackageLimitEvaluator
|
||||
|
||||
$package = $tenant->getActiveResellerPackage();
|
||||
|
||||
if ($package) {
|
||||
$limit = $package->package->max_events_per_year ?? 0;
|
||||
|
||||
if (! $package) {
|
||||
return [
|
||||
'code' => 'event_limit_exceeded',
|
||||
'title' => 'Event quota reached',
|
||||
'message' => 'Your current package has no remaining event slots. Please upgrade or renew your subscription.',
|
||||
'code' => 'event_limit_missing',
|
||||
'title' => 'No package assigned',
|
||||
'message' => 'Assign a package or addon to create events.',
|
||||
'status' => 402,
|
||||
'meta' => [
|
||||
'scope' => 'events',
|
||||
'used' => (int) $package->used_events,
|
||||
'limit' => $limit,
|
||||
'remaining' => max(0, $limit - $package->used_events),
|
||||
'tenant_package_id' => $package->id,
|
||||
'package_id' => $package->package_id,
|
||||
'used' => 0,
|
||||
'limit' => 0,
|
||||
'remaining' => 0,
|
||||
'tenant_package_id' => null,
|
||||
'package_id' => null,
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
$limit = $package->package->max_events_per_year ?? 0;
|
||||
|
||||
return [
|
||||
'code' => 'event_credits_exhausted',
|
||||
'title' => 'No event credits remaining',
|
||||
'message' => 'You have no event credits remaining. Purchase additional credits or a package to create new events.',
|
||||
'code' => 'event_limit_exceeded',
|
||||
'title' => 'Event quota reached',
|
||||
'message' => 'Your current package has no remaining event slots. Please upgrade or renew your subscription.',
|
||||
'status' => 402,
|
||||
'meta' => [
|
||||
'scope' => 'credits',
|
||||
'balance' => (int) ($tenant->event_credits_balance ?? 0),
|
||||
'scope' => 'events',
|
||||
'used' => (int) $package->used_events,
|
||||
'limit' => $limit,
|
||||
'remaining' => max(0, $limit - $package->used_events),
|
||||
'tenant_package_id' => $package->id,
|
||||
'package_id' => $package->package_id,
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
@@ -17,7 +17,6 @@ class TenantNotificationPreferences
|
||||
'event_limits' => true,
|
||||
'package_expiring' => true,
|
||||
'package_expired' => true,
|
||||
'credits_low' => true,
|
||||
];
|
||||
|
||||
public static function defaults(): array
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
|
||||
namespace App\Services\Packages;
|
||||
|
||||
use App\Events\Packages\TenantCreditsLow;
|
||||
use App\Events\Packages\TenantPackageEventLimitReached;
|
||||
use App\Events\Packages\TenantPackageEventThresholdReached;
|
||||
use App\Models\Tenant;
|
||||
@@ -66,32 +65,4 @@ class TenantUsageTracker
|
||||
$this->dispatcher->dispatch(new TenantPackageEventLimitReached($tenantPackage, $limit));
|
||||
}
|
||||
}
|
||||
|
||||
public function recordCreditBalance(Tenant $tenant, int $previousBalance, int $newBalance): void
|
||||
{
|
||||
$thresholds = collect(config('package-limits.credit_thresholds', []))
|
||||
->filter(fn ($value) => is_numeric($value) && $value >= 0)
|
||||
->map(fn ($value) => (int) $value)
|
||||
->sortDesc()
|
||||
->values();
|
||||
|
||||
$currentThreshold = $tenant->credit_warning_threshold ?? null;
|
||||
|
||||
foreach ($thresholds as $threshold) {
|
||||
if ($previousBalance > $threshold && $newBalance <= $threshold) {
|
||||
if ($currentThreshold !== null && $threshold >= $currentThreshold) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$tenant->forceFill([
|
||||
'credit_warning_sent_at' => now(),
|
||||
'credit_warning_threshold' => $threshold,
|
||||
])->save();
|
||||
|
||||
$this->dispatcher->dispatch(new TenantCreditsLow($tenant, $newBalance, $threshold));
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user