jodeveloper/approval-flow 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

jodeveloper/approval-flow

Composer 安装命令:

composer require jodeveloper/approval-flow

包简介

A Laravel package for managing approval workflows with enums and traits

README 文档

README

Latest Version on Packagist GitHub Tests Action Status GitHub Code Style Action Status Total Downloads

A powerful Laravel package for managing approval workflows using PHP 8.1+ enums and traits. Create complex approval processes with ease!

Features

  • Type-safe approval flows using PHP 8.1 enums
  • Reusable trait for any Eloquent model
  • Permission-based approvals with Laravel's authorization system
  • Event-driven architecture for notifications and logging
  • Automatic activity logging with user tracking
  • Bulk approval operations
  • Artisan command to generate approval flow enums
  • Comprehensive testing with Pest

Installation

You can install the package via composer:

composer require jodeveloper/approval-flow

You can publish and run the migrations with:

php artisan vendor:publish --tag="approval-flow-migrations"
php artisan migrate

You can publish the config file with:

php artisan vendor:publish --tag="approval-flow-config"

Quick Start

1. Create an Approval Flow Enum

Generate a new approval flow enum:

php artisan make:approval-flow Document

This creates app/Enums/DocumentStatuses.php:

<?php

namespace App\Enums;

use jodeveloper\ApprovalFlow\Contracts\ApprovalStatusInterface;
use jodeveloper\ApprovalFlow\DataTransferObjects\ApprovalFlowStep;

enum DocumentStatuses: string implements ApprovalStatusInterface
{
    case DRAFT = 'DRAFT';
    case MANAGER_REVIEW = 'MANAGER_REVIEW';
    case DIRECTOR_REVIEW = 'DIRECTOR_REVIEW';
    case APPROVED = 'APPROVED';
    case REJECTED = 'REJECTED';

    public static function getApprovalFlow(): array
    {
        return [
            self::DRAFT->name => new ApprovalFlowStep(
                permission: null, // No permission required for initial submission
                next: self::MANAGER_REVIEW->name,
            ),
            self::MANAGER_REVIEW->name => new ApprovalFlowStep(
                permission: 'managerApprove',
                next: self::DIRECTOR_REVIEW->name,
            ),
            self::DIRECTOR_REVIEW->name => new ApprovalFlowStep(
                permission: 'directorApprove',
                next: self::APPROVED->name,
            ),
        ];
    }

    public static function getRejectionStatuses(): array
    {
        return [
            self::MANAGER_REVIEW->value => self::REJECTED->value,
            self::DIRECTOR_REVIEW->value => self::REJECTED->value,
        ];
    }

    public static function getCompletedStatus(): string
    {
        return self::APPROVED->value;
    }

    /**
     * Define simple status transitions that bypass the approval workflow.
     * Use this for automatic transitions that don't require permissions.
     *
     * @return array<string, string> Maps current status to next status
     */
    public static function getStatusTransitions(): array
    {
        return [
            // Example: 'AUTO_APPROVED' => 'COMPLETED',
            // Example: 'EXPIRED' => 'CANCELLED',
        ];
    }
}

2. Add the Trait to Your Model

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use jodeveloper\ApprovalFlow\Traits\HasApprovalFlow;

class Document extends Model
{
    use HasApprovalFlow;

    protected $fillable = [
        'title',
        'content',
        'status_id',
        'approval_comment',
        'rejection_note',
    ];

    public function status()
    {
        return $this->belongsTo(Status::class);
    }

    public static function getStatusEnum(): string
    {
        return DocumentStatuses::class;
    }

    public static function getStatus(string $code)
    {
        return Status::where('code', $code)->first();
    }
}

3. Use in Controllers

<?php

namespace App\Http\Controllers;

use App\Models\Document;
use Illuminate\Http\Request;

class DocumentApprovalController extends Controller
{
    public function approve(Request $request, Document $document)
    {
        if (!$document->canApprove()) {
            return response()->json(['error' => 'Unauthorized'], 403);
        }

        if ($document->approve($request->comment)) {
            return response()->json([
                'message' => 'Document approved successfully',
                'status' => $document->fresh()->status->name
            ]);
        }

        return response()->json(['error' => 'Could not approve document'], 400);
    }

    public function reject(Request $request, Document $document)
    {
        $request->validate(['note' => 'required|string|max:1000']);

        if (!$document->canReject()) {
            return response()->json(['error' => 'Unauthorized'], 403);
        }

        if ($document->reject($request->note)) {
            return response()->json(['message' => 'Document rejected']);
        }

        return response()->json(['error' => 'Could not reject document'], 400);
    }
}

Usage Examples

Basic Approval Operations

$document = Document::find(1);

// Check permissions
if ($document->canApprove()) {
    $document->approve('Looks good!');
}

if ($document->canReject()) {
    $document->reject('Please revise section 3');
}

// Check status
if ($document->isCompleted()) {
    // Document is fully approved
}

if ($document->isInApprovalProcess()) {
    $step = $document->getCurrentApprovalStep();
    echo "Waiting for: " . $step->role;
}

Bulk Operations

use jodeveloper\ApprovalFlow\ApprovalFlowManager;

