Skip to content Docs index for AI agents (llms.txt)

coreWorkflows e Status

Workflows e Status

Updated 5 min read

Introduzione

Il modulo Workflows consente la gestione dei Flussi di Lavorazione associati a diversi moduli. Ogni workflow rappresenta una pipeline operativa composta da una sequenza di stati (statuses) che definiscono l’avanzamento di un flusso lavorativo.

La pagina è accessibile da: → Workflows

Consente di:

  • Visualizzare la lista dei flussi disponibili.
  • Gestire gli stati associati a ciascun flusso.
  • Assegnare i flussi ai team.
  • Salvare la configurazione.
# Resources Database Tables
1 app\Filament\Resources\Workflows\WorkflowResource.php workflows
2 app\config\workflows.php

Configurazione

I Workflows disponibili devono essere aggiunti nell'array restituito dal file di config app\config\workflows.php, in cui deve essere indicato il Model (class) interessato ed il name che verrà visualizzato nella resource di gestione.

php
return [

    'modules' => [
        [
            'class' => 'App\\Models\\Project\\ProjectStatus',
            'name' => 'Projects Statuses',
        ],
        [
            'class' => 'App\\Models\\Sale\\SaleQuoteStatus',
            'name' => 'Quotes Statuses',
        ],
        [
            'class' => 'App\\Models\\Sale\\SaleContractStatus',
            'name' => 'Contracts Statuses',
        ],
        [
            'class' => 'App\\Models\\Ticket\\TicketStatus',
            'name' => 'Tickets Statuses',
        ],
        [
            'class' => 'App\\Models\\Purchase\\PurchaseOrderStatus',
            'name' => 'Purchase Order Statuses',
        ],
    ],
];

solo i Models che sono relazionati con una tabella degli statuses possono implementare i Workflows

Project Statuses

Models coinvolti

  • app\models\workflow.php
  • App\Models\Purchase\OrderStatus
  • app\Models\Ticket\TicketStatus.php
  • app\Models\Project\ProjectStatus.php
  • app\Models\Sale\SaleContractStatus.php
  • app\Models\Sale\SaleQuoteStatus.php

il Model che controlla la resource deve avere il field es: project_status_id

php
public function status(): BelongsTo
{
    return $this->belongsTo(ProjectStatus::class, 'project_status_id');
}

E' necessario che nei rispettivi Observers la funzione updating sia settata nel seguente modo per far sì che i vari stati siano selezionabili, per Team, esclusivamente sulla base dell'array che restituisce la funzione getExclusiveFlags() (in questo esempio solo is_editable può essere selezionato contemporaneamente ad un qualsiasi altro status):

php
/**
 * Handle the ProjectStatus "updating" event.
 */
public function updating(ProjectStatus $record): void
{
    $exclusiveFlags = $record->getExclusiveFlags();

    foreach ($exclusiveFlags as $flag) {
        // If the exclusive flag was activated (changed to true)
        if ($record->isDirty($flag) && $record->$flag) {

            // Turn off the flag for other status records of the same team
            ProjectStatus::where('team_id', $record->team_id)
                ->where('id', '!=', $record->id)
                ->where($flag, true)
                ->update([$flag => false]);
        }
    }
}

Resources

La resource che implementa gli statuses deve avere un component Select per la Table ed uno per il Form, popolati e controllati dal servizio app\Libs\WorkflowService.php.

  • Nel Table schema aggiungere
php
Tables\Columns\SelectColumn::make('project_status_id')
->options(function ($record) {
    if (auth()->user()->hasRole('super_admin')) {
        return WorkflowService::getAllowedNoTeamedStatuses(ProjectStatus::class, $record);
    } else {
        return WorkflowService::getPermittedWorkflows(
            'App\\Models\\Project\\ProjectStatus',
            ['id', 'status', 'is_default', 'is_editable', 'to_process', 'is_processing', 'is_final_step', 'archived'],
            'sorting',
            'asc',
            $record->project_status_id
        );
    }
})
->searchable()
->label(__('project-project.Status'))
->disabled(! auth()->user()->can('update_project::project') && ! auth()->user()->hasRole(['super_admin'])),
  • Nel Form schema aggiungere
php
Forms\Components\Select::make('project_status_id')
    ->label(__('project-project.Status'))
    ->options(function ($record): array|Collection {
        return WorkflowService::getWorkflowOptions(ProjectStatus::class, $record?->project_status_id);
    })
    ->default(function ($record) {
        return WorkflowService::getWorkFlowDefaultPermittedOption(ProjectStatus::class, $record);
    })
    ->searchable(['status']),

Risultato

Ogni singolo Utente potrà modificare l'avanzamento di stato di un Preventivo, Ordine di Acquisto, Contratto, Progetto o Ticket solo fino allo stato consentito dal suo ruolo per come pianificato nelle rispettive tabelle degli statuses.

Ogni Team avrà i suoi statuses personalizzati

Contract Statuses Resource

es. immagine sopra:

  • gli Utenti con il ruolo di admin appartenenti al Team Prosoft Servizi potranno impostare lo status di un Ordine d'Acquisto da Creato ad Arrivato in Magazzino, passando sequenzialmente per tutti gli Stati intermedi.
  • Tutti gli altri status non saranno disponibili nè visibili.

Statuses

