Calculate upcoming charge when coupons are used
salmanhijazi opened this issue · 5 comments
Hello,
From my understanding so far, the discount of a coupon gets applied at the time the order is being processed. I want to show users the amount they will be charged in the next cycle when they have a coupon redeemed. Here's how I'm planning to get this done:
- Get the scheduled order item from the subscription
- Get the redeemed coupon details for the subscription and check if the redeemed coupon times_left > 0
- Get the discount amount/percentage from the coupon and calculate the final invoice amount
- Display it to the user
Is there a better way to do this? Doing it this way will require me to code the same logic as that in a coupon preprocessor. Maybe use some internal functions to execute preprocessors and calculate the amount but not create order items until they're needed?
Thanks!
Anything?
Notice that multiple order items can be scheduled for a billable model, not all are necessarily tied to a subscription.
In my use case so far, we only have one active subscription per user. There would be features with one-time fees coming up, but I don't think that would interfere with the scheduled items. Again, are there no internal functions that I can use to calculate these values? I tried looking through the source but didn't find anything outside of those that are executed at the time of processing.
Cheers
I agree a simpler method is desirable, I've struggled with the same in Spark. Feel free to suggest an approach for this and/or submit a PR.
We're planning to (alpha) launch v2 in a month or so, this feature would be good for v3.
I managed to get it done by using almost only package functions. Here's how I got around to it in my controller.
$scheduledOrderItems = $subscription->scheduledOrderItem->toCollection();
$redeemedCoupons = $subscription->redeemedCoupons()->active()->get();
$redeemedCoupons->each(function($redeemedCoupon) use (&$scheduledOrderItems) {
$scheduledOrderItems->push( $redeemedCoupon->handler()->getDiscountOrderItems($scheduledOrderItems)->first() );
});
$upcomingPayment['total_payable'] = money(0, $scheduledOrderItems->first()->getCurrency());
scheduledOrderItems->each(function ($item) use (&$upcomingPayment) {
$upcomingPayment['total_payable'] = $upcomingPayment['total_payable']->add($item->getTotal());
$upcomingPayment['payables'][] = array(
'description' => $item->description,
'price' => $this->formatAmount($item->getTotal())
);
});
$upcomingPayment['total_payable'] = $this->formatAmount($upcomingPayment['total_payable']);
Not the cleanest, but gets the job done for now. If you find any optimizations, please do suggest!
Looking forward to v2.
Thank you!