-
-
Notifications
You must be signed in to change notification settings - Fork 108
Expand file tree
/
Copy pathMobilePricing.php
More file actions
246 lines (199 loc) · 8.21 KB
/
MobilePricing.php
File metadata and controls
246 lines (199 loc) · 8.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
<?php
namespace App\Livewire;
use App\Enums\Subscription;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Laravel\Cashier\Cashier;
use Livewire\Attributes\Locked;
use Livewire\Attributes\On;
use Livewire\Attributes\Url;
use Livewire\Component;
class MobilePricing extends Component
{
#[Url]
public string $interval = 'month';
/** @var array{amount_due: string, raw_amount_due: int, new_charge: string, is_prorated: bool, credit: string|null, remaining_credit: string|null}|null */
public ?array $upgradePreview = null;
#[Locked]
public $user;
public function mount(): void
{
if (request()->has('email')) {
$this->user = $this->findOrCreateUser(request()->query('email'));
}
}
#[On('purchase-request-submitted')]
public function handlePurchaseRequest(array $data)
{
if (! $this->user) {
$user = $this->findOrCreateUser($data['email']);
}
return $this->createCheckoutSession($data['plan'], $this->user ?? $user);
}
public function createCheckoutSession(?string $plan, ?User $user = null)
{
// This method is somehow getting called without a plan being passed in.
// Not sure how (probably folks hacking or a bot thing),
// but we will just return early when this happens.
if (! $plan) {
return;
}
// If a user isn't passed into this method, Livewire will instantiate
// a new User. So we need to check that the user exists before using it,
// and then use the authenticated user as a fallback.
$user = $user?->exists ? $user : Auth::user();
if (! $user) {
Log::error('Failed to create checkout session. User does not exist and user is not authenticated.');
return;
}
if (! ($subscription = Subscription::tryFrom($plan))) {
Log::error('Failed to create checkout session. Invalid subscription plan name provided.');
return;
}
$user->createOrGetStripeCustomer();
$checkout = $user
->newSubscription('default', $subscription->stripePriceId(forceEap: $user->isEapCustomer(), interval: $this->interval))
->allowPromotionCodes()
->checkout([
'success_url' => $this->successUrl(),
'cancel_url' => route('pricing'),
'consent_collection' => [
'terms_of_service' => 'required',
],
'customer_update' => [
'name' => 'auto',
'address' => 'auto',
],
'tax_id_collection' => [
'enabled' => true,
],
]);
return redirect($checkout->url);
}
public function previewUpgrade(): void
{
$user = Auth::user();
if (! $user) {
return;
}
$subscription = $user->subscription('default');
if (! $subscription || ! $subscription->active()) {
return;
}
$newPriceId = Subscription::Max->stripePriceId(forceEap: $user->isEapCustomer(), interval: $this->interval);
try {
$invoice = $subscription->previewInvoice($newPriceId);
$currency = $invoice->asStripeInvoice()->currency;
$newPlanCharge = 0;
$prorationCredit = 0;
$prorationCharge = 0;
foreach ($invoice->invoiceLineItems() as $item) {
$raw = $item->asStripeInvoiceLineItem();
if (! $raw->proration) {
$newPlanCharge += $raw->amount;
} elseif ($raw->amount < 0) {
$prorationCredit += abs($raw->amount);
} else {
$prorationCharge += $raw->amount;
}
}
$displayedCharge = $prorationCharge ?: $newPlanCharge;
$amountDue = max(0, $displayedCharge - $prorationCredit);
$remainingCredit = max(0, $prorationCredit - $displayedCharge);
$this->upgradePreview = [
'amount_due' => Cashier::formatAmount($amountDue, $currency),
'raw_amount_due' => $amountDue,
'new_charge' => Cashier::formatAmount($displayedCharge, $currency),
'is_prorated' => $prorationCharge > 0,
'credit' => $prorationCredit > 0 ? Cashier::formatAmount($prorationCredit, $currency) : null,
'remaining_credit' => $remainingCredit > 0 ? Cashier::formatAmount($remainingCredit, $currency) : null,
];
} catch (\Exception $e) {
Log::error('Failed to preview upgrade invoice', ['error' => $e->getMessage()]);
$this->upgradePreview = null;
}
}
public function upgradeSubscription(): mixed
{
$user = Auth::user();
if (! $user) {
Log::error('Failed to upgrade subscription. User is not authenticated.');
return null;
}
$subscription = $user->subscription('default');
if (! $subscription || ! $subscription->active()) {
Log::error('Failed to upgrade subscription. No active subscription found.');
return null;
}
$newPriceId = Subscription::Max->stripePriceId(forceEap: $user->isEapCustomer(), interval: $this->interval);
$subscription->skipTrial()->swapAndInvoice($newPriceId);
return redirect(route('dashboard'))->with('success', 'Your subscription has been upgraded to Ultra!');
}
private function findOrCreateUser(string $email): User
{
Validator::validate(['email' => $email], [
'email' => 'required|email|max:255',
]);
return User::firstOrCreate([
'email' => $email,
], [
'password' => Hash::make(Str::random(72)),
]);
}
private function successUrl(): string
{
// This is a hack to get the route() function to work. If you try
// to pass {CHECKOUT_SESSION_ID} to the route function, it will
// throw an error.
return Str::replace(
'abc',
'{CHECKOUT_SESSION_ID}',
route('order.success', ['checkoutSessionId' => 'abc'])
);
}
public function render()
{
$hasExistingSubscription = false;
$currentPlanName = null;
$isAlreadyUltra = false;
$isEapCustomer = false;
$eapYearlyPrice = null;
$eapDiscountPercent = null;
$eapSavingsVsMonthly = null;
$regularYearlyPrice = config('subscriptions.plans.max.price_yearly');
if ($user = Auth::user()) {
$isEapCustomer = $user->isEapCustomer();
if ($isEapCustomer) {
$eapYearlyPrice = config('subscriptions.plans.max.eap_price_yearly');
$eapDiscountPercent = (int) round((1 - $eapYearlyPrice / $regularYearlyPrice) * 100);
$eapSavingsVsMonthly = (config('subscriptions.plans.max.price_monthly') * 12) - $eapYearlyPrice;
}
$subscription = $user->subscription('default');
if ($subscription && $subscription->active()) {
$hasExistingSubscription = true;
$isAlreadyUltra = $user->hasActiveUltraSubscription();
try {
$currentPlanName = Subscription::fromStripePriceId(
$subscription->items->first()?->stripe_price ?? $subscription->stripe_price
)->name();
} catch (\Exception $e) {
$currentPlanName = 'your current plan';
}
}
}
return view('livewire.mobile-pricing', [
'hasExistingSubscription' => $hasExistingSubscription,
'currentPlanName' => $currentPlanName,
'isAlreadyUltra' => $isAlreadyUltra,
'isEapCustomer' => $isEapCustomer,
'eapYearlyPrice' => $eapYearlyPrice,
'eapDiscountPercent' => $eapDiscountPercent,
'eapSavingsVsMonthly' => $eapSavingsVsMonthly,
'regularYearlyPrice' => $regularYearlyPrice,
]);
}
}