Files
thetool/db/migrations/20260117120000_add_shipping_note_number.php
2026-01-17 12:48:08 +00:00

51 lines
1.7 KiB
PHP

<?php
declare(strict_types=1);
use Phinx\Migration\AbstractMigration;
final class AddShippingNoteNumber extends AbstractMigration
{
public function up(): void
{
if ($this->getEnvironment() == "thetool") {
$table = $this->table('WarehouseShippingNote');
$table
->addColumn('shippingNoteNumber', 'string', ['limit' => 20, 'null' => true, 'after' => 'id'])
->addIndex(['shippingNoteNumber'], ['unique' => true])
->update();
// Get all shipping notes ordered by create timestamp to assign numbers in chronological order
$rows = $this->fetchAll(
"SELECT id, YEAR(FROM_UNIXTIME(`create`)) as year
FROM WarehouseShippingNote
ORDER BY `create` ASC, id ASC"
);
// Group by year and assign sequential numbers
$yearCounters = [];
foreach ($rows as $row) {
$year = $row['year'];
if (!isset($yearCounters[$year])) {
$yearCounters[$year] = 0;
}
$yearCounters[$year]++;
$shippingNoteNumber = 'LS' . $year . '-X' . str_pad((string)$yearCounters[$year], 4, '0', STR_PAD_LEFT);
$this->execute(
"UPDATE WarehouseShippingNote SET shippingNoteNumber = '{$shippingNoteNumber}' WHERE id = {$row['id']}"
);
}
}
}
public function down(): void
{
if ($this->getEnvironment() == "thetool") {
$table = $this->table('WarehouseShippingNote');
$table->removeColumn('shippingNoteNumber')->update();
}
}
}