Skip to content

A free open source IT asset/license management system

De-normed company ID on calendar events table

snipe74b476684787
diff --git a/app/Http/Controllers/Api/CalendarEventsController.php b/app/Http/Controllers/Api/CalendarEventsController.php
index 912f8725fc..cef74008dc 100644
--- a/app/Http/Controllers/Api/CalendarEventsController.php
+++ b/app/Http/Controllers/Api/CalendarEventsController.php
@@ -74,18 +74,26 @@ class CalendarEventsController extends Controller
fn (string $sourceClass) => Gate::allows('view', $sourceClass),
));
+ // CompanyableTrait on CalendarEvent installs the global
+ // CompanyableScope, so count / order / limit below run against
+ // a company-scoped query. `total` reflects only rows this
+ // caller is allowed to see and `limit` cannot be consumed by
+ // rows the per-row filter would strip later. The per-row
+ // filter below still runs as defense in depth to catch cases
+ // the SQL filter can't express (per-location scoping on top of
+ // FMCS, soft-deleted sources, etc.).
$baseQuery = $this->buildBaseQuery($rangeStart, $rangeEnd, $eventTypes)
->whereIn('source_type', $viewableSourceTypes);
$total = (clone $baseQuery)->count();
$rows = $baseQuery->orderBy('start')->limit($limit)->get();
- // Whether we hit the query limit. Honest signal for "there
- // might be more events after this batch". Comparing $total to
- // count($events) post-per-row-filter would report truncated=
- // true any time an FMCS-filtered event brought the returned
- // count below $total, misleading users into clicking "+N more"
- // links for events they never had permission to see.
- $hitLimit = $rows->count() >= $limit;
+ // Now that count and fetch run against the same company-scoped
+ // query, `truncated` can honestly reflect "more authorized
+ // events exist beyond this batch" rather than the earlier
+ // proxy that reported true whenever the pre-filter batch was
+ // full, even when per-row filtering reduced the response to
+ // fewer than $limit rows.
+ $hitLimit = $total > $limit;
$sourcesByType = $this->batchLoadSources($rows);
$authorizedRows = $this->filterAuthorizedRows($rows, $sourcesByType, $request);
@@ -113,8 +121,8 @@ class CalendarEventsController extends Controller
protected function resolveRange(Request $request): array
{
return [
- $this->parseDateOrDefault($request->input('start'), fn() => now()->subMonths(3)->startOfDay()),
- $this->parseDateOrDefault($request->input('end'), fn() => now()->addMonths(3)->endOfDay()),
+ $this->parseDateOrDefault($request->input('start'), fn () => now()->subMonths(3)->startOfDay()),
+ $this->parseDateOrDefault($request->input('end'), fn () => now()->addMonths(3)->endOfDay()),
];
}
@@ -124,7 +132,7 @@ class CalendarEventsController extends Controller
*/
private function parseDateOrDefault(mixed $value, callable $default): Carbon
{
- if (!is_string($value) || trim($value) === '') {
+ if (! is_string($value) || trim($value) === '') {
return $default();
}
diff --git a/app/Models/Asset.php b/app/Models/Asset.php
index 64012a16c3..f538b149c3 100644
--- a/app/Models/Asset.php
+++ b/app/Models/Asset.php
@@ -282,6 +282,25 @@ class Asset extends Depreciable
static::softDeleted(function (Asset $asset) {
$asset->requests()->delete();
});
+
+ // When an asset moves between companies, its own calendar
+ // events pick up the new company_id through the HasCalendarEvents
+ // trait's updated hook, but child Maintenances resolve their
+ // calendar_events company_id from the parent asset and would
+ // otherwise keep the stale value until they themselves are
+ // touched. Cascade the re-sync here so FMCS filtering stays
+ // accurate on both the asset's and the maintenance's rows.
+ static::updated(function (Asset $asset) {
+ if (array_key_exists('company_id', $asset->getChanges())) {
+ // withoutGlobalScopes bypasses CompanyableChildScope on
+ // Maintenance so the cascade reaches every related
+ // maintenance regardless of the saving context's auth
+ // state (CLI, system jobs, cross-tenant admin saves).
+ $asset->maintenances()->withoutGlobalScopes()->get()->each(
+ fn (Maintenance $m) => $m->forceSyncCalendarEvents(),
+ );
+ }
+ });
}
public function setExpectedCheckinAttribute($value)
@@ -1869,16 +1888,11 @@ class Asset extends Depreciable
);
}
- /**
- * Query builder scope for Archived assets counting
- *
- * This is primarily used for the tab counters so that IF the admin
- * has chosen to not display archived assets in their regular lists
- * and views, it will return the correct number.
- *
- * @param \Illuminate\Database\Query\Builder $query Query builder instance
- * @return \Illuminate\Database\Query\Builder Modified query builder
- */
+ public function calendarEventCompanyId(): ?int
+ {
+ return $this->company_id;
+ }
+
public function calendarEventDefinitions(): array
{
// Most entries are marked all_day: true because they represent
diff --git a/app/Models/CalendarEvent.php b/app/Models/CalendarEvent.php
index d35beed795..41481495f5 100644
--- a/app/Models/CalendarEvent.php
+++ b/app/Models/CalendarEvent.php
@@ -2,6 +2,7 @@
namespace App\Models;
+use App\Models\Traits\CompanyableTrait;
use App\Models\Traits\HasCalendarEvents;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphTo;
@@ -20,6 +21,7 @@ use Illuminate\Database\Eloquent\SoftDeletes;
*/
class CalendarEvent extends Model
{
+ use CompanyableTrait;
use SoftDeletes;
protected $fillable = [
@@ -29,6 +31,7 @@ class CalendarEvent extends Model
'event_type',
'start',
'end',
+ 'company_id',
];
protected $casts = [
diff --git a/app/Models/License.php b/app/Models/License.php
index 89e38ff3b1..e8d4707e18 100755
--- a/app/Models/License.php
+++ b/app/Models/License.php
@@ -190,6 +190,11 @@ class License extends Depreciable
&& ($this->deleted_at == '');
}
+ public function calendarEventCompanyId(): ?int
+ {
+ return $this->company_id;
+ }
+
public function calendarEventDefinitions(): array
{
return [
diff --git a/app/Models/Maintenance.php b/app/Models/Maintenance.php
index 4f7b068307..6af128a9ca 100644
--- a/app/Models/Maintenance.php
+++ b/app/Models/Maintenance.php
@@ -337,6 +337,15 @@ class Maintenance extends SnipeModel implements ICompanyableChild
return $this->morphTo('checked_out_to');
}
+ public function calendarEventCompanyId(): ?int
+ {
+ // loadMissing covers the observer path where the created hook
+ // fires before the $with eager-load has run. Without it the
+ // observer writes company_id=null and the FMCS scope filter
+ // on the read path hides the row from legitimate viewers.
+ return $this->loadMissing('asset')->asset?->company_id;
+ }
+
/**
* Fields published to the calendar_events index table via the
* HasCalendarEvents trait. A single range event per maintenance
diff --git a/app/Models/Traits/HasCalendarEvents.php b/app/Models/Traits/HasCalendarEvents.php
index 59c4c1aee1..158e8f3bc5 100644
--- a/app/Models/Traits/HasCalendarEvents.php
+++ b/app/Models/Traits/HasCalendarEvents.php
@@ -166,6 +166,17 @@ trait HasCalendarEvents
return false;
}
+ // company_id is an implicit trigger across every definition
+ // because it writes to the denormalized calendar_events.company_id
+ // the FMCS read filter runs against. Sources that resolve their
+ // company from a parent (Maintenance via Asset) rely on the
+ // parent model's own observer to cascade re-syncs, not on this
+ // check, since the parent column isn't on the source's own
+ // getChanges() payload.
+ if (array_key_exists('company_id', $changes)) {
+ return true;
+ }
+
foreach ($definitions as $definition) {
if (array_key_exists($definition['field'], $changes)) {
return true;
@@ -215,6 +226,7 @@ trait HasCalendarEvents
}
$end = $endField ? $this->{$endField} : null;
+ $companyId = $this->calendarEventCompanyId();
$existing = CalendarEvent::withTrashed()
->where('source_type', static::class)
@@ -227,6 +239,7 @@ trait HasCalendarEvents
'event_type' => $eventType,
'start' => $start,
'end' => $end,
+ 'company_id' => $companyId,
'deleted_at' => null,
])->save();
@@ -240,9 +253,30 @@ trait HasCalendarEvents
'event_type' => $eventType,
'start' => $start,
'end' => $end,
+ 'company_id' => $companyId,
]);
}
+ /**
+ * Resolve the company_id this source model's calendar events belong
+ * to under FMCS. Written to the denormalized `calendar_events.company_id`
+ * column on every observer-driven write, so the read path can filter
+ * at the SQL level before count / order / limit. The read-path null
+ * handling mirrors CompanyableTrait: a null company_id means
+ * "unscoped" and whether the event surfaces to a given caller depends
+ * on the `null_company_is_floater` setting.
+ *
+ * Default is null for sources that don't have a single parent
+ * company (users have the company_user pivot, requests derive their
+ * company from the requestable). Source models with a direct
+ * company_id column or a CompanyableChildTrait parent override this
+ * to return the resolved id.
+ */
+ public function calendarEventCompanyId(): ?int
+ {
+ return null;
+ }
+
/**
* Every declared calendar-event row for this source model
* instance. Not eager-loaded anywhere by default; consumers that
diff --git a/database/migrations/2026_08_13_160000_create_calendar_events_table.php b/database/migrations/2026_08_13_160000_create_calendar_events_table.php
index 5f7fa23102..2b69c317e4 100644
--- a/database/migrations/2026_08_13_160000_create_calendar_events_table.php
+++ b/database/migrations/2026_08_13_160000_create_calendar_events_table.php
@@ -39,6 +39,7 @@ return new class extends Migration
$table->dateTime('start');
$table->dateTime('end')->nullable();
+ $table->unsignedBigInteger('company_id')->nullable();
$table->timestamps();
$table->softDeletes();
@@ -55,6 +56,11 @@ return new class extends Migration
// BETWEEN ? AND ?. Composite lets the planner satisfy both
// predicates from the index.
$table->index(['event_type', 'start'], 'calendar_events_type_start_index');
+
+ // Read path FMCS filter: WHERE company_id IN (...) OR
+ // company_id IS NULL (floater). Standalone index because
+ // the composite above is ordered for the type+range query.
+ $table->index('company_id', 'calendar_events_company_id_index');
});
}
diff --git a/database/migrations/2026_10_05_120000_backfill_calendar_events_company_id.php b/database/migrations/2026_10_05_120000_backfill_calendar_events_company_id.php
new file mode 100644
index 0000000000..51c20a37c5
--- /dev/null
+++ b/database/migrations/2026_10_05_120000_backfill_calendar_events_company_id.php
@@ -0,0 +1,85 @@
+<?php
+
+use App\Models\Asset;
+use App\Models\License;
+use App\Models\Maintenance;
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\DB;
+use Illuminate\Support\Facades\Schema;
+
+/**
+ * Catch-up migration for installs that already ran the original
+ * create_calendar_events_table + backfill migrations before the
+ * calendar_events.company_id column existed. Fresh schemas built
+ * after the create migration gained the column no-op through this
+ * migration via the hasColumn gate, and even when the column exists
+ * we only touch rows whose company_id is still null, so an install
+ * that already got populated via the updated backfill migration
+ * skips the heavy work.
+ *
+ * Uses single-pass correlated-subquery UPDATEs per source class
+ * rather than iterating source rows through the observer. On a
+ * 500k-asset install the Eloquent-driven path would have fired
+ * half a million UPDATE round-trips. This is three statements
+ * total, scoped to NULL rows.
+ */
+return new class extends Migration
+{
+ public function up(): void
+ {
+ if (! Schema::hasColumn('calendar_events', 'company_id')) {
+ Schema::table('calendar_events', function (Blueprint $table) {
+ $table->unsignedBigInteger('company_id')->nullable()->after('end');
+ $table->index('company_id', 'calendar_events_company_id_index');
+ });
+ }
+
+ // Fast path. If every row already has company_id, there's
+ // nothing to do (fresh install, or an upgrade that walked
+ // the updated backfill migrations).
+ if (! DB::table('calendar_events')->whereNull('company_id')->exists()) {
+ return;
+ }
+
+ // Asset and License store company_id directly. One correlated-
+ // subquery UPDATE per source resolves the whole set.
+ foreach ([Asset::class, License::class] as $sourceClass) {
+ $table = (new $sourceClass)->getTable();
+ DB::statement(
+ "UPDATE calendar_events SET company_id = (
+ SELECT {$table}.company_id FROM {$table}
+ WHERE {$table}.id = calendar_events.source_id
+ ) WHERE source_type = ? AND company_id IS NULL",
+ [$sourceClass],
+ );
+ }
+
+ // Maintenance stores no company_id of its own. company lives on
+ // the parent asset (item_id when item_type matches Asset's
+ // class string). Two-hop correlated subquery through assets.
+ DB::statement(
+ 'UPDATE calendar_events SET company_id = (
+ SELECT a.company_id FROM assets a
+ INNER JOIN maintenances m ON m.item_id = a.id AND m.item_type = ?
+ WHERE m.id = calendar_events.source_id
+ ) WHERE source_type = ? AND company_id IS NULL',
+ [Asset::class, Maintenance::class],
+ );
+
+ // User and CheckoutRequest events stay null. Users carry pivot
+ // companies (no single value) and requests derive their
+ // company from the requestable. Both fall through to the
+ // null-company read-path semantics the controller applies.
+ }
+
+ public function down(): void
+ {
+ if (Schema::hasColumn('calendar_events', 'company_id')) {
+ Schema::table('calendar_events', function (Blueprint $table) {
+ $table->dropIndex('calendar_events_company_id_index');
+ $table->dropColumn('company_id');
+ });
+ }
+ }
+};
diff --git a/phpstan-baseline.neon b/phpstan-baseline.neon
index 40fd91b92e..cbadd8abb6 100644
--- a/phpstan-baseline.neon
+++ b/phpstan-baseline.neon
@@ -414,18 +414,6 @@ parameters:
count: 3
path: app/Console/Commands/MergeUsersByUsername.php
- -
- message: '#^Method Illuminate\\Filesystem\\FilesystemAdapter\:\:url\(\) invoked with 2 parameters, 1 required\.$#'
- identifier: arguments.count
- count: 1
- path: app/Console/Commands/MoveUploadsToNewDisk.php
-
- -
- message: '#^Static method Illuminate\\Filesystem\\FilesystemAdapter\:\:url\(\) invoked with 2 parameters, 1 required\.$#'
- identifier: arguments.count
- count: 1
- path: app/Console/Commands/MoveUploadsToNewDisk.php
-
-
message: '#^Method App\\Console\\Commands\\NormalizeUserNames\:\:handle\(\) should return int but return statement is missing\.$#'
identifier: return.missing
@@ -708,12 +696,6 @@ parameters:
count: 1
path: app/Helpers/Helper.php
- -
- message: '#^Access to an undefined property App\\Models\\Component\:\:\$sum_unconstrained_assets\.$#'
- identifier: property.notFound
- count: 1
- path: app/Helpers/Helper.php
-
-
message: '#^Access to an undefined property App\\Models\\Consumable\:\:\$consumables_users_count\.$#'
identifier: property.notFound
@@ -1500,12 +1482,6 @@ parameters:
count: 1
path: app/Http/Controllers/Api/ImportController.php
- -
- message: '#^Property App\\Models\\Import\:\:\$filesize \(int\) does not accept null\.$#'
- identifier: assign.propertyType
- count: 1
- path: app/Http/Controllers/Api/ImportController.php
-
-
message: '#^Variable \$model_perms might not be defined\.$#'
identifier: variable.undefined
@@ -3468,12 +3444,6 @@ parameters:
count: 1
path: app/Http/Controllers/Users/BulkUsersController.php
- -
- message: '#^Call to an undefined method Illuminate\\Database\\Eloquent\\Relations\\Relation\:\:sync\(\)\.$#'
- identifier: method.notFound
- count: 1
- path: app/Http/Controllers/Users/BulkUsersController.php
-
-
message: '#^Call to an undefined method Illuminate\\Database\\Eloquent\\Relations\\Relation\:\:updateExistingPivot\(\)\.$#'
identifier: method.notFound
@@ -4962,102 +4932,12 @@ parameters:
count: 2
path: app/Mail/CheckinLicenseMail.php
- -
- message: '#^Access to an undefined property App\\Mail\\CheckoutAccessoryMail\:\:\$acceptance\.$#'
- identifier: property.notFound
- count: 2
- path: app/Mail/CheckoutAccessoryMail.php
-
- -
- message: '#^Access to an undefined property App\\Mail\\CheckoutAccessoryMail\:\:\$admin\.$#'
- identifier: property.notFound
- count: 2
- path: app/Mail/CheckoutAccessoryMail.php
-
- -
- message: '#^Access to an undefined property App\\Mail\\CheckoutAccessoryMail\:\:\$checkout_qty\.$#'
- identifier: property.notFound
- count: 6
- path: app/Mail/CheckoutAccessoryMail.php
-
- -
- message: '#^Access to an undefined property App\\Mail\\CheckoutAccessoryMail\:\:\$item\.$#'
- identifier: property.notFound
- count: 6
- path: app/Mail/CheckoutAccessoryMail.php
-
- -
- message: '#^Access to an undefined property App\\Mail\\CheckoutAccessoryMail\:\:\$note\.$#'
- identifier: property.notFound
- count: 2
- path: app/Mail/CheckoutAccessoryMail.php
-
- -
- message: '#^Access to an undefined property App\\Mail\\CheckoutAccessoryMail\:\:\$settings\.$#'
- identifier: property.notFound
- count: 1
- path: app/Mail/CheckoutAccessoryMail.php
-
- -
- message: '#^Access to an undefined property App\\Mail\\CheckoutAccessoryMail\:\:\$target\.$#'
- identifier: property.notFound
- count: 3
- path: app/Mail/CheckoutAccessoryMail.php
-
-
message: '#^Access to an undefined property App\\Models\\Accessory\:\:\$checkout_qty\.$#'
identifier: property.notFound
count: 1
path: app/Mail/CheckoutAccessoryMail.php
- -
- message: '#^Access to an undefined property App\\Mail\\CheckoutAssetMail\:\:\$acceptance\.$#'
- identifier: property.notFound
- count: 3
- path: app/Mail/CheckoutAssetMail.php
-
- -
- message: '#^Access to an undefined property App\\Mail\\CheckoutAssetMail\:\:\$admin\.$#'
- identifier: property.notFound
- count: 2
- path: app/Mail/CheckoutAssetMail.php
-
- -
- message: '#^Access to an undefined property App\\Mail\\CheckoutAssetMail\:\:\$expected_checkin\.$#'
- identifier: property.notFound
- count: 2
- path: app/Mail/CheckoutAssetMail.php
-
- -
- message: '#^Access to an undefined property App\\Mail\\CheckoutAssetMail\:\:\$item\.$#'
- identifier: property.notFound
- count: 11
- path: app/Mail/CheckoutAssetMail.php
-
- -
- message: '#^Access to an undefined property App\\Mail\\CheckoutAssetMail\:\:\$last_checkout\.$#'
- identifier: property.notFound
- count: 2
- path: app/Mail/CheckoutAssetMail.php
-
- -
- message: '#^Access to an undefined property App\\Mail\\CheckoutAssetMail\:\:\$note\.$#'
- identifier: property.notFound
- count: 2
- path: app/Mail/CheckoutAssetMail.php
-
- -
- message: '#^Access to an undefined property App\\Mail\\CheckoutAssetMail\:\:\$settings\.$#'
- identifier: property.notFound
- count: 1
- path: app/Mail/CheckoutAssetMail.php
-
- -
- message: '#^Access to an undefined property App\\Mail\\CheckoutAssetMail\:\:\$target\.$#'
- identifier: property.notFound
- count: 3
- path: app/Mail/CheckoutAssetMail.php
-
-
message: '#^PHPDoc tag @param references unknown parameter\: \$notifiable$#'
identifier: parameter.notFound
@@ -5562,12 +5442,6 @@ parameters:
count: 1
path: app/Models/Actionlog.php
- -
- message: '#^PHPDoc tag @SuppressWarnings has invalid value \(\(PHPMD\.UnusedFormalParameter\)\)\: Unexpected token "\.UnusedFormalParameter\)", expected ''\)'' at offset 351 on line 10$#'
- identifier: phpDoc.parseError
- count: 1
- path: app/Models/Actionlog.php
-
-
message: '#^Property App\\Models\\Actionlog\:\:\$searchableAttributes \(array\) on left side of \?\? is not nullable\.$#'
identifier: nullCoalesce.property
@@ -5760,12 +5634,6 @@ parameters:
count: 2
path: app/Models/Asset.php
- -
- message: '#^PHPDoc tag @param references unknown parameter\: \$query$#'
- identifier: parameter.notFound
- count: 1
- path: app/Models/Asset.php
-
-
message: '#^PHPDoc tag @param references unknown parameter\: \$settings$#'
identifier: parameter.notFound
@@ -5784,12 +5652,6 @@ parameters:
count: 1
path: app/Models/Asset.php
- -
- message: '#^PHPDoc tag @return with type Illuminate\\Database\\Query\\Builder is incompatible with native type array\.$#'
- identifier: return.phpDocType
- count: 1
- path: app/Models/Asset.php
-
-
message: '#^PHPDoc tag @var above a method has no effect\.$#'
identifier: varTag.misplaced
@@ -6234,6 +6096,12 @@ parameters:
count: 1
path: app/Models/Builders/MaintenanceQueryBuilder.php
+ -
+ message: '#^Access to an undefined property Illuminate\\Database\\Eloquent\\Model\:\:\$company_id\.$#'
+ identifier: property.notFound
+ count: 2
+ path: app/Models/CalendarEvent.php
+
-
message: '#^Call to function is_array\(\) with string will always evaluate to false\.$#'
identifier: function.impossibleType
@@ -7206,6 +7074,12 @@ parameters:
count: 4
path: app/Models/Depreciation.php
+ -
+ message: '#^Call to an undefined method Illuminate\\Database\\Eloquent\\Relations\\Relation\:\:detach\(\)\.$#'
+ identifier: method.notFound
+ count: 1
+ path: app/Models/Group.php
+
-
message: '#^Call to function is_array\(\) with string will always evaluate to false\.$#'
identifier: function.impossibleType
@@ -7242,12 +7116,6 @@ parameters:
count: 4
path: app/Models/Group.php
- -
- message: '#^Call to an undefined method Illuminate\\Database\\Eloquent\\Relations\\Relation\:\:detach\(\)\.$#'
- identifier: method.notFound
- count: 1
- path: app/Models/Group.php
-
-
message: '#^Access to an undefined property App\\Models\\Asset\:\:\$assigned\.$#'
identifier: property.notFound
@@ -8034,12 +7902,6 @@ parameters:
count: 1
path: app/Models/SnipeSCIMConfig.php
- -
- message: '#^Variable \$subNode might not be defined\.$#'
- identifier: variable.undefined
- count: 1
- path: app/Models/SnipeSCIMConfig.php
-
-
message: '#^Call to function is_array\(\) with string will always evaluate to false\.$#'
identifier: function.impossibleType
@@ -8286,6 +8148,12 @@ parameters:
count: 1
path: app/Models/User.php
+ -
+ message: '#^Call to an undefined method Illuminate\\Database\\Eloquent\\Relations\\Relation\:\:detach\(\)\.$#'
+ identifier: method.notFound
+ count: 1
+ path: app/Models/User.php
+
-
message: '#^Call to an undefined method Illuminate\\Database\\Eloquent\\Relations\\Relation\:\:sync\(\)\.$#'
identifier: method.notFound
@@ -8442,12 +8310,6 @@ parameters:
count: 1
path: app/Models/User.php
- -
- message: '#^Call to an undefined method Illuminate\\Database\\Eloquent\\Relations\\Relation\:\:detach\(\)\.$#'
- identifier: method.notFound
- count: 1
- path: app/Models/User.php
-
-
message: '#^PHPDoc tag @param references unknown parameter\: \$notifiable$#'
identifier: parameter.notFound
@@ -10308,18 +10170,6 @@ parameters:
count: 2
path: database/seeders/AssetSeeder.php
- -
- message: '#^Binary operation "\." between ''Deleting\: '' and non\-empty\-array\<string\> results in an error\.$#'
- identifier: binaryOp.invalid
- count: 1
- path: database/seeders/AssetSeeder.php
-
- -
- message: '#^Binary operation "\." between ''assets/'' and non\-empty\-array\<string\> results in an error\.$#'
- identifier: binaryOp.invalid
- count: 1
- path: database/seeders/AssetSeeder.php
-
-
message: '#^Property Database\\Seeders\\AssetSeeder\:\:\$admin is unused\.$#'
identifier: property.unused
diff --git a/tests/Feature/CalendarEvents/CalendarFmcsPreAuthScopingTest.php b/tests/Feature/CalendarEvents/CalendarFmcsPreAuthScopingTest.php
new file mode 100644
index 0000000000..afe6078593
--- /dev/null
+++ b/tests/Feature/CalendarEvents/CalendarFmcsPreAuthScopingTest.php
@@ -0,0 +1,158 @@
+<?php
+
+namespace Tests\Feature\CalendarEvents;
+
+use App\Models\Asset;
+use App\Models\Company;
+use App\Models\Maintenance;
+use App\Models\User;
+use Illuminate\Support\Facades\DB;
+use Tests\TestCase;
+
+/**
+ * Regression tests for Wojciech Ciemski's CAND-07 report. Before
+ * CalendarEvent gained CompanyableTrait + a denormalized company_id
+ * column, the calendar API counted + ordered + limited rows BEFORE
+ * applying FMCS filtering. That meant total leaked the count of
+ * hidden events, and unauthorized rows at the start of the ordering
+ * displaced authorized rows past the limit.
+ */
+class CalendarFmcsPreAuthScopingTest extends TestCase
+{
+ public function test_total_reflects_only_authorized_rows_under_fmcs(): void
+ {
+ $this->settings->enableMultipleFullCompanySupport();
+
+ $companyA = Company::factory()->create();
+ $companyB = Company::factory()->create();
+ $assetA = Asset::factory()->for($companyA)->create();
+ $assetB = Asset::factory()->for($companyB)->create();
+
+ Maintenance::factory()->create([
+ 'asset_id' => $assetA->id,
+ 'start_date' => '2040-01-02 10:00:00',
+ 'expected_completion_date' => '2040-01-02 11:00:00',
+ ]);
+ Maintenance::factory()->create([
+ 'asset_id' => $assetB->id,
+ 'start_date' => '2040-01-01 10:00:00',
+ 'expected_completion_date' => '2040-01-01 11:00:00',
+ ]);
+
+ $actor = $companyA->users()->save(User::factory()->viewAssets()->editAssets()->make());
+
+ $response = $this->actingAsForApi($actor)
+ ->getJson(route('api.calendar.events', [
+ 'start' => '2040-01-01T00:00:00+00:00',
+ 'end' => '2040-01-03T00:00:00+00:00',
+ 'event_type' => ['maintenance.start'],
+ 'limit' => 500,
+ ]))
+ ->assertOk();
+
+ $this->assertSame(1, $response->json('total'), 'Total must count only the Company A event');
+ $this->assertCount(1, $response->json('events'));
+ }
+
+ public function test_limit_does_not_consume_authorized_rows_with_unauthorized_rows_under_fmcs(): void
+ {
+ // The failure mode in the original report: Company B's event
+ // sorts earlier, consumes the one-row limit, gets filtered,
+ // and the authorized Company A event never surfaces. After the
+ // fix, the limit applies to the authorized set so the
+ // Company A event comes back.
+ $this->settings->enableMultipleFullCompanySupport();
+
+ $companyA = Company::factory()->create();
+ $companyB = Company::factory()->create();
+ $assetA = Asset::factory()->for($companyA)->create();
+ $assetB = Asset::factory()->for($companyB)->create();
+
+ Maintenance::factory()->create([
+ 'asset_id' => $assetB->id,
+ 'start_date' => '2040-01-01 10:00:00',
+ 'expected_completion_date' => '2040-01-01 11:00:00',
+ ]);
+ $maintenanceA = Maintenance::factory()->create([
+ 'asset_id' => $assetA->id,
+ 'start_date' => '2040-01-02 10:00:00',
+ 'expected_completion_date' => '2040-01-02 11:00:00',
+ ]);
+
+ $actor = $companyA->users()->save(User::factory()->viewAssets()->editAssets()->make());
+
+ $response = $this->actingAsForApi($actor)
+ ->getJson(route('api.calendar.events', [
+ 'start' => '2040-01-01T00:00:00+00:00',
+ 'end' => '2040-01-03T00:00:00+00:00',
+ 'event_type' => ['maintenance.start'],
+ 'limit' => 1,
+ ]))
+ ->assertOk();
+
+ $this->assertSame(1, $response->json('total'));
+ $this->assertFalse($response->json('truncated'), 'Only one authorized event exists, so truncated must be false');
+
+ $sourceIds = collect($response->json('events'))->pluck('extendedProps.source_id')->all();
+ $this->assertContains($maintenanceA->id, $sourceIds);
+ }
+
+ public function test_asset_company_change_cascades_to_maintenance_calendar_events(): void
+ {
+ // When an admin moves an asset between companies, the child
+ // maintenance's calendar_events row needs to pick up the new
+ // company_id or FMCS filtering stays stale. Asset::booted()
+ // registers an updated hook that cascades forceSyncCalendarEvents
+ // to maintenances when company_id changes.
+ $this->settings->enableMultipleFullCompanySupport();
+
+ $companyA = Company::factory()->create();
+ $companyB = Company::factory()->create();
+ $asset = Asset::factory()->for($companyA)->create();
+ $maintenance = Maintenance::factory()->create([
+ 'asset_id' => $asset->id,
+ 'start_date' => '2040-01-02 10:00:00',
+ 'expected_completion_date' => '2040-01-02 11:00:00',
+ ]);
+
+ $this->assertSame($companyA->id, (int) DB::table('calendar_events')
+ ->where('source_type', Maintenance::class)
+ ->where('source_id', $maintenance->id)
+ ->value('company_id'));
+
+ $asset->update(['company_id' => $companyB->id]);
+
+ $this->assertSame($companyB->id, (int) DB::table('calendar_events')
+ ->where('source_type', Maintenance::class)
+ ->where('source_id', $maintenance->id)
+ ->value('company_id'));
+ }
+
+ public function test_asset_company_change_updates_the_assets_own_calendar_event_row(): void
+ {
+ // Direct test of the trait-level implicit company_id trigger
+ // added so sources with a company_id column auto-re-sync when
+ // it changes, without each definition declaring it.
+ $this->settings->enableMultipleFullCompanySupport();
+
+ $companyA = Company::factory()->create();
+ $companyB = Company::factory()->create();
+ $asset = Asset::factory()->for($companyA)->create([
+ 'next_audit_date' => '2040-02-01',
+ ]);
+
+ $this->assertSame($companyA->id, (int) DB::table('calendar_events')
+ ->where('source_type', Asset::class)
+ ->where('source_id', $asset->id)
+ ->where('event_type', 'asset.audit_due')
+ ->value('company_id'));
+
+ $asset->update(['company_id' => $companyB->id]);
+
+ $this->assertSame($companyB->id, (int) DB::table('calendar_events')
+ ->where('source_type', Asset::class)
+ ->where('source_id', $asset->id)
+ ->where('event_type', 'asset.audit_due')
+ ->value('company_id'));
+ }
+}