ifnex/04_Laravel/app/Console/Commands/SyncWordPressUsers.php
Kazem Alghasi a699c2dbee feat(laravel): implement user synchronization and shipment schema
Add new core functionality and database structures to support WordPress
integration and shipment tracking.

- Add `SyncWordPressUsers` Artisan command to synchronize users between
  WordPress and Laravel.
- Create `shipment_items` table migration.
- Fix `discount_codes` enum type by changing `percent` to `percentage`.
- Add `SampleDataSeeder` for testing shipments, transactions, and
  discount codes.
- Update project status documentation.
2026-08-08 04:58:01 +03:30

142 lines
5.8 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace App\Console\Commands;
use App\Models\User;
use App\Enums\UserRole;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
class SyncWordPressUsers extends Command
{
protected $signature = 'ifnex:sync-wp-users
{--email=info@ifnex.ir : ایمیل کاربر وردپرس برای sincron}
{--create-if-missing : ایجاد کاربر در لاراول اگر وجود نداشته باشد}';
protected $description = 'یک‌سازی کاربران وردپرس با لاراول و ساخت توکن Sanctum';
public function handle(): int
{
$wpEmail = $this->option('email');
$createIfMissing = $this->option('create-if-missing');
$this->info("🔍 در حال پیدا کردن کاربر وردپرس: $wpEmail");
// ۱. پیدا کردن کاربر لاراول
$laravelUser = User::where('email', $wpEmail)->first();
if (!$laravelUser) {
if ($createIfMissing) {
$this->warn("کاربر در لاراول یافت نشد. در حال ایجاد...");
$laravelUser = User::create([
'name' => 'IFNEX Admin',
'email' => $wpEmail,
'password' => bcrypt('password'),
'role' => UserRole::SuperAdmin,
'is_active' => true,
]);
$this->info("✅ کاربر در لاراول ایجاد شد: ID {$laravelUser->id}");
} else {
$this->error("❌ کاربر در لاراول یافت نشد. از --create-if-missing استفاده کنید.");
return 1;
}
} else {
$this->info("✅ کاربر در لاراول پیدا شد: ID {$laravelUser->id} ({$laravelUser->name})");
}
// ۲. پاک کردن توکن‌های قدیمی
$oldCount = $laravelUser->tokens()->count();
$laravelUser->tokens()->delete();
$this->info("🗑️ {$oldCount} توکن قدیمی پاک شد.");
// ۳. ساخت توکن جدید
$token = $laravelUser->createToken('wordpress-bridge')->plainTextToken;
$this->newLine();
$this->line('========================================');
$this->info('🔑 توکن Sanctum جدید (کپی کنید):');
$this->line('========================================');
$this->newLine();
$this->line($token);
$this->newLine();
$this->line('========================================');
$this->newLine();
// ۴. ذخیره توکن در دیتابیس وردپرس
$this->info("💾 در حال ذخیره توکن در دیتابیس وردپرس...");
try {
$wpPdo = DB::connection('mysql')->getPdo();
// اتصال به دیتابیس وردپرس
$wpDbName = env('WP_DB_NAME', 'ifnexwp');
$wpPdo->exec("USE `$wpDbName`");
// ذخیره توکن در user meta
$stmt = $wpPdo->prepare('
INSERT INTO wp_usermeta (user_id, meta_key, meta_value)
VALUES (1, "ifnex_laravel_token", :token)
ON DUPLICATE KEY UPDATE meta_value = :token
');
$stmt->execute(['token' => $token]);
// ذخیره تاریخ انقضا
$expiry = date('Y-m-d H:i:s', strtotime('+30 days'));
$stmt = $wpPdo->prepare('
INSERT INTO wp_usermeta (user_id, meta_key, meta_value)
VALUES (1, "ifnex_laravel_token_expiry", :expiry)
ON DUPLICATE KEY UPDATE meta_value = :expiry
');
$stmt->execute(['expiry' => $expiry]);
$this->info("✅ توکن در دیتابیس وردپرس ذخیره شد.");
$this->info(" User ID: 1 (admin)");
$this->info(" Token: " . substr($token, 0, 20) . "...");
$this->info(" Expires: $expiry");
} catch (\Exception $e) {
$this->error("❌ خطا در ذخیره توکن در وردپرس: " . $e->getMessage());
$this->warn("توکن تولید شد ولی در وردپرس ذخیره نشد.");
$this->warn("لطفاً دستی در دیتابیس وردپرس ذخیره کنید.");
}
// ۵. تست نهایی
$this->newLine();
$this->info("🧪 در حال تست اتصال...");
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://localhost:8000/api/v1/wallet/balance');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer ' . $token,
'Accept: application/json',
]);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($http_code === 200) {
$data = json_decode($response, true);
$this->info("✅ اتصال موفق!");
$this->info(" موجودی کیف پول: " . number_format($data['balance']) . " ریال");
$this->info(" کل واریزی: " . number_format($data['total_deposited']) . " ریال");
$this->info(" کل برداشت: " . number_format($data['total_withdrawn']) . " ریال");
} else {
$this->error("❌ تست ناموفق: HTTP $http_code");
$this->line(substr($response, 0, 200));
}
$this->newLine();
$this->info("🎉 آماده تست در وردپرس!");
$this->info(" آدرس: http://localhost/ifnexwp/?page_id=16");
$this->info(" ورود: admin / admin");
return 0;
}
}