Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
92 changes: 92 additions & 0 deletions app/Console/Commands/BackfillMissingPayouts.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
<?php

namespace App\Console\Commands;

use App\Enums\PayoutStatus;
use App\Enums\PluginType;
use App\Models\PluginLicense;
use App\Models\PluginPayout;
use Illuminate\Console\Command;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Log;

class BackfillMissingPayouts extends Command
{
protected $signature = 'payouts:backfill {--dry-run : List the payouts that would be created without creating them}';

protected $description = 'Create missing payout records for paid third-party plugin sales';

public function handle(): int
{
$licenses = PluginLicense::query()
->whereDoesntHave('payout')
->where('is_grandfathered', false)
->where('price_paid', '>', 0)
->whereHas('plugin', function (Builder $query): void {
$query->where('is_official', false)
->where('type', PluginType::Paid)
->whereNotNull('developer_account_id');
})
->with('plugin.developerAccount')
->get();

if ($licenses->isEmpty()) {
$this->info('No sales are missing payout records.');

return self::SUCCESS;
}

$dryRun = (bool) $this->option('dry-run');
$created = 0;

foreach ($licenses as $license) {
$developerAccount = $license->plugin->developerAccount;

$split = PluginPayout::calculateSplit($license->price_paid, $developerAccount->platformFeePercent());

$status = $developerAccount->canReceivePayouts()
? PayoutStatus::Pending
: PayoutStatus::Held;

$eligibleAt = $license->purchased_at?->clone()->addDays(15) ?? now();

$this->line(sprintf(
'%sLicense #%d (%s): gross $%s, developer $%s, status %s',
$dryRun ? '[dry-run] ' : '',
$license->id,
$license->plugin->name,
number_format($license->price_paid / 100, 2),
number_format($split['developer_amount'] / 100, 2),
$status->value,
));

if ($dryRun) {
continue;
}

PluginPayout::create([
'plugin_license_id' => $license->id,
'developer_account_id' => $developerAccount->id,
'gross_amount' => $license->price_paid,
'platform_fee' => $split['platform_fee'],
'developer_amount' => $split['developer_amount'],
'status' => $status,
'eligible_for_payout_at' => $eligibleAt,
]);

$created++;

Log::info('Backfilled missing payout', [
'plugin_license_id' => $license->id,
'developer_account_id' => $developerAccount->id,
'status' => $status->value,
]);
}

$this->info($dryRun
? "Found {$licenses->count()} sale(s) missing payout records."
: "Created {$created} payout record(s).");

return self::SUCCESS;
}
}
37 changes: 36 additions & 1 deletion app/Console/Commands/ProcessEligiblePayouts.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,22 @@

namespace App\Console\Commands;

use App\Enums\PayoutStatus;
use App\Jobs\ProcessPayoutTransfer;
use App\Models\PluginPayout;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class ProcessEligiblePayouts extends Command
{
protected $signature = 'payouts:process-eligible';

protected $description = 'Dispatch transfer jobs for pending payouts that have passed the 15-day holding period';
protected $description = 'Heal held payouts and dispatch transfer jobs for pending payouts that have passed the 15-day holding period';

public function handle(): int
{
$this->healHeldPayouts();

$eligiblePayouts = PluginPayout::pending()
->where('eligible_for_payout_at', '<=', now())
->get();
Expand All @@ -32,4 +36,35 @@ public function handle(): int

return self::SUCCESS;
}

/**
* Promote held payouts to pending once the developer's Stripe Connect
* account is able to receive payouts.
*/
private function healHeldPayouts(): void
{
$heldPayouts = PluginPayout::held()
->with('developerAccount')
->get();

$healed = 0;

foreach ($heldPayouts as $payout) {
if (! $payout->developerAccount?->canReceivePayouts()) {
continue;
}

$payout->update(['status' => PayoutStatus::Pending]);
$healed++;

Log::info('Healed held payout', [
'payout_id' => $payout->id,
'developer_account_id' => $payout->developer_account_id,
]);
}

if ($healed > 0) {
$this->info("Healed {$healed} held payout(s).");
}
}
}
3 changes: 3 additions & 0 deletions app/Enums/PayoutStatus.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,15 @@

