From 2ca386055748e204e6a2576f07452ab55d316dbf Mon Sep 17 00:00:00 2001 From: Eric Downing Date: Sun, 4 Oct 2026 20:34:19 -0700 Subject: [PATCH] added pricing, orgs --- .env.example | 13 + .env.testing.example | 14 +- app/Actions/Fortify/CreateNewUser.php | 25 ++ app/Http/Middleware/EnsureSubscribed.php | 26 ++ app/Http/Responses/RegisterResponse.php | 78 +++++ app/Models/Organization.php | 273 +++++++++++++++ app/Models/Setting.php | 77 ++++ app/Models/User.php | 61 +++- app/OrganizationRole.php | 20 ++ app/Providers/AppServiceProvider.php | 28 +- bootstrap/app.php | 13 +- composer.json | 3 +- composer.lock | 331 +++++++++++++++++- config/cashier.php | 130 +++++++ config/plans.php | 53 +++ database/factories/OrganizationFactory.php | 59 ++++ database/factories/SettingFactory.php | 25 ++ database/factories/UserFactory.php | 63 ++++ ...9_27_023318_create_subscriptions_table.php | 41 +++ ...023319_create_subscription_items_table.php | 34 ++ ...d_meter_id_to_subscription_items_table.php | 28 ++ ...event_name_to_subscription_items_table.php | 28 ++ ...9_27_023339_create_organizations_table.php | 41 +++ ..._023340_create_organization_user_table.php | 32 ++ ...current_organization_id_to_users_table.php | 32 ++ ...023342_backfill_personal_organizations.php | 54 +++ ...026_09_27_051310_create_settings_table.php | 40 +++ database/seeders/BaseDatabaseSeeder.php | 9 +- phpunit.xml | 6 + resources/views/layouts/app/sidebar.blade.php | 3 + resources/views/layouts/marketing.blade.php | 44 +++ .../pages/admin/⚡plan-pricing.blade.php | 133 +++++++ resources/views/pages/auth/register.blade.php | 74 +++- .../views/pages/settings/layout.blade.php | 1 + .../views/pages/settings/⚡billing.blade.php | 151 ++++++++ resources/views/pages/⚡dashboard.blade.php | 53 ++- resources/views/pages/⚡folders.blade.php | 2 +- resources/views/pages/⚡pricing.blade.php | 163 +++++++++ .../pages/⚡subscription-confirmed.blade.php | 96 +++++ resources/views/pages/⚡todos.blade.php | 51 ++- routes/settings.php | 17 + routes/web.php | 11 +- tests/Feature/Auth/RegistrationTest.php | 37 +- tests/Feature/BaseDataSeederTest.php | 12 + tests/Feature/Billing/BillingSettingsTest.php | 140 ++++++++ tests/Feature/Billing/CheckoutTest.php | 157 +++++++++ tests/Feature/Billing/EntitlementTest.php | 110 ++++++ tests/Feature/Billing/PlanPricingTest.php | 218 ++++++++++++ .../Feature/Billing/SignupPlanPickerTest.php | 211 +++++++++++ .../Feature/Billing/SubscriptionGateTest.php | 105 ++++++ tests/Feature/DashboardTest.php | 51 +++ tests/Feature/TodosTest.php | 37 ++ 52 files changed, 3467 insertions(+), 47 deletions(-) create mode 100644 app/Http/Middleware/EnsureSubscribed.php create mode 100644 app/Http/Responses/RegisterResponse.php create mode 100644 app/Models/Organization.php create mode 100644 app/Models/Setting.php create mode 100644 app/OrganizationRole.php create mode 100644 config/cashier.php create mode 100644 config/plans.php create mode 100644 database/factories/OrganizationFactory.php create mode 100644 database/factories/SettingFactory.php create mode 100644 database/migrations/2026_09_27_023318_create_subscriptions_table.php create mode 100644 database/migrations/2026_09_27_023319_create_subscription_items_table.php create mode 100644 database/migrations/2026_09_27_023320_add_meter_id_to_subscription_items_table.php create mode 100644 database/migrations/2026_09_27_023321_add_meter_event_name_to_subscription_items_table.php create mode 100644 database/migrations/2026_09_27_023339_create_organizations_table.php create mode 100644 database/migrations/2026_09_27_023340_create_organization_user_table.php create mode 100644 database/migrations/2026_09_27_023341_add_current_organization_id_to_users_table.php create mode 100644 database/migrations/2026_09_27_023342_backfill_personal_organizations.php create mode 100644 database/migrations/2026_09_27_051310_create_settings_table.php create mode 100644 resources/views/layouts/marketing.blade.php create mode 100644 resources/views/pages/admin/⚡plan-pricing.blade.php create mode 100644 resources/views/pages/settings/⚡billing.blade.php create mode 100644 resources/views/pages/⚡pricing.blade.php create mode 100644 resources/views/pages/⚡subscription-confirmed.blade.php create mode 100644 tests/Feature/Billing/BillingSettingsTest.php create mode 100644 tests/Feature/Billing/CheckoutTest.php create mode 100644 tests/Feature/Billing/EntitlementTest.php create mode 100644 tests/Feature/Billing/PlanPricingTest.php create mode 100644 tests/Feature/Billing/SignupPlanPickerTest.php create mode 100644 tests/Feature/Billing/SubscriptionGateTest.php diff --git a/.env.example b/.env.example index 36ccc0c..84c468d 100644 --- a/.env.example +++ b/.env.example @@ -67,3 +67,16 @@ AWS_BUCKET= AWS_USE_PATH_STYLE_ENDPOINT=false VITE_APP_NAME="${APP_NAME}" + +# The path Cashier registers its Stripe webhook on, and which route group the +# CSRF exemption for it is matched against. +CASHIER_PATH=stripe + +STRIPE_KEY= +STRIPE_SECRET= +STRIPE_WEBHOOK_SECRET= + +# Stripe price ids for the plans defined in config/plans.php. A plan without a +# price is treated as unconfigured and is hidden from the pricing page. +BILLING_PLAN_PRO_PRICE= +BILLING_TRIAL_DAYS=14 diff --git a/.env.testing.example b/.env.testing.example index 91be2c5..f33e763 100644 --- a/.env.testing.example +++ b/.env.testing.example @@ -62,4 +62,16 @@ AWS_DEFAULT_REGION=us-east-1 AWS_BUCKET= AWS_USE_PATH_STYLE_ENDPOINT=false -VITE_APP_NAME="${APP_NAME}" \ No newline at end of file +VITE_APP_NAME="${APP_NAME}" + +CASHIER_PATH=stripe + +# Tests never reach Stripe, so the credentials are placeholders. The plan price +# is a dummy id that satisfies the "is this plan configured" check, letting a +# test assert on which plans the pricing page offers. +STRIPE_KEY=pk_test_placeholder +STRIPE_SECRET=sk_test_placeholder +STRIPE_WEBHOOK_SECRET=whsec_placeholder + +BILLING_PLAN_PRO_PRICE=price_test_placeholder +BILLING_TRIAL_DAYS=14 diff --git a/app/Actions/Fortify/CreateNewUser.php b/app/Actions/Fortify/CreateNewUser.php index 3c7c00c..2c073c8 100644 --- a/app/Actions/Fortify/CreateNewUser.php +++ b/app/Actions/Fortify/CreateNewUser.php @@ -4,8 +4,10 @@ namespace App\Actions\Fortify; use App\Concerns\PasswordValidationRules; use App\Concerns\ProfileValidationRules; +use App\Models\Organization; use App\Models\User; use Illuminate\Support\Facades\Validator; +use Illuminate\Validation\Rule; use Laravel\Fortify\Contracts\CreatesNewUsers; class CreateNewUser implements CreatesNewUsers @@ -22,6 +24,7 @@ class CreateNewUser implements CreatesNewUsers Validator::make($input, [ ...$this->profileRules(), 'password' => $this->passwordRules(), + ...$this->planRules(), ])->validate(); return User::create([ @@ -30,4 +33,26 @@ class CreateNewUser implements CreatesNewUsers 'password' => $input['password'], ]); } + + /** + * Get the validation rules for the chosen plan. + * + * The plan is only required when there is something configured to buy. This + * keeps registration working on a deployment that has not set a Stripe + * price yet, which would otherwise leave nobody able to create an account. + * + * @return array> + */ + protected function planRules(): array + { + $plans = array_keys(Organization::availablePlans()); + + if ($plans === []) { + return []; + } + + return [ + 'plan' => ['required', Rule::in($plans)], + ]; + } } diff --git a/app/Http/Middleware/EnsureSubscribed.php b/app/Http/Middleware/EnsureSubscribed.php new file mode 100644 index 0000000..07e4a8d --- /dev/null +++ b/app/Http/Middleware/EnsureSubscribed.php @@ -0,0 +1,26 @@ +user()?->hasActiveSubscription() === true) { + return $next($request); + } + + return redirect()->route('pricing'); + } +} diff --git a/app/Http/Responses/RegisterResponse.php b/app/Http/Responses/RegisterResponse.php new file mode 100644 index 0000000..fe4f2dd --- /dev/null +++ b/app/Http/Responses/RegisterResponse.php @@ -0,0 +1,78 @@ +wantsJson()) { + return new JsonResponse('', 201); + } + + $plan = $request->input('plan'); + + // A plan is only required when at least one is configured. Without a + // Stripe price there is nothing to sell, so registration still succeeds + // and the pricing page explains that no plans are available rather than + // making the application impossible to sign up for. + if (! is_string($plan) || ! Organization::isAvailablePlan($plan)) { + return $this->defaultRedirect($request); + } + + $organization = $request->user()?->currentOrganization()->first(); + + if ($organization === null) { + return $this->defaultRedirect($request); + } + + try { + return $organization->checkoutForPlan($plan)->redirect(); + } catch (Throwable $e) { + // The account already exists by this point, so a Stripe outage must + // not turn a completed signup into an error page. Report it and fall + // back to the pricing page, where checkout can be retried. + report($e); + + $request->session()->flash( + 'billing.checkout_failed', + __('Your account was created, but we could not start checkout. Please try again to finish subscribing.'), + ); + + return redirect()->route('pricing'); + } + } + + /** + * Send the new account to the home route, as Fortify does by default. + */ + protected function defaultRedirect(Request $request): RedirectResponse + { + return redirect()->intended(Fortify::redirects('register')); + } +} diff --git a/app/Models/Organization.php b/app/Models/Organization.php new file mode 100644 index 0000000..b23ff90 --- /dev/null +++ b/app/Models/Organization.php @@ -0,0 +1,273 @@ + */ + use Billable, HasFactory; + + /** + * Get the attributes that should be cast. + * + * @return array + */ + protected function casts(): array + { + return [ + 'personal_workspace' => 'boolean', + 'lifetime_access' => 'boolean', + 'trial_ends_at' => 'datetime', + ]; + } + + /** + * @return BelongsToMany + */ + public function users(): BelongsToMany + { + return $this->belongsToMany(User::class) + ->withPivot('role') + ->withTimestamps(); + } + + /** + * Get the subscription type that Cashier stores this organization's + * subscriptions under. + */ + public function subscriptionType(): string + { + $type = config('plans.subscription_type'); + + return is_string($type) ? $type : 'default'; + } + + /** + * Get the organization's subscription, if it has one. + */ + public function currentSubscription(): ?Subscription + { + return $this->subscription($this->subscriptionType()); + } + + /** + * Determine whether the organization has perpetual access and therefore + * never needs to subscribe. Set for accounts that predate subscriptions. + */ + public function hasLifetimeAccess(): bool + { + return $this->lifetime_access; + } + + /** + * Determine whether the organization may use the application, either + * because it has an active subscription, is trialing, is within a + * cancellation grace period, or was grandfathered in. + * + * This reads the local subscription rows, so it never calls Stripe. + */ + public function isEntitled(): bool + { + return $this->hasLifetimeAccess() || $this->subscribed($this->subscriptionType()); + } + + /** + * Get the plan the organization is currently subscribed to. + * + * @return array{name: string, price: string, interval: string, amount: int}|null + */ + public function currentPlan(): ?array + { + $price = $this->currentSubscription()?->stripe_price; + + if ($price === null) { + return null; + } + + foreach ($this->availablePlans() as $plan) { + if ($plan['price'] === $price) { + return $plan; + } + } + + return null; + } + + /** + * Get the plans that are ready to be sold, that is, the ones with a Stripe + * price configured. + * + * The amount is what the plan is advertised at on the pricing and signup + * pages. It lives in the settings table rather than the configuration + * because an administrator can change it, while the Stripe price id it is + * sold against cannot be swapped once subscribers exist. + * + * @return array + */ + public static function availablePlans(): array + { + $plans = config('plans.plans'); + + if (! is_array($plans)) { + return []; + } + + $available = []; + + foreach ($plans as $key => $plan) { + $price = is_array($plan) ? ($plan['price'] ?? null) : null; + + if (is_string($price) && $price !== '') { + $available[$key] = [ + 'name' => is_string($plan['name'] ?? null) ? $plan['name'] : (string) $key, + 'price' => $price, + 'interval' => is_string($plan['interval'] ?? null) ? $plan['interval'] : 'month', + 'amount' => static::planAmount((string) $key), + ]; + } + } + + return $available; + } + + /** + * Get the amount, in minor units, that the given plan is advertised at. + */ + public static function planAmount(string $key): int + { + return Setting::amount(Setting::planAmountKey($key), static::defaultPlanAmount()); + } + + /** + * Get the amount a plan falls back to when it has no stored amount, which + * is the conventional price for a single-product plan. + */ + protected static function defaultPlanAmount(): int + { + return 1000; + } + + /** + * Format an amount, in minor units, as a price for display. + */ + public static function formatAmount(int $amount): string + { + $value = $amount / 100; + + $formatted = Number::currency($value, in: config('cashier.currency')); + + if ($formatted !== false) { + return $formatted; + } + + // Number::currency() returns false for a currency intl does not + // recognise, so fall back to a plain number rather than rendering a + // blank price next to the plan. + return number_format($value, 2); + } + + /** + * Determine whether the given plan key is configured and can be purchased. + */ + public static function isAvailablePlan(string $key): bool + { + return array_key_exists($key, static::availablePlans()); + } + + /** + * Get the trial to grant a new subscription, in days. + * + * Stripe rejects a Checkout trial shorter than 48 hours, so a configured + * value below that is reported as no trial at all rather than sent and + * failed. + */ + public static function trialDays(): int + { + $days = config('plans.trial_days'); + + return is_int($days) && $days >= 2 ? $days : 0; + } + + /** + * Get the options used for a Checkout session, so that starting a + * subscription from the pricing page and from signup behave identically. + * + * @return array + */ + public static function checkoutOptions(): array + { + return [ + 'success_url' => route('subscription.confirmed', [ + 'session_id' => '{CHECKOUT_SESSION_ID}', + ]), + 'cancel_url' => route('pricing'), + 'allow_promotion_codes' => true, + ]; + } + + /** + * Start a Checkout session for the given plan key. + * + * @throws HttpException if the plan is not configured + */ + public function checkoutForPlan(string $plan): Checkout + { + $price = static::availablePlans()[$plan]['price'] ?? null; + + if ($price === null) { + abort(422, 'That plan is not available.'); + } + + $builder = $this->newSubscription($this->subscriptionType(), $price); + + if (static::trialDays() > 0) { + $builder = $builder->trialDays(static::trialDays()); + } + + return $builder->checkout(static::checkoutOptions()); + } + + /** + * Determine whether the user holds the given role in this organization. + */ + public function userHasRole(User $user, OrganizationRole $role): bool + { + return $this->users() + ->where('users.id', $user->id) + ->wherePivot('role', $role->value) + ->exists(); + } +} diff --git a/app/Models/Setting.php b/app/Models/Setting.php new file mode 100644 index 0000000..73e28fa --- /dev/null +++ b/app/Models/Setting.php @@ -0,0 +1,77 @@ + */ + use HasFactory; + + /** + * The setting key holding the advertised amount, in minor units, of the + * given plan. + */ + public static function planAmountKey(string $plan): string + { + return "plans.{$plan}.amount"; + } + + /** + * Get a setting's value, falling back to the given default when the + * setting is absent or blank. + */ + public static function get(string $key, ?string $default = null): ?string + { + $value = static::query()->where('key', $key)->value('value'); + + return $value === null || $value === '' ? $default : $value; + } + + /** + * Get a setting's value as an integer amount in minor units. + * + * A value that is not a valid amount is treated as unset rather than shown + * as zero, so a bad edit cannot silently advertise a free plan. + */ + public static function amount(string $key, int $default): int + { + $value = static::get($key); + + return is_numeric($value) && (int) $value >= 0 ? (int) $value : $default; + } + + /** + * Create or update a setting's value. + */ + public static function put(string $key, string $value): void + { + static::query()->updateOrCreate(['key' => $key], ['value' => $value]); + } + + /** + * Convert a price typed in major units, such as "12.5", into the minor + * units amounts are stored in. + * + * The value is split as a string rather than multiplied, so that a price + * with cents is not subject to floating point drift. + */ + public static function toMinorUnits(string $amount): int + { + [$whole, $fraction] = array_pad(explode('.', str_replace(',', '.', trim($amount)), 2), 2, ''); + + $fraction = substr(str_pad($fraction, 2, '0'), 0, 2); + + return (int) $whole * 100 + (int) $fraction; + } +} diff --git a/app/Models/User.php b/app/Models/User.php index f8f3fd1..e18c1b6 100644 --- a/app/Models/User.php +++ b/app/Models/User.php @@ -3,10 +3,13 @@ namespace App\Models; // use Illuminate\Contracts\Auth\MustVerifyEmail; +use App\OrganizationRole; use Database\Factories\UserFactory; use Illuminate\Database\Eloquent\Attributes\Fillable; use Illuminate\Database\Eloquent\Attributes\Hidden; use Illuminate\Database\Eloquent\Factories\HasFactory; +use Illuminate\Database\Eloquent\Relations\BelongsTo; +use Illuminate\Database\Eloquent\Relations\BelongsToMany; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; use Illuminate\Support\Carbon; @@ -17,6 +20,7 @@ use Laravel\Fortify\TwoFactorAuthenticatable; /** * @property int $id + * @property int|null $current_organization_id * @property string $name * @property string $email * @property Carbon|null $email_verified_at @@ -30,13 +34,68 @@ use Laravel\Fortify\TwoFactorAuthenticatable; * @property Carbon|null $created_at * @property Carbon|null $updated_at */ -#[Fillable(['name', 'email', 'password', 'is_admin', 'notes_limit'])] +#[Fillable(['name', 'email', 'password', 'is_admin', 'notes_limit', 'current_organization_id'])] #[Hidden(['password', 'two_factor_secret', 'two_factor_recovery_codes', 'remember_token'])] class User extends Authenticatable implements PasskeyUser { /** @use HasFactory */ use HasFactory, Notifiable, PasskeyAuthenticatable, TwoFactorAuthenticatable; + /** + * Give every new account a personal organization to hold its subscription. + * The entitlement check silently depends on one existing, so this happens + * here rather than being left to each place that creates a user. + */ + protected static function booted(): void + { + static::created(function (User $user): void { + $user->createPersonalOrganization(); + }); + } + + /** + * @return BelongsTo + */ + public function currentOrganization(): BelongsTo + { + return $this->belongsTo(Organization::class, 'current_organization_id'); + } + + /** + * @return BelongsToMany + */ + public function organizations(): BelongsToMany + { + return $this->belongsToMany(Organization::class) + ->withPivot('role') + ->withTimestamps(); + } + + /** + * Create a personal organization owned by this user and make it current. + */ + public function createPersonalOrganization(): Organization + { + $organization = Organization::create([ + 'name' => $this->name."'s Workspace", + 'personal_workspace' => true, + ]); + + $this->organizations()->attach($organization, ['role' => OrganizationRole::Owner->value]); + $this->forceFill(['current_organization_id' => $organization->id])->save(); + + return $organization; + } + + /** + * Determine whether the current organization may use the application. A + * user without one is never entitled. + */ + public function hasActiveSubscription(): bool + { + return $this->currentOrganization()->first()?->isEntitled() ?? false; + } + /** * Get the attributes that should be cast. * diff --git a/app/OrganizationRole.php b/app/OrganizationRole.php new file mode 100644 index 0000000..312d059 --- /dev/null +++ b/app/OrganizationRole.php @@ -0,0 +1,20 @@ + 'Owner', + self::Member => 'Member', + }; + } +} diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php index f1525e9..6476541 100644 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -2,11 +2,15 @@ namespace App\Providers; +use App\Http\Responses\RegisterResponse; +use App\Models\Organization; use Carbon\CarbonImmutable; use Illuminate\Support\Facades\Date; use Illuminate\Support\Facades\DB; use Illuminate\Support\ServiceProvider; use Illuminate\Validation\Rules\Password; +use Laravel\Cashier\Cashier; +use Laravel\Fortify\Contracts\RegisterResponse as RegisterResponseContract; class AppServiceProvider extends ServiceProvider { @@ -15,7 +19,19 @@ class AppServiceProvider extends ServiceProvider */ public function register(): void { - // + $this->registerFortifyResponses(); + } + + /** + * Swap Fortify's registration response for one that starts checkout for the + * plan the account signed up with. + */ + protected function registerFortifyResponses(): void + { + $this->app->singleton( + RegisterResponseContract::class, + RegisterResponse::class, + ); } /** @@ -24,6 +40,16 @@ class AppServiceProvider extends ServiceProvider public function boot(): void { $this->configureDefaults(); + $this->configureCashier(); + } + + /** + * Make organizations, rather than users, the Stripe customer. This also + * determines the foreign key Cashier uses on the subscriptions table. + */ + protected function configureCashier(): void + { + Cashier::useCustomerModel(Organization::class); } /** diff --git a/bootstrap/app.php b/bootstrap/app.php index 1085719..fbac45e 100644 --- a/bootstrap/app.php +++ b/bootstrap/app.php @@ -1,5 +1,6 @@ withMiddleware(function (Middleware $middleware): void { - // + $middleware->alias([ + 'subscribed' => EnsureSubscribed::class, + ]); + + // Stripe posts to the Cashier webhook with no session and no CSRF + // token, so the path is exempted. "stripe" must match + // config('cashier.path'), which CASHIER_PATH can change; keep the two + // in step if the path is ever customized. + $middleware->validateCsrfTokens(except: [ + 'stripe/*', + ]); }) ->withExceptions(function (Exceptions $exceptions): void { $exceptions->shouldRenderJsonWhen( diff --git a/composer.json b/composer.json index 8f94ecb..1f36143 100644 --- a/composer.json +++ b/composer.json @@ -10,6 +10,7 @@ "license": "MIT", "require": { "php": "^8.3", + "laravel/cashier": "^16.8", "laravel/chisel": "^0.1.0", "laravel/fortify": "^1.37.2", "laravel/framework": "^13.17", @@ -114,4 +115,4 @@ }, "minimum-stability": "stable", "prefer-stable": true -} \ No newline at end of file +} diff --git a/composer.lock b/composer.lock index 7acfe06..ed8e46d 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "c892d5d289ab6ad60404f0e6ba800167", + "content-hash": "5df77883928ac298be1ce9e985cedf12", "packages": [ { "name": "bacon/bacon-qr-code", @@ -1212,6 +1212,95 @@ ], "time": "2026-08-24T17:13:02+00:00" }, + { + "name": "laravel/cashier", + "version": "v16.8.0", + "source": { + "type": "git", + "url": "https://github.com/laravel/cashier-stripe.git", + "reference": "3741d81d0e2b7ca8de52c2f9a272d30edfa741b9" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/laravel/cashier-stripe/zipball/3741d81d0e2b7ca8de52c2f9a272d30edfa741b9", + "reference": "3741d81d0e2b7ca8de52c2f9a272d30edfa741b9", + "shasum": "" + }, + "require": { + "ext-json": "*", + "illuminate/console": "^10.0|^11.0|^12.0|^13.0", + "illuminate/contracts": "^10.0|^11.0|^12.0|^13.0", + "illuminate/database": "^10.0|^11.0|^12.0|^13.0", + "illuminate/http": "^10.0|^11.0|^12.0|^13.0", + "illuminate/log": "^10.0|^11.0|^12.0|^13.0", + "illuminate/notifications": "^10.0|^11.0|^12.0|^13.0", + "illuminate/pagination": "^10.0|^11.0|^12.0|^13.0", + "illuminate/routing": "^10.0|^11.0|^12.0|^13.0", + "illuminate/support": "^10.0|^11.0|^12.0|^13.0", + "illuminate/view": "^10.0|^11.0|^12.0|^13.0", + "moneyphp/money": "^4.0", + "nesbot/carbon": "^2.0|^3.0", + "php": "^8.1", + "stripe/stripe-php": "^17.4|^18.0|^19.0|^20.0|^21.0", + "symfony/console": "^6.0|^7.0|^8.0", + "symfony/http-kernel": "^6.0|^7.0|^8.0", + "symfony/polyfill-intl-icu": "^1.22.1", + "symfony/polyfill-php84": "^1.32" + }, + "require-dev": { + "dompdf/dompdf": "^2.0|^3.0", + "orchestra/testbench": "^8.36|^9.15|^10.8|^11.0", + "phpstan/phpstan": "^1.10", + "spatie/laravel-ray": "^1.40" + }, + "suggest": { + "dompdf/dompdf": "Required when generating and downloading invoice PDF's using Dompdf (^2.0|^3.0).", + "ext-intl": "Allows for more locales besides the default \"en\" when formatting money values.", + "spatie/laravel-pdf": "Required when generating and downloading invoice PDF's using Cashier's LaravelPdfInvoiceRenderer." + }, + "type": "library", + "extra": { + "laravel": { + "providers": [ + "Laravel\\Cashier\\CashierServiceProvider" + ] + }, + "branch-alias": { + "dev-master": "16.x-dev" + } + }, + "autoload": { + "psr-4": { + "Laravel\\Cashier\\": "src/", + "Laravel\\Cashier\\Database\\Factories\\": "database/factories/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Taylor Otwell", + "email": "taylor@laravel.com" + }, + { + "name": "Dries Vints", + "email": "dries@laravel.com" + } + ], + "description": "Laravel Cashier provides an expressive, fluent interface to Stripe's subscription billing services.", + "keywords": [ + "billing", + "laravel", + "stripe" + ], + "support": { + "issues": "https://github.com/laravel/cashier/issues", + "source": "https://github.com/laravel/cashier" + }, + "time": "2026-09-01T13:29:00+00:00" + }, { "name": "laravel/chisel", "version": "v0.1.1", @@ -2575,6 +2664,96 @@ ], "time": "2026-09-14T19:27:16+00:00" }, + { + "name": "moneyphp/money", + "version": "v4.9.0", + "source": { + "type": "git", + "url": "https://github.com/moneyphp/money.git", + "reference": "d49ee625c6ba79b9d7a228ce153b02fc1032152b" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/moneyphp/money/zipball/d49ee625c6ba79b9d7a228ce153b02fc1032152b", + "reference": "d49ee625c6ba79b9d7a228ce153b02fc1032152b", + "shasum": "" + }, + "require": { + "ext-bcmath": "*", + "ext-filter": "*", + "ext-json": "*", + "php": "~8.1.0 || ~8.2.0 || ~8.3.0 || ~8.4.0 || ~8.5.0" + }, + "require-dev": { + "cache/taggable-cache": "^1.1.0", + "doctrine/coding-standard": "^12.0", + "doctrine/instantiator": "^1.5.0 || ^2.0", + "ext-gmp": "*", + "ext-intl": "*", + "florianv/exchanger": "^2.8.1", + "florianv/swap": "^4.3.0", + "moneyphp/crypto-currencies": "^1.1.0", + "moneyphp/iso-currencies": "^3.4", + "php-http/message": "^1.16.0", + "php-http/mock-client": "^1.6.0", + "phpbench/phpbench": "^1.2.5", + "phpstan/extension-installer": "^1.4", + "phpstan/phpstan": "^2.1.9", + "phpstan/phpstan-phpunit": "^2.0", + "phpunit/phpunit": "^10.5.9", + "psr/cache": "^1.0.1 || ^2.0 || ^3.0", + "ticketswap/phpstan-error-formatter": "^1.1" + }, + "suggest": { + "ext-gmp": "Calculate without integer limits", + "ext-intl": "Format Money objects with intl", + "florianv/exchanger": "Exchange rates library for PHP", + "florianv/swap": "Exchange rates library for PHP", + "psr/cache-implementation": "Used for Currency caching" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.x-dev" + } + }, + "autoload": { + "psr-4": { + "Money\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Mathias Verraes", + "email": "mathias@verraes.net", + "homepage": "http://verraes.net" + }, + { + "name": "Márk Sági-Kazár", + "email": "mark.sagikazar@gmail.com" + }, + { + "name": "Frederik Bosch", + "email": "f.bosch@genkgo.nl" + } + ], + "description": "PHP implementation of Fowler's Money pattern", + "homepage": "http://moneyphp.org", + "keywords": [ + "Value Object", + "money", + "vo" + ], + "support": { + "issues": "https://github.com/moneyphp/money/issues", + "source": "https://github.com/moneyphp/money/tree/v4.9.0" + }, + "time": "2026-05-04T20:23:15+00:00" + }, { "name": "monolog/monolog", "version": "3.12.0", @@ -4345,6 +4524,68 @@ ], "time": "2026-09-12T19:02:49+00:00" }, + { + "name": "stripe/stripe-php", + "version": "v21.3.2", + "source": { + "type": "git", + "url": "https://github.com/stripe/stripe-php.git", + "reference": "0d8b075e1a97d15c5324353a5277d0ea686ea525" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/stripe/stripe-php/zipball/0d8b075e1a97d15c5324353a5277d0ea686ea525", + "reference": "0d8b075e1a97d15c5324353a5277d0ea686ea525", + "shasum": "" + }, + "require": { + "ext-curl": "*", + "ext-json": "*", + "ext-mbstring": "*", + "php": ">=7.2.0" + }, + "require-dev": { + "friendsofphp/php-cs-fixer": "3.94.0", + "phpstan/phpstan": "^1.2", + "phpunit/phpunit": "^8.0 || ^9.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.0-dev" + } + }, + "autoload": { + "files": [ + "lib/version_check.php" + ], + "psr-4": { + "Stripe\\": "lib/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Stripe and contributors", + "homepage": "https://github.com/stripe/stripe-php/contributors" + } + ], + "description": "Stripe PHP Library", + "homepage": "https://stripe.com/", + "keywords": [ + "api", + "payment processing", + "stripe" + ], + "support": { + "issues": "https://github.com/stripe/stripe-php/issues", + "source": "https://github.com/stripe/stripe-php/tree/v21.3.2" + }, + "time": "2026-09-09T20:40:43+00:00" + }, { "name": "symfony/clock", "version": "v8.1.0", @@ -5499,6 +5740,94 @@ ], "time": "2026-07-28T08:25:59+00:00" }, + { + "name": "symfony/polyfill-intl-icu", + "version": "v1.38.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-intl-icu.git", + "reference": "445c90e341fccda10311019cf82ff73bb7343945" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-intl-icu/zipball/445c90e341fccda10311019cf82ff73bb7343945", + "reference": "445c90e341fccda10311019cf82ff73bb7343945", + "shasum": "" + }, + "require": { + "php": ">=7.2" + }, + "suggest": { + "ext-intl": "For best performance and support of other locales than \"en\"" + }, + "type": "library", + "extra": { + "thanks": { + "url": "https://github.com/symfony/polyfill", + "name": "symfony/polyfill" + } + }, + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Intl\\Icu\\": "" + }, + "classmap": [ + "Resources/stubs" + ], + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill for intl's ICU-related data and classes", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "icu", + "intl", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https://github.com/symfony/polyfill-intl-icu/tree/v1.38.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2026-05-25T11:52:53+00:00" + }, { "name": "symfony/polyfill-intl-idn", "version": "v1.42.0", diff --git a/config/cashier.php b/config/cashier.php new file mode 100644 index 0000000..574e2ca --- /dev/null +++ b/config/cashier.php @@ -0,0 +1,130 @@ + env('STRIPE_KEY'), + + 'secret' => env('STRIPE_SECRET'), + + /* + |-------------------------------------------------------------------------- + | Cashier Path + |-------------------------------------------------------------------------- + | + | This is the base URI path where Cashier's views, such as the payment + | verification screen, will be available from. You're free to tweak + | this path according to your preferences and application design. + | + */ + + 'path' => env('CASHIER_PATH', 'stripe'), + + /* + |-------------------------------------------------------------------------- + | Stripe Webhooks + |-------------------------------------------------------------------------- + | + | Your Stripe webhook secret is used to prevent unauthorized requests to + | your Stripe webhook handling controllers. The tolerance setting will + | check the drift between the current time and the signed request's. + | + */ + + 'webhook' => [ + 'secret' => env('STRIPE_WEBHOOK_SECRET'), + 'tolerance' => env('STRIPE_WEBHOOK_TOLERANCE', 300), + 'events' => WebhookCommand::DEFAULT_EVENTS, + ], + + /* + |-------------------------------------------------------------------------- + | Currency + |-------------------------------------------------------------------------- + | + | This is the default currency that will be used when generating charges + | from your application. Of course, you are welcome to use any of the + | various world currencies that are currently supported via Stripe. + | + */ + + 'currency' => env('CASHIER_CURRENCY', 'usd'), + + /* + |-------------------------------------------------------------------------- + | Currency Locale + |-------------------------------------------------------------------------- + | + | This is the default locale in which your money values are formatted in + | for display. To utilize other locales besides the default en locale + | verify you have the "intl" PHP extension installed on the system. + | + */ + + 'currency_locale' => env('CASHIER_CURRENCY_LOCALE', 'en'), + + /* + |-------------------------------------------------------------------------- + | Payment Confirmation Notification + |-------------------------------------------------------------------------- + | + | If this setting is enabled, Cashier will automatically notify customers + | whose payments require additional verification. You should listen to + | Stripe's webhooks in order for this feature to function correctly. + | + */ + + 'payment_notification' => env('CASHIER_PAYMENT_NOTIFICATION'), + + /* + |-------------------------------------------------------------------------- + | Invoice Settings + |-------------------------------------------------------------------------- + | + | The following options determine how Cashier invoices are converted from + | HTML into PDFs. You're free to change the options based on the needs + | of your application or your preferences regarding invoice styling. + | + */ + + 'invoices' => [ + // Supported: DompdfInvoiceRenderer::class, LaravelPdfInvoiceRenderer::class + 'renderer' => env('CASHIER_INVOICE_RENDERER', DompdfInvoiceRenderer::class), + + 'options' => [ + // Supported: 'letter', 'legal', 'A4' + 'paper' => env('CASHIER_PAPER', 'letter'), + + 'remote_enabled' => env('CASHIER_REMOTE_ENABLED', false), + ], + ], + + /* + |-------------------------------------------------------------------------- + | Stripe Logger + |-------------------------------------------------------------------------- + | + | This setting defines which logging channel will be used by the Stripe + | library to write log messages. You are free to specify any of your + | logging channels listed inside the "logging" configuration file. + | + */ + + 'logger' => env('CASHIER_LOGGER'), + +]; diff --git a/config/plans.php b/config/plans.php new file mode 100644 index 0000000..c5952d5 --- /dev/null +++ b/config/plans.php @@ -0,0 +1,53 @@ + 'default', + + /* + |-------------------------------------------------------------------------- + | Free Trial + |-------------------------------------------------------------------------- + | + | The number of trial days granted to new subscribers. Stripe requires a + | Checkout trial to be at least 48 hours, so anything below two is + | effectively ignored. Set to 0 to charge immediately on signup. + | + */ + + 'trial_days' => (int) env('BILLING_TRIAL_DAYS', 14), + + /* + |-------------------------------------------------------------------------- + | Plans + |-------------------------------------------------------------------------- + | + | Each plan needs the Stripe price id of the product you created in the + | Stripe dashboard. Plans without a price are treated as unconfigured and + | are hidden from the pricing page, so a half-finished deployment shows + | nothing rather than a broken checkout. + | + | Supported: "name", "price" and "interval". + | + */ + + 'plans' => [ + 'pro' => [ + 'name' => 'Pro', + 'price' => env('BILLING_PLAN_PRO_PRICE'), + 'interval' => 'month', + ], + ], + +]; diff --git a/database/factories/OrganizationFactory.php b/database/factories/OrganizationFactory.php new file mode 100644 index 0000000..56f1b87 --- /dev/null +++ b/database/factories/OrganizationFactory.php @@ -0,0 +1,59 @@ + + */ +class OrganizationFactory extends Factory +{ + /** + * Define the model's default state. + * + * @return array + */ + public function definition(): array + { + return [ + 'name' => fake()->unique()->company(), + 'personal_workspace' => false, + 'lifetime_access' => false, + ]; + } + + /** + * Indicate that the organization is a single user's personal workspace. + */ + public function personal(): static + { + return $this->state(fn (array $attributes) => [ + 'personal_workspace' => true, + ]); + } + + /** + * Give the organization perpetual access, as granted to accounts that + * predate subscriptions. + */ + public function withLifetimeAccess(): static + { + return $this->state(fn (array $attributes) => [ + 'lifetime_access' => true, + ]); + } + + /** + * Add the given user to the organization with the given role. + */ + public function withMember(User $user, OrganizationRole $role = OrganizationRole::Owner): static + { + return $this->afterCreating(function (Organization $organization) use ($user, $role): void { + $organization->users()->attach($user, ['role' => $role->value]); + }); + } +} diff --git a/database/factories/SettingFactory.php b/database/factories/SettingFactory.php new file mode 100644 index 0000000..32d1098 --- /dev/null +++ b/database/factories/SettingFactory.php @@ -0,0 +1,25 @@ + + */ +class SettingFactory extends Factory +{ + /** + * Define the model's default state. + * + * @return array + */ + public function definition(): array + { + return [ + 'key' => 'setting.'.fake()->unique()->word(), + 'value' => fake()->word(), + ]; + } +} diff --git a/database/factories/UserFactory.php b/database/factories/UserFactory.php index dacf80b..6312ff5 100644 --- a/database/factories/UserFactory.php +++ b/database/factories/UserFactory.php @@ -3,9 +3,13 @@ namespace Database\Factories; use App\Models\User; +use Illuminate\Database\Eloquent\Collection; use Illuminate\Database\Eloquent\Factories\Factory; +use Illuminate\Database\Eloquent\Model; +use Illuminate\Support\Collection as SupportCollection; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Str; +use Laravel\Cashier\Subscription; /** * @extends Factory @@ -17,6 +21,14 @@ class UserFactory extends Factory */ protected static ?string $password; + /** + * Whether created users are given an active subscription. + * + * A factory user defaults to being entitled so that tests can focus on the + * behaviour they are covering. Call unsubscribed() to opt out. + */ + protected bool $subscribed = true; + /** * Define the model's default state. * @@ -36,6 +48,43 @@ class UserFactory extends Factory ]; } + /** + * Create the model and, unless opted out, give it an active subscription on + * the personal organization the model's created hook just made. + * + * The flag is read here rather than in an afterCreating callback because + * afterCreating() hands back a new factory instance, so a closure registered + * there would close over a copy that unsubscribed() never reaches. + * + * @param array $attributes + * @return Collection|User + */ + public function create($attributes = [], ?Model $parent = null): Collection|User + { + $result = parent::create($attributes, $parent); + + if (! $this->subscribed) { + return $result; + } + + $users = $result instanceof SupportCollection ? $result : collect([$result]); + + $users->each(fn (User $user) => $this->subscribe($user)); + + return $result; + } + + /** + * Indicate that the model does not have an active subscription, as a newly + * registered account that has not been through checkout. + */ + public function unsubscribed(): static + { + $this->subscribed = false; + + return $this; + } + /** * Indicate that the model's email address should be unverified. */ @@ -77,4 +126,18 @@ class UserFactory extends Factory 'two_factor_confirmed_at' => now(), ]); } + + /** + * Attach an active subscription to the user's current organization. + */ + protected function subscribe(User $user): void + { + $organization = $user->currentOrganization()->first(); + + if ($organization === null) { + return; + } + + Subscription::factory()->create(['organization_id' => $organization->id]); + } } diff --git a/database/migrations/2026_09_27_023318_create_subscriptions_table.php b/database/migrations/2026_09_27_023318_create_subscriptions_table.php new file mode 100644 index 0000000..44adaf5 --- /dev/null +++ b/database/migrations/2026_09_27_023318_create_subscriptions_table.php @@ -0,0 +1,41 @@ +id(); + + // Cashier resolves the owner foreign key from the customer model + // (Subscription::owner()), which is App\Models\Organization here + // rather than App\Models\User. + $table->foreignId('organization_id'); + $table->string('type'); + $table->string('stripe_id')->unique(); + $table->string('stripe_status'); + $table->string('stripe_price')->nullable(); + $table->integer('quantity')->nullable(); + $table->timestamp('trial_ends_at')->nullable(); + $table->timestamp('ends_at')->nullable(); + $table->timestamps(); + + $table->index(['organization_id', 'stripe_status']); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::dropIfExists('subscriptions'); + } +}; diff --git a/database/migrations/2026_09_27_023319_create_subscription_items_table.php b/database/migrations/2026_09_27_023319_create_subscription_items_table.php new file mode 100644 index 0000000..420e23f --- /dev/null +++ b/database/migrations/2026_09_27_023319_create_subscription_items_table.php @@ -0,0 +1,34 @@ +id(); + $table->foreignId('subscription_id'); + $table->string('stripe_id')->unique(); + $table->string('stripe_product'); + $table->string('stripe_price'); + $table->integer('quantity')->nullable(); + $table->timestamps(); + + $table->index(['subscription_id', 'stripe_price']); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::dropIfExists('subscription_items'); + } +}; diff --git a/database/migrations/2026_09_27_023320_add_meter_id_to_subscription_items_table.php b/database/migrations/2026_09_27_023320_add_meter_id_to_subscription_items_table.php new file mode 100644 index 0000000..033bb82 --- /dev/null +++ b/database/migrations/2026_09_27_023320_add_meter_id_to_subscription_items_table.php @@ -0,0 +1,28 @@ +string('meter_id')->nullable()->after('stripe_price'); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::table('subscription_items', function (Blueprint $table) { + $table->dropColumn('meter_id'); + }); + } +}; diff --git a/database/migrations/2026_09_27_023321_add_meter_event_name_to_subscription_items_table.php b/database/migrations/2026_09_27_023321_add_meter_event_name_to_subscription_items_table.php new file mode 100644 index 0000000..b157b3a --- /dev/null +++ b/database/migrations/2026_09_27_023321_add_meter_event_name_to_subscription_items_table.php @@ -0,0 +1,28 @@ +string('meter_event_name')->nullable()->after('quantity'); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::table('subscription_items', function (Blueprint $table) { + $table->dropColumn('meter_event_name'); + }); + } +}; diff --git a/database/migrations/2026_09_27_023339_create_organizations_table.php b/database/migrations/2026_09_27_023339_create_organizations_table.php new file mode 100644 index 0000000..a4f5f00 --- /dev/null +++ b/database/migrations/2026_09_27_023339_create_organizations_table.php @@ -0,0 +1,41 @@ +id(); + $table->string('name'); + $table->boolean('personal_workspace')->default(true); + $table->boolean('lifetime_access')->default(false); + + // The remaining columns replace Cashier's published + // create_customer_columns migration, which targets the users table. + // This model is the Cashier customer, so they belong here. The + // binary collation keeps Stripe's case-sensitive ids intact on MySQL. + $table->string('stripe_id')->nullable()->charset('utf8')->collation('utf8_bin'); + $table->string('pm_type')->nullable(); + $table->string('pm_last_four', 4)->nullable(); + $table->timestamp('trial_ends_at')->nullable(); + $table->timestamps(); + + $table->index('stripe_id'); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::dropIfExists('organizations'); + } +}; diff --git a/database/migrations/2026_09_27_023340_create_organization_user_table.php b/database/migrations/2026_09_27_023340_create_organization_user_table.php new file mode 100644 index 0000000..2eec0f1 --- /dev/null +++ b/database/migrations/2026_09_27_023340_create_organization_user_table.php @@ -0,0 +1,32 @@ +id(); + $table->foreignId('organization_id')->constrained()->cascadeOnDelete(); + $table->foreignId('user_id')->constrained()->cascadeOnDelete(); + $table->string('role')->default('owner'); + $table->timestamps(); + + $table->unique(['organization_id', 'user_id']); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::dropIfExists('organization_user'); + } +}; diff --git a/database/migrations/2026_09_27_023341_add_current_organization_id_to_users_table.php b/database/migrations/2026_09_27_023341_add_current_organization_id_to_users_table.php new file mode 100644 index 0000000..52879aa --- /dev/null +++ b/database/migrations/2026_09_27_023341_add_current_organization_id_to_users_table.php @@ -0,0 +1,32 @@ +foreignId('current_organization_id') + ->nullable() + ->after('id') + ->constrained('organizations') + ->nullOnDelete(); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::table('users', function (Blueprint $table) { + $table->dropConstrainedForeignId('current_organization_id'); + }); + } +}; diff --git a/database/migrations/2026_09_27_023342_backfill_personal_organizations.php b/database/migrations/2026_09_27_023342_backfill_personal_organizations.php new file mode 100644 index 0000000..a20a7cd --- /dev/null +++ b/database/migrations/2026_09_27_023342_backfill_personal_organizations.php @@ -0,0 +1,54 @@ +select(['id', 'name', 'current_organization_id']) + ->whereNull('current_organization_id') + ->orderBy('id') + ->each(function (object $user): void { + $organizationId = DB::table('organizations')->insertGetId([ + 'name' => $user->name."'s Workspace", + 'personal_workspace' => true, + 'lifetime_access' => true, + 'created_at' => now(), + 'updated_at' => now(), + ]); + + DB::table('organization_user')->insert([ + 'organization_id' => $organizationId, + 'user_id' => $user->id, + 'role' => 'owner', + 'created_at' => now(), + 'updated_at' => now(), + ]); + + DB::table('users') + ->where('id', $user->id) + ->update(['current_organization_id' => $organizationId]); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + if (Schema::hasTable('organizations')) { + DB::table('organizations')->where('personal_workspace', true)->delete(); + } + } +}; diff --git a/database/migrations/2026_09_27_051310_create_settings_table.php b/database/migrations/2026_09_27_051310_create_settings_table.php new file mode 100644 index 0000000..eeed7d8 --- /dev/null +++ b/database/migrations/2026_09_27_051310_create_settings_table.php @@ -0,0 +1,40 @@ +id(); + $table->string('key')->unique(); + $table->text('value')->nullable(); + $table->timestamps(); + }); + + // The Pro plan's advertised amount starts as whole units, matching the + // conventional price, so the pages that show it have something sensible + // to render before an administrator has ever edited it. + DB::table('settings')->insert([ + 'key' => 'plans.pro.amount', + 'value' => '1000', + 'created_at' => now(), + 'updated_at' => now(), + ]); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::dropIfExists('settings'); + } +}; diff --git a/database/seeders/BaseDatabaseSeeder.php b/database/seeders/BaseDatabaseSeeder.php index 043d241..ea4a100 100644 --- a/database/seeders/BaseDatabaseSeeder.php +++ b/database/seeders/BaseDatabaseSeeder.php @@ -12,7 +12,7 @@ class BaseDatabaseSeeder extends Seeder */ public function run(): void { - User::updateOrCreate( + $admin = User::updateOrCreate( ['email' => config('admin.email')], [ 'name' => config('admin.name'), @@ -20,5 +20,12 @@ class BaseDatabaseSeeder extends Seeder 'is_admin' => true, ], ); + + // Grandfather the admin so a fresh install is usable before any Stripe + // price is configured. The organization itself is created by the + // model's created hook. + $admin->currentOrganization()->first()?->forceFill([ + 'lifetime_access' => true, + ])->save(); } } diff --git a/phpunit.xml b/phpunit.xml index 0b0adaf..937f85a 100644 --- a/phpunit.xml +++ b/phpunit.xml @@ -33,5 +33,11 @@ + + + + + + diff --git a/resources/views/layouts/app/sidebar.blade.php b/resources/views/layouts/app/sidebar.blade.php index 3f26c46..9f46877 100644 --- a/resources/views/layouts/app/sidebar.blade.php +++ b/resources/views/layouts/app/sidebar.blade.php @@ -28,6 +28,9 @@ {{ __('Notes limits') }} + + {{ __('Plan pricing') }} + @endif diff --git a/resources/views/layouts/marketing.blade.php b/resources/views/layouts/marketing.blade.php new file mode 100644 index 0000000..285cf4f --- /dev/null +++ b/resources/views/layouts/marketing.blade.php @@ -0,0 +1,44 @@ + + + + @include('partials.head') + + +
+
+
+ + + {{ config('app.name', 'Laravel') }} + + + +
+
+ +
+ {{ $slot }} +
+
+ + @persist('toast') + + + + @endpersist + + @fluxScripts + + diff --git a/resources/views/pages/admin/⚡plan-pricing.blade.php b/resources/views/pages/admin/⚡plan-pricing.blade.php new file mode 100644 index 0000000..320f000 --- /dev/null +++ b/resources/views/pages/admin/⚡plan-pricing.blade.php @@ -0,0 +1,133 @@ +user()->isAdmin()) { + abort(403); + } + + $this->amounts = $this->plans() + ->mapWithKeys(fn (array $plan): array => [ + $plan['key'] => self::formatMajorUnits(Organization::planAmount($plan['key'])), + ]) + ->all(); + } + + /** + * The price of each configured plan, keyed by plan, in major units so that + * it can be edited and shown as an administrator typed it. + * + * @var array + */ + public array $amounts = []; + + /** + * Get every configured plan, including any that cannot be sold yet, so a + * price can be set before the Stripe price is in place. + * + * @return Collection + */ + #[Computed] + public function plans(): Collection + { + $configured = config('plans.plans'); + $available = Organization::availablePlans(); + + if (! is_array($configured)) { + return collect(); + } + + return collect($configured)->map(function ($plan, string $key) use ($available): array { + $plan = is_array($plan) ? $plan : []; + + return [ + 'key' => $key, + 'name' => is_string($plan['name'] ?? null) ? $plan['name'] : $key, + 'interval' => is_string($plan['interval'] ?? null) ? $plan['interval'] : 'month', + 'purchasable' => array_key_exists($key, $available), + ]; + }); + } + + public function saveAmounts(): void + { + $validated = $this->validate([ + 'amounts' => ['required', 'array'], + 'amounts.*' => ['required', 'numeric', 'min:0', 'decimal:0,2'], + ]); + + foreach ($validated['amounts'] as $key => $amount) { + Setting::put(Setting::planAmountKey($key), (string) Setting::toMinorUnits((string) $amount)); + } + + unset($this->plans); + + Flux::toast(variant: 'success', text: __('Plan pricing updated.')); + } + + /** + * Render a stored amount, in minor units, as the major units an + * administrator edits it in. + */ + protected static function formatMajorUnits(int $amount): string + { + return intdiv($amount, 100).'.'.str_pad((string) ($amount % 100), 2, '0', STR_PAD_LEFT); + } +}; ?> + +
+
+ {{ __('Plan pricing') }} + {{ __('Set the price shown for each plan on the pricing page and at signup.') }} +
+ + @if ($this->plans->isEmpty()) + {{ __('No plans are configured.') }} + @else +
+ + @foreach ($this->plans as $plan) + + {{ $plan['name'] }} + + + + + {{ __('Billed every :interval.', ['interval' => $plan['interval']]) }} + + @unless ($plan['purchasable']) + {{ __('This plan is not on sale yet, because it has no Stripe price configured.') }} + @endunless + + + + + @endforeach + + +
+ + {{ __('Save') }} + +
+
+ @endif +
diff --git a/resources/views/pages/auth/register.blade.php b/resources/views/pages/auth/register.blade.php index 30ddb89..10a36cc 100644 --- a/resources/views/pages/auth/register.blade.php +++ b/resources/views/pages/auth/register.blade.php @@ -1,12 +1,82 @@ +@php + use App\Models\Organization; + + $plans = Organization::availablePlans(); + $trialDays = Organization::trialDays(); +@endphp +
- +
@csrf + + @if ($plans !== []) + {{-- Plan picker. Plain inputs rather than flux:radio because this form + is server rendered and does not load Livewire's UI runtime. --}} +
+ + {{ __('Choose your plan') }} + + + @foreach ($plans as $key => $plan) + + @endforeach + + @error('plan') + + @enderror +
+ @endif + - {{ __('Create account') }} + {{ $plans !== [] ? __('Continue to payment') : __('Create account') }}
diff --git a/resources/views/pages/settings/layout.blade.php b/resources/views/pages/settings/layout.blade.php index 3a65247..b509b9d 100644 --- a/resources/views/pages/settings/layout.blade.php +++ b/resources/views/pages/settings/layout.blade.php @@ -4,6 +4,7 @@ {{ __('Profile') }} {{ __('Security') }} {{ __('Appearance') }} + {{ __('Billing') }} diff --git a/resources/views/pages/settings/⚡billing.blade.php b/resources/views/pages/settings/⚡billing.blade.php new file mode 100644 index 0000000..29cba89 --- /dev/null +++ b/resources/views/pages/settings/⚡billing.blade.php @@ -0,0 +1,151 @@ +currentOrganization()->first(); + } + + /** + * Get the current subscription, if there is one. + */ + #[Computed] + public function subscription() + { + return $this->organization?->currentSubscription(); + } + + /** + * Get the plan the organization is on, falling back to a description built + * from the raw Stripe status for states that are not a plan. + * + * @return array{name: string, price: string, interval: string}|null + */ + #[Computed] + public function plan(): ?array + { + return $this->organization?->currentPlan(); + } + + /** + * Get a human readable label for the subscription status. + */ + #[Computed] + public function status(): string + { + $subscription = $this->subscription; + + if ($subscription === null) { + return __('No subscription'); + } + + return match ($subscription->stripe_status) { + 'active' => __('Active'), + 'trialing' => __('Free trial'), + 'past_due' => __('Past due'), + 'canceled' => __('Canceled'), + 'unpaid' => __('Unpaid'), + 'incomplete' => __('Incomplete'), + 'incomplete_expired' => __('Expired'), + default => ucfirst((string) $subscription->stripe_status), + }; + } + + /** + * Describe the state of the current subscription in a single sentence. + */ + #[Computed] + public function summary(): string + { + $subscription = $this->subscription; + + if ($this->organization?->hasLifetimeAccess() === true) { + return __('Lifetime access. No subscription is required.'); + } + + if ($subscription === null) { + return __('You are on the free plan and cannot use your workspace until you subscribe.'); + } + + if ($subscription->ends_at !== null && $subscription->ends_at->isFuture()) { + return __('Your plan stays active until :date. Subscribe again to keep your access after that.', [ + 'date' => $subscription->ends_at->toFormattedDateString(), + ]); + } + + if ($subscription->trial_ends_at !== null && $subscription->trial_ends_at->isFuture()) { + return __('Your free trial ends on :date.', [ + 'date' => $subscription->trial_ends_at->toFormattedDateString(), + ]); + } + + return __('Your subscription renews automatically.'); + } + + /** + * Determine whether the customer portal button should be shown. The portal + * only exists once Stripe knows about the organization as a customer. + */ + #[Computed] + public function canManagePaymentMethod(): bool + { + return $this->organization?->hasStripeId() === true; + } +}; ?> + +
+ @include('partials.settings-heading') + + {{ __('Billing settings') }} + + +
+ +
+
+ {{ $this->plan['name'] ?? __('Free') }} + + + {{ $this->status }} + +
+ + + {{ $this->organization?->isEntitled() ? __('Active') : __('Inactive') }} + +
+ + {{ $this->summary }} +
+ +
+ @if ($this->organization?->isEntitled() !== true) + + {{ __('Subscribe') }} + + @endif + + @if ($this->canManagePaymentMethod) +
+ @csrf + + + {{ __('Manage payment method') }} + +
+ @endif +
+
+
+
diff --git a/resources/views/pages/⚡dashboard.blade.php b/resources/views/pages/⚡dashboard.blade.php index a9617b7..bd317e3 100644 --- a/resources/views/pages/⚡dashboard.blade.php +++ b/resources/views/pages/⚡dashboard.blade.php @@ -266,10 +266,10 @@ new #[Title('Dashboard')] class extends Component { $this->todoForUser($todoId); - $ids = $this->filteredTodoQuery()->priority()->pluck('id')->all(); + $ids = $this->orderedTodoIds; $currentIndex = array_search($todoId, $ids, true); - if ($currentIndex === false || $ids === []) { + if ($currentIndex === false) { return; } @@ -279,40 +279,57 @@ new #[Title('Dashboard')] class extends Component return; } - $this->reorderTodo($todoId, $ids, $target); + $this->reorderTodo($todoId, $target); } public function handleSort(int $todoId, int $position): void { $this->todoForUser($todoId); - $ids = $this->filteredTodoQuery()->priority()->pluck('id')->all(); - $currentIndex = array_search($todoId, $ids, true); - - if ($currentIndex === false || $ids === []) { - return; - } - $offset = ($this->todos->currentPage() - 1) * self::PER_PAGE; - $this->reorderTodo($todoId, $ids, $offset + $position); + $this->reorderTodo($todoId, $offset + $position); } /** - * @param array $ids + * Move a todo to the given index of the currently visible order. The + * reordered todos are written back into the slots they already occupy in + * the user's full priority order, so reordering under an active filter + * permutes the visible todos without renumbering them from zero and + * colliding with the todos the filter hides. */ - private function reorderTodo(int $todoId, array $ids, int $newIndex): void + private function reorderTodo(int $todoId, int $newIndex): void { - unset($ids[array_search($todoId, $ids, true)]); - $ids = array_values($ids); + $visibleIds = $this->orderedTodoIds; + $currentIndex = array_search($todoId, $visibleIds, true); - $newIndex = max(0, min($newIndex, count($ids))); + if ($currentIndex === false) { + return; + } - array_splice($ids, $newIndex, 0, $todoId); + $newIndex = max(0, min($newIndex, count($visibleIds) - 1)); + + if ($newIndex === $currentIndex) { + return; + } + + $visibleOrder = $visibleIds; + unset($visibleOrder[$currentIndex]); + array_splice($visibleOrder, $newIndex, 0, $todoId); + + $ids = Todo::query()->forUser(auth()->id())->priority()->pluck('id')->all(); + + $slots = array_keys(array_intersect($ids, $visibleIds)); + + foreach ($slots as $visibleSlot => $slot) { + $ids[$slot] = $visibleOrder[$visibleSlot]; + } foreach ($ids as $position => $id) { Todo::query()->forUser(auth()->id())->whereKey($id)->update(['position' => $position]); } + + unset($this->todos, $this->orderedTodoIds); } /** @@ -493,7 +510,7 @@ new #[Title('Dashboard')] class extends Component @forelse ($this->todos as $todo) -
+
diff --git a/resources/views/pages/⚡folders.blade.php b/resources/views/pages/⚡folders.blade.php index 6e99927..54e2954 100644 --- a/resources/views/pages/⚡folders.blade.php +++ b/resources/views/pages/⚡folders.blade.php @@ -472,7 +472,7 @@ new #[Title('Folders')] class extends Component :class="dragging && 'opacity-40'" @dragstart="dragging = true; window.__mtFolderDrag = { folderId: {{ $node['folder']->id }} }; $dispatch('folder-drag-start')" @dragend="dragging = false; window.__mtFolderDrag = null; $dispatch('folder-drag-end')" - :title="__('Drag to move this folder')" + title="{{ __('Drag to move this folder') }}" data-test="drag-folder-{{ $node['folder']->id }}" > diff --git a/resources/views/pages/⚡pricing.blade.php b/resources/views/pages/⚡pricing.blade.php new file mode 100644 index 0000000..f0227b5 --- /dev/null +++ b/resources/views/pages/⚡pricing.blade.php @@ -0,0 +1,163 @@ +hasActiveSubscription() ?? false; + } + + /** + * Get the plans that are configured and available to purchase. + * + * @return array + */ + #[Computed] + public function plans(): array + { + return Organization::availablePlans(); + } + + /** + * Start a Stripe Checkout session for the given plan. + */ + public function subscribe(string $plan): RedirectResponse + { + abort_if(Auth::guest(), 403); + + $this->plan = $plan; + + $this->validate([ + 'plan' => ['required', Rule::in(array_keys(Organization::availablePlans()))], + ], [ + 'plan.in' => __('That plan is not available.'), + ]); + + $organization = Auth::user()->currentOrganization()->first(); + + abort_if($organization === null, 403); + + return $organization->checkoutForPlan($this->plan)->redirect(); + } +}; ?> + +
+
+ {{ __('Plans and pricing') }} + + @if (session('billing.checkout_failed')) + + {{ session('billing.checkout_failed') }} + + @endif + + @if ($this->isSubscribed) + + {{ __('Your workspace already has an active subscription.') }} + @else + + {{ __('Subscribe to unlock your todos, folders and notes.') }} + + @endif +
+ + @if ($this->isSubscribed) + + {{ __('Manage your subscription') }} + + @elseif (count($this->plans) === 0) + + {{ __('No plans are available right now. Please check back soon.') }} + + @else +
+ @foreach ($this->plans as $key => $plan) + +
+ {{ $plan['name'] }} + +

+ {{ Organization::formatAmount($plan['amount']) }} +

+ + + {{ __('Billed every :interval', ['interval' => $plan['interval']]) }} + +
+ +
    +
  • + + {{ __('Unlimited todos and folders') }} +
  • +
  • + + {{ __('Notes on every todo') }} +
  • +
  • + + {{ __('Status, due dates and priorities') }} +
  • +
+ + @auth + + {{ $this->trialDays() > 0 + ? __('Start :days-day free trial', ['days' => $this->trialDays()]) + : __('Subscribe') }} + + @else + + {{ __('Create an account') }} + + @endauth +
+ @endforeach +
+ + @if ($this->trialDays() > 0) + + {{ __('Your trial ends after :days days and you can cancel at any time.', ['days' => $this->trialDays()]) }} + + @endif + @endif + + @error('plan') + + @enderror +
diff --git a/resources/views/pages/⚡subscription-confirmed.blade.php b/resources/views/pages/⚡subscription-confirmed.blade.php new file mode 100644 index 0000000..36fe909 --- /dev/null +++ b/resources/views/pages/⚡subscription-confirmed.blade.php @@ -0,0 +1,96 @@ +hasSubscription) { + $this->redirect(route('dashboard'), navigate: true); + + return; + } + + $this->waitedSeconds += 1; + + if ($this->waitedSeconds >= self::TIMEOUT_SECONDS) { + $this->timedOut = true; + } + } + + #[Computed] + public function hasSubscription(): bool + { + return Auth::user()?->hasActiveSubscription() ?? false; + } +}; ?> + +
+ @if ($this->hasSubscription) + + + {{ __('Your subscription is active') }} + + {{ __('Welcome aboard. Taking you to your todos now.') }} + + + {{ __('Go to my todos') }} + + @elseif ($timedOut) + + + {{ __('Still confirming your payment') }} + + + {{ __('Your payment went through, but we have not heard from Stripe yet. Your access will turn on automatically as soon as it does.') }} + + + + {{ __('Back to plans') }} + + @else +
+ + {{ __('Confirming your subscription') }} + + {{ __('This usually takes a few seconds. Please do not close this page.') }} + @endif +
diff --git a/resources/views/pages/⚡todos.blade.php b/resources/views/pages/⚡todos.blade.php index bac1d37..2134d9f 100644 --- a/resources/views/pages/⚡todos.blade.php +++ b/resources/views/pages/⚡todos.blade.php @@ -248,7 +248,7 @@ new #[Title('Todos')] class extends Component $ids = $this->orderedTodoIds; $currentIndex = array_search($todoId, $ids, true); - if ($currentIndex === false || $ids === []) { + if ($currentIndex === false) { return; } @@ -258,38 +258,55 @@ new #[Title('Todos')] class extends Component return; } - $this->reorderTodo($todoId, $ids, $target); + $this->reorderTodo($todoId, $target); } public function handleSort(int $todoId, int $position): void { $this->todoForUser($todoId); - $ids = $this->orderedTodoIds; - $currentIndex = array_search($todoId, $ids, true); - - if ($currentIndex === false || $ids === []) { - return; - } - - $this->reorderTodo($todoId, $ids, $position); + $this->reorderTodo($todoId, $position); } /** - * @param array $ids + * Move a todo to the given index of the currently visible order. The + * reordered todos are written back into the slots they already occupy in + * the user's full priority order, so reordering under an active filter + * permutes the visible todos without renumbering them from zero and + * colliding with the todos the filter hides. */ - private function reorderTodo(int $todoId, array $ids, int $newIndex): void + private function reorderTodo(int $todoId, int $newIndex): void { - unset($ids[array_search($todoId, $ids, true)]); - $ids = array_values($ids); + $visibleIds = $this->orderedTodoIds; + $currentIndex = array_search($todoId, $visibleIds, true); - $newIndex = max(0, min($newIndex, count($ids))); + if ($currentIndex === false) { + return; + } - array_splice($ids, $newIndex, 0, $todoId); + $newIndex = max(0, min($newIndex, count($visibleIds) - 1)); + + if ($newIndex === $currentIndex) { + return; + } + + $visibleOrder = $visibleIds; + unset($visibleOrder[$currentIndex]); + array_splice($visibleOrder, $newIndex, 0, $todoId); + + $ids = Todo::query()->forUser(auth()->id())->priority()->pluck('id')->all(); + + $slots = array_keys(array_intersect($ids, $visibleIds)); + + foreach ($slots as $visibleSlot => $slot) { + $ids[$slot] = $visibleOrder[$visibleSlot]; + } foreach ($ids as $position => $id) { Todo::query()->forUser(auth()->id())->whereKey($id)->update(['position' => $position]); } + + unset($this->todos, $this->orderedTodoIds); } /** @@ -407,7 +424,7 @@ new #[Title('Todos')] class extends Component @forelse ($this->todos as $todo) -
+
diff --git a/routes/settings.php b/routes/settings.php index fda5fa6..494036f 100644 --- a/routes/settings.php +++ b/routes/settings.php @@ -1,11 +1,28 @@ group(function () { Route::redirect('settings', 'settings/profile'); Route::livewire('settings/profile', 'pages::settings.profile')->name('profile.edit'); + + // Deliberately outside the "subscribed" middleware group so that a lapsed + // subscriber can still manage their plan, or subscribe again. + Route::livewire('settings/billing', 'pages::settings.billing')->name('billing.edit'); + + Route::post('settings/billing/portal', function (): RedirectResponse { + $organization = request()->user()?->currentOrganization()->first(); + + // The Stripe customer portal only exists once an organization has been + // created as a Stripe customer, which happens on the first checkout. + if ($organization === null || ! $organization->hasStripeId()) { + return redirect()->route('billing.edit'); + } + + return redirect()->to($organization->billingPortalUrl(route('billing.edit'))); + })->name('billing.portal'); }); Route::middleware(['auth', 'verified'])->group(function () { diff --git a/routes/web.php b/routes/web.php index c12ed0a..2f55078 100644 --- a/routes/web.php +++ b/routes/web.php @@ -4,11 +4,20 @@ use Illuminate\Support\Facades\Route; Route::view('/', 'welcome')->name('home'); -Route::middleware(['auth', 'verified'])->group(function () { +// Reachable by signed-in users who have not subscribed yet, so it is kept +// outside the "subscribed" middleware group below. +Route::livewire('pricing', 'pages::pricing')->name('pricing'); + +Route::middleware(['auth'])->group(function () { + Route::livewire('subscription/confirmed', 'pages::subscription-confirmed')->name('subscription.confirmed'); +}); + +Route::middleware(['auth', 'verified', 'subscribed'])->group(function () { Route::livewire('dashboard', 'pages::dashboard')->name('dashboard'); Route::livewire('todos', 'pages::todos')->name('todos'); Route::livewire('folders', 'pages::folders')->name('folders'); Route::livewire('admin/notes-limits', 'pages::admin.notes-limits')->name('admin.notes-limits'); + Route::livewire('admin/plan-pricing', 'pages::admin.plan-pricing')->name('admin.plan-pricing'); }); require __DIR__.'/settings.php'; diff --git a/tests/Feature/Auth/RegistrationTest.php b/tests/Feature/Auth/RegistrationTest.php index f9c6493..0c24922 100644 --- a/tests/Feature/Auth/RegistrationTest.php +++ b/tests/Feature/Auth/RegistrationTest.php @@ -1,5 +1,6 @@ 'test@example.com', 'password' => 'password', 'password_confirmation' => 'password', + 'plan' => 'pro', ]); $response->assertSessionHasNoErrors() - ->assertRedirect(route('dashboard', absolute: false)); + ->assertRedirect(route('pricing', absolute: false)); $this->assertAuthenticated(); }); + +test('new users are given a personal organization to subscribe with', function () { + $this->post(route('register.store'), [ + 'name' => 'John Doe', + 'email' => 'test@example.com', + 'password' => 'password', + 'password_confirmation' => 'password', + 'plan' => 'pro', + ]); + + $user = User::where('email', 'test@example.com')->sole(); + + expect($user->currentOrganization()->first()) + ->not->toBeNull() + ->personal_workspace->toBeTrue() + ->lifetime_access->toBeFalse(); +}); + +test('a new user is sent to pricing because they have not subscribed', function () { + $this->post(route('register.store'), [ + 'name' => 'John Doe', + 'email' => 'test@example.com', + 'password' => 'password', + 'password_confirmation' => 'password', + 'plan' => 'pro', + ]); + + $user = User::where('email', 'test@example.com')->sole(); + + expect($user->hasActiveSubscription())->toBeFalse(); + + $this->actingAs($user)->get(route('dashboard'))->assertRedirect(route('pricing')); +}); diff --git a/tests/Feature/BaseDataSeederTest.php b/tests/Feature/BaseDataSeederTest.php index 83ffde0..0c54f50 100644 --- a/tests/Feature/BaseDataSeederTest.php +++ b/tests/Feature/BaseDataSeederTest.php @@ -22,3 +22,15 @@ test('base data seeding is idempotent', function () { expect(User::where('email', 'admin@example.com')->count())->toBe(1); }); + +test('the seeded admin is grandfathered so a fresh install works', function () { + seed(BaseDatabaseSeeder::class); + + $admin = User::where('email', 'admin@example.com')->firstOrFail(); + + expect($admin->currentOrganization()->first()) + ->not->toBeNull() + ->lifetime_access->toBeTrue(); + + expect($admin->hasActiveSubscription())->toBeTrue(); +}); diff --git a/tests/Feature/Billing/BillingSettingsTest.php b/tests/Feature/Billing/BillingSettingsTest.php new file mode 100644 index 0000000..8cd197d --- /dev/null +++ b/tests/Feature/Billing/BillingSettingsTest.php @@ -0,0 +1,140 @@ +actingAs(User::factory()->unsubscribed()->create()); + + Livewire::test('pages::settings.billing') + ->assertSee('Free') + ->assertSee('No subscription') + ->assertSee('Subscribe') + ->assertOk(); +}); + +test('a subscribed user sees their plan and status', function () { + $user = User::factory()->create(); + + $user->currentOrganization()->first()->subscriptions()->delete(); + Subscription::factory() + ->active() + ->withPrice('price_test_placeholder') + ->create(['organization_id' => $user->current_organization_id]); + + $this->actingAs($user); + + Livewire::test('pages::settings.billing') + ->assertSee('Pro') + ->assertSee('Active') + ->assertDontSee('Subscribe'); +}); + +test('a trialing user is told when the trial ends', function () { + $user = User::factory()->unsubscribed()->create(); + + Subscription::factory() + ->trialing(now()->addDays(5)) + ->create(['organization_id' => $user->current_organization_id]); + + $this->actingAs($user); + + Livewire::test('pages::settings.billing') + ->assertSee('Free trial') + ->assertSee('Your free trial ends on'); +}); + +test('a subscription that is set to cancel explains the access window', function () { + $user = User::factory()->unsubscribed()->create(); + + Subscription::factory()->create([ + 'organization_id' => $user->current_organization_id, + 'stripe_status' => 'canceled', + 'ends_at' => now()->addDays(10), + ]); + + $this->actingAs($user); + + Livewire::test('pages::settings.billing') + ->assertSee('Canceled') + ->assertSee('Your plan stays active until'); +}); + +test('a grandfathered user is told they never need to subscribe', function () { + $user = User::factory()->unsubscribed()->create(); + $user->currentOrganization()->first()->forceFill(['lifetime_access' => true])->save(); + + $this->actingAs($user); + + Livewire::test('pages::settings.billing') + ->assertSee('Lifetime access') + ->assertDontSee('Subscribe'); +}); + +test('the payment method button appears once the organization is a Stripe customer', function () { + $user = User::factory()->create(); + + $this->actingAs($user); + + Livewire::test('pages::settings.billing')->assertDontSee('Manage payment method'); + + $user->currentOrganization()->first()->forceFill(['stripe_id' => 'cus_123'])->save(); + + Livewire::test('pages::settings.billing')->assertSee('Manage payment method'); +}); + +test('the payment method button posts to the billing portal', function () { + $user = User::factory()->create(); + $user->currentOrganization()->first()->forceFill(['stripe_id' => 'cus_123'])->save(); + + $this->actingAs($user) + ->get(route('billing.edit')) + ->assertSee('action="'.route('billing.portal').'"', escape: false); +}); + +test('the billing portal falls back to billing settings without a Stripe customer', function () { + $this->actingAs(User::factory()->unsubscribed()->create()) + ->post(route('billing.portal')) + ->assertRedirect(route('billing.edit')); +}); + +test('a guest cannot reach the billing portal', function () { + $this->post(route('billing.portal'))->assertRedirect(route('login')); +}); + +test('billing is listed in the settings navigation', function () { + $this->actingAs(User::factory()->create()) + ->get(route('billing.edit')) + ->assertSee('data-test="billing-nav-link"', escape: false); +}); + +test('the confirmation page waits for the subscription to arrive', function () { + $this->actingAs(User::factory()->unsubscribed()->create()); + + Livewire::test('pages::subscription-confirmed') + ->assertSee('Confirming your subscription') + ->set('waitedSeconds', 29) + ->call('confirm') + ->assertSee('Still confirming your payment'); +}); + +test('the confirmation page moves on once the subscription lands', function () { + $user = User::factory()->unsubscribed()->create(); + + $this->actingAs($user); + + Livewire::test('pages::subscription-confirmed') + ->set('waitedSeconds', 29) + ->call('confirm') + ->assertSee('Still confirming your payment'); + + Subscription::factory()->active()->create([ + 'organization_id' => $user->current_organization_id, + ]); + + Livewire::test('pages::subscription-confirmed') + ->assertSee('Your subscription is active') + ->call('confirm') + ->assertRedirect(route('dashboard')); +}); diff --git a/tests/Feature/Billing/CheckoutTest.php b/tests/Feature/Billing/CheckoutTest.php new file mode 100644 index 0000000..e7eba4b --- /dev/null +++ b/tests/Feature/Billing/CheckoutTest.php @@ -0,0 +1,157 @@ +get(route('pricing'))->assertOk(); +}); + +test('a guest is asked to create an account rather than subscribe', function () { + Livewire::test('pages::pricing') + ->assertSee(route('register')) + ->assertDontSee('subscribe-', false); +}); + +test('a configured plan is offered with its trial', function () { + $this->actingAs(User::factory()->unsubscribed()->create()); + + Livewire::test('pages::pricing') + ->assertSee('Pro') + ->assertOk(); +}); + +test('a plan card shows the advertised price', function () { + Setting::put(Setting::planAmountKey('pro'), '1250'); + + $this->actingAs(User::factory()->unsubscribed()->create()); + + Livewire::test('pages::pricing') + ->assertOk() + ->assertSee('data-test="plan-pro-amount"', escape: false) + ->assertSee('$12.50'); +}); + +test('a plan without a price is hidden', function () { + config()->set('plans.plans', [ + 'pro' => ['name' => 'Pro', 'price' => null, 'interval' => 'month'], + ]); + + expect(Organization::availablePlans())->toBe([]); + + Livewire::test('pages::pricing') + ->assertSee('No plans are available'); +}); + +test('available plans fall back to a usable name and interval', function () { + config()->set('plans.plans', [ + 'mystery' => ['price' => 'price_123'], + ]); + + expect(Organization::availablePlans())->toBe([ + 'mystery' => ['name' => 'mystery', 'price' => 'price_123', 'interval' => 'month', 'amount' => 1000], + ]); +}); + +test('an unknown plan is not available', function () { + expect(Organization::isAvailablePlan('pro'))->toBeTrue() + ->and(Organization::isAvailablePlan('enterprise'))->toBeFalse(); +}); + +test('an already subscribed user is sent to manage their subscription instead', function () { + $this->actingAs(User::factory()->create()); + + Livewire::test('pages::pricing') + ->assertSee('Manage your subscription') + ->assertDontSee('Start 14-day free trial'); +}); + +test('a guest cannot start a subscription', function () { + Livewire::test('pages::pricing') + ->call('subscribe', 'pro') + ->assertForbidden(); +}); + +test('a plan that is not configured cannot be subscribed to', function () { + $this->actingAs(User::factory()->unsubscribed()->create()); + + Livewire::test('pages::pricing') + ->call('subscribe', 'enterprise') + ->assertHasErrors('plan'); +}); + +test('a plan removed from configuration cannot be subscribed to', function () { + $this->actingAs(User::factory()->unsubscribed()->create()); + + Livewire::test('pages::pricing')->assertOk(); + + config()->set('plans.plans', []); + + Livewire::test('pages::pricing') + ->call('subscribe', 'pro') + ->assertHasErrors('plan'); +}); + +test('a trial shorter than Stripe allows is treated as no trial', function () { + expect(Organization::trialDays())->toBe(14); + + config()->set('plans.trial_days', 1); + + expect(Organization::trialDays())->toBe(0); + + config()->set('plans.trial_days', 0); + + expect(Organization::trialDays())->toBe(0); +}); + +test('checkout options are shared by every entry point', function () { + expect(Organization::checkoutOptions()) + ->toHaveKey('success_url', route('subscription.confirmed', ['session_id' => '{CHECKOUT_SESSION_ID}'])) + ->toHaveKey('cancel_url', route('pricing')) + ->toHaveKey('allow_promotion_codes', true); +}); + +test('the trial length comes from configuration', function () { + config()->set('plans.trial_days', 0); + + $this->actingAs(User::factory()->unsubscribed()->create()); + + Livewire::test('pages::pricing') + ->assertSee('Subscribe') + ->assertDontSee('free trial'); +}); + +test('the current plan is resolved from the subscription price', function () { + $user = User::factory()->unsubscribed()->create(); + $organization = $user->currentOrganization()->first(); + + Subscription::factory() + ->active() + ->withPrice('price_test_placeholder') + ->create(['organization_id' => $organization->id]); + + expect($organization->refresh()->currentPlan())->toBe([ + 'name' => 'Pro', + 'price' => 'price_test_placeholder', + 'interval' => 'month', + 'amount' => 1000, + ]); +}); + +test('a subscription on an unknown price has no resolvable plan', function () { + $organization = Organization::factory()->create(); + + Subscription::factory() + ->active() + ->withPrice('price_legacy') + ->create(['organization_id' => $organization->id]); + + expect($organization->refresh()->currentPlan())->toBeNull(); +}); + +test('an organization with no subscription has no plan', function () { + expect(Organization::factory()->create()->currentPlan())->toBeNull(); +}); diff --git a/tests/Feature/Billing/EntitlementTest.php b/tests/Feature/Billing/EntitlementTest.php new file mode 100644 index 0000000..7e7cca1 --- /dev/null +++ b/tests/Feature/Billing/EntitlementTest.php @@ -0,0 +1,110 @@ +unsubscribed()->create(); + + $organization = $user->currentOrganization()->first(); + + expect($organization)->not->toBeNull() + ->and($organization->personal_workspace)->toBeTrue() + ->and($organization->lifetime_access)->toBeFalse() + ->and($organization->userHasRole($user, OrganizationRole::Owner))->toBeTrue(); +}); + +test('an active subscription entitles the user', function () { + $user = User::factory()->unsubscribed()->create(); + + expect($user->hasActiveSubscription())->toBeFalse(); + + Subscription::factory()->active()->create([ + 'organization_id' => $user->current_organization_id, + ]); + + expect($user->refresh()->hasActiveSubscription())->toBeTrue(); +}); + +test('a trialing subscription entitles the user', function () { + $user = User::factory()->unsubscribed()->create(); + + Subscription::factory()->trialing(now()->addDays(7))->create([ + 'organization_id' => $user->current_organization_id, + ]); + + expect($user->refresh()->hasActiveSubscription())->toBeTrue(); +}); + +test('a canceled subscription that has not lapsed yet still entitles the user', function () { + $user = User::factory()->unsubscribed()->create(); + + Subscription::factory()->create([ + 'organization_id' => $user->current_organization_id, + 'stripe_status' => 'canceled', + 'ends_at' => now()->addDays(14), + ]); + + expect($user->refresh()->hasActiveSubscription())->toBeTrue(); +}); + +test('a canceled subscription that has lapsed does not entitle the user', function () { + $user = User::factory()->unsubscribed()->create(); + + Subscription::factory()->create([ + 'organization_id' => $user->current_organization_id, + 'stripe_status' => 'canceled', + 'ends_at' => now()->subDay(), + ]); + + expect($user->refresh()->hasActiveSubscription())->toBeFalse(); +}); + +test('a past due subscription does not entitle the user', function () { + $user = User::factory()->unsubscribed()->create(); + + Subscription::factory()->pastDue()->create([ + 'organization_id' => $user->current_organization_id, + ]); + + expect($user->refresh()->hasActiveSubscription())->toBeFalse(); +}); + +test('a lifetime organization is entitled without any subscription', function () { + $organization = Organization::factory()->withLifetimeAccess()->create(); + + expect($organization->isEntitled())->toBeTrue() + ->and($organization->hasLifetimeAccess())->toBeTrue(); +}); + +test('an organization without a subscription is not entitled', function () { + $organization = Organization::factory()->create(); + + expect($organization->isEntitled())->toBeFalse(); +}); + +test('a user without a current organization is never entitled', function () { + $user = User::factory()->unsubscribed()->create(); + + $user->forceFill(['current_organization_id' => null])->save(); + + expect($user->refresh()->hasActiveSubscription())->toBeFalse(); +}); + +test('a subscription on another organization does not entitle the user', function () { + $user = User::factory()->unsubscribed()->create(); + $other = Organization::factory()->create(); + + Subscription::factory()->active()->create([ + 'organization_id' => $other->id, + ]); + + expect($user->refresh()->hasActiveSubscription())->toBeFalse(); +}); + +test('the factory user is entitled by default and unsubscribed opts out', function () { + expect(User::factory()->create()->hasActiveSubscription())->toBeTrue() + ->and(User::factory()->unsubscribed()->create()->hasActiveSubscription())->toBeFalse(); +}); diff --git a/tests/Feature/Billing/PlanPricingTest.php b/tests/Feature/Billing/PlanPricingTest.php new file mode 100644 index 0000000..4a3e4bc --- /dev/null +++ b/tests/Feature/Billing/PlanPricingTest.php @@ -0,0 +1,218 @@ +get(route('admin.plan-pricing')) + ->assertRedirect(route('login')); +}); + +test('non-admins cannot access the plan pricing page', function () { + $this->actingAs(User::factory()->create()); + + $this->get(route('admin.plan-pricing'))->assertForbidden(); +}); + +test('non-admins do not see the plan pricing navigation item', function () { + $this->actingAs(User::factory()->create()); + + $this->get(route('dashboard')) + ->assertOk() + ->assertDontSee('Plan pricing'); +}); + +test('admins see the plan pricing navigation item', function () { + $this->actingAs(User::factory()->asAdmin()->create()); + + $this->get(route('dashboard')) + ->assertOk() + ->assertSee('Plan pricing'); +}); + +test('admins can view the plan pricing page', function () { + $this->actingAs(User::factory()->asAdmin()->create()); + + $this->get(route('admin.plan-pricing'))->assertOk(); +}); + +test('the plan pricing page shows the current price for each configured plan', function () { + config()->set('plans.plans', [ + 'pro' => ['name' => 'Pro', 'price' => 'price_pro', 'interval' => 'month'], + 'team' => ['name' => 'Team', 'price' => 'price_team', 'interval' => 'year'], + ]); + + Setting::put(Setting::planAmountKey('pro'), '1250'); + Setting::put(Setting::planAmountKey('team'), '9900'); + + $this->actingAs(User::factory()->asAdmin()->create()); + + Livewire::test('pages::admin.plan-pricing') + ->assertOk() + ->assertSet('amounts.pro', '12.50') + ->assertSet('amounts.team', '99.00'); +}); + +test('the plan price field is pre-filled with the stored price', function () { + config()->set('plans.plans', [ + 'pro' => ['name' => 'Pro', 'price' => 'price_pro', 'interval' => 'month'], + ]); + + Setting::put(Setting::planAmountKey('pro'), '1250'); + + $this->actingAs(User::factory()->asAdmin()->create()); + + // A pre-filled field is what stops an administrator saving a blank price + // over a real one, so the value has to reach the rendered input. + expect(preg_replace('/\s+/', ' ', Livewire::test('pages::admin.plan-pricing')->html())) + ->toContain('value="12.50"'); +}); + +test('a plan without a Stripe price is still listed but marked as not on sale', function () { + config()->set('plans.plans', [ + 'pro' => ['name' => 'Pro', 'price' => null, 'interval' => 'month'], + ]); + + $this->actingAs(User::factory()->asAdmin()->create()); + + Livewire::test('pages::admin.plan-pricing') + ->assertOk() + ->assertSee('This plan is not on sale yet'); +}); + +test('a deployment with no plans configured says so', function () { + config()->set('plans.plans', []); + + $this->actingAs(User::factory()->asAdmin()->create()); + + Livewire::test('pages::admin.plan-pricing') + ->assertOk() + ->assertSee('No plans are configured'); +}); + +test('an admin can change the advertised price of a plan', function () { + config()->set('plans.plans', [ + 'pro' => ['name' => 'Pro', 'price' => 'price_pro', 'interval' => 'month'], + ]); + + $this->actingAs(User::factory()->asAdmin()->create()); + + Livewire::test('pages::admin.plan-pricing') + ->set('amounts.pro', '12.50') + ->call('saveAmounts') + ->assertHasNoErrors(); + + expect(Setting::get(Setting::planAmountKey('pro')))->toBe('1250') + ->and(Organization::planAmount('pro'))->toBe(1250); +}); + +test('an admin can give a plan away for free', function () { + config()->set('plans.plans', [ + 'pro' => ['name' => 'Pro', 'price' => 'price_pro', 'interval' => 'month'], + ]); + + $this->actingAs(User::factory()->asAdmin()->create()); + + Livewire::test('pages::admin.plan-pricing') + ->set('amounts.pro', '0') + ->call('saveAmounts') + ->assertHasNoErrors(); + + expect(Organization::planAmount('pro'))->toBe(0); +}); + +test('a price with cents is stored without floating point drift', function () { + config()->set('plans.plans', [ + 'pro' => ['name' => 'Pro', 'price' => 'price_pro', 'interval' => 'month'], + ]); + + $this->actingAs(User::factory()->asAdmin()->create()); + + Livewire::test('pages::admin.plan-pricing') + ->set('amounts.pro', '0.07') + ->call('saveAmounts') + ->assertHasNoErrors(); + + expect(Organization::planAmount('pro'))->toBe(7); +}); + +test('a negative price is rejected and the stored price is left alone', function () { + config()->set('plans.plans', [ + 'pro' => ['name' => 'Pro', 'price' => 'price_pro', 'interval' => 'month'], + ]); + + $this->actingAs(User::factory()->asAdmin()->create()); + + Livewire::test('pages::admin.plan-pricing') + ->set('amounts.pro', '-5') + ->call('saveAmounts') + ->assertHasErrors(['amounts.pro']); + + expect(Organization::planAmount('pro'))->toBe(1000); +}); + +test('a price with more than two decimal places is rejected', function () { + config()->set('plans.plans', [ + 'pro' => ['name' => 'Pro', 'price' => 'price_pro', 'interval' => 'month'], + ]); + + $this->actingAs(User::factory()->asAdmin()->create()); + + Livewire::test('pages::admin.plan-pricing') + ->set('amounts.pro', '1.234') + ->call('saveAmounts') + ->assertHasErrors(['amounts.pro']); +}); + +test('an emptied price is rejected rather than stored as a free plan', function () { + config()->set('plans.plans', [ + 'pro' => ['name' => 'Pro', 'price' => 'price_pro', 'interval' => 'month'], + ]); + + $this->actingAs(User::factory()->asAdmin()->create()); + + Livewire::test('pages::admin.plan-pricing') + ->set('amounts.pro', '') + ->call('saveAmounts') + ->assertHasErrors(['amounts.pro']); + + expect(Organization::planAmount('pro'))->toBe(1000); +}); + +test('a stored price that is not a number falls back to the default', function () { + config()->set('plans.plans', [ + 'pro' => ['name' => 'Pro', 'price' => 'price_pro', 'interval' => 'month'], + ]); + + Setting::put(Setting::planAmountKey('pro'), 'free'); + + expect(Organization::planAmount('pro'))->toBe(1000); +}); + +test('a plan with no stored price falls back to the default', function () { + config()->set('plans.plans', [ + 'pro' => ['name' => 'Pro', 'price' => 'price_pro', 'interval' => 'month'], + 'team' => ['name' => 'Team', 'price' => 'price_team', 'interval' => 'year'], + ]); + + Setting::put(Setting::planAmountKey('pro'), '2500'); + + expect(Organization::planAmount('pro'))->toBe(2500) + ->and(Organization::planAmount('team'))->toBe(1000); +}); + +test('the amount is formatted in the configured currency', function () { + expect(Organization::formatAmount(1250))->toBe('$12.50'); + + config()->set('cashier.currency', 'eur'); + + expect(Organization::formatAmount(1250))->toContain('12.50'); +}); + +test('an unrecognised currency falls back to a plain number rather than a blank price', function () { + config()->set('cashier.currency', 'x'); + + expect(Organization::formatAmount(1250))->toBe('12.50'); +}); diff --git a/tests/Feature/Billing/SignupPlanPickerTest.php b/tests/Feature/Billing/SignupPlanPickerTest.php new file mode 100644 index 0000000..fdc2f53 --- /dev/null +++ b/tests/Feature/Billing/SignupPlanPickerTest.php @@ -0,0 +1,211 @@ +skipUnlessFortifyHas(Features::registration()); +}); + +/** + * Get the response body with runs of whitespace collapsed to single spaces, so + * that assertions about attributes do not depend on Blade's indentation. + */ +function normalizedHtml($response): string +{ + return preg_replace('/\s+/', ' ', $response->getContent()); +} + +test('the signup form offers a plan picker', function () { + $this->get(route('register')) + ->assertOk() + ->assertSee('Choose your plan') + ->assertSee('value="pro"', escape: false) + ->assertSee('Free for 14 days, then billed every month') + ->assertSee('Continue to payment'); +}); + +test('the signup plan box shows the advertised price', function () { + $this->get(route('register')) + ->assertOk() + ->assertSee('data-test="register-plan-pro-amount"', escape: false) + ->assertSee('$10.00'); +}); + +test('the signup plan box shows a price changed by an administrator', function () { + Setting::put(Setting::planAmountKey('pro'), '1250'); + + $this->get(route('register')) + ->assertOk() + ->assertSee('$12.50') + ->assertDontSee('$10.00'); +}); + +test('each plan box shows its own price', function () { + config()->set('plans.plans', [ + 'pro' => ['name' => 'Pro', 'price' => 'price_pro', 'interval' => 'month'], + 'team' => ['name' => 'Team', 'price' => 'price_team', 'interval' => 'year'], + ]); + + Setting::put(Setting::planAmountKey('pro'), '1250'); + Setting::put(Setting::planAmountKey('team'), '9900'); + + $this->get(route('register')) + ->assertOk() + ->assertSee('$12.50') + ->assertSee('$99.00'); +}); + +test('the first plan is preselected', function () { + expect(normalizedHtml($this->get(route('register')))) + ->toContain('value="pro" checked'); +}); + +test('every configured plan gets an option', function () { + config()->set('plans.plans', [ + 'pro' => ['name' => 'Pro', 'price' => 'price_pro', 'interval' => 'month'], + 'team' => ['name' => 'Team', 'price' => 'price_team', 'interval' => 'year'], + ]); + + $this->get(route('register')) + ->assertSee('data-test="register-plan-pro"', escape: false) + ->assertSee('data-test="register-plan-team"', escape: false) + ->assertSee('billed every year'); +}); + +test('a plan is required when plans are configured', function () { + $this->post(route('register.store'), [ + 'name' => 'John Doe', + 'email' => 'test@example.com', + 'password' => 'password', + 'password_confirmation' => 'password', + ])->assertSessionHasErrors('plan'); + + expect(User::where('email', 'test@example.com')->exists())->toBeFalse(); +}); + +test('an unknown plan is rejected and no account is created', function () { + $this->post(route('register.store'), [ + 'name' => 'John Doe', + 'email' => 'test@example.com', + 'password' => 'password', + 'password_confirmation' => 'password', + 'plan' => 'enterprise', + ])->assertSessionHasErrors('plan'); + + expect(User::where('email', 'test@example.com')->exists())->toBeFalse(); +}); + +test('signing up with a plan creates the account and its organization', function () { + $this->post(route('register.store'), [ + 'name' => 'John Doe', + 'email' => 'test@example.com', + 'password' => 'password', + 'password_confirmation' => 'password', + 'plan' => 'pro', + ])->assertSessionHasNoErrors(); + + $user = User::where('email', 'test@example.com')->sole(); + + expect($user->currentOrganization()->first())->not->toBeNull() + ->personal_workspace->toBeTrue(); + + expect($user->hasActiveSubscription())->toBeFalse(); +}); + +test('a Stripe failure does not turn a completed signup into an error page', function () { + // Checkout calls Stripe, which is not reachable from the test suite, so + // this exercises the fallback: the account survives and the user is sent + // somewhere they can retry rather than shown a 500. + $response = $this->post(route('register.store'), [ + 'name' => 'John Doe', + 'email' => 'test@example.com', + 'password' => 'password', + 'password_confirmation' => 'password', + 'plan' => 'pro', + ]); + + $response->assertRedirect(route('pricing')); + $response->assertSessionHas('billing.checkout_failed'); + + $this->assertAuthenticated(); + expect(User::where('email', 'test@example.com')->exists())->toBeTrue(); +}); + +test('the fallback message is shown on the pricing page', function () { + $this->post(route('register.store'), [ + 'name' => 'John Doe', + 'email' => 'test@example.com', + 'password' => 'password', + 'password_confirmation' => 'password', + 'plan' => 'pro', + ]); + + $this->get(route('pricing')) + ->assertOk() + ->assertSee('we could not start checkout'); +}); + +test('signing up without a plan configured still works', function () { + config()->set('plans.plans', [ + 'pro' => ['name' => 'Pro', 'price' => null, 'interval' => 'month'], + ]); + + $this->get(route('register')) + ->assertOk() + ->assertDontSee('Choose your plan') + ->assertSee('Create account'); + + $this->post(route('register.store'), [ + 'name' => 'John Doe', + 'email' => 'test@example.com', + 'password' => 'password', + 'password_confirmation' => 'password', + ]) + ->assertSessionHasNoErrors() + ->assertRedirect(route('dashboard', absolute: false)); + + $this->assertAuthenticated(); +}); + +test('the chosen plan is remembered when validation fails', function () { + config()->set('plans.plans', [ + 'pro' => ['name' => 'Pro', 'price' => 'price_pro', 'interval' => 'month'], + 'team' => ['name' => 'Team', 'price' => 'price_team', 'interval' => 'year'], + ]); + + $this->post(route('register.store'), [ + 'name' => 'John Doe', + 'email' => 'not-an-email', + 'password' => 'password', + 'password_confirmation' => 'password', + 'plan' => 'team', + ])->assertSessionHasErrors('email'); + + expect(normalizedHtml($this->get(route('register')))) + ->toContain('value="team" checked'); +}); + +test('a json registration is unaffected by the plan picker', function () { + config()->set('plans.plans', []); + + $this->postJson(route('register.store'), [ + 'name' => 'John Doe', + 'email' => 'test@example.com', + 'password' => 'password', + 'password_confirmation' => 'password', + ])->assertCreated(); +}); + +test('the trial is not offered when it is shorter than Stripe allows', function () { + config()->set('plans.trial_days', 1); + + $this->get(route('register')) + ->assertOk() + ->assertSee('Billed every month') + ->assertDontSee('Free for 1 days'); + + expect(Organization::trialDays())->toBe(0); +}); diff --git a/tests/Feature/Billing/SubscriptionGateTest.php b/tests/Feature/Billing/SubscriptionGateTest.php new file mode 100644 index 0000000..9ac6fef --- /dev/null +++ b/tests/Feature/Billing/SubscriptionGateTest.php @@ -0,0 +1,105 @@ +get(route('dashboard'))->assertRedirect(route('login')); +}); + +test('an unsubscribed user is sent to pricing', function () { + $this->actingAs(User::factory()->unsubscribed()->create()) + ->get(route('dashboard')) + ->assertRedirect(route('pricing')); +}); + +test('an unsubscribed user cannot reach the other subscribed pages', function () { + $user = User::factory()->unsubscribed()->create(); + + foreach (['todos', 'folders', 'admin.notes-limits'] as $name) { + $this->actingAs($user) + ->get(route($name)) + ->assertRedirect(route('pricing')); + } +}); + +test('a subscribed user reaches the app', function () { + $this->actingAs(User::factory()->create()) + ->get(route('dashboard')) + ->assertOk(); +}); + +test('a grandfathered user reaches the app without a subscription', function () { + $user = User::factory()->unsubscribed()->create(); + + $user->currentOrganization()->first()->forceFill(['lifetime_access' => true])->save(); + + $this->actingAs($user) + ->get(route('dashboard')) + ->assertOk(); +}); + +test('a trialing user reaches the app', function () { + $user = User::factory()->unsubscribed()->create(); + + Subscription::factory()->trialing(now()->addDays(3))->create([ + 'organization_id' => $user->current_organization_id, + ]); + + $this->actingAs($user) + ->get(route('dashboard')) + ->assertOk(); +}); + +test('a user whose subscription lapsed is sent back to pricing', function () { + $user = User::factory()->unsubscribed()->create(); + + Subscription::factory()->create([ + 'organization_id' => $user->current_organization_id, + 'stripe_status' => 'canceled', + 'ends_at' => now()->subDay(), + ]); + + $this->actingAs($user) + ->get(route('dashboard')) + ->assertRedirect(route('pricing')); +}); + +test('billing settings stay reachable so a lapsed subscriber can resubscribe', function () { + $this->actingAs(User::factory()->unsubscribed()->create()) + ->get(route('billing.edit')) + ->assertOk(); +}); + +test('the other settings pages are not gated', function () { + $this->actingAs(User::factory()->unsubscribed()->create()) + ->get(route('profile.edit')) + ->assertOk(); +}); + +test('losing a subscription closes off the app on the next request', function () { + $user = User::factory()->create(); + + $this->actingAs($user)->get(route('dashboard'))->assertOk(); + + $organization = $user->currentOrganization()->first(); + $organization->forceFill(['lifetime_access' => false])->save(); + $organization->subscriptions()->delete(); + + $this->actingAs($user) + ->get(route('dashboard')) + ->assertRedirect(route('pricing')); +}); + +test('an organization that is not the current one does not grant access', function () { + $user = User::factory()->unsubscribed()->create(); + + Subscription::factory()->active()->create([ + 'organization_id' => Organization::factory()->create()->id, + ]); + + $this->actingAs($user) + ->get(route('dashboard')) + ->assertRedirect(route('pricing')); +}); diff --git a/tests/Feature/DashboardTest.php b/tests/Feature/DashboardTest.php index 92f6a6d..6f33822 100644 --- a/tests/Feature/DashboardTest.php +++ b/tests/Feature/DashboardTest.php @@ -607,6 +607,57 @@ test('dragging accounts for the pagination offset', function () { expect($todoTwelve->fresh()->position)->toBe(10); }); +test('the table re-renders in the new order after a drag', function () { + $user = User::factory()->create(); + $this->actingAs($user); + + $folder = Folder::factory()->for($user)->create(['name' => 'Work']); + + $first = Todo::factory()->recycle($user)->for($folder)->create(['description' => 'First todo', 'position' => 0]); + $second = Todo::factory()->recycle($user)->for($folder)->create(['description' => 'Second todo', 'position' => 1]); + $third = Todo::factory()->recycle($user)->for($folder)->create(['description' => 'Third todo', 'position' => 2]); + + Livewire::test('pages::dashboard') + ->assertSeeInOrder(['First todo', 'Second todo', 'Third todo']) + ->call('handleSort', $first->id, 2) + ->assertSeeInOrder(['Second todo', 'Third todo', 'First todo']); +}); + +test('the table re-renders in the new order after moving a todo', function () { + $user = User::factory()->create(); + $this->actingAs($user); + + $folder = Folder::factory()->for($user)->create(['name' => 'Work']); + + $first = Todo::factory()->recycle($user)->for($folder)->create(['description' => 'First todo', 'position' => 0]); + Todo::factory()->recycle($user)->for($folder)->create(['description' => 'Second todo', 'position' => 1]); + + Livewire::test('pages::dashboard') + ->assertSeeInOrder(['First todo', 'Second todo']) + ->call('moveTodo', $first->id, 'down') + ->assertSeeInOrder(['Second todo', 'First todo']); +}); + +test('reordering while filtered keeps the order of the todos the filter hides', function () { + $user = User::factory()->create(); + $this->actingAs($user); + + $work = Folder::factory()->for($user)->create(['name' => 'Work']); + $home = Folder::factory()->for($user)->create(['name' => 'Home']); + + Todo::factory()->recycle($user)->for($home)->create(['description' => 'Home one', 'position' => 0]); + Todo::factory()->recycle($user)->for($home)->create(['description' => 'Home two', 'position' => 1]); + $workOne = Todo::factory()->recycle($user)->for($work)->create(['description' => 'Work one', 'position' => 2]); + Todo::factory()->recycle($user)->for($work)->create(['description' => 'Work two', 'position' => 3]); + + Livewire::test('pages::dashboard') + ->set('folderId', $work->id) + ->call('handleSort', $workOne->id, 1); + + Livewire::test('pages::dashboard') + ->assertSeeInOrder(['Home one', 'Home two', 'Work two', 'Work one']); +}); + test('completed todos sort last regardless of their position', function () { $user = User::factory()->create(); $this->actingAs($user); diff --git a/tests/Feature/TodosTest.php b/tests/Feature/TodosTest.php index 1723f23..3629433 100644 --- a/tests/Feature/TodosTest.php +++ b/tests/Feature/TodosTest.php @@ -202,6 +202,43 @@ test('users can move a todo up in the priority order', function () { expect($third->fresh()->position)->toBe(1); }); +test('the reorder arrows reflect the new order after a move', function () { + $user = User::factory()->create(); + $this->actingAs($user); + + $folder = Folder::factory()->for($user)->create(['name' => 'Work']); + + Todo::factory()->recycle($user)->for($folder)->create(['description' => 'First todo', 'position' => 0]); + Todo::factory()->recycle($user)->for($folder)->create(['description' => 'Second todo', 'position' => 1]); + $third = Todo::factory()->recycle($user)->for($folder)->create(['description' => 'Third todo', 'position' => 2]); + + // The last todo cannot move down until it has been moved up. + Livewire::test('pages::todos') + ->assertDontSee('move-todo-down-'.$third->id) + ->call('moveTodo', $third->id, 'up') + ->assertSee('move-todo-down-'.$third->id); +}); + +test('reordering while filtered keeps the order of the todos the filter hides', function () { + $user = User::factory()->create(); + $this->actingAs($user); + + $work = Folder::factory()->for($user)->create(['name' => 'Work']); + $home = Folder::factory()->for($user)->create(['name' => 'Home']); + + Todo::factory()->recycle($user)->for($home)->create(['description' => 'Home one', 'position' => 0]); + Todo::factory()->recycle($user)->for($home)->create(['description' => 'Home two', 'position' => 1]); + $workOne = Todo::factory()->recycle($user)->for($work)->create(['description' => 'Work one', 'position' => 2]); + Todo::factory()->recycle($user)->for($work)->create(['description' => 'Work two', 'position' => 3]); + + Livewire::test('pages::todos') + ->set('folderId', $work->id) + ->call('handleSort', $workOne->id, 1); + + Livewire::test('pages::todos') + ->assertSeeInOrder(['Home one', 'Home two', 'Work two', 'Work one']); +}); + test('users can delete a todo', function () { $user = User::factory()->create(); $this->actingAs($user);