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
2 changes: 1 addition & 1 deletion .github/workflows/ui-layer.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ jobs:
- uses: actions/checkout@v4
with:
repository: trakli/webui
ref: 5caf9d16b0cfb392b2d6ddb42930c98cb4b03caf
ref: 7b36da2e849fb561f2d8a1ab368569e16b305d59
path: .host-ui
- uses: actions/setup-node@v4
with:
Expand Down
14 changes: 14 additions & 0 deletions config/workspace-billing.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?php

return [
'pricing' => Trakli\Cloud\Billing\BasePlusMemberPricing::class,
'currency' => 'usd',
'return_url' => rtrim(env('FRONTEND_URL', 'http://localhost:3001'), '/'),
'base_amount_cents' => (int) env('CLOUD_GROUP_BASE_AMOUNT_CENTS', 1200),
'included_members' => (int) env('CLOUD_GROUP_INCLUDED_MEMBERS', 2),
'additional_member_amount_cents' => (int) env('CLOUD_GROUP_ADDITIONAL_MEMBER_AMOUNT_CENTS', 500),
'max_members' => (int) env('CLOUD_GROUP_MAX_MEMBERS', 100),
'feature_keys' => ['shared_workspaces', 'plaid', 'bank_connections'],
'member_feature_keys' => ['plaid', 'bank_connections'],
'limits' => ['max_wallets' => null, 'max_categories' => null],
];
10 changes: 10 additions & 0 deletions routes/api.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,13 @@
Route::post('/billing/checkout', [CloudController::class, 'checkout']);
Route::post('/billing/portal', [CloudController::class, 'billingPortal']);
});

Route::middleware('auth:sanctum')->group(function () {
Route::get('/workspace-pricing', [\Trakli\Cloud\Http\Controllers\WorkspaceBillingController::class, 'quote']);
Route::prefix('/workspaces/{workspace:slug}/billing')->group(function () {
Route::get('/', [\Trakli\Cloud\Http\Controllers\WorkspaceBillingController::class, 'status']);
Route::post('/checkout', [\Trakli\Cloud\Http\Controllers\WorkspaceBillingController::class, 'checkout']);
Route::post('/cancel-checkout', [\Trakli\Cloud\Http\Controllers\WorkspaceBillingController::class, 'cancelCheckout']);
Route::post('/portal', [\Trakli\Cloud\Http\Controllers\WorkspaceBillingController::class, 'portal']);
});
});
35 changes: 35 additions & 0 deletions src/Billing/BasePlusMemberPricing.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<?php

namespace Trakli\Cloud\Billing;

use InvalidArgumentException;
use Trakli\Cloud\Contracts\WorkspacePricing;

class BasePlusMemberPricing implements WorkspacePricing
{
public function quote(int $members): array
{
$config = config('workspace-billing');
$included = (int) $config['included_members'];
$base = (int) $config['base_amount_cents'];
$additional = (int) $config['additional_member_amount_cents'];
$max = (int) $config['max_members'];
if ($included < 1 || $base < 1 || $additional < 0 || $max < $included) {
throw new InvalidArgumentException('Invalid workspace pricing configuration.');
}
if ($members < $included || $members > $max) {
throw new InvalidArgumentException("Choose between {$included} and {$max} members, including the owner.");
}

return [
'currency' => $config['currency'],
'interval' => 'month',
'members' => $members,
'included_members' => $included,
'max_members' => $max,
'base_amount_cents' => $base,
'additional_member_amount_cents' => $additional,
'amount_cents' => $base + max(0, $members - $included) * $additional,
];
}
}
29 changes: 29 additions & 0 deletions src/Billing/WorkspaceCheckoutProvider.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php

namespace Trakli\Cloud\Billing;

use Illuminate\Database\Eloquent\Model;
use Whilesmart\EntitlementsCashier\CashierBillingProvider;
use Whilesmart\Entitlements\Models\Plan;