enum PayoutStatus: string
{
case Held = 'held';
case Pending = 'pending';
case Transferred = 'transferred';
case Failed = 'failed';

public function label(): string
{
return match ($this) {
self::Held => 'Held',
self::Pending => 'Pending',
self::Transferred => 'Transferred',
self::Failed => 'Failed',
Expand All @@ -20,6 +22,7 @@ public function label(): string
public function color(): string
{
return match ($this) {
self::Held => 'gray',
self::Pending => 'yellow',
self::Transferred => 'green',
self::Failed => 'red',
Expand Down
213 changes: 213 additions & 0 deletions app/Filament/Resources/PluginPayoutResource.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,213 @@
<?php

namespace App\Filament\Resources;

use App\Enums\PayoutStatus;
use App\Filament\Resources\PluginPayoutResource\Pages;
use App\Filament\Resources\PluginPayoutResource\RelationManagers;
use App\Jobs\ProcessPayoutTransfer;
use App\Models\PluginPayout;
use Filament\Actions;
use Filament\Infolists;
use Filament\Notifications\Notification;
use Filament\Resources\Resource;
use Filament\Schemas;
use Filament\Schemas\Schema;
use Filament\Tables;
use Filament\Tables\Table;

class PluginPayoutResource extends Resource
{
protected static ?string $model = PluginPayout::class;

protected static \BackedEnum|string|null $navigationIcon = 'heroicon-o-currency-dollar';

protected static ?string $navigationLabel = 'Payouts';

protected static \UnitEnum|string|null $navigationGroup = 'Products';

protected static ?int $navigationSort = 4;

protected static ?string $modelLabel = 'Payout';

protected static ?string $pluralModelLabel = 'Payouts';

protected static ?string $slug = 'plugin-payouts';

public static function canCreate(): bool
{
return false;
}

public static function form(Schema $schema): Schema
{
return $schema->schema([]);
}

public static function infolist(Schema $schema): Schema
{
return $schema
->inlineLabel()
->columns(1)
->schema([
Schemas\Components\Section::make('Payout Details')
->inlineLabel()
->columns(1)
->schema([
Infolists\Components\TextEntry::make('pluginLicense.plugin.display_name')
->label('Plugin')
->default(fn (PluginPayout $record): ?string => $record->pluginLicense?->plugin?->name),
Infolists\Components\TextEntry::make('pluginLicense.user.email')
->label('Customer')
->copyable(),
Infolists\Components\TextEntry::make('developerAccount.user.email')
->label('Seller')
->copyable(),
Infolists\Components\TextEntry::make('status')
->badge()
->color(fn (PayoutStatus $state): string => $state->color())
->formatStateUsing(fn (PayoutStatus $state): string => $state->label()),
Infolists\Components\TextEntry::make('gross_amount')
->label('Customer Paid')
->formatStateUsing(fn (int $state): string => '$'.number_format($state / 100, 2)),
Infolists\Components\TextEntry::make('developer_amount')
->label('Due to Seller')
->formatStateUsing(fn (int $state): string => '$'.number_format($state / 100, 2)),
Infolists\Components\TextEntry::make('platform_fee')
->label('Platform Fee')
->formatStateUsing(fn (int $state): string => '$'.number_format($state / 100, 2)),
Infolists\Components\TextEntry::make('stripe_transfer_id')
->label('Stripe Transfer ID')
->copyable()
->placeholder('—'),
Infolists\Components\TextEntry::make('attempt_count')
->label('Total Attempts'),
Infolists\Components\TextEntry::make('last_attempted_at')
->label('Last Attempt')
->dateTime()
->placeholder('—'),
Infolists\Components\TextEntry::make('transferred_at')
->label('Transferred At')
->dateTime()
->placeholder('—'),
Infolists\Components\TextEntry::make('eligible_for_payout_at')
->label('Eligible From')
->dateTime()
->placeholder('—'),
Infolists\Components\TextEntry::make('created_at')
->label('Created')
->dateTime(),
]),

Schemas\Components\Section::make('Latest Failure Reason')
->inlineLabel()
->columns(1)
->schema([
Infolists\Components\TextEntry::make('failure_reason')
->label('Reason')
->placeholder('—'),
])
->visible(fn (PluginPayout $record): bool => $record->failure_reason !== null),
]);
}

public static function table(Table $table): Table
{
return $table
->columns([
Tables\Columns\TextColumn::make('id')
->label('#')
->sortable(),

Tables\Columns\TextColumn::make('pluginLicense.plugin.name')
->label('Plugin')
->searchable()
->sortable(),

Tables\Columns\TextColumn::make('pluginLicense.user.email')
->label('Customer')
->searchable()
->sortable(),

Tables\Columns\TextColumn::make('gross_amount')
->label('Paid')
->formatStateUsing(fn (int $state): string => '$'.number_format($state / 100, 2))
->sortable(),

Tables\Columns\TextColumn::make('developer_amount')
->label('Due to Seller')
->formatStateUsing(fn (int $state): string => '$'.number_format($state / 100, 2))
->sortable(),

Tables\Columns\TextColumn::make('status')
->badge()
->color(fn (PayoutStatus $state): string => $state->color())
->formatStateUsing(fn (PayoutStatus $state): string => $state->label())
->sortable(),

Tables\Columns\IconColumn::make('paid_out')
->label('Paid Out')
->boolean()
->getStateUsing(fn (PluginPayout $record): bool => $record->isTransferred()),

Tables\Columns\TextColumn::make('attempt_count')
->label('Attempts')
->sortable(),

Tables\Columns\TextColumn::make('created_at')
->label('Created')
->dateTime()
->sortable(),
])
->filters([
Tables\Filters\SelectFilter::make('status')
->options(collect(PayoutStatus::cases())
->mapWithKeys(fn (PayoutStatus $status) => [$status->value => $status->label()])
->toArray()),
])
->actions([
Actions\ViewAction::make(),
Actions\Action::make('retryPayout')
->label('Retry Payout')
->icon('heroicon-o-arrow-path')
->color('warning')
->requiresConfirmation()
->modalHeading('Retry Payout')
->modalDescription('This will reset the payout to pending and dispatch the transfer job. Continue?')
->modalSubmitActionLabel('Retry')
->visible(fn (PluginPayout $record): bool => $record->isFailed())
->action(function (PluginPayout $record): void {
$record->update([
'status' => PayoutStatus::Pending,
]);

ProcessPayoutTransfer::dispatch($record);

Notification::make()
->title("Payout #{$record->id} queued for retry")
->success()
->send();
}),
])
->bulkActions([])
->defaultSort('created_at', 'desc')
->recordUrl(
fn ($record) => static::getUrl('view', ['record' => $record])
);
}

public static function getRelations(): array
{
return [
RelationManagers\AttemptsRelationManager::class,
];
}

public static function getPages(): array
{
return [
'index' => Pages\ListPluginPayouts::route('/'),
'view' => Pages\ViewPluginPayout::route('/{record}'),
];
}
}
Loading
Loading