$manager = app(ApprovalFlowManager::class);

// Bulk approve multiple documents
$documents = Document::where('status_id', $pendingStatusId)->get();
$results = $manager->bulkApprove($documents, 'Batch approval');

// Results contain success and failed arrays
echo "Approved: " . count($results['success']);
echo "Failed: " . count($results['failed']);

Approval Statistics

$manager = app(ApprovalFlowManager::class);
$stats = $manager->getApprovalStats($document);

/*
Array output:
[
    'total_approvals' => 2,
    'total_rejections' => 1,
    'current_status' => 'MANAGER_REVIEW',
    'is_completed' => false,
    'can_approve' => true,
    'can_reject' => true,
    'next_step' => 'Manager'
]
*/

Event Handling

The package fires events that you can listen to:

// In your EventServiceProvider
use jodeveloper\ApprovalFlow\Events\ModelApproved;
use jodeveloper\ApprovalFlow\Events\ModelRejected;

protected $listen = [
    ModelApproved::class => [
        SendApprovalNotification::class,
    ],
    ModelRejected::class => [
        SendRejectionNotification::class,
    ],
];

Create listeners:

<?php

namespace App\Listeners;

use jodeveloper\ApprovalFlow\Events\ModelApproved;
use Illuminate\Support\Facades\Mail;

class SendApprovalNotification
{
    public function handle(ModelApproved $event): void
    {
        // Send notification to next approver or completion notification
        $model = $event->model;
        $nextStep = $model->getCurrentApprovalStep();
        
        if ($nextStep) {
            // Notify next approver
            Mail::to($nextStep->role)->send(new ApprovalNeeded($model));
        } else {
            // Notify completion
            Mail::to($model->user)->send(new ApprovalCompleted($model));
        }
    }
}

Approval History

// Get approval history for a model
$history = $document->approvalHistory;

foreach ($history as $log) {
    echo "{$log->user->name} {$log->action} on {$log->created_at}";
    if ($log->comment) {
        echo " - Comment: {$log->comment}";
    }
}

Custom Status Transitions

For simple status changes that don't require approval workflow:

enum DocumentStatuses: string implements ApprovalStatusInterface
{
    case DRAFT = 'DRAFT';
    case ON_HOLD = 'ON_HOLD';
    case ARCHIVED = 'ARCHIVED';
    case AUTO_APPROVED = 'AUTO_APPROVED';
    case EXPIRED = 'EXPIRED';
    // ... other cases

    public static function getStatusTransitions(): array
    {
        return [
            // Simple transitions without permissions
            self::DRAFT->name => self::ON_HOLD->name,
            self::ON_HOLD->name => self::DRAFT->name,

            // Automatic system transitions
            self::AUTO_APPROVED->name => self::APPROVED->name,
            self::EXPIRED->name => self::ARCHIVED->name,
        ];
    }

    // ... other methods
}

When to use getStatusTransitions():

  • Automatic transitions (system-triggered)
  • Simple state changes (no approval needed)
  • Performance optimization (bypass permission checks)
  • Fallback transitions (when approval flow not applicable)

When to use getApprovalFlow():

  • Permission-based approvals
  • Multi-step workflows
  • User-triggered transitions
  • Audit trails required

Advanced Configuration

Custom Approval Log Model

If you want to extend the approval logging functionality:

<?php

namespace App\Models;

use jodeveloper\ApprovalFlow\Models\ApprovalLog as BaseApprovalLog;

class CustomApprovalLog extends BaseApprovalLog
{
    protected $fillable = [
        ...parent::$fillable,
        'department',
        'priority',
    ];

    // Add custom relationships or methods
    public function department()
    {
        return $this->belongsTo(Department::class);
    }
}

Then update your config:

// config/approval-flow.php
return [
    'models' => [
        'approval_log' => \App\Models\CustomApprovalLog::class,
    ],
    // ...
];

Disable Logging

// In your .env file
APPROVAL_FLOW_LOG_ENABLED=false

// Or in config/approval-flow.php
'log_approvals' => false,

Testing

composer test

Package Structure

src/
├── ApprovalFlowServiceProvider.php
├── ApprovalFlowManager.php
├── Commands/
│   └── MakeApprovalFlowCommand.php
├── Contracts/
│   └── ApprovalStatusInterface.php
├── DataTransferObjects/
│   └── ApprovalFlowStep.php
├── Events/
│   ├── ModelApproved.php
│   └── ModelRejected.php
├── Exceptions/
│   └── ApprovalFlowException.php
├── Listeners/
│   └── LogApprovalActivity.php
├── Models/
│   └── ApprovalLog.php
└── Traits/
    └── HasApprovalFlow.php

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

License

The MIT License (MIT). Please see License File for more information.

jodeveloper/approval-flow 适用场景与选型建议

jodeveloper/approval-flow 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 6 次下载、GitHub Stars 达 0, 最近一次更新时间为 2025 年 09 月 17 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「workflow」 「enum」 「trait」 「laravel」 「approval」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 jodeveloper/approval-flow 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 jodeveloper/approval-flow 我们能提供哪些服务?
定制开发 / 二次开发

基于 jodeveloper/approval-flow 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 6
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 28
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-09-17