Gli stati dei records (statuses) rappresentano una sequanza di stati che ogni singolo record può attraversare, per sua stessa natura, nel suo arco di vita. Sono attivati ed attivabili solo su alcune tipologie di Models: Ordini di acquisto, Preventivi di vendita, Contratti di vendita, Progetti e Tickets.

Ad ogni status di ogni Model può essere abbinato da FE un determinato colore, questo fà si che nella visualizzazione tabella la row di ogni record sarà colorata con il colore assegnato al suo stato.

L'assegnazione dei colori ai vari stati avviene dalla pagina lista tabella degli status relativi alla resource es: app\Filament\Clusters\Projects\Resources\ProjectStatuses\ProjectStatusResource.php quindi:

  • nella resource principale dele essere effettuato l'override della getEloquentQuery():
php
public static function getEloquentQuery(): Builder
{
    return parent::getEloquentQuery()->with(['status']);
}
  • la funcion che definisce la tabella deve richiamare il metodo ->recordClasses
php
public static function table(Table $table): Table
{
    return static::defineTable($table)
        ->recordClasses(fn (Model $record) => self::getCssStatus($record))
        ->recordUrl(null)
        ->defaultSort('date', 'desc');
}
  • il model deve includere il trait HasStatuses (app\Traits\HasStatuses.php) e definire l'attributo
php
protected string $statusForeignKey = 'project_status_id';
  • I Models degli statuses devono estendere l'abstract model StatusModel:
php
<?php

namespace App\Models\Abstract;

use App\Models\StatusColor;
use App\Models\Team;
use App\Models\Workflow;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\MorphMany;

abstract class StatusModel extends BaseModel
{
    protected $fillable = [
        'team_id',
        'status',
        'is_default',
        'is_editable',
        'to_process',
        'is_processing',
        'is_final_step',
        'archived',
        'sorting',
    ];

    protected $casts = [
        'sorting' => 'integer',
    ];

    public function team(): BelongsTo
    {
        return $this->belongsTo(Team::class);
    }

    /**
     * Get all of the status's workflow.
     */
    public function workflow(): MorphMany
    {
        return $this->morphMany(Workflow::class, 'model');
    }

    /**
     * Interact with default attribute.
     */
    public function setDefaultAttribute($value)
    {
        $this->attributes['is_default'] = $value ? 1 : 0;
    }

    /**
     * Interact with editable attribute.
     */
    public function setIsEditableAttribute($value)
    {
        $this->attributes['is_editable'] = $value ? 1 : 0;
    }

    /**
     * Interact with to_process attribute.
     */
    public function setToProcessAttribute($value)
    {
        $this->attributes['to_process'] = $value ? 1 : 0;
    }

    /**
     * Interact with is_processing attribute.
     */
    public function setIsProcessingAttribute($value)
    {
        $this->attributes['is_processing'] = $value ? 1 : 0;
    }

    /**
     * Interact with is_final_step attribute.
     */
    public function setIsFinalStepAttribute($value)
    {
        $this->attributes['is_final_step'] = $value ? 1 : 0;
    }

    /**
     * Interact with archived attribute.
     */
    public function setArchivedAttribute($value)
    {
        $this->attributes['archived'] = $value ? 1 : 0;
    }

    /**
     * Get all status colors for the current context and team.
     */
    public function statusColors(): HasMany
    {
        // Link models using 'team_id' as both the foreign and local key,
        // filtering by the specific context class name.
        return $this->hasMany(StatusColor::class, 'team_id', 'team_id')
            ->where('context', class_basename(static::class));
    }

    /**
     * Get the ID of the default status.
     */
    public static function getDefaultId()
    {
        return static::whereDefault(true)->value('id');
    }

    /**
     * Get the ID of the editable status.
     */
    public static function getIsEditableId()
    {
        return static::whereIsEditable(true)->value('id');
    }

    /**
     * Get the ID of the to_process status.
     */
    public static function getToProcessId()
    {
        return static::whereToProcess(true)->value('id');
    }

    /**
     * Get the ID of the is_processing status.
     */
    public static function getIsProcessingId()
    {
        return static::whereIsProcessing(true)->value('id');
    }

    /**
     * Get the ID of the is_final_step status.
     */
    public static function getIsFinalStepId()
    {
        return static::whereIsFinalStep(true)->value('id');
    }

    /**
     * Get the ID of the archived status.
     */
    public static function getArchivedId()
    {
        return static::whereArchived(true)->value('id');
    }

    public function getExclusiveFlags(): array
    {
        // remain strictly unique (exclusive) per team.
        return ['is_default', 'to_process', 'is_processing', 'is_final_step', 'archived'];
    }
}
  • nella pagina list della resource degli status effettuare l'override della funzione getHeaderActions() aggiungendo l'action StatusColorAction:
php
<?php

namespace App\Filament\Clusters\Projects\Resources\ProjectStatuses\Pages;

use App\Filament\Clusters\Projects\Resources\ProjectStatuses\ProjectStatusResource;
use App\Filament\Imports\ProjectStatusImporter;
use App\Filament\Actions\StatusColorAction;
use App\Traits\BaseListSettings;
use Filament\Actions\ImportAction;
use Filament\Resources\Pages\ListRecords;

class ListProjectStatuses extends ListRecords
{
    use BaseListSettings;

    protected static string $resource = ProjectStatusResource::class;

    protected function getHeaderActions(): array
    {
        return [
            ...
            StatusColorAction::make('status_color_action'),
            ...
        ];
    }
}