بهط پهلقشفث

This commit is contained in:
2026-06-26 22:37:00 +03:30
parent 14d417d9ec
commit 89d33bc0a0
@@ -17,6 +17,26 @@ return new class extends Migration
return;
}
if (! Schema::hasColumn('customers', 'referral_id')) {
Schema::table('customers', function (Blueprint $table) {
if (Schema::hasColumn('customers', 'type')) {
$table->string('referral_id', 20)->nullable()->after('type');
} else {
$table->string('referral_id', 20)->nullable();
}
});
}
if (! Schema::hasColumn('customers', 'referral_to_id')) {
Schema::table('customers', function (Blueprint $table) {
if (Schema::hasColumn('customers', 'referral_id')) {
$table->string('referral_to_id', 20)->nullable()->after('referral_id');
} else {
$table->string('referral_to_id', 20)->nullable();
}
});
}
if (! Schema::hasColumn('customers', 'total_referrals')) {
Schema::table('customers', function (Blueprint $table) {
if (Schema::hasColumn('customers', 'referral_to_id')) {
@@ -27,10 +47,51 @@ return new class extends Migration
});
}
if (! Schema::hasColumn('customers', 'total_referrals')) {
if (
! Schema::hasColumn('customers', 'referral_id')
|| ! Schema::hasColumn('customers', 'referral_to_id')
|| ! Schema::hasColumn('customers', 'total_referrals')
) {
return;
}
$this->backfillMissingReferralIds();
$this->backfillTotalReferrals();
}
public function down(): void
{
// عمداً خالی — rollback ستون را حذف نمی‌کند
}
private function backfillMissingReferralIds(): void
{
$query = DB::table('customers')
->where(function ($q) {
$q->whereNull('referral_id')->orWhere('referral_id', '');
});
if (Schema::hasColumn('customers', 'deleted_at')) {
$query->whereNull('deleted_at');
}
$customerIds = $query->pluck('id');
foreach ($customerIds as $customerId) {
do {
$uniqueId = substr(str_shuffle('0123456789abcdefghijklmnopqrstuvwxyz'), 0, 4);
} while (DB::table('customers')->where('referral_id', $uniqueId)->exists());
DB::table('customers')->where('id', $customerId)->update(['referral_id' => $uniqueId]);
}
}
private function backfillTotalReferrals(): void
{
$deletedAtClause = Schema::hasColumn('customers', 'deleted_at')
? 'AND `deleted_at` IS NULL'
: '';
DB::statement("
UPDATE `customers` AS c
SET c.`total_referrals` = (
@@ -39,16 +100,11 @@ return new class extends Migration
SELECT `id`
FROM `customers`
WHERE `referral_to_id` = c.`referral_id`
AND `deleted_at` IS NULL
{$deletedAtClause}
) AS r
)
WHERE c.`referral_id` IS NOT NULL
AND TRIM(c.`referral_id`) <> ''
");
}
public function down(): void
{
// عمداً خالی — rollback ستون را حذف نمی‌کند
}
};