Files
CKB/app/Console/Commands/ClearOpnameData.php
2025-06-10 18:38:06 +07:00

93 lines
3.4 KiB
PHP

<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Schema;
use App\Models\Opname;
use App\Models\OpnameDetail;
use App\Models\Stock;
use App\Models\StockLog;
class ClearOpnameData extends Command
{
protected $signature = 'opname:clear {--force : Force clear without confirmation}';
protected $description = 'Clear all opname-related data including opnames, details, stocks, logs, and reset all IDs to 1';
public function handle()
{
if (!$this->option('force')) {
if (!$this->confirm('This will delete ALL opname data, stocks, stock logs, and reset ALL IDs to 1. This is irreversible! Are you sure?')) {
$this->info('Operation cancelled.');
return;
}
}
$this->info('Starting complete data cleanup...');
try {
// Disable foreign key checks
DB::statement('SET FOREIGN_KEY_CHECKS=0;');
// 1. Clear and reset stock logs
if (Schema::hasTable('stock_logs')) {
DB::table('stock_logs')->truncate();
DB::statement('ALTER TABLE stock_logs AUTO_INCREMENT = 1;');
$this->info('✓ Cleared and reset stock_logs table');
}
// 2. Clear and reset stocks
if (Schema::hasTable('stocks')) {
DB::table('stocks')->truncate();
DB::statement('ALTER TABLE stocks AUTO_INCREMENT = 1;');
$this->info('✓ Cleared and reset stocks table');
}
// 3. Clear and reset opname details
if (Schema::hasTable('opname_details')) {
DB::table('opname_details')->truncate();
DB::statement('ALTER TABLE opname_details AUTO_INCREMENT = 1;');
$this->info('✓ Cleared and reset opname_details table');
}
// 4. Clear and reset opnames
if (Schema::hasTable('opnames')) {
DB::table('opnames')->truncate();
DB::statement('ALTER TABLE opnames AUTO_INCREMENT = 1;');
$this->info('✓ Cleared and reset opnames table');
}
// Re-enable foreign key checks
DB::statement('SET FOREIGN_KEY_CHECKS=1;');
$this->info('Successfully cleared all data and reset IDs to 1!');
$this->info('Cleared tables:');
$this->info('- stock_logs');
$this->info('- stocks');
$this->info('- opname_details');
$this->info('- opnames');
Log::info('Complete data cleared and IDs reset by command', [
'user' => auth()->user() ? auth()->user()->id : 'system',
'timestamp' => now(),
'tables_cleared' => ['stock_logs', 'stocks', 'opname_details', 'opnames']
]);
} catch (\Exception $e) {
// Re-enable foreign key checks if they were disabled
DB::statement('SET FOREIGN_KEY_CHECKS=1;');
$this->error('Error clearing data: ' . $e->getMessage());
Log::error('Error in ClearOpnameData command: ' . $e->getMessage(), [
'exception' => $e,
'trace' => $e->getTraceAsString()
]);
return 1; // Return error code
}
return 0; // Return success code
}
}