@@ -0,0 +1,430 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\SchoolYearClosingBatchModel;
|
||||
use App\Models\SchoolYearClosingItemModel;
|
||||
use App\Models\SchoolYearModel;
|
||||
use App\Support\SchoolYear\SchoolYearStatus;
|
||||
use CodeIgniter\Database\BaseConnection;
|
||||
use InvalidArgumentException;
|
||||
use RuntimeException;
|
||||
|
||||
final class SchoolYearClosingService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly SchoolYearModel $schoolYearModel,
|
||||
private readonly SchoolYearClosingBatchModel $batchModel,
|
||||
private readonly SchoolYearClosingItemModel $itemModel,
|
||||
private readonly SchoolYearManagementService $managementService,
|
||||
private readonly BaseConnection $db,
|
||||
) {
|
||||
}
|
||||
|
||||
public function preview(int $sourceYearId, ?int $targetYearId = null): array
|
||||
{
|
||||
$source = $this->requireYear($sourceYearId);
|
||||
$target = $targetYearId !== null ? $this->schoolYearModel->find($targetYearId) : $this->nextDraftYear((string) $source['name']);
|
||||
$sourceName = (string) $source['name'];
|
||||
|
||||
$finance = $this->financialSummary($sourceName);
|
||||
$overview = [
|
||||
'students' => $this->countBySchoolYear('student_class', $sourceName, 'student_id'),
|
||||
'families' => $this->countFamilies($sourceName),
|
||||
'classes' => $this->countBySchoolYear('classSection', $sourceName, 'class_id'),
|
||||
'teachers' => $this->countBySchoolYear('teacher_class', $sourceName, 'teacher_id'),
|
||||
'invoices' => $finance['invoice_count'],
|
||||
'total_invoiced' => $finance['total_invoiced'],
|
||||
'total_paid' => $finance['total_paid'],
|
||||
'total_outstanding' => $finance['total_outstanding'],
|
||||
];
|
||||
|
||||
$findings = [];
|
||||
if ($target === null) {
|
||||
$findings[] = $this->finding('blocking', 'Missing target year', 'Create a draft target school year before starting closing.');
|
||||
} elseif (! in_array((string) $target['status'], [SchoolYearStatus::DRAFT, SchoolYearStatus::ACTIVE], true)) {
|
||||
$findings[] = $this->finding('blocking', 'Invalid target year', 'The target school year must be draft or active.');
|
||||
}
|
||||
|
||||
foreach ($this->unpaidInvoiceFindings($sourceName) as $finding) {
|
||||
$findings[] = $finding;
|
||||
}
|
||||
|
||||
if ($this->countMissingSchoolYearRows('invoices') > 0) {
|
||||
$findings[] = $this->finding('blocking', 'Invoices missing school year', 'Some invoice records are not assigned to a school year.');
|
||||
}
|
||||
|
||||
$carryForward = $this->carryForwardFamilies($sourceName);
|
||||
$warnings = array_values(array_filter($findings, static fn (array $f): bool => $f['severity'] === 'warning'));
|
||||
$blockers = array_values(array_filter($findings, static fn (array $f): bool => $f['severity'] === 'blocking'));
|
||||
|
||||
$result = [
|
||||
'source' => $source,
|
||||
'target' => $target,
|
||||
'overview' => $overview,
|
||||
'finance' => $finance,
|
||||
'findings' => $findings,
|
||||
'blockers' => $blockers,
|
||||
'warnings' => $warnings,
|
||||
'carry_forward' => $carryForward,
|
||||
'generated_at' => date('Y-m-d H:i:s'),
|
||||
];
|
||||
$result['hash'] = $this->hashPreview($result);
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
public function start(int $sourceYearId, int $targetYearId, ?int $userId = null): void
|
||||
{
|
||||
$this->assertClosingTablesExist();
|
||||
|
||||
$source = $this->requireYear($sourceYearId);
|
||||
|
||||
if (($source['status'] ?? '') !== SchoolYearStatus::ACTIVE) {
|
||||
throw new InvalidArgumentException('Only an active school year can begin closing.');
|
||||
}
|
||||
|
||||
$preview = $this->preview($sourceYearId, $targetYearId);
|
||||
if ($preview['blockers'] !== []) {
|
||||
throw new InvalidArgumentException('Resolve blocking closing issues before starting closing.');
|
||||
}
|
||||
|
||||
$this->db->transStart();
|
||||
$now = date('Y-m-d H:i:s');
|
||||
$batchId = $this->batchModel->insert([
|
||||
'source_school_year_id' => $sourceYearId,
|
||||
'target_school_year_id' => $targetYearId,
|
||||
'status' => 'started',
|
||||
'preview_hash' => $preview['hash'],
|
||||
'total_families' => count($preview['carry_forward']),
|
||||
'total_positive_balance' => $preview['finance']['positive_balance'],
|
||||
'total_credit_balance' => $preview['finance']['credit_balance'],
|
||||
'started_by' => $userId,
|
||||
'started_at' => $now,
|
||||
], true);
|
||||
|
||||
foreach ($preview['carry_forward'] as $row) {
|
||||
$this->itemModel->insert([
|
||||
'closing_batch_id' => $batchId,
|
||||
'family_id' => (int) $row['family_id'],
|
||||
'source_balance' => $row['source_balance'],
|
||||
'credit_amount' => $row['credit_amount'],
|
||||
'carry_forward_amount' => $row['carry_forward_amount'],
|
||||
'status' => 'pending',
|
||||
]);
|
||||
}
|
||||
|
||||
$this->schoolYearModel->update($sourceYearId, [
|
||||
'status' => SchoolYearStatus::CLOSING,
|
||||
'closing_started_at' => $now,
|
||||
'updated_by' => $userId,
|
||||
]);
|
||||
$this->managementService->log($sourceYearId, SchoolYearStatus::ACTIVE, SchoolYearStatus::CLOSING, 'closing_start', $userId, [
|
||||
'target_school_year_id' => $targetYearId,
|
||||
'closing_batch_id' => $batchId,
|
||||
'preview_hash' => $preview['hash'],
|
||||
]);
|
||||
$this->db->transComplete();
|
||||
|
||||
if ($this->db->transStatus() === false) {
|
||||
throw new RuntimeException('Unable to start school year closing.');
|
||||
}
|
||||
}
|
||||
|
||||
public function execute(int $sourceYearId, ?int $userId = null): void
|
||||
{
|
||||
$this->assertClosingTablesExist();
|
||||
|
||||
$batch = $this->latestOpenBatch($sourceYearId);
|
||||
if ($batch === null) {
|
||||
throw new InvalidArgumentException('No open closing batch exists.');
|
||||
}
|
||||
|
||||
$preview = $this->preview($sourceYearId, (int) $batch['target_school_year_id']);
|
||||
if ($preview['hash'] !== (string) $batch['preview_hash']) {
|
||||
throw new InvalidArgumentException('Closing preview has changed. Refresh and restart closing before executing carry-forward.');
|
||||
}
|
||||
|
||||
$this->db->transStart();
|
||||
$items = $this->itemModel->where('closing_batch_id', (int) $batch['id'])->findAll();
|
||||
foreach ($items as $item) {
|
||||
if (($item['status'] ?? '') === 'completed') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$this->itemModel->update((int) $item['id'], ['status' => 'completed']);
|
||||
}
|
||||
$this->batchModel->update((int) $batch['id'], ['status' => 'executed']);
|
||||
$this->managementService->log($sourceYearId, SchoolYearStatus::CLOSING, SchoolYearStatus::CLOSING, 'carry_forward_execute', $userId, [
|
||||
'closing_batch_id' => (int) $batch['id'],
|
||||
'note' => 'Marked previewed carry-forward items complete. Target accounting records require the dedicated opening-balance schema.',
|
||||
]);
|
||||
$this->db->transComplete();
|
||||
|
||||
if ($this->db->transStatus() === false) {
|
||||
throw new RuntimeException('Unable to execute carry-forward.');
|
||||
}
|
||||
}
|
||||
|
||||
public function complete(int $sourceYearId, ?int $userId = null): void
|
||||
{
|
||||
$this->assertClosingTablesExist();
|
||||
|
||||
$batch = $this->latestOpenBatch($sourceYearId);
|
||||
if ($batch === null || ($batch['status'] ?? '') !== 'executed') {
|
||||
throw new InvalidArgumentException('Carry-forward must be executed before completing closing.');
|
||||
}
|
||||
|
||||
$pending = $this->itemModel
|
||||
->where('closing_batch_id', (int) $batch['id'])
|
||||
->where('status !=', 'completed')
|
||||
->countAllResults();
|
||||
if ($pending > 0) {
|
||||
throw new InvalidArgumentException('All closing batch items must complete before the year can be closed.');
|
||||
}
|
||||
|
||||
$this->db->transStart();
|
||||
$now = date('Y-m-d H:i:s');
|
||||
$this->batchModel->update((int) $batch['id'], [
|
||||
'status' => 'completed',
|
||||
'completed_by' => $userId,
|
||||
'completed_at' => $now,
|
||||
]);
|
||||
$this->schoolYearModel->update($sourceYearId, [
|
||||
'status' => SchoolYearStatus::CLOSED,
|
||||
'closed_at' => $now,
|
||||
'updated_by' => $userId,
|
||||
]);
|
||||
$this->managementService->log($sourceYearId, SchoolYearStatus::CLOSING, SchoolYearStatus::CLOSED, 'closing_complete', $userId, [
|
||||
'closing_batch_id' => (int) $batch['id'],
|
||||
]);
|
||||
$this->db->transComplete();
|
||||
|
||||
if ($this->db->transStatus() === false) {
|
||||
throw new RuntimeException('Unable to complete closing.');
|
||||
}
|
||||
}
|
||||
|
||||
public function cancel(int $sourceYearId, ?int $userId = null): void
|
||||
{
|
||||
$this->assertClosingTablesExist();
|
||||
|
||||
$batch = $this->latestOpenBatch($sourceYearId);
|
||||
if ($batch !== null && in_array((string) $batch['status'], ['executed', 'completed'], true)) {
|
||||
throw new InvalidArgumentException('Closing cannot be cancelled after carry-forward has executed.');
|
||||
}
|
||||
|
||||
$this->db->transStart();
|
||||
if ($batch !== null) {
|
||||
$this->batchModel->update((int) $batch['id'], ['status' => 'cancelled']);
|
||||
}
|
||||
$this->schoolYearModel->update($sourceYearId, [
|
||||
'status' => SchoolYearStatus::ACTIVE,
|
||||
'updated_by' => $userId,
|
||||
]);
|
||||
$this->managementService->log($sourceYearId, SchoolYearStatus::CLOSING, SchoolYearStatus::ACTIVE, 'closing_cancel', $userId, [
|
||||
'closing_batch_id' => $batch['id'] ?? null,
|
||||
]);
|
||||
$this->db->transComplete();
|
||||
|
||||
if ($this->db->transStatus() === false) {
|
||||
throw new RuntimeException('Unable to cancel closing.');
|
||||
}
|
||||
}
|
||||
|
||||
public function latestBatch(int $sourceYearId): ?array
|
||||
{
|
||||
if (! $this->db->tableExists('school_year_closing_batches')) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $this->batchModel
|
||||
->where('source_school_year_id', $sourceYearId)
|
||||
->orderBy('id', 'DESC')
|
||||
->first();
|
||||
}
|
||||
|
||||
private function requireYear(int $id): array
|
||||
{
|
||||
$year = $this->schoolYearModel->find($id);
|
||||
if ($year === null) {
|
||||
throw new InvalidArgumentException('School year not found.');
|
||||
}
|
||||
|
||||
return $year;
|
||||
}
|
||||
|
||||
private function nextDraftYear(string $sourceName): ?array
|
||||
{
|
||||
if (! preg_match('/^(\d{4})-(\d{4})$/', $sourceName, $matches)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$nextName = $matches[2] . '-' . ((int) $matches[2] + 1);
|
||||
|
||||
return $this->schoolYearModel
|
||||
->where('name', $nextName)
|
||||
->first();
|
||||
}
|
||||
|
||||
private function financialSummary(string $schoolYear): array
|
||||
{
|
||||
$summary = [
|
||||
'invoice_count' => 0,
|
||||
'total_invoiced' => 0.0,
|
||||
'total_paid' => 0.0,
|
||||
'total_outstanding' => 0.0,
|
||||
'positive_balance' => 0.0,
|
||||
'credit_balance' => 0.0,
|
||||
];
|
||||
|
||||
if (! $this->db->tableExists('invoices')) {
|
||||
return $summary;
|
||||
}
|
||||
|
||||
$row = $this->db->table('invoices')
|
||||
->select('COUNT(*) AS invoice_count')
|
||||
->select('COALESCE(SUM(total_amount), 0) AS total_invoiced')
|
||||
->select('COALESCE(SUM(paid_amount), 0) AS total_paid')
|
||||
->select('COALESCE(SUM(balance), 0) AS total_outstanding')
|
||||
->select('COALESCE(SUM(CASE WHEN balance > 0 THEN balance ELSE 0 END), 0) AS positive_balance', false)
|
||||
->select('COALESCE(SUM(CASE WHEN balance < 0 THEN ABS(balance) ELSE 0 END), 0) AS credit_balance', false)
|
||||
->where('school_year', $schoolYear)
|
||||
->get()
|
||||
->getRowArray() ?? [];
|
||||
|
||||
foreach ($summary as $key => $value) {
|
||||
$summary[$key] = $key === 'invoice_count' ? (int) ($row[$key] ?? 0) : round((float) ($row[$key] ?? 0), 2);
|
||||
}
|
||||
|
||||
return $summary;
|
||||
}
|
||||
|
||||
private function unpaidInvoiceFindings(string $schoolYear): array
|
||||
{
|
||||
if (! $this->db->tableExists('invoices')) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$count = $this->db->table('invoices')
|
||||
->where('school_year', $schoolYear)
|
||||
->where('balance >', 0)
|
||||
->countAllResults();
|
||||
|
||||
return $count > 0
|
||||
? [$this->finding('warning', 'Outstanding balances exist', "{$count} invoice(s) still have a positive balance and will require carry-forward review.")]
|
||||
: [];
|
||||
}
|
||||
|
||||
private function carryForwardFamilies(string $schoolYear): array
|
||||
{
|
||||
if (! $this->db->tableExists('invoices')) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$rows = $this->db->table('invoices i')
|
||||
->select('i.parent_id AS family_id')
|
||||
->select('COALESCE(SUM(i.balance), 0) AS source_balance')
|
||||
->where('i.school_year', $schoolYear)
|
||||
->groupBy('i.parent_id')
|
||||
->having('source_balance !=', 0)
|
||||
->orderBy('i.parent_id', 'ASC')
|
||||
->get()
|
||||
->getResultArray();
|
||||
|
||||
return array_map(static function (array $row): array {
|
||||
$balance = round((float) $row['source_balance'], 2);
|
||||
|
||||
return [
|
||||
'family_id' => (int) $row['family_id'],
|
||||
'family' => 'Family #' . (int) $row['family_id'],
|
||||
'source_balance' => $balance,
|
||||
'credit_amount' => $balance < 0 ? abs($balance) : 0.0,
|
||||
'adjustment_amount' => 0.0,
|
||||
'carry_forward_amount' => $balance,
|
||||
];
|
||||
}, $rows);
|
||||
}
|
||||
|
||||
private function countBySchoolYear(string $table, string $schoolYear, string $distinctField): int
|
||||
{
|
||||
if (! $this->db->tableExists($table) || ! $this->db->fieldExists('school_year', $table)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
$row = $this->db->table($table)
|
||||
->select("COUNT(DISTINCT {$distinctField}) AS total", false)
|
||||
->where('school_year', $schoolYear)
|
||||
->get()
|
||||
->getRowArray();
|
||||
|
||||
return (int) ($row['total'] ?? 0);
|
||||
}
|
||||
|
||||
private function countFamilies(string $schoolYear): int
|
||||
{
|
||||
if ($this->db->tableExists('invoices')) {
|
||||
$row = $this->db->table('invoices')
|
||||
->select('COUNT(DISTINCT parent_id) AS total', false)
|
||||
->where('school_year', $schoolYear)
|
||||
->get()
|
||||
->getRowArray();
|
||||
|
||||
return (int) ($row['total'] ?? 0);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
private function countMissingSchoolYearRows(string $table): int
|
||||
{
|
||||
if (! $this->db->tableExists($table) || ! $this->db->fieldExists('school_year', $table)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return $this->db->table($table)
|
||||
->groupStart()
|
||||
->where('school_year', null)
|
||||
->orWhere('school_year', '')
|
||||
->groupEnd()
|
||||
->countAllResults();
|
||||
}
|
||||
|
||||
private function latestOpenBatch(int $sourceYearId): ?array
|
||||
{
|
||||
return $this->batchModel
|
||||
->where('source_school_year_id', $sourceYearId)
|
||||
->whereIn('status', ['started', 'executed'])
|
||||
->orderBy('id', 'DESC')
|
||||
->first();
|
||||
}
|
||||
|
||||
private function assertClosingTablesExist(): void
|
||||
{
|
||||
foreach (['school_year_closing_batches', 'school_year_closing_items', 'school_year_transition_logs'] as $table) {
|
||||
if (! $this->db->tableExists($table)) {
|
||||
throw new RuntimeException('School year lifecycle tables are missing. Run database migrations before closing a school year.');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private function finding(string $severity, string $title, string $detail): array
|
||||
{
|
||||
return [
|
||||
'severity' => $severity,
|
||||
'title' => $title,
|
||||
'detail' => $detail,
|
||||
];
|
||||
}
|
||||
|
||||
private function hashPreview(array $preview): string
|
||||
{
|
||||
return hash('sha256', json_encode([
|
||||
'source_id' => $preview['source']['id'] ?? null,
|
||||
'target_id' => $preview['target']['id'] ?? null,
|
||||
'finance' => $preview['finance'],
|
||||
'carry_forward' => $preview['carry_forward'],
|
||||
'blockers' => $preview['blockers'],
|
||||
], JSON_UNESCAPED_SLASHES));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\SchoolYearModel;
|
||||
use App\Support\SchoolYear\SchoolYearContext;
|
||||
use CodeIgniter\HTTP\IncomingRequest;
|
||||
use RuntimeException;
|
||||
|
||||
final class SchoolYearContextService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly SchoolYearModel $schoolYearModel,
|
||||
) {
|
||||
}
|
||||
|
||||
public function resolve(
|
||||
IncomingRequest $request,
|
||||
?int $routeSchoolYearId = null
|
||||
): SchoolYearContext {
|
||||
$requestedId = $routeSchoolYearId
|
||||
?? $this->normalizeInt($request->getGet('school_year_id'));
|
||||
|
||||
$requestedName = trim((string) $request->getGet('school_year'));
|
||||
|
||||
if ($requestedId !== null && $requestedName !== '') {
|
||||
$row = $this->schoolYearModel->find($requestedId);
|
||||
|
||||
if ($row === null || (string) ($row['name'] ?? '') !== $requestedName) {
|
||||
throw new RuntimeException('Selected school-year parameters conflict.');
|
||||
}
|
||||
|
||||
return $this->fromRow($row, true);
|
||||
}
|
||||
|
||||
if ($requestedId !== null) {
|
||||
$row = $this->schoolYearModel->find($requestedId);
|
||||
|
||||
if ($row === null) {
|
||||
throw new RuntimeException('Selected school year was not found.');
|
||||
}
|
||||
|
||||
return $this->fromRow($row, true);
|
||||
}
|
||||
|
||||
if ($requestedName !== '') {
|
||||
$row = $this->schoolYearModel
|
||||
->where('name', $requestedName)
|
||||
->first();
|
||||
|
||||
if ($row === null) {
|
||||
throw new RuntimeException('Selected school year was not found.');
|
||||
}
|
||||
|
||||
return $this->fromRow($row, true);
|
||||
}
|
||||
|
||||
$sessionYearId = session('selected_school_year_id');
|
||||
|
||||
if (is_numeric($sessionYearId)) {
|
||||
$row = $this->schoolYearModel->find((int) $sessionYearId);
|
||||
|
||||
if ($row !== null) {
|
||||
return $this->fromRow($row, false);
|
||||
}
|
||||
}
|
||||
|
||||
$active = $this->schoolYearModel->active();
|
||||
|
||||
if ($active === null) {
|
||||
throw new RuntimeException('No active school year is configured.');
|
||||
}
|
||||
|
||||
return $this->fromRow($active, false);
|
||||
}
|
||||
|
||||
private function normalizeInt(mixed $value): ?int
|
||||
{
|
||||
if ($value === null || $value === '' || ! ctype_digit((string) $value)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (int) $value;
|
||||
}
|
||||
|
||||
private function fromRow(array $row, bool $explicit): SchoolYearContext
|
||||
{
|
||||
return new SchoolYearContext(
|
||||
id: (int) $row['id'],
|
||||
yearName: (string) $row['name'],
|
||||
status: (string) $row['status'],
|
||||
explicitSelection: $explicit,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,313 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\ConfigurationModel;
|
||||
use App\Models\SchoolYearClosingBatchModel;
|
||||
use App\Models\SchoolYearModel;
|
||||
use App\Models\SchoolYearTransitionLogModel;
|
||||
use App\Support\SchoolYear\SchoolYearStatus;
|
||||
use CodeIgniter\Database\BaseConnection;
|
||||
use InvalidArgumentException;
|
||||
use RuntimeException;
|
||||
|
||||
final class SchoolYearManagementService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly SchoolYearModel $schoolYearModel,
|
||||
private readonly ConfigurationModel $configurationModel,
|
||||
private readonly SchoolYearTransitionLogModel $transitionLogModel,
|
||||
private readonly SchoolYearClosingBatchModel $closingBatchModel,
|
||||
private readonly SchoolYearValidationService $validationService,
|
||||
private readonly BaseConnection $db,
|
||||
) {
|
||||
}
|
||||
|
||||
public function createDraft(array $payload, ?int $userId = null): int
|
||||
{
|
||||
$payload = $this->metadataPayload($payload);
|
||||
$payload['status'] = SchoolYearStatus::DRAFT;
|
||||
$payload['created_by'] = $userId;
|
||||
$payload['updated_by'] = $userId;
|
||||
|
||||
$this->validationService->validateMetadata($payload);
|
||||
|
||||
$this->db->transStart();
|
||||
$id = $this->schoolYearModel->insert($payload, true);
|
||||
if ($id !== false) {
|
||||
$this->log((int) $id, null, SchoolYearStatus::DRAFT, 'create', $userId);
|
||||
}
|
||||
$this->db->transComplete();
|
||||
|
||||
if ($id === false || $this->db->transStatus() === false) {
|
||||
throw new RuntimeException($this->firstModelError('Unable to create school year.'));
|
||||
}
|
||||
|
||||
return (int) $id;
|
||||
}
|
||||
|
||||
public function updateMetadata(int $id, array $payload, ?int $userId = null): void
|
||||
{
|
||||
$year = $this->requireYear($id);
|
||||
$status = (string) $year['status'];
|
||||
|
||||
if (SchoolYearStatus::isReadonly($status) || $status === SchoolYearStatus::CLOSING) {
|
||||
throw new InvalidArgumentException('This school year is read-only and cannot be edited.');
|
||||
}
|
||||
|
||||
$payload = $this->metadataPayload($payload);
|
||||
$payload['updated_by'] = $userId;
|
||||
$this->validationService->validateMetadata($payload, $id);
|
||||
|
||||
$this->db->transStart();
|
||||
$updated = $this->schoolYearModel->update($id, $payload);
|
||||
if ($updated !== false) {
|
||||
$this->log($id, $status, $status, 'metadata_update', $userId);
|
||||
}
|
||||
$this->db->transComplete();
|
||||
|
||||
if ($updated === false || $this->db->transStatus() === false) {
|
||||
throw new RuntimeException($this->firstModelError('Unable to update school year.'));
|
||||
}
|
||||
}
|
||||
|
||||
public function activate(int $id, ?int $userId = null): void
|
||||
{
|
||||
$year = $this->requireYear($id);
|
||||
$from = (string) $year['status'];
|
||||
|
||||
if (! SchoolYearStatus::canTransition($from, SchoolYearStatus::ACTIVE)) {
|
||||
throw new InvalidArgumentException('Only draft or approved reopened school years can be activated.');
|
||||
}
|
||||
|
||||
$this->db->transStart();
|
||||
$activeYears = $this->schoolYearModel->where('status', SchoolYearStatus::ACTIVE)->findAll();
|
||||
$now = date('Y-m-d H:i:s');
|
||||
|
||||
foreach ($activeYears as $activeYear) {
|
||||
if ((int) $activeYear['id'] === $id) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$this->schoolYearModel->update((int) $activeYear['id'], [
|
||||
'status' => SchoolYearStatus::CLOSING,
|
||||
'closing_started_at' => $now,
|
||||
'updated_by' => $userId,
|
||||
]);
|
||||
$this->log((int) $activeYear['id'], SchoolYearStatus::ACTIVE, SchoolYearStatus::CLOSING, 'activation_displaced_active_year', $userId, [
|
||||
'activated_school_year_id' => $id,
|
||||
]);
|
||||
}
|
||||
|
||||
$this->schoolYearModel->update($id, [
|
||||
'status' => SchoolYearStatus::ACTIVE,
|
||||
'activated_at' => $now,
|
||||
'updated_by' => $userId,
|
||||
]);
|
||||
$this->configurationModel->setConfigValueByKey('school_year', (string) $year['name']);
|
||||
$this->log($id, $from, SchoolYearStatus::ACTIVE, 'activate', $userId);
|
||||
|
||||
$this->db->transComplete();
|
||||
|
||||
if ($this->db->transStatus() === false) {
|
||||
throw new RuntimeException('Unable to activate school year.');
|
||||
}
|
||||
}
|
||||
|
||||
public function deleteDraft(int $id, ?int $userId = null): void
|
||||
{
|
||||
$year = $this->requireYear($id);
|
||||
if (($year['status'] ?? '') !== SchoolYearStatus::DRAFT) {
|
||||
throw new InvalidArgumentException('Only unused draft school years can be deleted. Archive historical years instead.');
|
||||
}
|
||||
|
||||
if ($this->hasDependentRecords($id, (string) $year['name'])) {
|
||||
throw new InvalidArgumentException('This school year cannot be deleted because related data exists. Archive historical years instead.');
|
||||
}
|
||||
|
||||
$this->db->transStart();
|
||||
$this->log($id, SchoolYearStatus::DRAFT, null, 'delete_draft', $userId);
|
||||
$this->schoolYearModel->delete($id);
|
||||
$this->db->transComplete();
|
||||
|
||||
if ($this->db->transStatus() === false) {
|
||||
throw new RuntimeException('Unable to delete draft school year.');
|
||||
}
|
||||
}
|
||||
|
||||
public function archive(int $id, ?int $userId = null): void
|
||||
{
|
||||
$this->transition($id, SchoolYearStatus::ARCHIVED, 'archive', $userId, [
|
||||
'archived_at' => date('Y-m-d H:i:s'),
|
||||
]);
|
||||
}
|
||||
|
||||
public function reopen(int $id, string $reason, ?int $userId = null): void
|
||||
{
|
||||
if (trim($reason) === '') {
|
||||
throw new InvalidArgumentException('A reopen reason is required.');
|
||||
}
|
||||
|
||||
$this->transition($id, SchoolYearStatus::ACTIVE, 'reopen', $userId, [
|
||||
'metadata' => ['reason' => trim($reason)],
|
||||
]);
|
||||
}
|
||||
|
||||
public function latestTransitionByYear(): array
|
||||
{
|
||||
if (! $this->db->tableExists('school_year_transition_logs')) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$rows = $this->transitionLogModel
|
||||
->orderBy('created_at', 'DESC')
|
||||
->findAll();
|
||||
$latest = [];
|
||||
|
||||
foreach ($rows as $row) {
|
||||
$yearId = (int) ($row['school_year_id'] ?? 0);
|
||||
if ($yearId > 0 && ! isset($latest[$yearId])) {
|
||||
$latest[$yearId] = $row;
|
||||
}
|
||||
}
|
||||
|
||||
return $latest;
|
||||
}
|
||||
|
||||
public function log(int $schoolYearId, ?string $from, ?string $to, string $action, ?int $userId = null, array $metadata = []): void
|
||||
{
|
||||
if (! $this->db->tableExists('school_year_transition_logs')) {
|
||||
throw new RuntimeException('School year lifecycle tables are missing. Run database migrations before changing school-year status.');
|
||||
}
|
||||
|
||||
$this->transitionLogModel->insert([
|
||||
'school_year_id' => $schoolYearId,
|
||||
'from_status' => $from,
|
||||
'to_status' => $to,
|
||||
'action' => $action,
|
||||
'performed_by' => $userId,
|
||||
'metadata_json' => $metadata !== [] ? json_encode($metadata, JSON_UNESCAPED_SLASHES) : null,
|
||||
'created_at' => date('Y-m-d H:i:s'),
|
||||
]);
|
||||
}
|
||||
|
||||
private function transition(int $id, string $to, string $action, ?int $userId, array $options = []): void
|
||||
{
|
||||
$year = $this->requireYear($id);
|
||||
$from = (string) $year['status'];
|
||||
|
||||
if (! SchoolYearStatus::canTransition($from, $to)) {
|
||||
throw new InvalidArgumentException("Cannot transition school year from {$from} to {$to}.");
|
||||
}
|
||||
|
||||
if ($to === SchoolYearStatus::ARCHIVED && ! $this->hasFinalizedClosingBatch($id)) {
|
||||
throw new InvalidArgumentException('A school year can be archived only after a finalized closing batch exists.');
|
||||
}
|
||||
|
||||
if ($to === SchoolYearStatus::ACTIVE) {
|
||||
$otherActive = $this->schoolYearModel
|
||||
->where('status', SchoolYearStatus::ACTIVE)
|
||||
->where('id !=', $id)
|
||||
->first();
|
||||
if ($otherActive !== null) {
|
||||
throw new InvalidArgumentException('Another school year is already active. Activate or close years through the controlled lifecycle first.');
|
||||
}
|
||||
}
|
||||
|
||||
$this->db->transStart();
|
||||
$data = [
|
||||
'status' => $to,
|
||||
'updated_by' => $userId,
|
||||
];
|
||||
|
||||
foreach (['archived_at', 'closed_at', 'closing_started_at'] as $field) {
|
||||
if (isset($options[$field])) {
|
||||
$data[$field] = $options[$field];
|
||||
}
|
||||
}
|
||||
|
||||
$this->schoolYearModel->update($id, $data);
|
||||
$this->log($id, $from, $to, $action, $userId, $options['metadata'] ?? []);
|
||||
$this->db->transComplete();
|
||||
|
||||
if ($this->db->transStatus() === false) {
|
||||
throw new RuntimeException('Unable to update school year status.');
|
||||
}
|
||||
}
|
||||
|
||||
private function requireYear(int $id): array
|
||||
{
|
||||
$year = $this->schoolYearModel->find($id);
|
||||
if ($year === null) {
|
||||
throw new InvalidArgumentException('School year not found.');
|
||||
}
|
||||
|
||||
return $year;
|
||||
}
|
||||
|
||||
private function metadataPayload(array $payload): array
|
||||
{
|
||||
return [
|
||||
'name' => trim((string) ($payload['name'] ?? '')),
|
||||
'starts_on' => $this->nullableDate($payload['starts_on'] ?? null),
|
||||
'ends_on' => $this->nullableDate($payload['ends_on'] ?? null),
|
||||
'description' => trim((string) ($payload['description'] ?? '')) ?: null,
|
||||
'registration_starts_on' => $this->nullableDate($payload['registration_starts_on'] ?? null),
|
||||
'registration_ends_on' => $this->nullableDate($payload['registration_ends_on'] ?? null),
|
||||
'previous_school_year_id' => $this->nullableInt($payload['previous_school_year_id'] ?? null),
|
||||
];
|
||||
}
|
||||
|
||||
private function nullableDate(mixed $value): ?string
|
||||
{
|
||||
$value = trim((string) $value);
|
||||
|
||||
return $value !== '' ? $value : null;
|
||||
}
|
||||
|
||||
private function nullableInt(mixed $value): ?int
|
||||
{
|
||||
return is_numeric($value) && (int) $value > 0 ? (int) $value : null;
|
||||
}
|
||||
|
||||
private function hasDependentRecords(int $id, string $name): bool
|
||||
{
|
||||
if (
|
||||
$this->db->tableExists('school_year_closing_batches')
|
||||
&& $this->closingBatchModel->where('source_school_year_id', $id)->orWhere('target_school_year_id', $id)->first() !== null
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
|
||||
foreach (['invoices', 'payments', 'student_class', 'teacher_class', 'calendar_events', 'events'] as $table) {
|
||||
if ($this->db->tableExists($table) && $this->db->fieldExists('school_year', $table)) {
|
||||
$count = $this->db->table($table)->where('school_year', $name)->countAllResults();
|
||||
if ($count > 0) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private function hasFinalizedClosingBatch(int $sourceSchoolYearId): bool
|
||||
{
|
||||
if (! $this->db->tableExists('school_year_closing_batches')) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $this->closingBatchModel
|
||||
->where('source_school_year_id', $sourceSchoolYearId)
|
||||
->whereIn('status', ['completed', 'closed'])
|
||||
->first() !== null;
|
||||
}
|
||||
|
||||
private function firstModelError(string $fallback): string
|
||||
{
|
||||
$errors = $this->schoolYearModel->errors();
|
||||
$first = reset($errors);
|
||||
|
||||
return is_string($first) && $first !== '' ? $first : $fallback;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Models\SchoolYearModel;
|
||||
use DateTimeImmutable;
|
||||
use InvalidArgumentException;
|
||||
|
||||
final class SchoolYearValidationService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly SchoolYearModel $schoolYearModel,
|
||||
) {
|
||||
}
|
||||
|
||||
public function validateMetadata(array $payload, ?int $exceptId = null): void
|
||||
{
|
||||
$name = trim((string) ($payload['name'] ?? ''));
|
||||
|
||||
if (! $this->isValidYearName($name)) {
|
||||
throw new InvalidArgumentException('School year must use YYYY-YYYY with consecutive years.');
|
||||
}
|
||||
|
||||
$existing = $this->schoolYearModel->where('name', $name);
|
||||
if ($exceptId !== null) {
|
||||
$existing->where('id !=', $exceptId);
|
||||
}
|
||||
if ($existing->first() !== null) {
|
||||
throw new InvalidArgumentException('That school year already exists.');
|
||||
}
|
||||
|
||||
$startsOn = $this->dateOrNull($payload['starts_on'] ?? null);
|
||||
$endsOn = $this->dateOrNull($payload['ends_on'] ?? null);
|
||||
if ($startsOn !== null && $endsOn !== null && $startsOn >= $endsOn) {
|
||||
throw new InvalidArgumentException('School year start date must be before the end date.');
|
||||
}
|
||||
|
||||
$registrationStarts = $this->dateOrNull($payload['registration_starts_on'] ?? null);
|
||||
$registrationEnds = $this->dateOrNull($payload['registration_ends_on'] ?? null);
|
||||
if ($registrationStarts !== null && $registrationEnds !== null && $registrationStarts > $registrationEnds) {
|
||||
throw new InvalidArgumentException('Registration start date must be on or before the registration end date.');
|
||||
}
|
||||
}
|
||||
|
||||
public function isValidYearName(string $value): bool
|
||||
{
|
||||
if (! preg_match('/^(\d{4})-(\d{4})$/', $value, $matches)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return (int) $matches[2] === (int) $matches[1] + 1;
|
||||
}
|
||||
|
||||
private function dateOrNull(mixed $value): ?DateTimeImmutable
|
||||
{
|
||||
$value = trim((string) $value);
|
||||
if ($value === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
$date = DateTimeImmutable::createFromFormat('!Y-m-d', $value);
|
||||
if (! $date instanceof DateTimeImmutable || $date->format('Y-m-d') !== $value) {
|
||||
throw new InvalidArgumentException('Dates must use YYYY-MM-DD.');
|
||||
}
|
||||
|
||||
return $date;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Support\SchoolYear\SchoolYearContext;
|
||||
use RuntimeException;
|
||||
|
||||
final class SchoolYearWriteGuard
|
||||
{
|
||||
public function assertWritable(
|
||||
SchoolYearContext $context,
|
||||
bool $allowDraftForAdmin = false,
|
||||
bool $isAdmin = false
|
||||
): void {
|
||||
if ($context->status() === 'active') {
|
||||
return;
|
||||
}
|
||||
|
||||
if ($context->status() === 'draft' && $allowDraftForAdmin && $isAdmin) {
|
||||
return;
|
||||
}
|
||||
|
||||
throw new RuntimeException('The selected school year is read-only.');
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user