Add Video Projects schema and workflow engine core (tasks #31, #32)

Foundational layer for the YouTube Content Creation System project,
built as a fully independent domain per the earlier decision (task
#47) — no foreign keys into the existing projects/tasks/ideas tables.

Schema: video_projects, workflow_steps, assets, ai_providers,
workflow_templates (named to avoid colliding with the existing
Post-templates `templates` table).

WorkflowEngine (app/Support/VideoWorkflow/) drives a project's step
sequence: start/startFromTemplate, currentStep, completeStep (with
optional approval gating), approveStep/rejectStep, failStep/retryStep,
skipStep. It only manages state transitions — actual step execution
(AI calls, rendering, etc.) is out of scope here (tasks #33+).

Also fixes four Publisher classes (WordPress/Reddit/Twitter/LinkedIn)
that were missing a `use App\Models\SocialAccount;` import after an
earlier interface change, which broke the entire test suite at
bootstrap; and PostFactory, which still set the now-removed
`social_account_id` column instead of the SocialAccount pivot.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
m105
2026-08-06 20:38:52 +03:00
co-authored by Claude Sonnet 5
parent efdec9eabd
commit 6ff7f78c9c
25 changed files with 1049 additions and 25 deletions
+26
View File
@@ -0,0 +1,26 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class AiProvider extends Model
{
use HasFactory;
public const PROVIDERS = ['openai', 'stability_ai', 'elevenlabs', 'other'];
protected $fillable = [
'name',
'provider',
'api_key',
'config',
'is_active',
];
protected $casts = [
'config' => 'array',
'is_active' => 'boolean',
];
}
+39
View File
@@ -0,0 +1,39 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class Asset extends Model
{
use HasFactory;
public const TYPES = ['script', 'image', 'video', 'audio', 'other'];
protected $fillable = [
'video_project_id',
'workflow_step_id',
'type',
'disk_path',
'mime_type',
'size_bytes',
'version',
'metadata',
];
protected $casts = [
'metadata' => 'array',
];
public function videoProject(): BelongsTo
{
return $this->belongsTo(VideoProject::class);
}
public function workflowStep(): BelongsTo
{
return $this->belongsTo(WorkflowStep::class);
}
}
+38
View File
@@ -0,0 +1,38 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;
class VideoProject extends Model
{
use HasFactory, SoftDeletes;
public const STATUSES = ['draft', 'in_progress', 'completed', 'archived'];
protected $fillable = [
'title',
'description',
'status',
'workflow_template_id',
];
public function workflowTemplate(): BelongsTo
{
return $this->belongsTo(WorkflowTemplate::class);
}
public function steps(): HasMany
{
return $this->hasMany(WorkflowStep::class)->orderBy('order');
}
public function assets(): HasMany
{
return $this->hasMany(Asset::class);
}
}
+62
View File
@@ -0,0 +1,62 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
class WorkflowStep extends Model
{
use HasFactory;
// Mirrors the content-generation modules in the YouTube Content
// Creation System project (script through publish).
public const TYPES = [
'script_generation',
'tts_voiceover',
'storyboard',
'video_generation',
'video_editing',
'thumbnail_generation',
'metadata_generation',
'youtube_publish',
];
public const STATUSES = [
'pending', 'in_progress', 'awaiting_approval',
'completed', 'rejected', 'failed', 'skipped',
];
protected $fillable = [
'video_project_id',
'type',
'order',
'status',
'requires_approval',
'input',
'output',
'error',
'started_at',
'completed_at',
];
protected $casts = [
'requires_approval' => 'boolean',
'input' => 'array',
'output' => 'array',
'started_at' => 'datetime',
'completed_at' => 'datetime',
];
public function videoProject(): BelongsTo
{
return $this->belongsTo(VideoProject::class);
}
public function assets(): HasMany
{
return $this->hasMany(Asset::class);
}
}
+27
View File
@@ -0,0 +1,27 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
class WorkflowTemplate extends Model
{
use HasFactory;
protected $fillable = [
'name',
'description',
'steps',
];
protected $casts = [
'steps' => 'array',
];
public function videoProjects(): HasMany
{
return $this->hasMany(VideoProject::class);
}
}
@@ -3,6 +3,7 @@
namespace App\Support\Publishing; namespace App\Support\Publishing;
use App\Models\Post; use App\Models\Post;
use App\Models\SocialAccount;
use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Process; use Illuminate\Support\Facades\Process;
@@ -3,6 +3,7 @@
namespace App\Support\Publishing; namespace App\Support\Publishing;
use App\Models\Post; use App\Models\Post;
use App\Models\SocialAccount;
use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Process; use Illuminate\Support\Facades\Process;
@@ -3,6 +3,7 @@
namespace App\Support\Publishing; namespace App\Support\Publishing;
use App\Models\Post; use App\Models\Post;
use App\Models\SocialAccount;
use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Process; use Illuminate\Support\Facades\Process;
@@ -4,6 +4,7 @@ namespace App\Support\Publishing;
use App\Models\Post; use App\Models\Post;
use App\Models\Site; use App\Models\Site;
use App\Models\SocialAccount;
use Illuminate\Http\Client\ConnectionException; use Illuminate\Http\Client\ConnectionException;
use Illuminate\Support\Facades\Http; use Illuminate\Support\Facades\Http;
@@ -0,0 +1,191 @@
<?php
namespace App\Support\VideoWorkflow;
use App\Models\VideoProject;
use App\Models\WorkflowStep;
use App\Models\WorkflowTemplate;
/**
* Drives a VideoProject's pipeline: creates its step sequence and manages
* step state transitions (execution, approval, failure, retry).
*
* Steps run strictly in `order`. Each step is one of:
* pending -> in_progress -> awaiting_approval -> completed
* \-> completed (skips approval if not required)
* \-> failed -> in_progress (retry)
* awaiting_approval -> rejected -> in_progress (retry)
* pending | in_progress -> skipped
*
* This class only manages state — it doesn't know how to actually generate
* a script, render video, etc. Whatever does that work (a future AI
* provider integration, a human, an Artisan command) calls completeStep()/
* failStep() to report the result.
*/
class WorkflowEngine
{
/**
* Create the step sequence for a project and activate the first one.
*
* @param array<int, array{type: string, requires_approval?: bool}> $steps
*/
public function start(VideoProject $project, array $steps): WorkflowStep
{
if ($project->steps()->exists()) {
throw new WorkflowTransitionException("Video project {$project->id} already has workflow steps.");
}
if (empty($steps)) {
throw new WorkflowTransitionException('Cannot start a workflow with no steps.');
}
foreach (array_values($steps) as $order => $step) {
$project->steps()->create([
'type' => $step['type'],
'order' => $order,
'status' => 'pending',
'requires_approval' => $step['requires_approval'] ?? false,
]);
}
$project->update(['status' => 'in_progress']);
$first = $project->steps()->orderBy('order')->firstOrFail();
return $this->activate($first);
}
public function startFromTemplate(VideoProject $project, WorkflowTemplate $template): WorkflowStep
{
$project->update(['workflow_template_id' => $template->id]);
return $this->start($project, $template->steps);
}
/**
* The step currently blocking progress — pending, running, awaiting
* approval, or stuck on failure/rejection. Null once every step is
* completed or skipped.
*/
public function currentStep(VideoProject $project): ?WorkflowStep
{
return $project->steps()
->whereNotIn('status', ['completed', 'skipped'])
->orderBy('order')
->first();
}
public function completeStep(WorkflowStep $step, array $output = []): WorkflowStep
{
$this->assertStatus($step, 'in_progress');
$step->update([
'output' => $output,
'error' => null,
'completed_at' => now(),
'status' => $step->requires_approval ? 'awaiting_approval' : 'completed',
]);
if ($step->status === 'completed') {
$this->activateNext($step);
}
return $step->fresh();
}
public function approveStep(WorkflowStep $step): WorkflowStep
{
$this->assertStatus($step, 'awaiting_approval');
$step->update(['status' => 'completed']);
$this->activateNext($step);
return $step->fresh();
}
/**
* Rejecting does not advance the pipeline — it stays blocked on this
* step until retryStep() is called.
*/
public function rejectStep(WorkflowStep $step, ?string $reason = null): WorkflowStep
{
$this->assertStatus($step, 'awaiting_approval');
$step->update(['status' => 'rejected', 'error' => $reason]);
return $step->fresh();
}
public function failStep(WorkflowStep $step, string $error): WorkflowStep
{
$this->assertStatus($step, 'in_progress');
$step->update(['status' => 'failed', 'error' => $error]);
return $step->fresh();
}
public function retryStep(WorkflowStep $step): WorkflowStep
{
if (! in_array($step->status, ['failed', 'rejected'], true)) {
throw new WorkflowTransitionException("Step {$step->id} can only be retried from failed or rejected, currently '{$step->status}'.");
}
$step->update([
'status' => 'in_progress',
'error' => null,
'output' => null,
'started_at' => now(),
'completed_at' => null,
]);
return $step->fresh();
}
public function skipStep(WorkflowStep $step): WorkflowStep
{
if (! in_array($step->status, ['pending', 'in_progress'], true)) {
throw new WorkflowTransitionException("Step {$step->id} can only be skipped from pending or in_progress, currently '{$step->status}'.");
}
$step->update(['status' => 'skipped', 'completed_at' => now()]);
$this->activateNext($step);
return $step->fresh();
}
private function activate(WorkflowStep $step): WorkflowStep
{
$step->update(['status' => 'in_progress', 'started_at' => now()]);
return $step->fresh();
}
private function activateNext(WorkflowStep $justFinished): void
{
$project = $justFinished->videoProject;
$next = $project->steps()
->where('order', '>', $justFinished->order)
->whereNotIn('status', ['completed', 'skipped'])
->orderBy('order')
->first();
if ($next) {
$this->activate($next);
return;
}
$project->update(['status' => 'completed']);
}
private function assertStatus(WorkflowStep $step, string $expected): void
{
if ($step->status !== $expected) {
throw new WorkflowTransitionException("Step {$step->id} must be '{$expected}' for this transition, currently '{$step->status}'.");
}
}
}
@@ -0,0 +1,7 @@
<?php
namespace App\Support\VideoWorkflow;
use RuntimeException;
class WorkflowTransitionException extends RuntimeException {}
+21
View File
@@ -0,0 +1,21 @@
<?php
namespace Database\Factories;
use App\Models\AiProvider;
use Illuminate\Database\Eloquent\Factories\Factory;
class AiProviderFactory extends Factory
{
protected $model = AiProvider::class;
public function definition(): array
{
return [
'name' => fake()->company().' Account',
'provider' => fake()->randomElement(AiProvider::PROVIDERS),
'api_key' => fake()->uuid(),
'is_active' => true,
];
}
}
+24
View File
@@ -0,0 +1,24 @@
<?php
namespace Database\Factories;
use App\Models\Asset;
use App\Models\VideoProject;
use Illuminate\Database\Eloquent\Factories\Factory;
class AssetFactory extends Factory
{
protected $model = Asset::class;
public function definition(): array
{
return [
'video_project_id' => VideoProject::factory(),
'type' => fake()->randomElement(Asset::TYPES),
'disk_path' => 'video-projects/'.fake()->uuid().'.bin',
'mime_type' => 'application/octet-stream',
'size_bytes' => fake()->numberBetween(1000, 5_000_000),
'version' => 1,
];
}
}
-1
View File
@@ -14,7 +14,6 @@ class PostFactory extends Factory
{ {
return [ return [
'site_id' => Site::factory(), 'site_id' => Site::factory(),
'social_account_id' => null,
'type' => fake()->randomElement(Post::TYPES), 'type' => fake()->randomElement(Post::TYPES),
'title' => fake()->optional()->sentence(), 'title' => fake()->optional()->sentence(),
'body' => fake()->paragraph(), 'body' => fake()->paragraph(),
@@ -0,0 +1,20 @@
<?php
namespace Database\Factories;
use App\Models\VideoProject;
use Illuminate\Database\Eloquent\Factories\Factory;
class VideoProjectFactory extends Factory
{
protected $model = VideoProject::class;
public function definition(): array
{
return [
'title' => fake()->sentence(4),
'description' => fake()->optional()->paragraph(),
'status' => 'draft',
];
}
}
@@ -0,0 +1,23 @@
<?php
namespace Database\Factories;
use App\Models\VideoProject;
use App\Models\WorkflowStep;
use Illuminate\Database\Eloquent\Factories\Factory;
class WorkflowStepFactory extends Factory
{
protected $model = WorkflowStep::class;
public function definition(): array
{
return [
'video_project_id' => VideoProject::factory(),
'type' => fake()->randomElement(WorkflowStep::TYPES),
'order' => 0,
'status' => 'pending',
'requires_approval' => false,
];
}
}
@@ -0,0 +1,24 @@
<?php
namespace Database\Factories;
use App\Models\WorkflowTemplate;
use Illuminate\Database\Eloquent\Factories\Factory;
class WorkflowTemplateFactory extends Factory
{
protected $model = WorkflowTemplate::class;
public function definition(): array
{
return [
'name' => fake()->sentence(3),
'description' => fake()->optional()->sentence(),
'steps' => [
['type' => 'script_generation', 'requires_approval' => true],
['type' => 'tts_voiceover', 'requires_approval' => false],
['type' => 'video_generation', 'requires_approval' => true],
],
];
}
}
@@ -0,0 +1,32 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('workflow_templates', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->text('description')->nullable();
// Ordered array of step definitions, e.g.
// [{"type": "script_generation", "requires_approval": true}, ...]
$table->json('steps');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('workflow_templates');
}
};
@@ -0,0 +1,36 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* Deliberately independent of the existing projects/tasks/ideas tables —
* no foreign keys into them. See Task #47 on the "YouTube Content
* Creation System" project for why.
*/
public function up(): void
{
Schema::create('video_projects', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('description')->nullable();
$table->string('status')->default('draft');
$table->foreignId('workflow_template_id')->nullable()->constrained()->nullOnDelete();
$table->softDeletes();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('video_projects');
}
};
@@ -0,0 +1,39 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('workflow_steps', function (Blueprint $table) {
$table->id();
$table->foreignId('video_project_id')->constrained()->cascadeOnDelete();
$table->string('type');
$table->unsignedInteger('order');
$table->string('status')->default('pending');
$table->boolean('requires_approval')->default(false);
$table->json('input')->nullable();
$table->json('output')->nullable();
$table->text('error')->nullable();
$table->timestamp('started_at')->nullable();
$table->timestamp('completed_at')->nullable();
$table->timestamps();
$table->unique(['video_project_id', 'order']);
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('workflow_steps');
}
};
@@ -0,0 +1,35 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('assets', function (Blueprint $table) {
$table->id();
$table->foreignId('video_project_id')->constrained()->cascadeOnDelete();
$table->foreignId('workflow_step_id')->nullable()->constrained()->nullOnDelete();
$table->string('type');
$table->string('disk_path');
$table->string('mime_type')->nullable();
$table->unsignedBigInteger('size_bytes')->nullable();
$table->unsignedInteger('version')->default(1);
$table->json('metadata')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('assets');
}
};
@@ -0,0 +1,32 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('ai_providers', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('provider');
$table->string('api_key');
$table->json('config')->nullable();
$table->boolean('is_active')->default(true);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('ai_providers');
}
};
@@ -13,7 +13,8 @@ test('it supports reddit posts only', function () {
}); });
test('it rejects a post with no title', function () { test('it rejects a post with no title', function () {
$post = Post::factory()->for(SocialAccount::factory()->state(['network' => 'reddit']), 'socialAccount') $post = Post::factory()
->hasAttached(SocialAccount::factory()->state(['network' => 'reddit']), [], 'socialAccounts')
->create(['type' => 'reddit', 'title' => null, 'target' => 'test']); ->create(['type' => 'reddit', 'title' => null, 'target' => 'test']);
$result = (new RedditPublisher)->publish($post); $result = (new RedditPublisher)->publish($post);
@@ -24,7 +25,8 @@ test('it rejects a post with no title', function () {
}); });
test('it rejects a post with no target subreddit', function () { test('it rejects a post with no target subreddit', function () {
$post = Post::factory()->for(SocialAccount::factory()->state(['network' => 'reddit']), 'socialAccount') $post = Post::factory()
->hasAttached(SocialAccount::factory()->state(['network' => 'reddit']), [], 'socialAccounts')
->create(['type' => 'reddit', 'title' => 'Hi', 'target' => null]); ->create(['type' => 'reddit', 'title' => 'Hi', 'target' => null]);
$result = (new RedditPublisher)->publish($post); $result = (new RedditPublisher)->publish($post);
@@ -35,7 +37,7 @@ test('it rejects a post with no target subreddit', function () {
}); });
test('it rejects a post with no linked reddit account', function () { test('it rejects a post with no linked reddit account', function () {
$post = Post::factory()->create(['type' => 'reddit', 'title' => 'Hi', 'target' => 'test', 'social_account_id' => null]); $post = Post::factory()->create(['type' => 'reddit', 'title' => 'Hi', 'target' => 'test']);
$result = (new RedditPublisher)->publish($post); $result = (new RedditPublisher)->publish($post);
@@ -50,14 +52,10 @@ test('it publishes successfully via the sidecar', function () {
]); ]);
$account = SocialAccount::factory()->create(['network' => 'reddit', 'username' => 'redditor']); $account = SocialAccount::factory()->create(['network' => 'reddit', 'username' => 'redditor']);
$post = Post::factory()->create([ $post = Post::factory()->create(['type' => 'reddit', 'title' => 'Hi', 'target' => 'test']);
'type' => 'reddit', $post->socialAccounts()->attach($account);
'title' => 'Hi',
'target' => 'test',
'social_account_id' => $account->id,
]);
$result = (new RedditPublisher)->publish($post); $result = (new RedditPublisher)->publish($post->fresh());
expect($result->success)->toBeTrue(); expect($result->success)->toBeTrue();
expect($result->url)->toBe('https://reddit.com/r/test/comments/abc123'); expect($result->url)->toBe('https://reddit.com/r/test/comments/abc123');
@@ -75,14 +73,10 @@ test('it treats a sidecar-reported failure as an attempted, failed publish', fun
]); ]);
$account = SocialAccount::factory()->create(['network' => 'reddit']); $account = SocialAccount::factory()->create(['network' => 'reddit']);
$post = Post::factory()->create([ $post = Post::factory()->create(['type' => 'reddit', 'title' => 'Hi', 'target' => 'test']);
'type' => 'reddit', $post->socialAccounts()->attach($account);
'title' => 'Hi',
'target' => 'test',
'social_account_id' => $account->id,
]);
$result = (new RedditPublisher)->publish($post); $result = (new RedditPublisher)->publish($post->fresh());
expect($result->success)->toBeFalse(); expect($result->success)->toBeFalse();
expect($result->attempted)->toBeTrue(); expect($result->attempted)->toBeTrue();
@@ -95,14 +89,10 @@ test('it fails gracefully when the sidecar output is unparseable', function () {
]); ]);
$account = SocialAccount::factory()->create(['network' => 'reddit']); $account = SocialAccount::factory()->create(['network' => 'reddit']);
$post = Post::factory()->create([ $post = Post::factory()->create(['type' => 'reddit', 'title' => 'Hi', 'target' => 'test']);
'type' => 'reddit', $post->socialAccounts()->attach($account);
'title' => 'Hi',
'target' => 'test',
'social_account_id' => $account->id,
]);
$result = (new RedditPublisher)->publish($post); $result = (new RedditPublisher)->publish($post->fresh());
expect($result->success)->toBeFalse(); expect($result->success)->toBeFalse();
expect($result->attempted)->toBeTrue(); expect($result->attempted)->toBeTrue();
@@ -0,0 +1,98 @@
<?php
use App\Models\AiProvider;
use App\Models\Asset;
use App\Models\VideoProject;
use App\Models\WorkflowStep;
use App\Models\WorkflowTemplate;
test('a video project has ordered steps', function () {
$project = VideoProject::factory()->create();
WorkflowStep::factory()->for($project)->create(['type' => 'video_generation', 'order' => 1]);
WorkflowStep::factory()->for($project)->create(['type' => 'script_generation', 'order' => 0]);
expect($project->steps->pluck('type')->all())->toBe(['script_generation', 'video_generation']);
});
test('a video project belongs to a workflow template', function () {
$template = WorkflowTemplate::factory()->create();
$project = VideoProject::factory()->create(['workflow_template_id' => $template->id]);
expect($project->workflowTemplate->id)->toBe($template->id);
expect($template->videoProjects->first()->id)->toBe($project->id);
});
test('deleting a video project cascades to its steps and assets', function () {
$project = VideoProject::factory()->create();
$step = WorkflowStep::factory()->for($project)->create();
$asset = Asset::factory()->for($project)->create(['workflow_step_id' => $step->id]);
$project->forceDelete();
expect(WorkflowStep::find($step->id))->toBeNull();
expect(Asset::find($asset->id))->toBeNull();
});
test('a video project is soft deleted by default', function () {
$project = VideoProject::factory()->create();
$project->delete();
expect(VideoProject::find($project->id))->toBeNull();
expect(VideoProject::withTrashed()->find($project->id))->not->toBeNull();
});
test('deleting the workflow step an asset belongs to nulls the reference instead of deleting the asset', function () {
$project = VideoProject::factory()->create();
$step = WorkflowStep::factory()->for($project)->create();
$asset = Asset::factory()->for($project)->create(['workflow_step_id' => $step->id]);
$step->delete();
expect($asset->fresh()->workflow_step_id)->toBeNull();
});
test('workflow step input/output/requires_approval cast correctly', function () {
$step = WorkflowStep::factory()->create([
'requires_approval' => true,
'input' => ['prompt' => 'write a script'],
'output' => ['script' => 'once upon a time'],
]);
expect($step->fresh())
->requires_approval->toBeTrue()
->input->toBe(['prompt' => 'write a script'])
->output->toBe(['script' => 'once upon a time']);
});
test('asset metadata casts to an array', function () {
$asset = Asset::factory()->create(['metadata' => ['duration_seconds' => 42]]);
expect($asset->fresh()->metadata)->toBe(['duration_seconds' => 42]);
});
test('an ai provider stores its config as an array and defaults to active', function () {
$provider = AiProvider::factory()->create([
'provider' => 'elevenlabs',
'config' => ['voice_id' => 'abc123'],
]);
expect($provider->fresh())
->provider->toBe('elevenlabs')
->config->toBe(['voice_id' => 'abc123'])
->is_active->toBeTrue();
});
test('a workflow template stores its steps as an ordered array', function () {
$template = WorkflowTemplate::factory()->create([
'steps' => [
['type' => 'script_generation', 'requires_approval' => true],
['type' => 'youtube_publish', 'requires_approval' => false],
],
]);
expect($template->fresh()->steps)->toBe([
['type' => 'script_generation', 'requires_approval' => true],
['type' => 'youtube_publish', 'requires_approval' => false],
]);
});
@@ -0,0 +1,257 @@
<?php
use App\Models\VideoProject;
use App\Models\WorkflowTemplate;
use App\Support\VideoWorkflow\WorkflowEngine;
use App\Support\VideoWorkflow\WorkflowTransitionException;
beforeEach(function () {
$this->engine = new WorkflowEngine;
});
test('starting a workflow creates ordered steps and activates the first one', function () {
$project = VideoProject::factory()->create();
$first = $this->engine->start($project, [
['type' => 'script_generation', 'requires_approval' => true],
['type' => 'tts_voiceover'],
['type' => 'video_generation'],
]);
expect($project->fresh()->status)->toBe('in_progress');
expect($project->steps)->toHaveCount(3);
expect($first)
->type->toBe('script_generation')
->order->toBe(0)
->status->toBe('in_progress')
->requires_approval->toBeTrue();
expect($first->started_at)->not->toBeNull();
expect($project->steps()->where('order', 1)->first())
->type->toBe('tts_voiceover')
->status->toBe('pending');
});
test('it refuses to start a project that already has steps', function () {
$project = VideoProject::factory()->create();
$this->engine->start($project, [['type' => 'script_generation']]);
$this->engine->start($project, [['type' => 'tts_voiceover']]);
})->throws(WorkflowTransitionException::class);
test('it refuses to start a workflow with no steps', function () {
$project = VideoProject::factory()->create();
$this->engine->start($project, []);
})->throws(WorkflowTransitionException::class);
test('startFromTemplate uses the template steps and links the project to it', function () {
$template = WorkflowTemplate::factory()->create([
'steps' => [
['type' => 'script_generation'],
['type' => 'youtube_publish'],
],
]);
$project = VideoProject::factory()->create();
$this->engine->startFromTemplate($project, $template);
expect($project->fresh())
->workflow_template_id->toBe($template->id)
->status->toBe('in_progress');
expect($project->steps)->toHaveCount(2);
});
test('currentStep returns the earliest non-terminal step', function () {
$project = VideoProject::factory()->create();
$this->engine->start($project, [
['type' => 'script_generation'],
['type' => 'tts_voiceover'],
]);
expect($this->engine->currentStep($project)->type)->toBe('script_generation');
});
test('currentStep is null once every step is completed', function () {
$project = VideoProject::factory()->create();
$step = $this->engine->start($project, [['type' => 'script_generation']]);
$this->engine->completeStep($step);
expect($this->engine->currentStep($project->fresh()))->toBeNull();
});
test('completing a step without approval advances straight to the next step', function () {
$project = VideoProject::factory()->create();
$step = $this->engine->start($project, [
['type' => 'script_generation'],
['type' => 'tts_voiceover'],
]);
$completed = $this->engine->completeStep($step, ['script' => 'Hello world']);
expect($completed)
->status->toBe('completed')
->output->toBe(['script' => 'Hello world']);
expect($completed->completed_at)->not->toBeNull();
$next = $project->steps()->where('order', 1)->first();
expect($next->status)->toBe('in_progress');
});
test('completing a step that requires approval stops at awaiting_approval', function () {
$project = VideoProject::factory()->create();
$step = $this->engine->start($project, [
['type' => 'script_generation', 'requires_approval' => true],
['type' => 'tts_voiceover'],
]);
$completed = $this->engine->completeStep($step, ['script' => 'Draft']);
expect($completed->status)->toBe('awaiting_approval');
$next = $project->steps()->where('order', 1)->first();
expect($next->status)->toBe('pending');
});
test('completing a step that is not in_progress throws', function () {
$project = VideoProject::factory()->create();
$step = $this->engine->start($project, [['type' => 'script_generation']]);
$this->engine->completeStep($step);
$this->engine->completeStep($step->fresh());
})->throws(WorkflowTransitionException::class);
test('approving a step advances the pipeline', function () {
$project = VideoProject::factory()->create();
$step = $this->engine->start($project, [
['type' => 'script_generation', 'requires_approval' => true],
['type' => 'tts_voiceover'],
]);
$this->engine->completeStep($step, ['script' => 'Draft']);
$approved = $this->engine->approveStep($step->fresh());
expect($approved->status)->toBe('completed');
expect($project->steps()->where('order', 1)->first()->status)->toBe('in_progress');
});
test('rejecting a step blocks the pipeline without advancing', function () {
$project = VideoProject::factory()->create();
$step = $this->engine->start($project, [
['type' => 'script_generation', 'requires_approval' => true],
['type' => 'tts_voiceover'],
]);
$this->engine->completeStep($step, ['script' => 'Bad draft']);
$rejected = $this->engine->rejectStep($step->fresh(), 'Tone is wrong');
expect($rejected)
->status->toBe('rejected')
->error->toBe('Tone is wrong');
expect($project->steps()->where('order', 1)->first()->status)->toBe('pending');
});
test('approving a step that is not awaiting_approval throws', function () {
$project = VideoProject::factory()->create();
$step = $this->engine->start($project, [['type' => 'script_generation']]);
$this->engine->approveStep($step);
})->throws(WorkflowTransitionException::class);
test('a failed step blocks the pipeline and records the error', function () {
$project = VideoProject::factory()->create();
$step = $this->engine->start($project, [
['type' => 'script_generation'],
['type' => 'tts_voiceover'],
]);
$failed = $this->engine->failStep($step, 'OpenAI API timed out');
expect($failed)
->status->toBe('failed')
->error->toBe('OpenAI API timed out');
expect($project->steps()->where('order', 1)->first()->status)->toBe('pending');
});
test('a failed step can be retried', function () {
$project = VideoProject::factory()->create();
$step = $this->engine->start($project, [['type' => 'script_generation']]);
$this->engine->failStep($step, 'timed out');
$retried = $this->engine->retryStep($step->fresh());
expect($retried)
->status->toBe('in_progress')
->error->toBeNull();
});
test('a rejected step can be retried', function () {
$project = VideoProject::factory()->create();
$step = $this->engine->start($project, [['type' => 'script_generation', 'requires_approval' => true]]);
$this->engine->completeStep($step, ['script' => 'v1']);
$this->engine->rejectStep($step->fresh(), 'no good');
$retried = $this->engine->retryStep($step->fresh());
expect($retried)
->status->toBe('in_progress')
->output->toBeNull();
});
test('retrying a step that is not failed or rejected throws', function () {
$project = VideoProject::factory()->create();
$step = $this->engine->start($project, [['type' => 'script_generation']]);
$this->engine->retryStep($step);
})->throws(WorkflowTransitionException::class);
test('skipping a pending or in_progress step advances the pipeline', function () {
$project = VideoProject::factory()->create();
$step = $this->engine->start($project, [
['type' => 'script_generation'],
['type' => 'tts_voiceover'],
]);
$skipped = $this->engine->skipStep($step);
expect($skipped->status)->toBe('skipped');
expect($project->steps()->where('order', 1)->first()->status)->toBe('in_progress');
});
test('completing the last step marks the project completed', function () {
$project = VideoProject::factory()->create();
$step = $this->engine->start($project, [['type' => 'script_generation']]);
$this->engine->completeStep($step);
expect($project->fresh()->status)->toBe('completed');
});
test('a full multi-step pipeline runs end to end', function () {
$project = VideoProject::factory()->create();
$script = $this->engine->start($project, [
['type' => 'script_generation', 'requires_approval' => true],
['type' => 'tts_voiceover'],
['type' => 'video_generation', 'requires_approval' => true],
]);
$this->engine->completeStep($script, ['script' => 'Hello']);
$script = $script->fresh();
expect($script->status)->toBe('awaiting_approval');
$this->engine->approveStep($script);
$tts = $this->engine->currentStep($project->fresh());
expect($tts->type)->toBe('tts_voiceover');
$this->engine->completeStep($tts, ['audio_path' => '/tmp/a.mp3']);
$video = $this->engine->currentStep($project->fresh());
expect($video->type)->toBe('video_generation');
$this->engine->completeStep($video, ['video_path' => '/tmp/v.mp4']);
$this->engine->approveStep($video->fresh());
expect($project->fresh())
->status->toBe('completed');
expect($this->engine->currentStep($project->fresh()))->toBeNull();
});