class WorkspaceCheckoutProvider extends CashierBillingProvider
{
public function createCheckout(Model $owner, Plan $plan): string
{
$previous = ['entitlements-cashier.success_url' => config('entitlements-cashier.success_url'),
'entitlements-cashier.cancel_url' => config('entitlements-cashier.cancel_url')];
$url = rtrim(config('workspace-billing.return_url'), '/').'/workspaces/'.$owner->slug;
config(['entitlements-cashier.success_url' => $url.'?checkout=success',

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The cancel return emits ?checkout=cancel, but the shared checkoutNotice helper and BillingSettings only recognise success/cancelled, and WorkspaceBilling.vue handles only success. A user who abandons workspace checkout therefore gets no confirmation that nothing changed. Emit cancelled here and surface it via checkoutNotice in WorkspaceBilling.vue.

Suggested change
config(['entitlements-cashier.success_url' => $url.'?checkout=success',
config(['entitlements-cashier.success_url' => $url.'?checkout=success',
'entitlements-cashier.cancel_url' => $url.'?checkout=cancelled']);

'entitlements-cashier.cancel_url' => $url.'?checkout=cancelled']);
try {
return parent::createCheckout($owner, $plan);
} finally {
config($previous);
}
}

protected function trialDays(): ?int
{
return null;
}
}
16 changes: 16 additions & 0 deletions src/Billing/WorkspaceDeletionGuard.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php

namespace Trakli\Cloud\Billing;

use App\Models\Workspace;
use App\Services\WorkspaceFinance;

class WorkspaceDeletionGuard
{
public function deleting(Workspace $workspace): void
{
if (! app(WorkspaceSubscription::class)->canDelete($workspace)) {
app(WorkspaceFinance::class)->deny('End the workspace subscription and cancel any pending checkout before deleting this space.', 409);
}
}
}
29 changes: 29 additions & 0 deletions src/Billing/WorkspaceInvitationGuard.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php

namespace Trakli\Cloud\Billing;

use Illuminate\Contracts\Auth\Authenticatable;
use Whilesmart\Entitlements\Contracts\Entitlements;
use Whilesmart\Workspaces\Contracts\InvitationGuard;
use Whilesmart\Workspaces\Models\Workspace;
use Whilesmart\Workspaces\Models\WorkspaceInvitation;

class WorkspaceInvitationGuard implements InvitationGuard
{
public function beforeInvite(Workspace $workspace, string $email, string $role, ?Authenticatable $inviter): void
{
abort_unless(app(Entitlements::class)->allows($workspace, 'shared_workspaces'), 402, 'Activate the workspace subscription before inviting members.');
}

public function beforeAccept(WorkspaceInvitation $invitation, Authenticatable $user): void
{
$model = config('workspaces.workspace_model');
$workspace = $model::whereKey($invitation->workspace_id)->lockForUpdate()->firstOrFail();
abort_unless(app(Entitlements::class)->allows($workspace, 'shared_workspaces'), 402, 'The workspace subscription is inactive.');
if ($user->belongsToWorkspace($workspace)) {
return;
}
$capacity = app(Entitlements::class)->limit($workspace, 'workspace_members');
abort_if($workspace->members()->distinct()->count('users.id') >= $capacity, 402, 'The owner must add a member to the subscription before you can join.');
}
}
60 changes: 60 additions & 0 deletions src/Billing/WorkspaceMemberEntitlements.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
<?php

namespace Trakli\Cloud\Billing;

use App\Models\User;
use App\Models\Workspace;
use Illuminate\Database\Eloquent\Model;
use Whilesmart\Entitlements\Support\AccessResult;
use Whilesmart\Entitlements\Support\PlanEntitlements;

class WorkspaceMemberEntitlements extends PlanEntitlements
{
public function check(?Model $owner, string $feature): AccessResult
{
if ($feature === 'shared_workspaces') {
if ($owner instanceof User) {
return AccessResult::allow($feature);
}
if ($owner instanceof Workspace) {
$capacity = app(WorkspaceSubscription::class)->capacity($owner);

return $capacity > 0 && $owner->members()->distinct()->count('users.id') <= $capacity
? parent::check($owner, $feature)
: AccessResult::deny($feature, 'workspace_subscription_inactive');
}
}
$result = parent::check($owner, $feature);
if ($result->allowed || ! in_array($feature, config('workspace-billing.member_feature_keys', []), true)) {
return $result;
}

return $this->hasWorkspaceAccess($owner, $feature) ? AccessResult::allow($feature) : $result;
}

public function limit(?Model $owner, string $key): ?int
{
if ($owner instanceof Workspace && $key === 'workspace_members') {
return app(WorkspaceSubscription::class)->capacity($owner);
}
if (array_key_exists($key, config('workspace-billing.limits', [])) && $this->hasWorkspaceAccess($owner)) {
return config('workspace-billing.limits.'.$key);
}

return parent::limit($owner, $key);
}

private function hasWorkspaceAccess(?Model $owner, ?string $feature = null): bool
{
if (! $owner instanceof User) {
return false;
}
foreach ($owner->workspaces()->where('is_active', true)->where('is_personal', false)->distinct()->get() as $workspace) {
if ($this->allows($workspace, 'shared_workspaces') && ($feature === null || parent::check($workspace, $feature)->allowed)) {
return true;
}
}

return false;
}
}
42 changes: 42 additions & 0 deletions src/Billing/WorkspaceSubscription.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
<?php

namespace Trakli\Cloud\Billing;

use App\Models\Workspace;
use Whilesmart\Entitlements\Support\PlanEntitlements;
use Whilesmart\Entitlements\Models\Plan;
use Whilesmart\EntitlementsCashier\Models\BillingProfile;

class WorkspaceSubscription
{
public function canDelete(Workspace $workspace): bool
{
$model = config('entitlements-cashier.billing_profile_model', BillingProfile::class);
$profile = $model::where('owner_type', $workspace->getMorphClass())->where('owner_id', $workspace->id)->first();
$subscription = $profile?->subscription('default');

return (! $subscription || $subscription->ended())
&& ! ($profile?->checkout_expires_at?->isFuture() && filled($profile->checkout_parameters));
}

public function capacity(Workspace $workspace): int
{
$entitlements = app(PlanEntitlements::class);
if (! $workspace->is_active || ! $entitlements->allows($workspace, 'shared_workspaces')) {
return 0;
}
$model = config('entitlements-cashier.billing_profile_model', BillingProfile::class);
$profile = $model::where('owner_type', $workspace->getMorphClass())->where('owner_id', $workspace->id)->first();
$subscription = $profile?->subscription('default');
if (! $subscription || ! in_array($subscription->stripe_status, ['active', 'trialing'], true) || $subscription->ended()) {
return 0;
}
$planModel = config('entitlements.models.plan', Plan::class);
$paidPlan = $planModel::where('provider_price_id', $subscription->stripe_price)->first();
if (! ($paidPlan?->features['shared_workspaces'] ?? false)) {
return 0;
}

return min((int) ($paidPlan->limits['workspace_members'] ?? 0), (int) $entitlements->limit($workspace, 'workspace_members'));
}
}
7 changes: 5 additions & 2 deletions src/CloudServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
use Whilesmart\Entitlements\Contracts\Entitlements;
use Whilesmart\Entitlements\Contracts\PlanSource;
use Whilesmart\Entitlements\Contracts\UsageMeter;
use Whilesmart\Entitlements\Support\PlanEntitlements;

class CloudServiceProvider extends ServiceProvider
{
Expand All @@ -25,6 +24,8 @@ class CloudServiceProvider extends ServiceProvider
public function register(): void
{
$this->mergeConfigFrom(__DIR__ . '/../config/cloudplans.php', 'cloudplans');
$this->mergeConfigFrom(__DIR__ . '/../config/workspace-billing.php', 'workspace-billing');
$this->app->bind(\Trakli\Cloud\Contracts\WorkspacePricing::class, fn ($app) => $app->make(config('workspace-billing.pricing')));
}

/**
Expand Down Expand Up @@ -74,7 +75,9 @@ protected function enforcePlans(): void

$this->app->singleton(PlanSource::class, FreePlanFallbackSource::class);
$this->app->singleton(UsageMeter::class, TokenMeterUsage::class);
$this->app->singleton(Entitlements::class, PlanEntitlements::class);
$this->app->singleton(Entitlements::class, \Trakli\Cloud\Billing\WorkspaceMemberEntitlements::class);
\App\Models\Workspace::observe(\Trakli\Cloud\Billing\WorkspaceDeletionGuard::class);
$this->app->bind(\Whilesmart\Workspaces\Contracts\InvitationGuard::class, \Trakli\Cloud\Billing\WorkspaceInvitationGuard::class);
}

/**
Expand Down
7 changes: 6 additions & 1 deletion src/Console/SyncPlansCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,17 @@

class SyncPlansCommand extends Command
{
protected $signature = 'cloud:sync-plans';
protected $signature = 'cloud:sync-plans {--features-only : Update existing plan features without syncing prices}';

protected $description = 'Mirror the configured cloud plans into the entitlements tables and ensure a Stripe price for each';

public function handle(CloudPlanSync $plans, PlanPriceSync $prices): int
{
if ($this->option('features-only')) {
$this->info(sprintf('Synced features for %d existing plans.', $plans->featuresOnly()));
return self::SUCCESS;
}

$this->info(sprintf('Synced %d plans.', $plans->run()));

$prices->run();
Expand Down
8 changes: 8 additions & 0 deletions src/Contracts/WorkspacePricing.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<?php

namespace Trakli\Cloud\Contracts;

interface WorkspacePricing
{
public function quote(int $members): array;
}
8 changes: 5 additions & 3 deletions src/Http/Controllers/CloudController.php
Original file line number Diff line number Diff line change
Expand Up @@ -314,13 +314,15 @@ public function billingStatus(Request $request): JsonResponse
->where('owner_id', $owner->getKey())->latest('id')->first();
$used = app(\Trakli\Cloud\Support\TokenMeterUsage::class)->used($owner);
$paid = $entitlements->allows($owner, 'bank_connections');
$ai = $entitlements->allows($owner, 'ai');
$workspaceAccess = $paid && ! app(\Whilesmart\Entitlements\Support\PlanEntitlements::class)->allows($owner, 'bank_connections');
$start = now('UTC')->startOfMonth();

return $this->success([
'has_billing_account' => app(config('entitlements-cashier.billing_profile_model', \Whilesmart\EntitlementsCashier\Models\BillingProfile::class))->newQuery()
->where('owner_type', $owner->getMorphClass())->where('owner_id', $owner->getKey())->whereNotNull('stripe_id')->exists(),
'paid_access' => $paid,
'status' => $subscription?->status?->value ?? 'free',
'status' => $workspaceAccess ? 'group' : ($subscription?->status?->value ?? 'free'),
'paid_through' => $subscription?->current_period_end?->toIso8601String(),
'limits' => [
'wallets' => $entitlements->limit($owner, 'max_wallets'),
Expand All @@ -329,8 +331,8 @@ public function billingStatus(Request $request): JsonResponse
],
'ai_usage' => [
'used' => $used,
'allowance' => $paid ? 100000 : 0,
'remaining' => $paid ? max(0, 100000 - $used) : 0,
'allowance' => $ai ? 100000 : 0,
'remaining' => $ai ? max(0, 100000 - $used) : 0,
'period_start' => $start->toIso8601String(),
'period_end' => $start->copy()->addMonth()->toIso8601String(),
],
Expand Down
Loading
Loading