A free open source IT asset/license management system
Maintenances: renamed completion_date to expected_completion_date
snipedf85e75f7387
diff --git a/app/Http/Controllers/Api/MaintenancesController.php b/app/Http/Controllers/Api/MaintenancesController.phpindex da2496d21a..20dccb60bd 100644--- a/app/Http/Controllers/Api/MaintenancesController.php+++ b/app/Http/Controllers/Api/MaintenancesController.php@@ -124,6 +124,10 @@ class MaintenancesController extends Controller'asset_maintenance_time','cost','start_date',+ 'expected_completion_date',+ // Legacy alias: API v1 callers passed sort=completion_date+ // against the pre-rename column. Kept in the allow-list and+ // mapped below so those callers keep sorting the same rows.'completion_date','completed_at','notes',@@ -177,6 +181,11 @@ class MaintenancesController extends Controllercase 'completed_at':$maintenances = $maintenances->orderByCompletedAt($order);break;+ case 'completion_date':+ // Legacy alias for the renamed expected_completion_date+ // column; keep API v1 sort= callers working.+ $maintenances = $maintenances->orderBy('expected_completion_date', $order);+ break;default:$maintenances = $maintenances->orderBy($sort, $order);break;diff --git a/app/Http/Controllers/MaintenancesController.php b/app/Http/Controllers/MaintenancesController.phpindex 4c255e32d1..5c337d1497 100644--- a/app/Http/Controllers/MaintenancesController.php+++ b/app/Http/Controllers/MaintenancesController.php@@ -103,10 +103,20 @@ class MaintenancesController extends Controller$maintenance->maintenance_type_id = $request->input('maintenance_type_id');$maintenance->name = $request->input('name');$maintenance->start_date = $request->input('start_date');- $maintenance->completion_date = $request->input('completion_date');+ $maintenance->expected_completion_date = $request->input('expected_completion_date', $request->input('completion_date'));$maintenance->responsible_party_id = $request->input('responsible_party_id') ?: auth()->id();$maintenance->created_by = auth()->id();+ // Backfilled completion: user is recording a maintenance that+ // was already finished. Same transition logic as update() —+ // null-blank submissions stay null, a supplied date marks the+ // row complete and stamps who did it plus how long it took.+ $shouldLogComplete = $this->applyCompletionState(+ $maintenance,+ $request->filled('completed_at') ? $request->input('completed_at') : null,+ wasCompletedBefore: false,+ );+$request->handleImages($maintenance);// Was the asset maintenance created?@@ -114,6 +124,10 @@ class MaintenancesController extends Controllerreturn redirect()->back()->withInput()->withErrors($maintenance->getErrors());}+ if ($shouldLogComplete) {+ $this->logMaintenanceCompleteAction($maintenance);+ }+$this->storeUploadedFiles($request, $maintenance);}@@ -174,14 +188,24 @@ class MaintenancesController extends Controller$maintenance->maintenance_type_id = $request->input('maintenance_type_id');$maintenance->name = $request->input('name');$maintenance->start_date = $request->input('start_date');- $maintenance->completion_date = $request->input('completion_date');+ $maintenance->expected_completion_date = $request->input('expected_completion_date', $request->input('completion_date'));$maintenance->responsible_party_id = $request->input('responsible_party_id');$maintenance->url = $request->input('url');$request->handleImages($maintenance);+ $shouldLogComplete = $this->applyCompletionState(+ $maintenance,+ $request->filled('completed_at') ? $request->input('completed_at') : null,+ wasCompletedBefore: $maintenance->completed_at !== null,+ );+if ($maintenance->save()) {$this->storeUploadedFiles($request, $maintenance);+ if ($shouldLogComplete) {+ $this->logMaintenanceCompleteAction($maintenance);+ }+return redirect()->route('maintenances.index')->with('success', trans('admin/maintenances/message.edit.success'));}@@ -189,6 +213,65 @@ class MaintenancesController extends Controllerreturn redirect()->back()->withInput()->withErrors($maintenance->getErrors());}+ /**+ * Apply the null / date / cleared transitions of `completed_at` on+ * either create or edit. Returns true when the transition is+ * "not-completed → completed" so the caller knows to fire the+ * MaintenanceComplete action log AFTER the row is saved (and thus+ * has an id).+ *+ * asset_maintenance_time uses start_date → completed_at (not+ * created_at → completed_at). For a real-time completion the two are+ * effectively the same; for a backfill (start_date well in the past,+ * created_at just now) using start_date is the truthful duration of+ * the actual maintenance work.+ */+ private function applyCompletionState(Maintenance $maintenance, ?string $submittedCompletedAt, bool $wasCompletedBefore): bool+ {+ if ($submittedCompletedAt !== null) {+ $maintenance->completed_at = $submittedCompletedAt;+ if (! $wasCompletedBefore) {+ $maintenance->completed_by = auth()->id();+ $maintenance->asset_maintenance_time = $this->computeMaintenanceDurationDays($maintenance);++ return true;+ }++ return false;+ }++ $maintenance->completed_at = null;+ $maintenance->completed_by = null;+ $maintenance->asset_maintenance_time = null;++ return false;+ }++ /**+ * Days between start_date and completed_at, absolute so ordering of+ * inputs doesn't matter. Falls back to now() for start_date when the+ * caller somehow submitted a completion without a start (shouldn't+ * happen — start_date is required by the model — but guards against+ * a null-deref if a future validation change lets one through).+ */+ private function computeMaintenanceDurationDays(Maintenance $maintenance): int+ {+ $start = $maintenance->start_date ?? now();++ return (int) $start->diffInDays($maintenance->completed_at, true);+ }++ private function logMaintenanceCompleteAction(Maintenance $maintenance): void+ {+ $logAction = new Actionlog;+ $logAction->item_type = Maintenance::class;+ $logAction->item_id = $maintenance->id;+ $logAction->target_type = Asset::class;+ $logAction->target_id = $maintenance->asset_id;+ $logAction->created_by = auth()->id();+ $logAction->logaction(ActionType::MaintenanceComplete);+ }+/*** Stores any generic file uploads submitted from the maintenance form.*/diff --git a/app/Http/Controllers/ReportsController.php b/app/Http/Controllers/ReportsController.phpindex e0982100d6..0f2458dce0 100644--- a/app/Http/Controllers/ReportsController.php+++ b/app/Http/Controllers/ReportsController.php@@ -1233,12 +1233,22 @@ class ReportsController extends Controllertrans('admin/maintenances/form.title'),trans('admin/maintenances/form.start_date'),trans('admin/maintenances/form.completion_date'),+ trans('admin/maintenances/form.completed_at'),+ trans('admin/maintenances/form.completed_by'),trans('admin/maintenances/form.asset_maintenance_time'),trans('admin/maintenances/form.cost'),+ trans('admin/maintenances/form.is_warranty'),+ trans('admin/maintenances/form.notes'),];fputcsv($handle, $header);- Maintenance::with('asset', 'supplier')+ // No completed-filter here — exports every maintenance, active+ // or completed. Eager-load the four relations the row loop+ // dereferences so a 10K-row export doesn't fan out into 40K++ // queries. maintenanceType replaces the pre-#19039+ // `improvement_type` accessor that no longer exists on the+ // model (would silently write empty cells otherwise).+ Maintenance::with('asset', 'supplier', 'maintenanceType', 'completedByUser')->orderBy('created_at', 'DESC')->chunk(500, function ($maintenances) use ($handle, $formatter) {foreach ($maintenances as $maintenance) {@@ -1247,15 +1257,19 @@ class ReportsController extends Controller: (int) $maintenance->asset_maintenance_time;$row = [- $maintenance->asset->asset_tag,- $maintenance->asset->name,- $maintenance->supplier->name,- $maintenance->improvement_type,+ $maintenance->asset?->asset_tag,+ $maintenance->asset?->name,+ $maintenance->supplier?->name,+ $maintenance->maintenanceType?->name,$maintenance->name,$maintenance->start_date,- $maintenance->completion_date,+ $maintenance->expected_completion_date,+ $maintenance->completed_at,+ $maintenance->completedByUser?->display_name,$improvementTime,trans('general.currency').Helper::formatCurrencyOutput($maintenance->cost),+ $maintenance->is_warranty ? trans('general.yes') : trans('general.no'),+ $maintenance->notes,];if (config('app.escape_formulas') === false) {diff --git a/app/Http/Transformers/MaintenancesTransformer.php b/app/Http/Transformers/MaintenancesTransformer.phpindex 34a6553cee..2bf380a777 100644--- a/app/Http/Transformers/MaintenancesTransformer.php+++ b/app/Http/Transformers/MaintenancesTransformer.php@@ -73,7 +73,12 @@ class MaintenancesTransformer'asset_maintenance_type' => e($assetmaintenance->asset_maintenance_type),'start_date' => Helper::getFormattedDateObject($assetmaintenance->start_date, 'date'),'asset_maintenance_time' => (int) $assetmaintenance->asset_maintenance_time,- 'completion_date' => Helper::getFormattedDateObject($assetmaintenance->completion_date, 'date'),+ 'expected_completion_date' => Helper::getFormattedDateObject($assetmaintenance->expected_completion_date, 'date'),+ // Legacy alias for `expected_completion_date` (the column was+ // renamed to match the "Expected Completion" UI label). Kept+ // in the payload so API v1 consumers reading .completion_date+ // don't break. Both keys point at the same underlying value.+ 'completion_date' => Helper::getFormattedDateObject($assetmaintenance->expected_completion_date, 'date'),'user_id' => ($assetmaintenance->adminuser) ? ['id' => $assetmaintenance->adminuser->id,'name' => e($assetmaintenance->adminuser->display_name),@@ -151,7 +156,10 @@ class MaintenancesTransformer'asset_maintenance_type' => e($assetmaintenance->asset_maintenance_type),'start_date' => Helper::getFormattedDateObject($assetmaintenance->start_date, 'date'),'asset_maintenance_time' => $assetmaintenance->asset_maintenance_time,- 'completion_date' => Helper::getFormattedDateObject($assetmaintenance->completion_date, 'date'),+ 'expected_completion_date' => Helper::getFormattedDateObject($assetmaintenance->expected_completion_date, 'date'),+ // Legacy alias for `expected_completion_date`; see the+ // matching comment in transformMaintenance() above.+ 'completion_date' => Helper::getFormattedDateObject($assetmaintenance->expected_completion_date, 'date'),'responsible_party' => ($assetmaintenance->responsibleParty) ? ['id' => (int) $assetmaintenance->responsibleParty->id,'name' => e($assetmaintenance->responsibleParty->display_name),diff --git a/app/Models/Builders/MaintenanceQueryBuilder.php b/app/Models/Builders/MaintenanceQueryBuilder.phpindex 06c49f497f..7cac41bd1a 100644--- a/app/Models/Builders/MaintenanceQueryBuilder.php+++ b/app/Models/Builders/MaintenanceQueryBuilder.php@@ -23,9 +23,9 @@ class MaintenanceQueryBuilder extends Builder$interval = (int) ($settings->audit_warning_days ?? 0);$today = Carbon::now();- return $this->whereNotNull('maintenances.completion_date')+ return $this->whereNotNull('maintenances.expected_completion_date')->whereNull('maintenances.completed_at')- ->whereBetween('maintenances.completion_date', [+ ->whereBetween('maintenances.expected_completion_date', [$today->format('Y-m-d'),$today->copy()->addDays($interval)->format('Y-m-d'),]);@@ -33,9 +33,9 @@ class MaintenanceQueryBuilder extends Builderpublic function overdueForCompletion(): static{- return $this->whereNotNull('maintenances.completion_date')+ return $this->whereNotNull('maintenances.expected_completion_date')->whereNull('maintenances.completed_at')- ->where('maintenances.completion_date', '<', Carbon::now()->format('Y-m-d'));+ ->where('maintenances.expected_completion_date', '<', Carbon::now()->format('Y-m-d'));}public function dueOrOverdueForCompletion(Setting $settings): staticdiff --git a/app/Models/Maintenance.php b/app/Models/Maintenance.phpindex 9b99a41a80..5e2fa86471 100644--- a/app/Models/Maintenance.php+++ b/app/Models/Maintenance.php@@ -43,17 +43,19 @@ class Maintenance extends SnipeModel implements ICompanyableChild'name' => 'required|max:100','is_warranty' => 'boolean','start_date' => 'required|date',- 'completion_date' => 'date|nullable|after_or_equal:start_date',+ 'expected_completion_date' => 'date|nullable|after_or_equal:start_date','notes' => 'string|nullable','cost' => 'numeric|nullable|gte:0|max:99999999999999999.99','url' => 'nullable|url|max:255','responsible_party_id' => 'nullable|integer|exists:users,id','completed_by' => 'nullable|integer|exists:users,id',+ 'completed_at' => 'nullable|date|after_or_equal:start_date|before_or_equal:now',];protected $casts = ['start_date' => 'datetime',- 'completion_date' => 'datetime',+ 'expected_completion_date' => 'datetime',+ 'completed_at' => 'datetime',];/**@@ -69,6 +71,11 @@ class Maintenance extends SnipeModel implements ICompanyableChild'maintenance_type_id','is_warranty','start_date',+ 'expected_completion_date',+ // Legacy alias for expected_completion_date. Kept fillable so an+ // API v1 caller doing Maintenance::create(['completion_date' =>+ // ...]) or ->update(...) still routes through the mutator that+ // forwards to the renamed column.'completion_date','asset_maintenance_time','notes',@@ -94,7 +101,7 @@ class Maintenance extends SnipeModel implements ICompanyableChild'notes','cost','start_date',- 'completion_date',+ 'expected_completion_date',];/**@@ -173,12 +180,30 @@ class Maintenance extends SnipeModel implements ICompanyableChild$this->attributes['notes'] = $value;}- public function setCompletionDateAttribute($value)+ public function setExpectedCompletionDateAttribute($value){if ($value == '' || $value == '0000-00-00' || $value == '0000-00-00 00:00:00') {$value = null;}- $this->attributes['completion_date'] = $value;+ $this->attributes['expected_completion_date'] = $value;+ }++ /**+ * Legacy alias for the old `completion_date` field name (renamed to+ * `expected_completion_date` to match the "Expected Completion" UI+ * label). Kept so API v1 consumers that still write to the old key+ * — either as a mass-assigned Eloquent create/update or as raw HTTP+ * form field — keep working. The API transformer emits both keys+ * on read (see MaintenancesTransformer) for the same reason.+ */+ public function setCompletionDateAttribute($value)+ {+ $this->setExpectedCompletionDateAttribute($value);+ }++ public function getCompletionDateAttribute()+ {+ return $this->expected_completion_date;}/**diff --git a/app/Presenters/MaintenancesPresenter.php b/app/Presenters/MaintenancesPresenter.phpindex 9a8d8a0bd2..8739b1441a 100644--- a/app/Presenters/MaintenancesPresenter.php+++ b/app/Presenters/MaintenancesPresenter.php@@ -174,7 +174,7 @@ class MaintenancesPresenter extends Presenter'title' => trans('admin/maintenances/form.start_date'),'formatter' => 'dateDisplayFormatter',], [- 'field' => 'completion_date',+ 'field' => 'expected_completion_date','scope' => 'col','searchable' => true,'sortable' => true,@@ -379,7 +379,7 @@ class MaintenancesPresenter extends Presenter'title' => trans('admin/maintenances/form.start_date'),'formatter' => 'dateDisplayFormatter',], [- 'field' => 'completion_date',+ 'field' => 'expected_completion_date','scope' => 'col','searchable' => true,'sortable' => true,diff --git a/database/migrations/2026_07_21_000001_rename_completion_date_to_expected_completion_date.php b/database/migrations/2026_07_21_000001_rename_completion_date_to_expected_completion_date.phpnew file mode 100644index 0000000000..00a58109a7--- /dev/null+++ b/database/migrations/2026_07_21_000001_rename_completion_date_to_expected_completion_date.php@@ -0,0 +1,22 @@+<?php++use Illuminate\Database\Migrations\Migration;+use Illuminate\Database\Schema\Blueprint;+use Illuminate\Support\Facades\Schema;++return new class extends Migration+{+ public function up(): void+ {+ Schema::table('maintenances', function (Blueprint $table) {+ $table->renameColumn('completion_date', 'expected_completion_date');+ });+ }++ public function down(): void+ {+ Schema::table('maintenances', function (Blueprint $table) {+ $table->renameColumn('expected_completion_date', 'completion_date');+ });+ }+};diff --git a/resources/lang/en-US/admin/maintenances/form.php b/resources/lang/en-US/admin/maintenances/form.phpindex a60714a2ee..abfbf15bb6 100644--- a/resources/lang/en-US/admin/maintenances/form.php+++ b/resources/lang/en-US/admin/maintenances/form.php@@ -15,6 +15,7 @@ return ['responsible_party' => 'Responsible Party','checked_out_to_at_creation' => 'Checked Out To','completed_at' => 'Completed At',+ 'completed_at_help' => 'When this maintenance was actually finished. Leave blank if not yet complete. Setting a date here is equivalent to clicking Mark Complete but lets you enter a past date instead of using the current time.','completed_by' => 'Completed By','mark_complete' => 'Mark Complete','already_complete' => 'Already Completed',diff --git a/resources/views/maintenances/edit.blade.php b/resources/views/maintenances/edit.blade.phpindex 322ad2c3fa..4ec01de4d5 100644--- a/resources/views/maintenances/edit.blade.php+++ b/resources/views/maintenances/edit.blade.php@@ -93,12 +93,35 @@<x-form.row:label="trans('admin/maintenances/form.completion_date')"- name="completion_date"+ name="expected_completion_date"type="datetimepicker":item="$item"input_div_class="col-md-4"/>+ {{-- Editable actual-completion date. Available on create as+ well as edit so users can backfill historical+ maintenances that were already done before being+ recorded. Setting this from null → date is equivalent+ to clicking Mark Complete (fires MaintenanceComplete,+ stamps completed_by, computes asset_maintenance_time).+ Clearing it un-completes the row.++ default_now MUST stay false — the field must never+ prefill with today. Editing a maintenance to change+ something unrelated should not accidentally stamp it+ complete just because the datetimepicker helpfully+ defaulted the empty value to now. --}}+ <x-form.row+ :label="trans('admin/maintenances/form.completed_at')"+ name="completed_at"+ type="datetimepicker"+ :item="$item"+ input_div_class="col-md-4"+ :help_text="trans('admin/maintenances/form.completed_at_help')"+ :default_now="false"+ />+<x-input.supplier-select:label="trans('general.supplier')"name="supplier_id"diff --git a/resources/views/maintenances/view.blade.php b/resources/views/maintenances/view.blade.phpindex e4e7a48eca..c0946161e1 100644--- a/resources/views/maintenances/view.blade.php+++ b/resources/views/maintenances/view.blade.php@@ -86,9 +86,9 @@ use Carbon\Carbon;{{ Helper::getFormattedDateObject($maintenance->start_date, 'datetime', false) }}</x-data-row>- <x-data-row :label="trans('admin/maintenances/form.completion_date')" copy_what="completion_date">- @if ($maintenance->completion_date)- {{ Helper::getFormattedDateObject($maintenance->completion_date, 'datetime', false) }}+ <x-data-row :label="trans('admin/maintenances/form.completion_date')" copy_what="expected_completion_date">+ @if ($maintenance->expected_completion_date)+ {{ Helper::getFormattedDateObject($maintenance->expected_completion_date, 'datetime', false) }}@else{{ trans('admin/maintenances/message.asset_maintenance_incomplete') }}@endif@@ -155,15 +155,15 @@ use Carbon\Carbon;@php$startCarbon = $maintenance->start_date ? Carbon::parse($maintenance->start_date) : null;- $endCarbon = $maintenance->completion_date- ? Carbon::parse($maintenance->completion_date)+ $endCarbon = $maintenance->expected_completion_date+ ? Carbon::parse($maintenance->expected_completion_date): null;$maintenancePercent = 0;if ($startCarbon) {$progressLabel = App\Helpers\Helper::getFormattedDateObject($maintenance->start_date, 'date', false);if ($endCarbon) {- $progressLabel .= ' - '.App\Helpers\Helper::getFormattedDateObject($maintenance->completion_date, 'date', false);;+ $progressLabel .= ' - '.App\Helpers\Helper::getFormattedDateObject($maintenance->expected_completion_date, 'date', false);;// Completed: show how far through the total duration we are as of today$totalDays = max(1, $startCarbon->diffInDays($endCarbon));$elapsedDays = min($totalDays, $startCarbon->diffInDays(Carbon::now()));diff --git a/tests/Feature/Maintenances/Api/CreateMaintenanceTest.php b/tests/Feature/Maintenances/Api/CreateMaintenanceTest.phpindex 1ece4e0c52..c743f67beb 100644--- a/tests/Feature/Maintenances/Api/CreateMaintenanceTest.php+++ b/tests/Feature/Maintenances/Api/CreateMaintenanceTest.php@@ -62,7 +62,7 @@ class CreateMaintenanceTest extends TestCase'name' => 'Test Maintenance','is_warranty' => 1,'start_date' => '2021-01-01 00:00:00',- 'completion_date' => '2021-01-10 00:00:00',+ 'expected_completion_date' => '2021-01-10 00:00:00','notes' => 'A note','url' => 'https://snipeitapp.com','image' => $maintenance->image,@@ -147,4 +147,58 @@ class CreateMaintenanceTest extends TestCase->assertOk()->assertJsonPath('status', 'error');}++ public function test_legacy_completion_date_fieldname_still_works_on_create()+ {+ // API v1 back-compat: the DB column was renamed from+ // completion_date to expected_completion_date, but old API+ // consumers still POST the legacy fieldname. The model's+ // setCompletionDateAttribute mutator (kept fillable) routes it+ // to the new column.+ $actor = User::factory()->superuser()->create();+ $asset = Asset::factory()->create();+ $type = MaintenanceType::factory()->create();++ $this->actingAsForApi($actor)+ ->postJson(route('api.maintenances.store'), [+ 'name' => 'Legacy Field Test',+ 'asset_id' => $asset->id,+ 'maintenance_type_id' => $type->id,+ 'start_date' => '2021-01-01 00:00:00',+ 'completion_date' => '2021-01-15 00:00:00',+ 'is_warranty' => 0,+ ])+ ->assertOk()+ ->assertJsonPath('status', 'success');++ $this->assertDatabaseHas('maintenances', [+ 'name' => 'Legacy Field Test',+ 'expected_completion_date' => '2021-01-15 00:00:00',+ ]);+ }++ public function test_new_expected_completion_date_fieldname_works_on_create()+ {+ // Companion assertion: the new-name write path is honored too.+ $actor = User::factory()->superuser()->create();+ $asset = Asset::factory()->create();+ $type = MaintenanceType::factory()->create();++ $this->actingAsForApi($actor)+ ->postJson(route('api.maintenances.store'), [+ 'name' => 'New Field Test',+ 'asset_id' => $asset->id,+ 'maintenance_type_id' => $type->id,+ 'start_date' => '2021-01-01 00:00:00',+ 'expected_completion_date' => '2021-01-20 00:00:00',+ 'is_warranty' => 0,+ ])+ ->assertOk()+ ->assertJsonPath('status', 'success');++ $this->assertDatabaseHas('maintenances', [+ 'name' => 'New Field Test',+ 'expected_completion_date' => '2021-01-20 00:00:00',+ ]);+ }}diff --git a/tests/Feature/Maintenances/Api/EditMaintenanceTest.php b/tests/Feature/Maintenances/Api/EditMaintenanceTest.phpindex 4bfff0f123..c11ad0460a 100644--- a/tests/Feature/Maintenances/Api/EditMaintenanceTest.php+++ b/tests/Feature/Maintenances/Api/EditMaintenanceTest.php@@ -58,7 +58,7 @@ class EditMaintenanceTest extends TestCase'name' => 'Test Maintenance','is_warranty' => 1,'start_date' => '2021-01-01 00:00:00',- 'completion_date' => '2021-01-10 00:00:00',+ 'expected_completion_date' => '2021-01-10 00:00:00','notes' => 'A note','url' => 'https://snipeitapp.com','image' => $maintenance->image,diff --git a/tests/Feature/Maintenances/Api/IndexMaintenanceTest.php b/tests/Feature/Maintenances/Api/IndexMaintenanceTest.phpindex ebf8632e42..204c5e6659 100644--- a/tests/Feature/Maintenances/Api/IndexMaintenanceTest.php+++ b/tests/Feature/Maintenances/Api/IndexMaintenanceTest.php@@ -239,4 +239,56 @@ class IndexMaintenanceTest extends TestCase$this->assertContains($matchingMaintenance->id, $ids);$this->assertNotContains($otherMaintenance->id, $ids);}++ public function test_response_emits_both_completion_date_and_expected_completion_date()+ {+ // API v1 back-compat: consumers reading rows[].completion_date+ // must not break when the underlying DB column was renamed to+ // expected_completion_date. The transformer emits the same value+ // under both keys so old and new consumers can coexist.+ $actor = User::factory()->superuser()->create();+ Maintenance::factory()->create([+ 'start_date' => '2021-01-01 00:00:00',+ 'expected_completion_date' => '2021-02-01',+ ]);++ $row = $this->actingAsForApi($actor)+ ->getJson(route('api.maintenances.index'))+ ->assertOk()+ ->json('rows.0');++ $this->assertArrayHasKey('completion_date', $row, 'Legacy key completion_date must still appear in the response');+ $this->assertArrayHasKey('expected_completion_date', $row, 'New key expected_completion_date must also appear');+ $this->assertNotNull($row['completion_date']);+ $this->assertSame($row['expected_completion_date'], $row['completion_date'], 'Both keys must point at the same value');+ }++ public function test_legacy_sort_by_completion_date_still_works()+ {+ // API v1 back-compat: consumers passing sort=completion_date+ // (the pre-rename name) get the same ordering as+ // sort=expected_completion_date.+ $actor = User::factory()->superuser()->create();+ $early = Maintenance::factory()->create([+ 'start_date' => '2021-01-01',+ 'expected_completion_date' => '2021-01-05',+ ]);+ $late = Maintenance::factory()->create([+ 'start_date' => '2021-01-01',+ 'expected_completion_date' => '2021-06-05',+ ]);++ $ids = collect($this->actingAsForApi($actor)+ ->getJson(route('api.maintenances.index', ['sort' => 'completion_date', 'order' => 'asc']))+ ->assertOk()+ ->json('rows'))+ ->pluck('id')+ ->all();++ $earlyIndex = array_search($early->id, $ids);+ $lateIndex = array_search($late->id, $ids);+ $this->assertNotFalse($earlyIndex);+ $this->assertNotFalse($lateIndex);+ $this->assertLessThan($lateIndex, $earlyIndex, 'sort=completion_date must order the same as expected_completion_date');+ }}diff --git a/tests/Feature/Maintenances/Ui/CreateMaintenanceTest.php b/tests/Feature/Maintenances/Ui/CreateMaintenanceTest.phpindex 297bcd164d..2f7c3d2a97 100644--- a/tests/Feature/Maintenances/Ui/CreateMaintenanceTest.php+++ b/tests/Feature/Maintenances/Ui/CreateMaintenanceTest.php@@ -79,7 +79,7 @@ class CreateMaintenanceTest extends TestCase'name' => 'Test Maintenance','is_warranty' => 1,'start_date' => '2021-01-01 00:00:00',- 'completion_date' => '2021-01-10 00:00:00',+ 'expected_completion_date' => '2021-01-10 00:00:00','notes' => 'A note','url' => 'https://snipeitapp.com','cost' => '100.00',@@ -89,4 +89,73 @@ class CreateMaintenanceTest extends TestCase$this->assertHasTheseActionLogs($maintenance, ['create', 'uploaded']);}++ public function test_can_backfill_a_completed_maintenance_via_create()+ {+ // Users record maintenances that were already finished (backfill).+ // Setting completed_at on create should: (a) persist the value,+ // (b) stamp completed_by, (c) compute asset_maintenance_time from+ // start_date → completed_at, and (d) fire the MaintenanceComplete+ // action log alongside the create log.+ $actor = User::factory()->superuser()->create();+ $asset = Asset::factory()->create();+ $type = MaintenanceType::factory()->create();++ $this->actingAs($actor)+ ->post(route('maintenances.store'), [+ 'name' => 'Backfilled Maintenance',+ 'selected_assets' => [$asset->id],+ 'maintenance_type_id' => $type->id,+ 'start_date' => '2021-01-01 00:00:00',+ 'completed_at' => '2021-01-08 00:00:00',+ 'cost' => '0.00',+ 'notes' => 'Backfilled after the fact',+ ])+ ->assertSessionHasNoErrors()+ ->assertRedirect(route('maintenances.index'));++ $maintenance = Maintenance::where('name', 'Backfilled Maintenance')->firstOrFail();++ $this->assertEquals('2021-01-08 00:00:00', $maintenance->completed_at->format('Y-m-d H:i:s'));+ $this->assertEquals($actor->id, $maintenance->completed_by);+ $this->assertEquals(7, $maintenance->asset_maintenance_time, 'Duration should be start_date → completed_at, not created_at → completed_at (created_at is now, not the historical timeline)');++ $this->assertDatabaseHas('action_logs', [+ 'item_type' => Maintenance::class,+ 'item_id' => $maintenance->id,+ 'action_type' => 'completed',+ 'created_by' => $actor->id,+ ]);+ }++ public function test_creating_without_completed_at_leaves_maintenance_active()+ {+ // Sanity guard: the default create flow (no completed_at) must+ // not accidentally stamp anything. Snipe called this out — a+ // datetimepicker that defaults to now() would silently mark+ // freshly-created maintenances complete.+ $actor = User::factory()->superuser()->create();+ $asset = Asset::factory()->create();+ $type = MaintenanceType::factory()->create();++ $this->actingAs($actor)+ ->post(route('maintenances.store'), [+ 'name' => 'Active Maintenance',+ 'selected_assets' => [$asset->id],+ 'maintenance_type_id' => $type->id,+ 'start_date' => '2021-01-01 00:00:00',+ ])+ ->assertSessionHasNoErrors();++ $maintenance = Maintenance::where('name', 'Active Maintenance')->firstOrFail();++ $this->assertNull($maintenance->completed_at);+ $this->assertNull($maintenance->completed_by);+ $this->assertNull($maintenance->asset_maintenance_time);+ $this->assertDatabaseMissing('action_logs', [+ 'item_type' => Maintenance::class,+ 'item_id' => $maintenance->id,+ 'action_type' => 'completed',+ ]);+ }}diff --git a/tests/Feature/Maintenances/Ui/EditMaintenanceTest.php b/tests/Feature/Maintenances/Ui/EditMaintenanceTest.phpindex 54cd133c10..bda47afe0e 100644--- a/tests/Feature/Maintenances/Ui/EditMaintenanceTest.php+++ b/tests/Feature/Maintenances/Ui/EditMaintenanceTest.php@@ -75,7 +75,7 @@ class EditMaintenanceTest extends TestCase'name' => 'Test Maintenance','is_warranty' => 1,'start_date' => '2021-01-01 00:00:00',- 'completion_date' => '2021-01-10 00:00:00',+ 'expected_completion_date' => '2021-01-10 00:00:00','notes' => 'A note','url' => 'https://snipeitapp.com','cost' => '100.99',@@ -95,6 +95,173 @@ class EditMaintenanceTest extends TestCase$this->assertArrayHasKey('name', json_decode($updateLog->log_meta, true));}+ public function test_setting_completed_at_on_edit_marks_maintenance_complete()+ {+ // Editing a maintenance from null → a completed_at date is+ // equivalent to clicking Mark Complete: stamps completed_by,+ // computes asset_maintenance_time from created_at → the entered+ // date, and fires the MaintenanceComplete action log. This lets+ // users backfill completion for maintenances someone forgot to+ // close out at the time.+ $actor = User::factory()->superuser()->create();+ // Pin created_at well in the past so a completion date 5 days+ // later is still safely <= now(). The before_or_equal:now rule+ // would otherwise reject anything that lands in the future.+ $maintenance = Maintenance::factory()->create([+ 'start_date' => '2021-01-01 00:00:00',+ 'completed_at' => null,+ 'created_at' => '2021-01-01 00:00:00',+ ]);+ $completionDate = '2021-01-06 00:00:00';++ $this->actingAs($actor)+ ->put(route('maintenances.update', $maintenance), [+ 'name' => $maintenance->name,+ 'asset_id' => $maintenance->asset_id,+ 'maintenance_type_id' => $maintenance->maintenance_type_id,+ 'start_date' => '2021-01-01 00:00:00',+ 'completed_at' => $completionDate,+ ])+ ->assertSessionHasNoErrors()+ ->assertRedirect(route('maintenances.index'));++ $maintenance->refresh();++ $this->assertNotNull($maintenance->completed_at);+ $this->assertEquals($completionDate, $maintenance->completed_at->format('Y-m-d H:i:s'));+ $this->assertEquals($actor->id, $maintenance->completed_by);+ $this->assertEquals(5, $maintenance->asset_maintenance_time);++ $this->assertDatabaseHas('action_logs', [+ 'item_type' => Maintenance::class,+ 'item_id' => $maintenance->id,+ 'action_type' => 'completed',+ 'created_by' => $actor->id,+ ]);+ }++ public function test_clearing_completed_at_on_edit_uncompletes_the_maintenance()+ {+ // Value → null on edit reverses the completion: clears+ // completed_at, completed_by, and asset_maintenance_time so the+ // row goes back to the active list. No new log fires.+ $actor = User::factory()->superuser()->create();+ $originalCompleter = User::factory()->create();+ $maintenance = Maintenance::factory()->create([+ 'start_date' => '2021-01-01 00:00:00',+ 'completed_at' => '2021-01-10 00:00:00',+ 'completed_by' => $originalCompleter->id,+ 'asset_maintenance_time' => 9,+ ]);++ $this->actingAs($actor)+ ->put(route('maintenances.update', $maintenance), [+ 'name' => $maintenance->name,+ 'asset_id' => $maintenance->asset_id,+ 'maintenance_type_id' => $maintenance->maintenance_type_id,+ 'start_date' => '2021-01-01 00:00:00',+ 'completed_at' => '',+ ])+ ->assertSessionHasNoErrors()+ ->assertRedirect(route('maintenances.index'));++ $maintenance->refresh();+ $this->assertNull($maintenance->completed_at);+ $this->assertNull($maintenance->completed_by);+ $this->assertNull($maintenance->asset_maintenance_time);+ }++ public function test_editing_completed_at_on_already_completed_maintenance_preserves_completed_by_and_does_not_relog()+ {+ // date → different-date is a corrective edit, not a fresh+ // completion. Original completer stays put, no second+ // MaintenanceComplete log entry gets fired.+ $actor = User::factory()->superuser()->create();+ $originalCompleter = User::factory()->create();+ $maintenance = Maintenance::factory()->create([+ 'start_date' => '2021-01-01 00:00:00',+ 'completed_at' => '2021-01-10 00:00:00',+ 'completed_by' => $originalCompleter->id,+ ]);++ $priorLogCount = Actionlog::query()+ ->where('item_type', Maintenance::class)+ ->where('item_id', $maintenance->id)+ ->where('action_type', 'completed')+ ->count();++ $this->actingAs($actor)+ ->put(route('maintenances.update', $maintenance), [+ 'name' => $maintenance->name,+ 'asset_id' => $maintenance->asset_id,+ 'maintenance_type_id' => $maintenance->maintenance_type_id,+ 'start_date' => '2021-01-01 00:00:00',+ 'completed_at' => '2021-01-15 00:00:00',+ ])+ ->assertSessionHasNoErrors();++ $maintenance->refresh();+ $this->assertEquals('2021-01-15 00:00:00', $maintenance->completed_at->format('Y-m-d H:i:s'));+ $this->assertEquals($originalCompleter->id, $maintenance->completed_by, 'Original completer should not be overwritten by a corrective edit');++ $newLogCount = Actionlog::query()+ ->where('item_type', Maintenance::class)+ ->where('item_id', $maintenance->id)+ ->where('action_type', 'completed')+ ->count();+ $this->assertEquals($priorLogCount, $newLogCount, 'Corrective edit should not fire a fresh MaintenanceComplete action log');+ }++ public function test_completed_at_rejects_date_before_start_date()+ {+ // Model-level rule: completed_at must be >= start_date. Prevents+ // "completed before it began" nonsense.+ $actor = User::factory()->superuser()->create();+ $maintenance = Maintenance::factory()->create([+ 'start_date' => '2021-06-01 00:00:00',+ 'completed_at' => null,+ ]);++ $this->actingAs($actor)+ ->from(route('maintenances.edit', $maintenance))+ ->put(route('maintenances.update', $maintenance), [+ 'name' => $maintenance->name,+ 'asset_id' => $maintenance->asset_id,+ 'maintenance_type_id' => $maintenance->maintenance_type_id,+ 'start_date' => '2021-06-01 00:00:00',+ 'completed_at' => '2021-05-15 00:00:00',+ ])+ ->assertSessionHasErrors('completed_at')+ ->assertRedirect(route('maintenances.edit', $maintenance));++ $this->assertNull($maintenance->fresh()->completed_at);+ }++ public function test_completed_at_rejects_future_date()+ {+ // Model-level rule: completed_at must be <= now. You can't have+ // completed a maintenance in the future.+ $actor = User::factory()->superuser()->create();+ $maintenance = Maintenance::factory()->create([+ 'start_date' => '2021-01-01 00:00:00',+ 'completed_at' => null,+ ]);++ $this->actingAs($actor)+ ->from(route('maintenances.edit', $maintenance))+ ->put(route('maintenances.update', $maintenance), [+ 'name' => $maintenance->name,+ 'asset_id' => $maintenance->asset_id,+ 'maintenance_type_id' => $maintenance->maintenance_type_id,+ 'start_date' => '2021-01-01 00:00:00',+ 'completed_at' => now()->addYear()->format('Y-m-d H:i:s'),+ ])+ ->assertSessionHasErrors('completed_at')+ ->assertRedirect(route('maintenances.edit', $maintenance));++ $this->assertNull($maintenance->fresh()->completed_at);+ }+public function test_user_cannot_edit_maintenance_for_another_company_when_fmcs_enabled(){$this->settings->enableMultipleFullCompanySupport();diff --git a/tests/Feature/Reporting/MaintenanceReportTest.php b/tests/Feature/Reporting/MaintenanceReportTest.phpnew file mode 100644index 0000000000..c719dd5202--- /dev/null+++ b/tests/Feature/Reporting/MaintenanceReportTest.php@@ -0,0 +1,190 @@+<?php++namespace Tests\Feature\Reporting;++use App\Models\Asset;+use App\Models\Maintenance;+use App\Models\MaintenanceType;+use App\Models\Supplier;+use App\Models\User;+use Tests\TestCase;++/**+ * Coverage for /reports/export/maintenances — the server-side streamed+ * CSV export. Independent from the datatable-driven report at+ * /reports/maintenances (which uses the API + presenter and has its own+ * client-side export).+ *+ * The pre-#19039 CSV emitted a legacy `improvement_type` accessor that no+ * longer exists on the model, silently writing empty cells where the+ * maintenance type used to appear. It also skipped completed_at,+ * completed_by, is_warranty, and notes, and would crash on a null+ * supplier or a soft-deleted asset. These tests lock in the corrected+ * behavior.+ */+class MaintenanceReportTest extends TestCase+{+ public function test_requires_permission_to_export()+ {+ $this->actingAs(User::factory()->create())+ ->get(route('reports/export/maintenances'))+ ->assertForbidden();+ }++ public function test_export_returns_csv()+ {+ $this->actingAs(User::factory()->canViewReports()->create())+ ->get(route('reports/export/maintenances'))+ ->assertOk()+ ->assertHeader('content-type', 'text/csv; charset=utf-8');+ }++ public function test_export_includes_both_active_and_completed_maintenances()+ {+ $active = Maintenance::factory()->create([+ 'name' => 'Active-Repair-XYZ',+ 'completed_at' => null,+ ]);+ $completed = Maintenance::factory()->create([+ 'name' => 'Completed-Repair-ABC',+ 'start_date' => '2021-01-01 00:00:00',+ 'completed_at' => '2021-01-10 12:00:00',+ ]);++ $content = $this->actingAs(User::factory()->canViewReports()->create())+ ->get(route('reports/export/maintenances'))+ ->assertOk()+ ->streamedContent();++ $this->assertStringContainsString('Active-Repair-XYZ', $content);+ $this->assertStringContainsString('Completed-Repair-ABC', $content);+ }++ public function test_export_row_contains_maintenance_type_name()+ {+ // Before the #19039 rewrite the report emitted+ // $maintenance->improvement_type which has no accessor on the+ // current model — the type column silently came out empty. Now+ // it should be the related MaintenanceType.name.+ $type = MaintenanceType::factory()->create(['name' => 'Firmware-Upgrade-Test']);+ Maintenance::factory()->create(['maintenance_type_id' => $type->id]);++ $content = $this->actingAs(User::factory()->canViewReports()->create())+ ->get(route('reports/export/maintenances'))+ ->assertOk()+ ->streamedContent();++ $this->assertStringContainsString('Firmware-Upgrade-Test', $content);+ }++ public function test_export_row_contains_completed_at_and_completed_by()+ {+ $completer = User::factory()->create([+ 'first_name' => 'Rutherford',+ 'last_name' => 'Hayes',+ ]);+ Maintenance::factory()->create([+ 'name' => 'Backfill-Repair',+ 'start_date' => '2021-06-01 00:00:00',+ 'completed_at' => '2021-06-05 09:15:00',+ 'completed_by' => $completer->id,+ ]);++ $content = $this->actingAs(User::factory()->canViewReports()->create())+ ->get(route('reports/export/maintenances'))+ ->assertOk()+ ->streamedContent();++ // completed_at gets rendered by fputcsv as the Carbon toString+ // representation (Y-m-d H:i:s). Just look for the date portion so+ // this doesn't get flaky on timezone-dependent formatting.+ $this->assertStringContainsString('2021-06-05', $content);+ $this->assertStringContainsString($completer->display_name, $content);+ }++ public function test_export_row_survives_null_supplier()+ {+ // supplier_id is nullable on the maintenances table; the pre-fix+ // report did $maintenance->supplier->name unconditionally and+ // would fatal-error on any row without one.+ $maintenance = Maintenance::factory()->create([+ 'name' => 'Supplier-Less',+ 'supplier_id' => null,+ ]);++ $this->actingAs(User::factory()->canViewReports()->create())+ ->get(route('reports/export/maintenances'))+ ->assertOk()+ ->streamedContent();++ // Just confirming no 500. The presence assertion is that the row+ // still made it into the output.+ $content = $this->actingAs(User::factory()->canViewReports()->create())+ ->get(route('reports/export/maintenances'))+ ->streamedContent();+ $this->assertStringContainsString('Supplier-Less', $content);+ }++ public function test_export_row_shows_supplier_when_present()+ {+ $supplier = Supplier::factory()->create(['name' => 'Contoso-Repairs-Inc']);+ Maintenance::factory()->create(['supplier_id' => $supplier->id]);++ $content = $this->actingAs(User::factory()->canViewReports()->create())+ ->get(route('reports/export/maintenances'))+ ->assertOk()+ ->streamedContent();++ $this->assertStringContainsString('Contoso-Repairs-Inc', $content);+ }++ public function test_export_row_uses_new_expected_completion_date_value()+ {+ // Regression guard for the rename: the CSV must show the value+ // stored on expected_completion_date (the renamed column), not+ // an accidentally-empty cell if someone re-introduced the old+ // completion_date reference.+ Maintenance::factory()->create([+ 'name' => 'RenamedDateTest',+ 'start_date' => '2021-01-01 00:00:00',+ 'expected_completion_date' => '2021-01-31 00:00:00',+ ]);++ $content = $this->actingAs(User::factory()->canViewReports()->create())+ ->get(route('reports/export/maintenances'))+ ->assertOk()+ ->streamedContent();++ $this->assertStringContainsString('RenamedDateTest', $content);+ $this->assertStringContainsString('2021-01-31', $content);+ }++ public function test_export_includes_is_warranty_and_notes_columns()+ {+ Maintenance::factory()->create([+ 'name' => 'WarrantyNoteRow',+ 'is_warranty' => 1,+ 'notes' => 'A distinctive-note-blob-1729',+ ]);++ $content = $this->actingAs(User::factory()->canViewReports()->create())+ ->get(route('reports/export/maintenances'))+ ->assertOk()+ ->streamedContent();++ $this->assertStringContainsString('A distinctive-note-blob-1729', $content);+ }++ public function test_header_row_appears_only_once_even_with_many_rows()+ {+ Maintenance::factory()->count(3)->create();++ $content = $this->actingAs(User::factory()->canViewReports()->create())+ ->get(route('reports/export/maintenances'))+ ->assertOk()+ ->streamedContent();++ // The Cost header is unique enough not to appear as row data.+ $this->assertSame(1, substr_count($content, 'Cost'));+ }+}