@@ -69,6 +69,8 @@ class FinancialReimbursementPoHardening extends Migration
|
||||
|
||||
private function ensurePurchaseOrderInvariants(): void
|
||||
{
|
||||
$this->ensurePurchaseOrderSchoolYearColumns();
|
||||
|
||||
if (!$this->db->tableExists('purchase_order_items')) {
|
||||
return;
|
||||
}
|
||||
@@ -108,6 +110,63 @@ class FinancialReimbursementPoHardening extends Migration
|
||||
}
|
||||
}
|
||||
|
||||
private function ensurePurchaseOrderSchoolYearColumns(): void
|
||||
{
|
||||
foreach (['purchase_orders' => 'status', 'purchase_order_items' => 'purchase_order_id'] as $table => $after) {
|
||||
if (!$this->db->tableExists($table)) {
|
||||
continue;
|
||||
}
|
||||
if (!$this->db->fieldExists('school_year', $table)) {
|
||||
$this->forge->addColumn($table, [
|
||||
'school_year' => [
|
||||
'type' => 'VARCHAR',
|
||||
'constraint' => 9,
|
||||
'null' => true,
|
||||
'after' => $after,
|
||||
],
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
if ($this->db->tableExists('purchase_orders')) {
|
||||
$currentYear = $this->currentSchoolYear();
|
||||
$this->db->query(
|
||||
'UPDATE purchase_orders SET school_year = ? WHERE school_year IS NULL OR TRIM(school_year) = ?',
|
||||
[$currentYear, '']
|
||||
);
|
||||
$this->db->query('ALTER TABLE purchase_orders MODIFY school_year VARCHAR(9) NOT NULL');
|
||||
}
|
||||
|
||||
if ($this->db->tableExists('purchase_orders') && $this->db->tableExists('purchase_order_items')) {
|
||||
$this->db->query(
|
||||
"UPDATE purchase_order_items poi
|
||||
INNER JOIN purchase_orders po ON po.id = poi.purchase_order_id
|
||||
SET poi.school_year = po.school_year
|
||||
WHERE poi.school_year IS NULL OR TRIM(poi.school_year) = ''"
|
||||
);
|
||||
$this->db->query('ALTER TABLE purchase_order_items MODIFY school_year VARCHAR(9) NOT NULL');
|
||||
}
|
||||
}
|
||||
|
||||
private function currentSchoolYear(): string
|
||||
{
|
||||
if ($this->db->tableExists('school_years')) {
|
||||
$row = $this->db->table('school_years')
|
||||
->select('name')
|
||||
->where('status', 'active')
|
||||
->orderBy('id', 'DESC')
|
||||
->get(1)
|
||||
->getRowArray();
|
||||
$name = trim((string)($row['name'] ?? ''));
|
||||
if (preg_match('/^\d{4}-\d{4}$/', $name) === 1) {
|
||||
return $name;
|
||||
}
|
||||
}
|
||||
|
||||
$year = (int)date('Y');
|
||||
return $year . '-' . ($year + 1);
|
||||
}
|
||||
|
||||
private function createIndexIfMissing(string $table, string $indexName, string $sql): void
|
||||
{
|
||||
if (!$this->db->tableExists($table)) {
|
||||
|
||||
Reference in New Issue
Block a user