diff --git a/database/migrations/2026_08_02_000001_ensure_moshtari_code_on_customers_table.php b/database/migrations/2026_08_02_000001_ensure_moshtari_code_on_customers_table.php new file mode 100644 index 0000000..7dcb782 --- /dev/null +++ b/database/migrations/2026_08_02_000001_ensure_moshtari_code_on_customers_table.php @@ -0,0 +1,80 @@ +firstExistingColumn([ + 'tahesab_id', + 'finance_code', + 'pargar_id', + 'mobile', + ]); + + $this->addCustomerColumnIfMissing( + 'moshtari_code', + 'INT NULL DEFAULT NULL', + $after + ); + } + + public function down(): void + { + // عمداً خالی — rollback ستون حسابداری را حذف نمی‌کند + } + + /** @param list $candidates */ + private function firstExistingColumn(array $candidates): ?string + { + foreach ($candidates as $column) { + if ($this->customerColumnExists($column)) { + return $column; + } + } + + return null; + } + + private function customersTable(): string + { + return DB::getTablePrefix().'customers'; + } + + private function customerColumnExists(string $column): bool + { + $result = DB::selectOne( + 'SELECT COUNT(*) AS cnt FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? AND COLUMN_NAME = ?', + [DB::connection()->getDatabaseName(), $this->customersTable(), $column] + ); + + return (int) $result->cnt > 0; + } + + private function addCustomerColumnIfMissing(string $column, string $definition, ?string $after = null): void + { + if ($this->customerColumnExists($column)) { + return; + } + + $table = $this->customersTable(); + $afterClause = ($after !== null && $this->customerColumnExists($after)) + ? " AFTER `{$after}`" + : ''; + + DB::statement("ALTER TABLE `{$table}` ADD COLUMN `{$column}` {$definition}{$afterClause}"); + } +};