added pricing, orgs
tests / ci (push) Canceled after 0s

This commit is contained in:
2026-10-04 20:34:19 -07:00
parent 999d5ad28d
commit 2ca3860557
52 changed files with 3467 additions and 47 deletions
+13
View File
@@ -67,3 +67,16 @@ AWS_BUCKET=
AWS_USE_PATH_STYLE_ENDPOINT=false AWS_USE_PATH_STYLE_ENDPOINT=false
VITE_APP_NAME="${APP_NAME}" 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
+12
View File
@@ -63,3 +63,15 @@ AWS_BUCKET=
AWS_USE_PATH_STYLE_ENDPOINT=false AWS_USE_PATH_STYLE_ENDPOINT=false
VITE_APP_NAME="${APP_NAME}" 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
+25
View File
@@ -4,8 +4,10 @@ namespace App\Actions\Fortify;
use App\Concerns\PasswordValidationRules; use App\Concerns\PasswordValidationRules;
use App\Concerns\ProfileValidationRules; use App\Concerns\ProfileValidationRules;
use App\Models\Organization;
use App\Models\User; use App\Models\User;
use Illuminate\Support\Facades\Validator; use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use Laravel\Fortify\Contracts\CreatesNewUsers; use Laravel\Fortify\Contracts\CreatesNewUsers;
class CreateNewUser implements CreatesNewUsers class CreateNewUser implements CreatesNewUsers
@@ -22,6 +24,7 @@ class CreateNewUser implements CreatesNewUsers
Validator::make($input, [ Validator::make($input, [
...$this->profileRules(), ...$this->profileRules(),
'password' => $this->passwordRules(), 'password' => $this->passwordRules(),
...$this->planRules(),
])->validate(); ])->validate();
return User::create([ return User::create([
@@ -30,4 +33,26 @@ class CreateNewUser implements CreatesNewUsers
'password' => $input['password'], '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<string, array<int, mixed>>
*/
protected function planRules(): array
{
$plans = array_keys(Organization::availablePlans());
if ($plans === []) {
return [];
}
return [
'plan' => ['required', Rule::in($plans)],
];
}
} }
+26
View File
@@ -0,0 +1,26 @@
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class EnsureSubscribed
{
/**
* Send users without an active subscription to the pricing page, where
* they can subscribe. Reads the local subscription rows only, so it does
* not call Stripe on every request.
*
* @param Closure(Request): Response $next
*/
public function handle(Request $request, Closure $next): Response
{
if ($request->user()?->hasActiveSubscription() === true) {
return $next($request);
}
return redirect()->route('pricing');
}
}
+78
View File
@@ -0,0 +1,78 @@
<?php
namespace App\Http\Responses;
use App\Models\Organization;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Laravel\Fortify\Contracts\RegisterResponse as RegisterResponseContract;
use Laravel\Fortify\Fortify;
use Symfony\Component\HttpFoundation\Response;
use Throwable;
/**
* Sends a new account straight into checkout for the plan it signed up with.
*
* Fortify's default response redirects to the home route, which the
* "subscribed" middleware would then bounce to the pricing page. Reading the
* plan off the registration request keeps the account details and the plan
* choice in a single submission, so the user never sees an interstitial.
*/
class RegisterResponse implements RegisterResponseContract
{
/**
* Create an HTTP response that represents the object.
*
* The signature is left untyped to stay compatible with Responsable, which
* declares the parameter without a type.
*
* @param Request $request
*/
public function toResponse($request): Response
{
if ($request->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'));
}
}
+273
View File
@@ -0,0 +1,273 @@
<?php
namespace App\Models;
use App\OrganizationRole;
use Database\Factories\OrganizationFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Hidden;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Support\Carbon;
use Illuminate\Support\Number;
use Laravel\Cashier\Billable;
use Laravel\Cashier\Checkout;
use Laravel\Cashier\Subscription;
use Symfony\Component\HttpKernel\Exception\HttpException;
/**
* An organization owns the subscription and is the Stripe customer. Every user
* is given a personal organization when their account is created; group and
* company organizations are created later, which is why the model is not named
* after a person.
*
* @property int $id
* @property string $name
* @property bool $personal_workspace
* @property bool $lifetime_access
* @property string|null $stripe_id
* @property string|null $pm_type
* @property string|null $pm_last_four
* @property Carbon|null $trial_ends_at
* @property Carbon|null $created_at
* @property Carbon|null $updated_at
*/
#[Fillable(['name', 'personal_workspace', 'lifetime_access'])]
#[Hidden(['stripe_id'])]
class Organization extends Model
{
/** @use HasFactory<OrganizationFactory> */
use Billable, HasFactory;
/**
* Get the attributes that should be cast.
*
* @return array<string, string>
*/
protected function casts(): array
{
return [
'personal_workspace' => 'boolean',
'lifetime_access' => 'boolean',
'trial_ends_at' => 'datetime',
];
}
/**
* @return BelongsToMany<User, $this>
*/
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<string, array{name: string, price: string, interval: string, amount: int}>
*/
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<string, mixed>
*/
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();
}
}
+77
View File
@@ -0,0 +1,77 @@
<?php
namespace App\Models;
use Database\Factories\SettingFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
/**
* @property int $id
* @property string $key
* @property string|null $value
*/
#[Fillable(['key', 'value'])]
class Setting extends Model
{
/** @use HasFactory<SettingFactory> */
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;
}
}
+60 -1
View File
@@ -3,10 +3,13 @@
namespace App\Models; namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail; // use Illuminate\Contracts\Auth\MustVerifyEmail;
use App\OrganizationRole;
use Database\Factories\UserFactory; use Database\Factories\UserFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable; use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Hidden; use Illuminate\Database\Eloquent\Attributes\Hidden;
use Illuminate\Database\Eloquent\Factories\HasFactory; 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\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable; use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Carbon; use Illuminate\Support\Carbon;
@@ -17,6 +20,7 @@ use Laravel\Fortify\TwoFactorAuthenticatable;
/** /**
* @property int $id * @property int $id
* @property int|null $current_organization_id
* @property string $name * @property string $name
* @property string $email * @property string $email
* @property Carbon|null $email_verified_at * @property Carbon|null $email_verified_at
@@ -30,13 +34,68 @@ use Laravel\Fortify\TwoFactorAuthenticatable;
* @property Carbon|null $created_at * @property Carbon|null $created_at
* @property Carbon|null $updated_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'])] #[Hidden(['password', 'two_factor_secret', 'two_factor_recovery_codes', 'remember_token'])]
class User extends Authenticatable implements PasskeyUser class User extends Authenticatable implements PasskeyUser
{ {
/** @use HasFactory<UserFactory> */ /** @use HasFactory<UserFactory> */
use HasFactory, Notifiable, PasskeyAuthenticatable, TwoFactorAuthenticatable; 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<Organization, $this>
*/
public function currentOrganization(): BelongsTo
{
return $this->belongsTo(Organization::class, 'current_organization_id');
}
/**
* @return BelongsToMany<Organization, $this>
*/
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. * Get the attributes that should be cast.
* *
+20
View File
@@ -0,0 +1,20 @@
<?php
namespace App;
enum OrganizationRole: string
{
case Owner = 'owner';
case Member = 'member';
/**
* Get the human-friendly label for the role.
*/
public function label(): string
{
return match ($this) {
self::Owner => 'Owner',
self::Member => 'Member',
};
}
}
+27 -1
View File
@@ -2,11 +2,15 @@
namespace App\Providers; namespace App\Providers;
use App\Http\Responses\RegisterResponse;
use App\Models\Organization;
use Carbon\CarbonImmutable; use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\Date; use Illuminate\Support\Facades\Date;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use Illuminate\Support\ServiceProvider; use Illuminate\Support\ServiceProvider;
use Illuminate\Validation\Rules\Password; use Illuminate\Validation\Rules\Password;
use Laravel\Cashier\Cashier;
use Laravel\Fortify\Contracts\RegisterResponse as RegisterResponseContract;
class AppServiceProvider extends ServiceProvider class AppServiceProvider extends ServiceProvider
{ {
@@ -15,7 +19,19 @@ class AppServiceProvider extends ServiceProvider
*/ */
public function register(): void 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 public function boot(): void
{ {
$this->configureDefaults(); $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);
} }
/** /**
+12 -1
View File
@@ -1,5 +1,6 @@
<?php <?php
use App\Http\Middleware\EnsureSubscribed;
use Illuminate\Foundation\Application; use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions; use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware; use Illuminate\Foundation\Configuration\Middleware;
@@ -12,7 +13,17 @@ return Application::configure(basePath: dirname(__DIR__))
health: '/up', health: '/up',
) )
->withMiddleware(function (Middleware $middleware): void { ->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 { ->withExceptions(function (Exceptions $exceptions): void {
$exceptions->shouldRenderJsonWhen( $exceptions->shouldRenderJsonWhen(
+1
View File
@@ -10,6 +10,7 @@
"license": "MIT", "license": "MIT",
"require": { "require": {
"php": "^8.3", "php": "^8.3",
"laravel/cashier": "^16.8",
"laravel/chisel": "^0.1.0", "laravel/chisel": "^0.1.0",
"laravel/fortify": "^1.37.2", "laravel/fortify": "^1.37.2",
"laravel/framework": "^13.17", "laravel/framework": "^13.17",
Generated
+330 -1
View File
@@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically" "This file is @generated automatically"
], ],
"content-hash": "c892d5d289ab6ad60404f0e6ba800167", "content-hash": "5df77883928ac298be1ce9e985cedf12",
"packages": [ "packages": [
{ {
"name": "bacon/bacon-qr-code", "name": "bacon/bacon-qr-code",
@@ -1212,6 +1212,95 @@
], ],
"time": "2026-08-24T17:13:02+00:00" "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", "name": "laravel/chisel",
"version": "v0.1.1", "version": "v0.1.1",
@@ -2575,6 +2664,96 @@
], ],
"time": "2026-09-14T19:27:16+00:00" "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", "name": "monolog/monolog",
"version": "3.12.0", "version": "3.12.0",
@@ -4345,6 +4524,68 @@
], ],
"time": "2026-09-12T19:02:49+00:00" "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", "name": "symfony/clock",
"version": "v8.1.0", "version": "v8.1.0",
@@ -5499,6 +5740,94 @@
], ],
"time": "2026-07-28T08:25:59+00:00" "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", "name": "symfony/polyfill-intl-idn",
"version": "v1.42.0", "version": "v1.42.0",
+130
View File
@@ -0,0 +1,130 @@
<?php
use Laravel\Cashier\Console\WebhookCommand;
use Laravel\Cashier\Invoices\DompdfInvoiceRenderer;
// use Laravel\Cashier\Invoices\LaravelPdfInvoiceRenderer;
return [
/*
|--------------------------------------------------------------------------
| Stripe Keys
|--------------------------------------------------------------------------
|
| The Stripe publishable key and secret key give you access to Stripe's
| API. The "publishable" key is typically used when interacting with
| Stripe.js while the "secret" key accesses private API endpoints.
|
*/
'key' => 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'),
];
+53
View File
@@ -0,0 +1,53 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Subscription Type
|--------------------------------------------------------------------------
|
| Cashier stores subscriptions under a "type" key, which lets an
| organization hold more than one subscription over time. This
| application only needs one, so every plan shares this type.
|
*/
'subscription_type' => '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',
],
],
];
@@ -0,0 +1,59 @@
<?php
namespace Database\Factories;
use App\Models\Organization;
use App\Models\User;
use App\OrganizationRole;
use Illuminate\Database\Eloquent\Factories\Factory;
/**
* @extends Factory<Organization>
*/
class OrganizationFactory extends Factory
{
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
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]);
});
}
}
+25
View File
@@ -0,0 +1,25 @@
<?php
namespace Database\Factories;
use App\Models\Setting;
use Illuminate\Database\Eloquent\Factories\Factory;
/**
* @extends Factory<Setting>
*/
class SettingFactory extends Factory
{
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
public function definition(): array
{
return [
'key' => 'setting.'.fake()->unique()->word(),
'value' => fake()->word(),
];
}
}
+63
View File
@@ -3,9 +3,13 @@
namespace Database\Factories; namespace Database\Factories;
use App\Models\User; use App\Models\User;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Factories\Factory; 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\Facades\Hash;
use Illuminate\Support\Str; use Illuminate\Support\Str;
use Laravel\Cashier\Subscription;
/** /**
* @extends Factory<User> * @extends Factory<User>
@@ -17,6 +21,14 @@ class UserFactory extends Factory
*/ */
protected static ?string $password; 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. * 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<string, mixed> $attributes
* @return Collection<int, User>|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. * Indicate that the model's email address should be unverified.
*/ */
@@ -77,4 +126,18 @@ class UserFactory extends Factory
'two_factor_confirmed_at' => now(), '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]);
}
} }
@@ -0,0 +1,41 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('subscriptions', function (Blueprint $table) {
$table->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');
}
};
@@ -0,0 +1,34 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('subscription_items', function (Blueprint $table) {
$table->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');
}
};
@@ -0,0 +1,28 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::table('subscription_items', function (Blueprint $table) {
$table->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');
});
}
};
@@ -0,0 +1,28 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::table('subscription_items', function (Blueprint $table) {
$table->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');
});
}
};
@@ -0,0 +1,41 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('organizations', function (Blueprint $table) {
$table->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');
}
};
@@ -0,0 +1,32 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('organization_user', function (Blueprint $table) {
$table->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');
}
};
@@ -0,0 +1,32 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::table('users', function (Blueprint $table) {
$table->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');
});
}
};
@@ -0,0 +1,54 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Give every user who existed before subscriptions existed a personal
* organization with permanent access, so that turning registration into a
* paid wall does not lock the existing accounts out of their own data.
*
* Idempotent: users that already have a current organization are skipped.
*/
public function up(): void
{
DB::table('users')
->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();
}
}
};
@@ -0,0 +1,40 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('settings', function (Blueprint $table) {
$table->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');
}
};
+8 -1
View File
@@ -12,7 +12,7 @@ class BaseDatabaseSeeder extends Seeder
*/ */
public function run(): void public function run(): void
{ {
User::updateOrCreate( $admin = User::updateOrCreate(
['email' => config('admin.email')], ['email' => config('admin.email')],
[ [
'name' => config('admin.name'), 'name' => config('admin.name'),
@@ -20,5 +20,12 @@ class BaseDatabaseSeeder extends Seeder
'is_admin' => true, '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();
} }
} }
+6
View File
@@ -33,5 +33,11 @@
<env name="PULSE_ENABLED" value="false"/> <env name="PULSE_ENABLED" value="false"/>
<env name="TELESCOPE_ENABLED" value="false"/> <env name="TELESCOPE_ENABLED" value="false"/>
<env name="NIGHTWATCH_ENABLED" value="false"/> <env name="NIGHTWATCH_ENABLED" value="false"/>
<env name="CASHIER_PATH" value="stripe"/>
<env name="STRIPE_KEY" value="pk_test_placeholder"/>
<env name="STRIPE_SECRET" value="sk_test_placeholder"/>
<env name="STRIPE_WEBHOOK_SECRET" value="whsec_placeholder"/>
<env name="BILLING_PLAN_PRO_PRICE" value="price_test_placeholder"/>
<env name="BILLING_TRIAL_DAYS" value="14"/>
</php> </php>
</phpunit> </phpunit>
@@ -28,6 +28,9 @@
<flux:sidebar.item icon="users" :href="route('admin.notes-limits')" :current="request()->routeIs('admin.notes-limits')" wire:navigate> <flux:sidebar.item icon="users" :href="route('admin.notes-limits')" :current="request()->routeIs('admin.notes-limits')" wire:navigate>
{{ __('Notes limits') }} {{ __('Notes limits') }}
</flux:sidebar.item> </flux:sidebar.item>
<flux:sidebar.item icon="currency-dollar" :href="route('admin.plan-pricing')" :current="request()->routeIs('admin.plan-pricing')" wire:navigate>
{{ __('Plan pricing') }}
</flux:sidebar.item>
</flux:sidebar.group> </flux:sidebar.group>
@endif @endif
</flux:sidebar.nav> </flux:sidebar.nav>
@@ -0,0 +1,44 @@
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}" class="dark">
<head>
@include('partials.head')
</head>
<body class="min-h-screen bg-white antialiased dark:bg-linear-to-b dark:from-neutral-950 dark:to-neutral-900">
<div class="flex min-h-svh flex-col">
<header class="border-b border-zinc-200 px-6 py-4 dark:border-white/10">
<div class="mx-auto flex w-full max-w-5xl items-center justify-between">
<a href="{{ route('home') }}" class="flex items-center gap-2 font-medium" wire:navigate>
<x-app-logo-icon class="size-8 fill-current text-zinc-900 dark:text-white" />
<span class="text-sm font-semibold text-zinc-900 dark:text-white">{{ config('app.name', 'Laravel') }}</span>
</a>
<nav class="flex items-center gap-4 text-sm">
@auth
<flux:link :href="route('dashboard')" wire:navigate>{{ __('Dashboard') }}</flux:link>
@else
<flux:link :href="route('login')" wire:navigate>{{ __('Log in') }}</flux:link>
@if (Route::has('register'))
<flux:button :href="route('register')" variant="primary" size="sm" wire:navigate>
{{ __('Sign up') }}
</flux:button>
@endif
@endauth
</nav>
</div>
</header>
<main class="flex flex-1 flex-col items-center px-6 py-12 md:py-16">
{{ $slot }}
</main>
</div>
@persist('toast')
<flux:toast.group>
<flux:toast />
</flux:toast.group>
@endpersist
@fluxScripts
</body>
</html>
@@ -0,0 +1,133 @@
<?php
use App\Models\Organization;
use App\Models\Setting;
use Flux\Flux;
use Illuminate\Support\Collection;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Title;
use Livewire\Component;
new #[Title('Plan pricing')] class extends Component
{
public function mount(): void
{
if (! auth()->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<string, string>
*/
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<string, array{key: string, name: string, interval: string, purchasable: bool}>
*/
#[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);
}
}; ?>
<div class="flex h-full w-full flex-1 flex-col gap-6">
<div>
<flux:heading size="xl">{{ __('Plan pricing') }}</flux:heading>
<flux:text class="mt-1">{{ __('Set the price shown for each plan on the pricing page and at signup.') }}</flux:text>
</div>
@if ($this->plans->isEmpty())
<flux:callout variant="warning">{{ __('No plans are configured.') }}</flux:callout>
@else
<form wire:submit="saveAmounts" class="flex max-w-2xl flex-col gap-6">
<flux:card class="flex flex-col gap-5">
@foreach ($this->plans as $plan)
<flux:field>
<flux:label>{{ $plan['name'] }}</flux:label>
<flux:input
wire:model="amounts.{{ $plan['key'] }}"
:value="$amounts[$plan['key']] ?? null"
type="number"
step="0.01"
min="0"
inputmode="decimal"
data-test="plan-amount-input-{{ $plan['key'] }}"
/>
<flux:text size="sm" class="text-zinc-500 dark:text-zinc-400">
{{ __('Billed every :interval.', ['interval' => $plan['interval']]) }}
@unless ($plan['purchasable'])
{{ __('This plan is not on sale yet, because it has no Stripe price configured.') }}
@endunless
</flux:text>
<flux:error name="amounts.{{ $plan['key'] }}" />
</flux:field>
@endforeach
</flux:card>
<div class="flex justify-end">
<flux:button type="submit" variant="primary" data-test="save-plan-amounts-button">
{{ __('Save') }}
</flux:button>
</div>
</form>
@endif
</div>
+72 -2
View File
@@ -1,12 +1,82 @@
@php
use App\Models\Organization;
$plans = Organization::availablePlans();
$trialDays = Organization::trialDays();
@endphp
<x-layouts::auth :title="__('Register')"> <x-layouts::auth :title="__('Register')">
<div class="flex flex-col gap-6"> <div class="flex flex-col gap-6">
<x-auth-header :title="__('Create an account')" :description="__('Enter your details below to create your account')" /> <x-auth-header
:title="__('Create an account')"
:description="$plans !== []
? __('Choose a plan, then enter your details to get started')
: __('Enter your details below to create your account')"
/>
<!-- Session Status --> <!-- Session Status -->
<x-auth-session-status class="text-center" :status="session('status')" /> <x-auth-session-status class="text-center" :status="session('status')" />
<form method="POST" action="{{ route('register.store') }}" class="flex flex-col gap-6"> <form method="POST" action="{{ route('register.store') }}" class="flex flex-col gap-6">
@csrf @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. --}}
<fieldset class="flex flex-col gap-2">
<legend class="text-sm font-medium text-zinc-800 dark:text-white">
{{ __('Choose your plan') }}
</legend>
@foreach ($plans as $key => $plan)
<label
@class([
'flex cursor-pointer items-start gap-3 rounded-lg border border-zinc-200 p-3 transition has-[:checked]:border-accent-500 has-[:checked]:bg-zinc-50 dark:border-white/10 dark:has-[:checked]:bg-white/5',
'border-zinc-400 bg-zinc-50 dark:border-zinc-500 dark:bg-white/5' => old('plan', array_key_first($plans)) === $key,
])
data-test="register-plan-{{ $key }}"
>
<input
type="radio"
name="plan"
value="{{ $key }}"
@checked(old('plan', array_key_first($plans)) === $key)
required
class="mt-0.5 size-4 shrink-0 accent-accent-500"
/>
<span class="flex flex-col gap-0.5">
<span class="flex items-baseline justify-between gap-3">
<span class="text-sm font-medium text-zinc-800 dark:text-white">
{{ $plan['name'] }}
</span>
<span
class="text-sm font-semibold text-zinc-900 dark:text-white"
data-test="register-plan-{{ $key }}-amount"
>
{{ Organization::formatAmount($plan['amount']) }}
</span>
</span>
<span class="text-xs text-zinc-500 dark:text-zinc-400">
{{ $trialDays > 0
? __('Free for :days days, then billed every :interval', [
'days' => $trialDays,
'interval' => $plan['interval'],
])
: __('Billed every :interval', ['interval' => $plan['interval']]) }}
</span>
</span>
</label>
@endforeach
@error('plan')
<flux:error name="plan" />
@enderror
</fieldset>
@endif
<!-- Name --> <!-- Name -->
<flux:input <flux:input
name="name" name="name"
@@ -56,7 +126,7 @@
<div class="flex items-center justify-end"> <div class="flex items-center justify-end">
<flux:button type="submit" variant="primary" class="w-full" data-test="register-user-button"> <flux:button type="submit" variant="primary" class="w-full" data-test="register-user-button">
{{ __('Create account') }} {{ $plans !== [] ? __('Continue to payment') : __('Create account') }}
</flux:button> </flux:button>
</div> </div>
</form> </form>
@@ -4,6 +4,7 @@
<flux:navlist.item :href="route('profile.edit')" wire:navigate>{{ __('Profile') }}</flux:navlist.item> <flux:navlist.item :href="route('profile.edit')" wire:navigate>{{ __('Profile') }}</flux:navlist.item>
<flux:navlist.item :href="route('security.edit')" wire:navigate>{{ __('Security') }}</flux:navlist.item> <flux:navlist.item :href="route('security.edit')" wire:navigate>{{ __('Security') }}</flux:navlist.item>
<flux:navlist.item :href="route('appearance.edit')" wire:navigate>{{ __('Appearance') }}</flux:navlist.item> <flux:navlist.item :href="route('appearance.edit')" wire:navigate>{{ __('Appearance') }}</flux:navlist.item>
<flux:navlist.item :href="route('billing.edit')" wire:navigate data-test="billing-nav-link">{{ __('Billing') }}</flux:navlist.item>
</flux:navlist> </flux:navlist>
</div> </div>
@@ -0,0 +1,151 @@
<?php
use Illuminate\Support\Facades\Auth;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Title;
use Livewire\Component;
new #[Title('Billing settings')]
class extends Component
{
/**
* Get the organization that holds the subscription being managed.
*/
#[Computed]
public function organization()
{
return Auth::user()?->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;
}
}; ?>
<section class="w-full">
@include('partials.settings-heading')
<flux:heading level="2" class="sr-only">{{ __('Billing settings') }}</flux:heading>
<x-pages::settings.layout :heading="__('Billing')" :subheading="__('Manage your plan and payment details')">
<div class="space-y-6" data-test="billing-overview">
<flux:card class="space-y-3">
<div class="flex items-center justify-between gap-4">
<div>
<flux:heading size="sm">{{ $this->plan['name'] ?? __('Free') }}</flux:heading>
<flux:text size="sm" class="text-zinc-500 dark:text-zinc-400">
{{ $this->status }}
</flux:text>
</div>
<flux:badge :color="$this->organization?->isEntitled() ? 'green' : 'red'" size="sm">
{{ $this->organization?->isEntitled() ? __('Active') : __('Inactive') }}
</flux:badge>
</div>
<flux:text size="sm">{{ $this->summary }}</flux:text>
</flux:card>
<div class="flex flex-wrap items-center gap-3">
@if ($this->organization?->isEntitled() !== true)
<flux:button :href="route('pricing')" variant="primary" wire:navigate data-test="subscribe-button">
{{ __('Subscribe') }}
</flux:button>
@endif
@if ($this->canManagePaymentMethod)
<form method="POST" action="{{ route('billing.portal') }}">
@csrf
<flux:button type="submit" variant="ghost" data-test="billing-portal-button">
{{ __('Manage payment method') }}
</flux:button>
</form>
@endif
</div>
</div>
</x-pages::settings.layout>
</section>
+35 -18
View File
@@ -266,10 +266,10 @@ new #[Title('Dashboard')] class extends Component
{ {
$this->todoForUser($todoId); $this->todoForUser($todoId);
$ids = $this->filteredTodoQuery()->priority()->pluck('id')->all(); $ids = $this->orderedTodoIds;
$currentIndex = array_search($todoId, $ids, true); $currentIndex = array_search($todoId, $ids, true);
if ($currentIndex === false || $ids === []) { if ($currentIndex === false) {
return; return;
} }
@@ -279,40 +279,57 @@ new #[Title('Dashboard')] class extends Component
return; return;
} }
$this->reorderTodo($todoId, $ids, $target); $this->reorderTodo($todoId, $target);
} }
public function handleSort(int $todoId, int $position): void public function handleSort(int $todoId, int $position): void
{ {
$this->todoForUser($todoId); $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; $offset = ($this->todos->currentPage() - 1) * self::PER_PAGE;
$this->reorderTodo($todoId, $ids, $offset + $position); $this->reorderTodo($todoId, $offset + $position);
} }
/** /**
* @param array<int, int> $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)]); $visibleIds = $this->orderedTodoIds;
$ids = array_values($ids); $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) { foreach ($ids as $position => $id) {
Todo::query()->forUser(auth()->id())->whereKey($id)->update(['position' => $position]); 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) @forelse ($this->todos as $todo)
<flux:table.row :key="$todo->id" wire:sort:item="{{ $todo->id }}" data-test="todo-row"> <flux:table.row :key="$todo->id" wire:sort:item="{{ $todo->id }}" data-test="todo-row">
<flux:table.cell class="py-0 text-zinc-300 dark:text-zinc-600"> <flux:table.cell class="py-0 text-zinc-300 dark:text-zinc-600">
<div wire:sort:handle class="inline-flex cursor-grab" :title="__('Reorder')"> <div wire:sort:handle class="inline-flex cursor-grab" title="{{ __('Reorder') }}">
<flux:icon.chevrons-up-down variant="micro" /> <flux:icon.chevrons-up-down variant="micro" />
</div> </div>
</flux:table.cell> </flux:table.cell>
+1 -1
View File
@@ -472,7 +472,7 @@ new #[Title('Folders')] class extends Component
:class="dragging && 'opacity-40'" :class="dragging && 'opacity-40'"
@dragstart="dragging = true; window.__mtFolderDrag = { folderId: {{ $node['folder']->id }} }; $dispatch('folder-drag-start')" @dragstart="dragging = true; window.__mtFolderDrag = { folderId: {{ $node['folder']->id }} }; $dispatch('folder-drag-start')"
@dragend="dragging = false; window.__mtFolderDrag = null; $dispatch('folder-drag-end')" @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 }}" data-test="drag-folder-{{ $node['folder']->id }}"
> >
<flux:icon.chevrons-up-down variant="micro" /> <flux:icon.chevrons-up-down variant="micro" />
+163
View File
@@ -0,0 +1,163 @@
<?php
use App\Models\Organization;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\Rule;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Component;
new #[Layout('layouts::marketing')]
#[Title('Pricing')]
class extends Component
{
/**
* The plan key the visitor chose. Held as state so the server can validate
* it against the configured plans rather than trusting the button.
*/
public string $plan = '';
/**
* The trial length configured for new subscriptions.
*/
public function trialDays(): int
{
return Organization::trialDays();
}
/**
* Determine whether the signed-in user already has access, in which case
* there is nothing to sell them.
*/
#[Computed]
public function isSubscribed(): bool
{
return Auth::user()?->hasActiveSubscription() ?? false;
}
/**
* Get the plans that are configured and available to purchase.
*
* @return array<string, array{name: string, price: string, interval: string}>
*/
#[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();
}
}; ?>
<section class="flex w-full max-w-5xl flex-col gap-10">
<div class="flex flex-col items-center gap-3 text-center">
<flux:heading size="xl" level="1">{{ __('Plans and pricing') }}</flux:heading>
@if (session('billing.checkout_failed'))
<flux:callout variant="danger" class="w-full" data-test="pricing-status">
{{ session('billing.checkout_failed') }}
</flux:callout>
@endif
@if ($this->isSubscribed)
<flux:subheading>{{ __('Your workspace already has an active subscription.') }}</flux:subheading>
@else
<flux:subheading class="max-w-2xl text-center">
{{ __('Subscribe to unlock your todos, folders and notes.') }}
</flux:subheading>
@endif
</div>
@if ($this->isSubscribed)
<flux:button :href="route('billing.edit')" variant="primary" wire:navigate data-test="manage-subscription-button">
{{ __('Manage your subscription') }}
</flux:button>
@elseif (count($this->plans) === 0)
<flux:callout variant="warning" class="mx-auto max-w-2xl">
{{ __('No plans are available right now. Please check back soon.') }}
</flux:callout>
@else
<div class="grid w-full gap-6 md:grid-cols-2 lg:grid-cols-3">
@foreach ($this->plans as $key => $plan)
<flux:card class="flex flex-col gap-5" data-test="plan-{{ $key }}">
<div class="flex flex-col gap-1">
<flux:heading size="lg">{{ $plan['name'] }}</flux:heading>
<p class="text-2xl font-semibold text-zinc-900 dark:text-white" data-test="plan-{{ $key }}-amount">
{{ Organization::formatAmount($plan['amount']) }}
</p>
<flux:text size="sm" class="text-zinc-500 dark:text-zinc-400">
{{ __('Billed every :interval', ['interval' => $plan['interval']]) }}
</flux:text>
</div>
<ul class="flex flex-1 flex-col gap-2 text-sm">
<li class="flex items-center gap-2">
<flux:icon.check class="size-4 shrink-0" />
<span>{{ __('Unlimited todos and folders') }}</span>
</li>
<li class="flex items-center gap-2">
<flux:icon.check class="size-4 shrink-0" />
<span>{{ __('Notes on every todo') }}</span>
</li>
<li class="flex items-center gap-2">
<flux:icon.check class="size-4 shrink-0" />
<span>{{ __('Status, due dates and priorities') }}</span>
</li>
</ul>
@auth
<flux:button
wire:click="subscribe('{{ $key }}')"
variant="primary"
class="w-full"
data-test="subscribe-{{ $key }}-button"
>
{{ $this->trialDays() > 0
? __('Start :days-day free trial', ['days' => $this->trialDays()])
: __('Subscribe') }}
</flux:button>
@else
<flux:button :href="route('register')" variant="primary" class="w-full" wire:navigate>
{{ __('Create an account') }}
</flux:button>
@endauth
</flux:card>
@endforeach
</div>
@if ($this->trialDays() > 0)
<flux:text size="sm" class="text-center text-zinc-500 dark:text-zinc-400">
{{ __('Your trial ends after :days days and you can cancel at any time.', ['days' => $this->trialDays()]) }}
</flux:text>
@endif
@endif
@error('plan')
<flux:error name="plan" />
@enderror
</section>
@@ -0,0 +1,96 @@
<?php
use Illuminate\Support\Facades\Auth;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Attributes\Url;
use Livewire\Component;
new #[Layout('layouts::marketing')]
#[Title('Confirming your subscription')]
class extends Component
{
/**
* How long to keep polling for the webhook before giving up.
*/
private const TIMEOUT_SECONDS = 30;
/**
* The Stripe Checkout session id, used only to correlate the page with
* the checkout that just completed.
*/
#[Url(as: 'session_id', except: '')]
public string $sessionId = '';
/**
* Seconds spent waiting so far.
*/
public int $waitedSeconds = 0;
public bool $timedOut = false;
/**
* Confirm the subscription arrived. Cashier 16 has no checkout session
* lookup, so the webhook is polled against the local subscription row.
*/
public function confirm(): void
{
if ($this->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;
}
}; ?>
<section class="flex w-full max-w-xl flex-col items-center gap-6 text-center"
@if (! $timedOut)
wire:poll.2s="confirm"
@endif
>
@if ($this->hasSubscription)
<flux:icon.check class="size-12 text-green-500" />
<flux:heading size="xl" level="1">{{ __('Your subscription is active') }}</flux:heading>
<flux:subheading>{{ __('Welcome aboard. Taking you to your todos now.') }}</flux:subheading>
<flux:button :href="route('dashboard')" variant="primary" wire:navigate data-test="go-to-dashboard-button">
{{ __('Go to my todos') }}
</flux:button>
@elseif ($timedOut)
<flux:icon.clock class="size-12 text-zinc-500" />
<flux:heading size="xl" level="1">{{ __('Still confirming your payment') }}</flux:heading>
<flux:subheading>
{{ __('Your payment went through, but we have not heard from Stripe yet. Your access will turn on automatically as soon as it does.') }}
</flux:subheading>
<flux:button :href="route('pricing')" variant="primary" wire:navigate data-test="back-to-pricing-button">
{{ __('Back to plans') }}
</flux:button>
@else
<div
class="size-12 animate-spin rounded-full border-4 border-zinc-200 border-t-zinc-500 dark:border-white/10 dark:border-t-zinc-300"
role="status"
></div>
<flux:heading size="xl" level="1">{{ __('Confirming your subscription') }}</flux:heading>
<flux:subheading>{{ __('This usually takes a few seconds. Please do not close this page.') }}</flux:subheading>
@endif
</section>
+34 -17
View File
@@ -248,7 +248,7 @@ new #[Title('Todos')] class extends Component
$ids = $this->orderedTodoIds; $ids = $this->orderedTodoIds;
$currentIndex = array_search($todoId, $ids, true); $currentIndex = array_search($todoId, $ids, true);
if ($currentIndex === false || $ids === []) { if ($currentIndex === false) {
return; return;
} }
@@ -258,38 +258,55 @@ new #[Title('Todos')] class extends Component
return; return;
} }
$this->reorderTodo($todoId, $ids, $target); $this->reorderTodo($todoId, $target);
} }
public function handleSort(int $todoId, int $position): void public function handleSort(int $todoId, int $position): void
{ {
$this->todoForUser($todoId); $this->todoForUser($todoId);
$ids = $this->orderedTodoIds; $this->reorderTodo($todoId, $position);
$currentIndex = array_search($todoId, $ids, true);
if ($currentIndex === false || $ids === []) {
return;
}
$this->reorderTodo($todoId, $ids, $position);
} }
/** /**
* @param array<int, int> $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)]); $visibleIds = $this->orderedTodoIds;
$ids = array_values($ids); $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) { foreach ($ids as $position => $id) {
Todo::query()->forUser(auth()->id())->whereKey($id)->update(['position' => $position]); 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) @forelse ($this->todos as $todo)
<flux:table.row :key="$todo->id" wire:sort:item="{{ $todo->id }}" data-test="todo-row"> <flux:table.row :key="$todo->id" wire:sort:item="{{ $todo->id }}" data-test="todo-row">
<flux:table.cell class="py-0 text-zinc-300 dark:text-zinc-600"> <flux:table.cell class="py-0 text-zinc-300 dark:text-zinc-600">
<div wire:sort:handle class="inline-flex cursor-grab" :title="__('Reorder')"> <div wire:sort:handle class="inline-flex cursor-grab" title="{{ __('Reorder') }}">
<flux:icon.chevrons-up-down variant="micro" /> <flux:icon.chevrons-up-down variant="micro" />
</div> </div>
</flux:table.cell> </flux:table.cell>
+17
View File
@@ -1,11 +1,28 @@
<?php <?php
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\Route;
Route::middleware(['auth'])->group(function () { Route::middleware(['auth'])->group(function () {
Route::redirect('settings', 'settings/profile'); Route::redirect('settings', 'settings/profile');
Route::livewire('settings/profile', 'pages::settings.profile')->name('profile.edit'); 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 () { Route::middleware(['auth', 'verified'])->group(function () {
+10 -1
View File
@@ -4,11 +4,20 @@ use Illuminate\Support\Facades\Route;
Route::view('/', 'welcome')->name('home'); 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('dashboard', 'pages::dashboard')->name('dashboard');
Route::livewire('todos', 'pages::todos')->name('todos'); Route::livewire('todos', 'pages::todos')->name('todos');
Route::livewire('folders', 'pages::folders')->name('folders'); Route::livewire('folders', 'pages::folders')->name('folders');
Route::livewire('admin/notes-limits', 'pages::admin.notes-limits')->name('admin.notes-limits'); 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'; require __DIR__.'/settings.php';
+36 -1
View File
@@ -1,5 +1,6 @@
<?php <?php
use App\Models\User;
use Laravel\Fortify\Features; use Laravel\Fortify\Features;
beforeEach(function () { beforeEach(function () {
@@ -18,10 +19,44 @@ test('new users can register', function () {
'email' => 'test@example.com', 'email' => 'test@example.com',
'password' => 'password', 'password' => 'password',
'password_confirmation' => 'password', 'password_confirmation' => 'password',
'plan' => 'pro',
]); ]);
$response->assertSessionHasNoErrors() $response->assertSessionHasNoErrors()
->assertRedirect(route('dashboard', absolute: false)); ->assertRedirect(route('pricing', absolute: false));
$this->assertAuthenticated(); $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'));
});
+12
View File
@@ -22,3 +22,15 @@ test('base data seeding is idempotent', function () {
expect(User::where('email', 'admin@example.com')->count())->toBe(1); 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();
});
@@ -0,0 +1,140 @@
<?php
use App\Models\User;
use Laravel\Cashier\Subscription;
use Livewire\Livewire;
test('an unsubscribed user sees why they have no access', function () {
$this->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'));
});
+157
View File
@@ -0,0 +1,157 @@
<?php
use App\Models\Organization;
use App\Models\Setting;
use App\Models\User;
use Laravel\Cashier\Subscription;
use Livewire\Livewire;
test('guests can see the pricing page', function () {
$this->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();
});
+110
View File
@@ -0,0 +1,110 @@
<?php
use App\Models\Organization;
use App\Models\User;
use App\OrganizationRole;
use Laravel\Cashier\Subscription;
test('every new account is given a personal organization that is current', function () {
$user = User::factory()->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();
});
+218
View File
@@ -0,0 +1,218 @@
<?php
use App\Models\Organization;
use App\Models\Setting;
use App\Models\User;
use Livewire\Livewire;
test('guests are redirected from the plan pricing page', function () {
$this->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');
});
@@ -0,0 +1,211 @@
<?php
use App\Models\Organization;
use App\Models\Setting;
use App\Models\User;
use Laravel\Fortify\Features;
beforeEach(function () {
$this->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);
});
@@ -0,0 +1,105 @@
<?php
use App\Models\Organization;
use App\Models\User;
use Laravel\Cashier\Subscription;
test('guests are sent to login', function () {
$this->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'));
});
+51
View File
@@ -607,6 +607,57 @@ test('dragging accounts for the pagination offset', function () {
expect($todoTwelve->fresh()->position)->toBe(10); 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 () { test('completed todos sort last regardless of their position', function () {
$user = User::factory()->create(); $user = User::factory()->create();
$this->actingAs($user); $this->actingAs($user);
+37
View File
@@ -202,6 +202,43 @@ test('users can move a todo up in the priority order', function () {
expect($third->fresh()->position)->toBe(1); 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 () { test('users can delete a todo', function () {
$user = User::factory()->create(); $user = User::factory()->create();
$this->actingAs($user); $this->actingAs($user);