forked from mollie/laravel-cashier-mollie
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSubscription.php
More file actions
979 lines (836 loc) · 27.9 KB
/
Copy pathSubscription.php
File metadata and controls
979 lines (836 loc) · 27.9 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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
<?php
namespace Laravel\Cashier;
use Carbon\Carbon;
use Illuminate\Contracts\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Event;
use Laravel\Cashier\Coupon\AppliedCoupon;
use Laravel\Cashier\Coupon\Contracts\AcceptsCoupons;
use Laravel\Cashier\Events\SubscriptionCancelled;
use Laravel\Cashier\Events\SubscriptionPlanSwapped;
use Laravel\Cashier\Events\SubscriptionQuantityUpdated;
use Laravel\Cashier\Events\SubscriptionResumed;
use Laravel\Cashier\Events\SubscriptionStarted;
use Laravel\Cashier\Order\Contracts\InteractsWithOrderItems;
use Laravel\Cashier\Order\Contracts\PreprocessesOrderItems;
use Laravel\Cashier\Order\OrderItem;
use Laravel\Cashier\Order\OrderItemCollection;
use Laravel\Cashier\Plan\Contracts\Plan;
use Laravel\Cashier\Plan\Contracts\PlanRepository;
use Laravel\Cashier\Refunds\Contracts\IsRefundable;
use Laravel\Cashier\Refunds\RefundItem;
use Laravel\Cashier\Traits\HasOwner;
use Laravel\Cashier\Types\SubscriptionCancellationReason;
use LogicException;
use Money\Currency;
use Money\Money;
/**
* @property int id
* @property \Carbon\Carbon cycle_ends_at
* @property \Carbon\Carbon cycle_started_at
* @property \Carbon\Carbon ends_at
* @property mixed owner_id
* @property string owner_type
* @property string next_plan
* @property string plan
* @property int quantity
* @property mixed scheduled_order_item_id
* @property OrderItem scheduledOrderItem
* @property float tax_percentage
* @property \Carbon\Carbon trial_ends_at
* @property float cycle_progress
* @property float cycle_left
* @property string $currency
*/
class Subscription extends Model implements InteractsWithOrderItems, PreprocessesOrderItems, AcceptsCoupons, IsRefundable
{
use HasOwner;
/**
* The attributes that are not mass assignable.
*
* @var array
*/
protected $guarded = [];
/**
* The attributes that should be mutated to dates.
*
* @var array
*/
protected $casts = [
'trial_ends_at' => 'datetime',
'cycle_started_at' => 'datetime',
'cycle_ends_at' => 'datetime',
'ends_at' => 'datetime',
];
/**
* The event map for the model.
*
* @var array
*/
protected $dispatchesEvents = [
'created' => SubscriptionStarted::class,
];
public function scopeWhereActive(Builder $query): Builder
{
return $query->whereNull('ends_at')
->orWhere(fn (Builder $query) => $this->scopeWhereOnTrial($query))
->orWhere(fn (Builder $query) => $this->scopeWhereOnGracePeriod($query));
}
public function scopeWhereNotActive(Builder $query): Builder
{
return $query->whereNotNull('ends_at')
->where(fn (Builder $query) => $this->scopeWhereNotOnTrial($query))
->where(fn (Builder $query) => $this->scopeWhereNotOnGracePeriod($query));
}
public function scopeWhereCancelled(Builder $query): Builder
{
return $query->whereNotNull('ends_at')
->where(fn (Builder $query) => $this->scopeWhereNotOnGracePeriod($query));
}
public function scopeWhereNotCancelled(Builder $query): Builder
{
return $query->whereNull('ends_at')
->orWhere(fn (Builder $query) => $this->scopeWhereOnGracePeriod($query));
}
public function scopeWhereOnTrial(Builder $query): Builder
{
return $query->whereNotNull('trial_ends_at')
->where('trial_ends_at', '>', now());
}
public function scopeWhereNotOnTrial(Builder $query): Builder
{
return $query->whereNull('trial_ends_at')
->orWhere('trial_ends_at', '<=', now());
}
public function scopeWhereOnGracePeriod(Builder $query): Builder
{
return $query->whereNotNull('ends_at')
->where('ends_at', '>', now());
}
public function scopeWhereNotOnGracePeriod(Builder $query): Builder
{
return $query->whereNull('ends_at')
->orWhere('ends_at', '<=', now());
}
public function scopeWhereRecurring(Builder $query): Builder
{
return $query->where(fn (Builder $query) => $this->scopeWhereNotOnTrial($query))
->where(fn (Builder $query) => $this->scopeWhereNotCancelled($query));
}
public function scopeWhereNotRecurring(Builder $query): Builder
{
return $query->where(fn (Builder $query) => $this->scopeWhereOnTrial($query))
->orWhere(fn (Builder $query) => $this->scopeWhereCancelled($query));
}
/**
* Determine if the subscription is valid.
*
* @return bool
*/
public function valid()
{
return $this->active();
}
/**
* Determine if the subscription is active.
*
* @return bool
*/
public function active()
{
return is_null($this->ends_at) || $this->onTrial() || $this->onGracePeriod();
}
/**
* Determine if the subscription has ended and the grace period has expired.
*
* @return bool
*/
public function ended()
{
return $this->cancelled() && !$this->onGracePeriod();
}
/**
* Determine if the subscription is within its trial period.
*
* @return bool
*/
public function onTrial()
{
return $this->trial_ends_at && $this->trial_ends_at->isFuture();
}
/**
* Determine if the subscription is within its grace period after cancellation.
*
* @return bool
*/
public function onGracePeriod()
{
return $this->ends_at && $this->ends_at->isFuture();
}
/**
* Determine if the subscription is recurring and not on trial.
*
* @return bool
*/
public function recurring()
{
return !$this->onTrial() && !$this->cancelled();
}
/**
* Determine if the subscription is no longer active.
*
* @return bool
*/
public function cancelled()
{
return !is_null($this->ends_at);
}
/**
* Helper function to determine the current billing cycle progress ratio.
* Ranging from 0 (not started) to 1 (completed).
*
* @param Carbon|null $now
* @param int $precision
* @return float
*/
public function getCycleProgressAttribute($now = null, $precision = 5)
{
$now = $now ?: now();
$cycle_started_at = $this->cycle_started_at->copy();
$cycle_ends_at = $this->cancelled() ? $this->ends_at->copy() : $this->cycle_ends_at->copy();
// Cycle completed
if ($cycle_ends_at->lessThanOrEqualTo($now)) {
return 1;
}
// Cycle not yet started
if ($cycle_started_at->greaterThanOrEqualTo($now)) {
return 0;
}
$total_cycle_seconds = $cycle_started_at->diffInSeconds($cycle_ends_at);
$seconds_progressed = $cycle_started_at->diffInSeconds($now);
return abs(round($seconds_progressed / $total_cycle_seconds, $precision));
}
/**
* Helper function to determine the current billing cycle inverted progress ratio.
* Ranging from 0 (completed) to 1 (not yet started).
*
* @param \Carbon\Carbon|null $now
* @param int|null $precision
* @return float
*/
public function getCycleLeftAttribute(?Carbon $now = null, ?int $precision = 5)
{
return (float) 1 - $this->getCycleProgressAttribute($now, $precision);
}
/**
* Swap the subscription to another plan right now by ending the current billing cycle and starting a new one.
* A new Order is processed along with the payment.
*
* @param string $plan
* @param bool $invoiceNow
* @return $this
*/
public function swap(string $plan, $invoiceNow = true)
{
/** @var Plan $newPlan */
$newPlan = app(PlanRepository::class)::findOrFail($plan);
$previousPlan = $this->plan;
if ($this->cancelled()) {
$this->cycle_ends_at = $this->ends_at;
$this->ends_at = null;
}
$applyNewSettings = function () use ($newPlan) {
$this->plan = $newPlan->name();
};
$this->restartCycleWithModifications($applyNewSettings, now(), $invoiceNow);
Event::dispatch(new SubscriptionPlanSwapped($this, $previousPlan));
return $this;
}
/**
* Swap the subscription to a new plan, and invoice immediately.
*
* @param string $plan
* @return $this
*/
public function swapAndInvoice($plan)
{
return $this->swap($plan, true);
}
/**
* Schedule this subscription to be swapped to another plan once the current cycle has completed.
*
* @param string $plan
* @return $this
*/
public function swapNextCycle(string $plan)
{
/** @var Plan $newPlan */
$newPlan = app(PlanRepository::class)::findOrFail($plan);
return DB::transaction(function () use ($plan, $newPlan) {
if ($this->cancelled()) {
$this->cycle_ends_at = $this->ends_at;
$this->ends_at = null;
}
$this->next_plan = $plan;
$this->removeScheduledOrderItem();
$this->scheduleNewOrderItemAt($this->cycle_ends_at, [], true, $newPlan);
$this->save();
return $this;
});
}
/**
* Cancel the subscription at the end of the billing period.
*
* @param string|null $reason
* @return $this
*/
public function cancel($reason = SubscriptionCancellationReason::UNKNOWN)
{
// If the user was on trial, we will set the grace period to end when the trial
// would have ended. Otherwise, we'll retrieve the end of the billing cycle
// period and make that the end of the grace period for this current user.
$grace_ends_at = $this->onTrial() ? $this->trial_ends_at : $this->cycle_ends_at;
return $this->cancelAt($grace_ends_at, $reason);
}
/**
* Cancel the subscription at the date provided.
*
* @param \Carbon\Carbon $endsAt
* @param string $reason
* @return $this
*/
public function cancelAt(Carbon $endsAt, $reason = SubscriptionCancellationReason::UNKNOWN)
{
DB::transaction(function () use ($endsAt) {
$this->removeScheduledOrderItem();
$this->fill([
'ends_at' => $endsAt,
'cycle_ends_at' => null,
])->save();
});
Event::dispatch(new SubscriptionCancelled($this, $reason));
return $this;
}
/**
* Cancel the subscription immediately.
*
* @param string $reason
* @return $this
*/
public function cancelNow($reason = SubscriptionCancellationReason::UNKNOWN)
{
return $this->cancelAt(now(), $reason);
}
/**
* Remove the subscription's scheduled order item.
* Optionally persists the reference removal on the subscription.
*
* @param false bool $save
* @return $this
*
* @throws \Exception
*/
protected function removeScheduledOrderItem($save = false)
{
$item = $this->scheduledOrderItem;
if ($item && $item->isProcessed(false)) {
$item->delete();
}
$this->fill(['scheduled_order_item_id' => null]);
if ($save) {
$this->save();
}
return $this;
}
/**
* Resume the cancelled subscription.
*
* @return $this
*
* @throws \LogicException
*/
public function resume()
{
if (!$this->cancelled()) {
throw new LogicException('Unable to resume a subscription that is not cancelled.');
}
if (!$this->onGracePeriod()) {
throw new LogicException('Unable to resume a subscription that is not within grace period.');
}
return DB::transaction(function () {
$item = $this->scheduleNewOrderItemAt($this->ends_at);
$this->fill([
'cycle_ends_at' => $this->ends_at,
'ends_at' => null,
'scheduled_order_item_id' => $item->id,
])->save();
Event::dispatch(new SubscriptionResumed($this));
return $this;
});
}
/**
* Get the order items for this subscription.
*
* @return \Illuminate\Database\Eloquent\Relations\MorphMany
*/
public function orderItems()
{
return $this->morphMany(Cashier::$orderItemModel, 'orderable');
}
/**
* Relation to the scheduled order item, if defined.
*
* @return \Illuminate\Database\Eloquent\Relations\HasOne
*/
public function scheduledOrderItem()
{
return $this->hasOne(Cashier::$orderItemModel, 'id', 'scheduled_order_item_id');
}
/**
* Relation to the scheduled order item, if defined.
*
* @return \Illuminate\Database\Eloquent\Relations\HasOne
*/
public function scheduled_order_item()
{
return $this->scheduledOrderItem();
}
/**
* Schedule a new subscription order item at the provided datetime.
*
* @param Carbon|null $process_at
* @param array $item_overrides
* @param bool $fill_link Indicates whether scheduled_order_item_id field should be filled to point to the newly scheduled order item
* @param \Laravel\Cashier\Plan\Contracts\Plan|null $plan
* @return \Illuminate\Database\Eloquent\Model|\Laravel\Cashier\Order\OrderItem
*/
public function scheduleNewOrderItemAt(Carbon $process_at, $item_overrides = [], $fill_link = true, ?Plan $plan = null)
{
if ($this->scheduled_order_item_id) {
throw new LogicException('Cannot schedule a new subscription order item if there is already one scheduled.');
}
if (is_null($plan)) {
$plan = $this->plan();
}
$item = $this->orderItems()->create(array_merge(
[
'owner_id' => $this->owner_id,
'owner_type' => $this->owner_type,
'process_at' => $process_at,
'currency' => $plan->amount()->getCurrency()->getCode(),
'unit_price' => (int) $plan->amount()->getAmount(),
'quantity' => $this->quantity ?: 1,
'tax_percentage' => $this->tax_percentage,
'description' => $plan->description(),
],
$item_overrides
));
if ($fill_link) {
$this->fill([
'scheduled_order_item_id' => $item->id,
]);
}
return $item;
}
/**
* Called right before processing the order item into an order.
*
* @param OrderItem $item
* @return \Laravel\Cashier\Order\OrderItemCollection
*/
public static function preprocessOrderItem(OrderItem $item)
{
/** @var Subscription $subscription */
$subscription = $item->orderable;
return $subscription->plan()->orderItemPreprocessors()->handle($item);
}
/**
* Called after processing the order item into an order.
*
* @param OrderItem $item
* @return OrderItem The order item that's being processed
*/
public static function processOrderItem(OrderItem $item)
{
/** @var Subscription scheduled_order_item_id */
$subscription = $item->orderable;
$plan_swapped = false;
$previousPlan = null;
if (!empty($subscription->next_plan)) {
$plan_swapped = true;
$previousPlan = $subscription->plan;
$subscription->plan = $subscription->next_plan;
$subscription->next_plan = null;
}
$item = DB::transaction(function () use (&$subscription, $item) {
$subscription->cycle_started_at = $subscription->cycle_ends_at;
$subscription->cycle_ends_at = $subscription->plan()->interval()->getEndOfNextSubscriptionCycle($subscription);
// Requires cleared scheduled order item before continuing
$subscription->scheduled_order_item_id = null;
$subscription->scheduleNewOrderItemAt($subscription->cycle_ends_at);
$subscription->save();
$item->description_extra_lines = [
trans('cashier::order_item.cycle', [
'from' => $subscription->cycle_started_at->format('Y-m-d'),
'to' => $subscription->cycle_ends_at->format('Y-m-d'),
]),
];
return $item;
});
if ($plan_swapped) {
Event::dispatch(new SubscriptionPlanSwapped($subscription, $previousPlan));
}
return $item;
}
/**
* Sync the tax percentage of the owner to the subscription.
*
* @return Subscription
*/
public function syncTaxPercentage()
{
return DB::transaction(function () {
$this->update([
'tax_percentage' => $this->owner->taxPercentage(),
]);
return $this;
});
}
/**
* Get the plan instance for this subscription.
*
* @return \Laravel\Cashier\Plan\Plan
*/
public function plan()
{
return app(PlanRepository::class)::find($this->plan);
}
/**
* Get the plan instance for this subscription's next cycle.
*
* @return \Laravel\Cashier\Plan\Plan
*/
public function nextPlan()
{
return app(PlanRepository::class)::find($this->next_plan);
}
/**
* Get the currency for this subscription.
*
* @example EUR
*
* @return string
*/
public function getCurrencyAttribute()
{
return optional($this->plan())->amount()->getCurrency()->getCode();
}
/**
* Gets the amount to be reimbursed for the subscription's unused time.
*
* Result range value: (-X up to 0)
*
* @param \Carbon\Carbon|null $now
* @return \Money\Money
*/
public function getReimbursableAmountForUnusedTime(?Carbon $now = null): Money
{
$now = $now ?: now();
if ($this->onTrial()) {
return $this->zero();
}
if (round($this->getCycleLeftAttribute($now), 5) == 0) {
return $this->zero();
}
return $this->reimbursableAmount()
->negative()
->multiply(sprintf('%.8F', $this->getCycleLeftAttribute($now)));
}
/**
* Handle a failed payment.
*
* @param \Laravel\Cashier\Order\OrderItem $item
* @return void
*/
public static function handlePaymentFailed(OrderItem $item)
{
$subscription = $item->orderable;
$endsAt = $subscription->onTrial() ? $subscription->trial_ends_at : now();
$subscription->cancelAt($endsAt, SubscriptionCancellationReason::PAYMENT_FAILED);
}
/**
* Handle a paid payment.
*
* @param \Laravel\Cashier\Order\OrderItem $item
* @return void
*/
public static function handlePaymentPaid(OrderItem $item)
{
$subscription = $item->orderable;
if ($subscription->ends_at !== null) {
DB::transaction(function () use ($item, $subscription) {
if (!$subscription->scheduled_order_item_id) {
$item = $subscription->scheduleNewOrderItemAt($subscription->ends_at);
}
$subscription->fill([
'cycle_ends_at' => $subscription->plan()->interval()->getEndOfNextSubscriptionCycle($subscription),
'ends_at' => null,
'scheduled_order_item_id' => $item->id,
])->save();
});
}
}
public static function handlePaymentRefunded(RefundItem $refundItem)
{
//
}
public static function handlePaymentRefundFailed(RefundItem $refundItem)
{
//
}
/**
* Increment the quantity of the subscription.
*
* @param int $count
* @param bool $invoiceNow
* @return \Laravel\Cashier\Subscription
*
* @throws \Throwable
*/
public function incrementQuantity(int $count = 1, $invoiceNow = true)
{
return $this->updateQuantity($this->quantity + $count, $invoiceNow);
}
/**
* Increment the quantity of the subscription, and invoice immediately.
*
* @param int $count
* @return \Laravel\Cashier\Subscription
*
* @throws \Throwable
*/
public function incrementAndInvoice($count = 1)
{
return $this->incrementQuantity($count, true);
}
/**
* Decrement the quantity of the subscription.
*
* @param int $count
* @param bool $invoiceNow
* @return \Laravel\Cashier\Subscription
*
* @throws \Throwable
*/
public function decrementQuantity(int $count = 1, $invoiceNow = true)
{
return $this->updateQuantity($this->quantity - $count, $invoiceNow);
}
/**
* Update the quantity of the subscription.
*
* @param int $quantity
* @param bool $invoiceNow
* @return $this
*
* @throws \Throwable
*/
public function updateQuantity(int $quantity, $invoiceNow = true)
{
throw_if(
$quantity < 1,
new LogicException('Subscription quantity must be at least 1.')
);
$oldQuantity = $this->quantity;
$this->restartCycleWithModifications(function () use ($quantity) {
$this->quantity = $quantity;
}, now(), $invoiceNow);
$this->save();
Event::dispatch(new SubscriptionQuantityUpdated($this, $oldQuantity));
return $this;
}
/**
* Force the trial to end immediately.
*
* This method must be combined with swap, resume, etc.
*
* @return $this
*/
public function skipTrial()
{
$this->trial_ends_at = null;
return $this;
}
/**
* @param \Money\Money $amount
* @param array $overrides
* @return OrderItem
*/
protected function reimburse(Money $amount, array $overrides = [])
{
return $this->owner->orderItems()->create(array_merge([
'process_at' => now(),
'description' => $this->plan()->description(),
'currency' => $amount->getCurrency()->getCode(),
'unit_price' => $amount->getAmount(),
'quantity' => 1,
'tax_percentage' => $this->tax_percentage,
], $overrides));
}
/**
* The maximum amount that can be reimbursed, ranging from zero to a positive Money amount.
*
* @return \Money\Money
*/
protected function reimbursableAmount()
{
// Determine base amount eligible to reimburse
$latestProcessedOrderItem = $this->latestProcessedOrderItem();
if (!$latestProcessedOrderItem) {
return $this->zero();
}
$reimbursableAmount = $latestProcessedOrderItem->getTotal()
->subtract($latestProcessedOrderItem->getTax()); // tax calculated elsewhere
// Subtract any refunds
/** @var \Laravel\Cashier\Refunds\RefundItemCollection $refundItems */
$refundItems = Cashier::$refundItemModel::where('original_order_item_id', $latestProcessedOrderItem->id)->get();
if ($refundItems->isNotEmpty()) {
$reimbursableAmount = $reimbursableAmount->subtract($refundItems->getTotal());
}
// Subtract any applied coupons
$order = $latestProcessedOrderItem->order;
$orderId = $order->id;
$appliedCoupons = $this->appliedCoupons()->with('orderItems')->get();
$appliedCouponOrderItems = $appliedCoupons->reduce(function (OrderItemCollection $carry, AppliedCoupon $coupon) use ($orderId) {
$items = $coupon->orderItems->filter(function (OrderItem $item) use ($orderId) {
return $item->order_id === $orderId;
});
return $carry->concat($items->toArray());
}, new OrderItemCollection);
if ($appliedCouponOrderItems->isNotEmpty()) {
$discountTotal = $appliedCouponOrderItems->getTotal();
$reimbursableAmount = $reimbursableAmount->subtract($discountTotal->absolute());
}
// Guard against a negative value
if ($reimbursableAmount->isNegative()) {
return $this->zero();
}
return $reimbursableAmount;
}
/**
* @param \Carbon\Carbon|null $now
* @return null|\Laravel\Cashier\Order\OrderItem
*/
protected function reimburseUnusedTime(?Carbon $now = null)
{
$now = $now ?: now();
if ($this->onTrial()) {
return null;
}
if (round($this->getCycleLeftAttribute($now), 5) == 0) {
return null;
}
$amount = $this->reimbursableAmount()
->negative()
->multiply(sprintf('%.8F', $this->getCycleLeftAttribute($now)));
if ($amount->isZero()) {
return null;
}
return $this->reimburse($amount, ['description' => $this->plan()->description()]);
}
/**
* Wrap up the current billing cycle, apply modifications to this subscription and start a new cycle.
*
* @param \Closure $applyNewSettings
* @param \Carbon\Carbon|null $now
* @param bool $invoiceNow
* @return \Laravel\Cashier\Subscription
*/
public function restartCycleWithModifications(\Closure $applyNewSettings, ?Carbon $now = null, $invoiceNow = true)
{
$now = $now ?: now();
return DB::transaction(function () use ($applyNewSettings, $now, $invoiceNow) {
// Wrap up current billing cycle
$this->removeScheduledOrderItem();
$reimbursement = $this->reimburseUnusedTime($now);
$orderItems = (new OrderItemCollection([$reimbursement]))->filter();
// Apply new subscription settings
call_user_func($applyNewSettings);
$onTrial = $this->onTrial();
if ($onTrial) {
// Reschedule next cycle's OrderItem using the new subscription settings
$orderItems[] = $this->scheduleNewOrderItemAt($this->trial_ends_at);
} else { // Start a new billing cycle using the new subscription settings
// Reset the billing cycle
$this->cycle_started_at = $now;
$this->cycle_ends_at = $now;
// Create a new OrderItem, starting a new billing cycle
$orderItems[] = $this->scheduleNewOrderItemAt($now);
}
$this->save();
if (!$onTrial && $invoiceNow) {
$order = Cashier::$orderModel::createFromItems($orderItems);
$order->processPayment();
}
return $this;
});
}
/**
* Wrap up the current billing cycle and start a new cycle.
*
* @param \Carbon\Carbon|null $now
* @param bool $invoiceNow
* @return \Laravel\Cashier\Subscription
*/
public function restartCycle(?Carbon $now = null, $invoiceNow = true)
{
return $this->restartCycleWithModifications(function () {
}, $now, $invoiceNow);
}
/**
* Any coupons redeemed for this subscription
*
* @return \Illuminate\Database\Eloquent\Relations\MorphMany
*/
public function redeemedCoupons()
{
return $this->morphMany(Cashier::$redeemedCouponModel, 'model');
}
/**
* Any coupons applied to this subscription
*
* @return \Illuminate\Database\Eloquent\Relations\MorphMany
*/
public function appliedCoupons()
{
return $this->morphMany(Cashier::$appliedCouponModel, 'model');
}
/**
* @return string
*/
public function ownerType()
{
return $this->owner_type;
}
/**
* @return mixed
*/
public function ownerId()
{
return $this->owner_id;
}
/**
* Retrieve the latest processed order item.
*
* @return OrderItem|null
*/
public function latestProcessedOrderItem()
{
return $this->orderItems()->processed()->orderByDesc('process_at')->first();
}
private function zero(): Money
{
return new Money('0.00', new Currency($this->currency));
}
}