Fix endcustomer package allocation and event create gating
This commit is contained in:
@@ -0,0 +1,76 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
if (! Schema::hasTable('package_purchases') || ! Schema::hasTable('tenant_packages') || ! Schema::hasTable('packages')) {
|
||||
return;
|
||||
}
|
||||
|
||||
$groupedPurchases = DB::table('package_purchases')
|
||||
->join('packages', 'packages.id', '=', 'package_purchases.package_id')
|
||||
->where('packages.type', 'endcustomer')
|
||||
->whereNotNull('package_purchases.tenant_id')
|
||||
->where(function ($query) {
|
||||
$query->whereNull('package_purchases.refunded')
|
||||
->orWhere('package_purchases.refunded', false);
|
||||
})
|
||||
->orderBy('package_purchases.purchased_at')
|
||||
->orderBy('package_purchases.id')
|
||||
->get([
|
||||
'package_purchases.tenant_id',
|
||||
'package_purchases.package_id',
|
||||
'package_purchases.price',
|
||||
'package_purchases.purchased_at',
|
||||
])
|
||||
->groupBy(fn ($row) => "{$row->tenant_id}:{$row->package_id}");
|
||||
|
||||
foreach ($groupedPurchases as $purchases) {
|
||||
if ($purchases->isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$tenantId = (int) $purchases[0]->tenant_id;
|
||||
$packageId = (int) $purchases[0]->package_id;
|
||||
|
||||
$existingCount = DB::table('tenant_packages')
|
||||
->where('tenant_id', $tenantId)
|
||||
->where('package_id', $packageId)
|
||||
->count();
|
||||
|
||||
if ($existingCount >= $purchases->count()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$missingPurchases = $purchases->slice($existingCount)->values();
|
||||
|
||||
foreach ($missingPurchases as $purchase) {
|
||||
$purchasedAt = $purchase->purchased_at ? Carbon::parse($purchase->purchased_at) : now();
|
||||
$expiresAt = $purchasedAt->copy()->addYear();
|
||||
|
||||
DB::table('tenant_packages')->insert([
|
||||
'tenant_id' => $tenantId,
|
||||
'package_id' => $packageId,
|
||||
'price' => $purchase->price ?? 0,
|
||||
'purchased_at' => $purchasedAt,
|
||||
'expires_at' => $expiresAt,
|
||||
'used_events' => 0,
|
||||
'active' => $expiresAt->isFuture(),
|
||||
'created_at' => now(),
|
||||
'updated_at' => now(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
//
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user