Skip to content

A free open source IT asset/license management system

Added requestable+archived mutex

snipe1224a8ec2898
diff --git a/app/Models/Consumable.php b/app/Models/Consumable.php
index 5441dcf6f7..d08d51fd61 100644
--- a/app/Models/Consumable.php
+++ b/app/Models/Consumable.php
@@ -14,6 +14,7 @@ use App\Models\Traits\Requestable;
use App\Models\Traits\Searchable;
use App\Presenters\ConsumablePresenter;
use App\Presenters\Presentable;
+use App\Rules\RequestableArchivedMutex;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
@@ -46,6 +47,7 @@ class Consumable extends SnipeModel
protected $casts = [
'requestable' => 'boolean',
+ 'archived' => 'boolean',
'category_id' => 'integer',
'company_id' => 'integer',
'qty' => 'integer',
@@ -53,7 +55,7 @@ class Consumable extends SnipeModel
];
/**
- * Category validation rules
+ * validation rules
*/
public $rules = [
'name' => 'required|max:255',
@@ -66,9 +68,40 @@ class Consumable extends SnipeModel
'purchase_date' => 'date_format:Y-m-d|nullable',
'default_supplier_id' => 'nullable|integer|exists:suppliers,id',
'default_purchase_cost' => 'numeric|nullable|gte:0|max:99999999999999999.99',
- 'requestable' => 'nullable|boolean',
+ 'requestable' => ['nullable', 'boolean'],
+ 'archived' => ['nullable', 'boolean'],
];
+ /**
+ * PHP 8.2 blocks `new X` in property defaults, so the rule object
+ * gets spliced in here rather than in $rules above. Mirrors
+ * Accessory::getRules() so the mutex and the no-archive-with-
+ * checkouts guard behave identically across checkoutable items.
+ */
+ public function getRules(): array
+ {
+ $rules = $this->rules ?? [];
+ $mutex = new RequestableArchivedMutex;
+
+ $noArchivingWithOutstanding = function (string $attribute, mixed $value, \Closure $fail): void {
+ if (filter_var($value, FILTER_VALIDATE_BOOLEAN) && $this->exists && $this->numOutstanding() > 0) {
+ // Consumables close their lifecycle via mark-consumed,
+ // not check-in, so the standard archived_blocked_by_checkouts
+ // string points admins at the wrong action. Use the
+ // outstanding-specific variant that names the right path.
+ $fail(trans('general.archived_blocked_by_outstanding', [
+ 'item_type' => trans('general.consumable'),
+ 'attribute' => $attribute,
+ ]));
+ }
+ };
+
+ $rules['requestable'] = array_merge((array) ($rules['requestable'] ?? []), [$mutex]);
+ $rules['archived'] = array_merge((array) ($rules['archived'] ?? []), [$mutex, $noArchivingWithOutstanding]);
+
+ return $rules;
+ }
+
/**
* Whether the model should inject it's identifier to the unique
* validation rules before attempting validation. If this property
@@ -100,6 +133,7 @@ class Consumable extends SnipeModel
'qty',
'min_amt',
'requestable',
+ 'archived',
'notes',
'default_supplier_id',
'default_purchase_cost',
@@ -149,6 +183,15 @@ class Consumable extends SnipeModel
protected static function booted(): void
{
static::forceDeleted(function (self $consumable) {
+ // Pivot rows + uploads + image hold the item's lifecycle
+ // state. Keep them intact across soft-delete + restore,
+ // and only tear them down when the parent is actually
+ // being destroyed. Direct DB purge (snipeit:purge)
+ // bypasses Eloquent, so the Purge command carries the
+ // same cleanup for consumables_users in its childTables
+ // map.
+ $consumable->users()->detach();
+
if ($consumable->image) {
try {
Storage::disk('public')->delete(FileStorage::Consumables->publicPath().$consumable->image);
@@ -183,10 +226,23 @@ class Consumable extends SnipeModel
$this->attributes['requestable'] = filter_var($value, FILTER_VALIDATE_BOOLEAN);
}
+ /**
+ * Mirror for the archived flag. Normalizes empty-string / null /
+ * missing-column CSV cells to false so the NOT NULL `archived`
+ * column never receives a literal null.
+ */
+ public function setArchivedAttribute($value): void
+ {
+ if ($value == '') {
+ $value = null;
+ }
+ $this->attributes['archived'] = filter_var($value, FILTER_VALIDATE_BOOLEAN);
+ }
+
public function isDeletable()
{
return Gate::allows('delete', $this)
- && ($this->numCheckedOut() === 0)
+ && ($this->numOutstanding() === 0)
&& ($this->deleted_at == '');
}
@@ -204,6 +260,17 @@ class Consumable extends SnipeModel
return $this->hasMany(ConsumableAssignment::class);
}
+ /**
+ * Pivot rows the recipient has not yet reported as used up.
+ * `consumed_at` is one-way: once set, the row never re-enters the
+ * outstanding bucket. Backs numOutstanding() and the archive +
+ * delete gates.
+ */
+ public function outstandingAssignments()
+ {
+ return $this->consumableAssignments()->outstanding();
+ }
+
public function percentRemaining()
{
if ($this->consumables_users_count == 0) {
@@ -386,6 +453,43 @@ class Consumable extends SnipeModel
return $this->consumables_users_count ?? $this->users()->count();
}
+ /**
+ * Units that have been handed out but the recipient has not yet
+ * reported as used up. Feeds the archive + delete gates (the
+ * historical stockroom-remaining math still runs off
+ * numCheckedOut).
+ */
+ public function numOutstanding(): int
+ {
+ return (int) ($this->outstanding_assignments_count
+ ?? $this->outstandingAssignments()->count());
+ }
+
+ /**
+ * Units that have been distributed and reported used up. Permanent
+ * state. A consumed row never re-enters the outstanding bucket.
+ * Admins see this as the "Consumed" column so they can read how
+ * much of lifetime stock has actually been destroyed.
+ */
+ public function numConsumed(): int
+ {
+ return (int) $this->numCheckedOut() - $this->numOutstanding();
+ }
+
+ /**
+ * Units that are either still on the shelf OR distributed-but-not-
+ * yet-consumed. The low-inventory alert threshold runs off this
+ * count so a consumable only trips the "below minimum" alarm when
+ * stock is actually destroyed, not merely handed out to someone
+ * who may still return it or who the admin can chase up. Shelf
+ * remaining = qty - distributed stays the headline "available
+ * right now" number and drives the per-checkout quantity cap.
+ */
+ public function numInPlay(): int
+ {
+ return (int) $this->qty - $this->numConsumed();
+ }
+
/**
* AdjustsQuantity trait hook: units currently distributed to users.
* The adjust-quantity modal uses this to reject decrements that
diff --git a/app/Models/ConsumableAssignment.php b/app/Models/ConsumableAssignment.php
index b6762bdc61..a4f713b428 100644
--- a/app/Models/ConsumableAssignment.php
+++ b/app/Models/ConsumableAssignment.php
@@ -3,6 +3,7 @@
namespace App\Models;
use App\Models\Traits\CompanyableTrait;
+use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Watson\Validating\ValidatingTrait;
@@ -16,6 +17,14 @@ class ConsumableAssignment extends Model
protected $table = 'consumables_users';
+ protected $fillable = [
+ 'consumed_at',
+ ];
+
+ protected $casts = [
+ 'consumed_at' => 'datetime',
+ ];
+
public $rules = [
'assigned_to' => 'required|exists:users,id',
];
@@ -34,4 +43,28 @@ class ConsumableAssignment extends Model
{
return $this->belongsTo(User::class, 'created_by')->withTrashed();
}
+
+ /**
+ * Scope: rows the recipient has not yet reported as used up. These
+ * still count against the parent consumable's outstanding total and
+ * block archive/delete.
+ */
+ public function scopeOutstanding(Builder $query): void
+ {
+ $query->whereNull('consumables_users.consumed_at');
+ }
+
+ /**
+ * Scope: rows that have been marked consumed. Preserved for audit
+ * and historical reporting but no longer gate archive or delete.
+ */
+ public function scopeConsumed(Builder $query): void
+ {
+ $query->whereNotNull('consumables_users.consumed_at');
+ }
+
+ public function isConsumed(): bool
+ {
+ return $this->consumed_at !== null;
+ }
}
diff --git a/app/Observers/AccessoryObserver.php b/app/Observers/AccessoryObserver.php
index de6c92ffcf..da21965fb3 100644
--- a/app/Observers/AccessoryObserver.php
+++ b/app/Observers/AccessoryObserver.php
@@ -69,12 +69,23 @@ class AccessoryObserver
}
/**
- * Listen to the Accessory deleting event.
+ * Listen to the Accessory deleting event. Mirrors the archive-time
+ * cancellation in updated() so the two lifecycle transitions
+ * have the same posture: open CheckoutRequest rows get canceled
+ * so they stop surfacing on /account/requested while the parent
+ * is unavailable. The actionlog write preserves the audit trail
+ * either way.
*
* @return void
*/
public function deleting(Accessory $accessory)
{
+ $accessory->openRequests()->get()->each(function (CheckoutRequest $request): void {
+ $request->canceled_at = now();
+ $request->state = CheckoutRequestState::Canceled;
+ $request->saveQuietly();
+ });
+
$logAction = new Actionlog;
$logAction->item_type = Accessory::class;
$logAction->item_id = $accessory->id;
diff --git a/app/Observers/ComponentObserver.php b/app/Observers/ComponentObserver.php
index 9ce1e51067..eae1be88e8 100644
--- a/app/Observers/ComponentObserver.php
+++ b/app/Observers/ComponentObserver.php
@@ -2,7 +2,9 @@
namespace App\Observers;
+use App\Enums\CheckoutRequestState;
use App\Models\Actionlog;
+use App\Models\CheckoutRequest;
use App\Models\Component;
class ComponentObserver
@@ -18,6 +20,9 @@ class ComponentObserver
$changed = [];
foreach ($component->getRawOriginal() as $key => $value) {
+ if ($key === 'updated_at') {
+ continue;
+ }
// SoftDeletes drives the delete + restore flows through
// save(), which fires `updated` with deleted_at as the
// changed field. The `deleting`/`restored` observers log
@@ -49,6 +54,14 @@ class ComponentObserver
$logAction->logaction('update');
}
+ // Archive-time request cleanup.
+ if ($component->wasChanged('archived') && $component->archived) {
+ $component->openRequests()->get()->each(function (CheckoutRequest $request): void {
+ $request->canceled_at = now();
+ $request->state = CheckoutRequestState::Canceled;
+ $request->saveQuietly();
+ });
+ }
}
/**
@@ -63,12 +76,23 @@ class ComponentObserver
}
/**
- * Listen to the Component deleting event.
+ * Listen to the Component deleting event. Mirrors the archive-time
+ * cancellation in updated() so the two lifecycle transitions
+ * have the same posture: open CheckoutRequest rows get canceled
+ * so they stop surfacing on /account/requested while the parent
+ * is unavailable. The actionlog write preserves the audit trail
+ * either way.
*
* @return void
*/
public function deleting(Component $component)
{
+ $component->openRequests()->get()->each(function (CheckoutRequest $request): void {
+ $request->canceled_at = now();
+ $request->state = CheckoutRequestState::Canceled;
+ $request->saveQuietly();
+ });
+
$logAction = new Actionlog;
$logAction->item_type = Component::class;
$logAction->item_id = $component->id;
diff --git a/app/Observers/ConsumableObserver.php b/app/Observers/ConsumableObserver.php
index 60bc0caca5..273ca480de 100644
--- a/app/Observers/ConsumableObserver.php
+++ b/app/Observers/ConsumableObserver.php
@@ -2,12 +2,11 @@
namespace App\Observers;
-use App\Enums\FileStorage;
+use App\Enums\CheckoutRequestState;
use App\Models\Actionlog;
use App\Models\CheckoutAcceptance;
+use App\Models\CheckoutRequest;
use App\Models\Consumable;
-use Illuminate\Support\Facades\Log;
-use Illuminate\Support\Facades\Storage;
class ConsumableObserver
{
@@ -22,7 +21,18 @@ class ConsumableObserver
$changed = [];
foreach ($consumable->getRawOriginal() as $key => $value) {
- // Check and see if the value changed
+ if ($key === 'updated_at') {
+ continue;
+ }
+ // SoftDeletes drives the delete + restore flows through
+ // save(), which fires `updated` with deleted_at as the
+ // changed field. The `deleting`/`restored` observers log
+ // those actions directly, so excluding deleted_at here
+ // keeps us from double-logging a "delete" plus an "update"
+ // row that only shows the deleted_at diff.
+ if ($key === 'deleted_at') {
+ continue;
+ }
if ($consumable->getRawOriginal()[$key] != $consumable->getAttributes()[$key]) {
$changed[$key]['old'] = $consumable->getRawOriginal()[$key];
$changed[$key]['new'] = $consumable->getAttributes()[$key];
@@ -38,6 +48,15 @@ class ConsumableObserver
$logAction->log_meta = json_encode($changed);
$logAction->logaction('update');
}
+
+ // Archive-time request cleanup.
+ if ($consumable->wasChanged('archived') && $consumable->archived) {
+ $consumable->openRequests()->get()->each(function (CheckoutRequest $request): void {
+ $request->canceled_at = now();
+ $request->state = CheckoutRequestState::Canceled;
+ $request->saveQuietly();
+ });
+ }
}
/**
@@ -54,31 +73,32 @@ class ConsumableObserver
/**
* Listen to the Consumable deleting event.
*
+ * Soft-delete preserves pivot history, uploads, and the image so a
+ * restore brings the item back to the pre-delete state. The
+ * destructive actions here are limited to lifecycle records that
+ * admins and users can't act on while the parent is soft-deleted:
+ * pending CheckoutAcceptance rows (post-checkout acknowledgment)
+ * and open CheckoutRequest rows (pre-checkout wish list) both
+ * get cleared. The CheckoutRequest cleanup mirrors the archive
+ * flow in updated() so both lifecycle transitions have the same
+ * posture toward pending requests. Pivot rows, uploads, and the
+ * image are cleaned up by the Consumable model's forceDeleted
+ * hook so the lifecycle data survives soft-delete + restore.
+ *
* @return void
*/
public function deleting(Consumable $consumable)
{
-
- $consumable->users()->detach();
-
CheckoutAcceptance::pending()
->where('checkoutable_type', Consumable::class)
->where('checkoutable_id', $consumable->id)
->delete();
- $uploads = $consumable->uploads;
-
- foreach ($uploads as $file) {
- try {
- Storage::delete(FileStorage::Consumables->privateStorageKey().$file->filename);
- $file->delete();
- } catch (\Exception $e) {
- Log::info($e);
- }
- }
-
- // Image file cleanup lives on the Consumable model's forceDeleted
- // hook so soft-delete + restore preserves the image reference.
+ $consumable->openRequests()->get()->each(function (CheckoutRequest $request): void {
+ $request->canceled_at = now();
+ $request->state = CheckoutRequestState::Canceled;
+ $request->saveQuietly();
+ });
$logAction = new Actionlog;
$logAction->item_type = Consumable::class;