Files
ladill-care/app/Http/Controllers/Care/ProController.php
T
isaaccladandCursor 22646dfb62
Deploy Ladill Care / deploy (push) Successful in 1m46s
Add Care Enterprise per-branch billing and Paystack prepaid plans.
Mirrors Queue with GHS 499/branch Enterprise and 6/12/24 month Paystack checkout.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-30 01:55:38 +00:00

274 lines
11 KiB
PHP

<?php
namespace App\Http\Controllers\Care;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Care\Concerns\ScopesToAccount;
use App\Models\Organization;
use App\Services\Billing\BillingClient;
use App\Services\Care\CarePermissions;
use App\Services\Care\PlanService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\View\View;
class ProController extends Controller
{
use ScopesToAccount;
public function index(Request $request, PlanService $plans): View
{
$organization = $this->organization($request);
$canManage = app(CarePermissions::class)->can($this->member($request), 'settings.manage');
$settings = $organization->settings ?? [];
$expiresAt = ! empty($settings['plan_expires_at'])
? Carbon::parse($settings['plan_expires_at'])
: null;
$planKey = $plans->planKey($organization);
$branchCount = $plans->activeBranchCount($organization);
$enterprisePrice = $plans->enterprisePriceMinor($organization);
return view('care.pro.index', [
'organization' => $organization,
'planKey' => $planKey,
'isPro' => $planKey === 'pro',
'isEnterprise' => $planKey === 'enterprise',
'hasPaidPlan' => $plans->hasPaidPlan($organization),
'canManage' => $canManage,
'proPriceMinor' => $plans->proPriceMinor(),
'enterprisePricePerBranchMinor' => $plans->enterprisePricePerBranchMinor(),
'enterprisePriceMinor' => $enterprisePrice,
'branchCount' => $branchCount,
'canSubscribeEnterprise' => $plans->canSubscribeEnterprise($organization),
'enterpriseMinBranches' => (int) config('care.enterprise.min_branches', 2),
'prepaidMonths' => (array) config('care.prepaid_months', [6, 12, 24]),
'currency' => (string) config('billing.currency', 'GHS'),
'planExpiresAt' => $expiresAt,
'enterpriseBilledBranches' => (int) ($settings['enterprise_billed_branches'] ?? $branchCount),
'salesUrl' => ladill_platform_url('contact-sales'),
]);
}
public function subscribe(Request $request, PlanService $plans, BillingClient $billing): RedirectResponse
{
$this->authorizeAbility($request, 'settings.manage');
$organization = $this->organization($request);
if ($plans->hasPaidPlan($organization)) {
return redirect()->route('care.pro.index')
->with('success', 'Your organization already has an active paid plan.');
}
return $this->chargeMonthlyWallet(
$organization,
$billing,
$plans->proPriceMinor(),
'pro',
'care_pro',
'care-pro-'.$organization->id.'-'.now()->format('Y-m-d-His'),
'Ladill Care Pro — monthly subscription',
'Welcome to Care Pro — active for one month.',
);
}
public function subscribeEnterprise(Request $request, PlanService $plans, BillingClient $billing): RedirectResponse
{
$this->authorizeAbility($request, 'settings.manage');
$organization = $this->organization($request);
if ($plans->hasPaidPlan($organization)) {
return redirect()->route('care.pro.index')
->with('success', 'Your organization already has an active paid plan.');
}
if (! $plans->canSubscribeEnterprise($organization)) {
$min = (int) config('care.enterprise.min_branches', 2);
return redirect()->route('care.pro.index')
->with('error', "Enterprise billing requires at least {$min} active branches. Add another branch or choose Pro for a single site.");
}
return $this->chargeMonthlyWallet(
$organization,
$billing,
$plans->enterprisePriceMinor($organization),
'enterprise',
'care_enterprise',
'care-enterprise-'.$organization->id.'-'.now()->format('Y-m-d-His'),
'Ladill Care Enterprise — monthly subscription',
'Welcome to Care Enterprise — active for one month.',
$plans->activeBranchCount($organization),
);
}
public function subscribePrepaid(Request $request, PlanService $plans, BillingClient $billing): RedirectResponse
{
$this->authorizeAbility($request, 'settings.manage');
$validated = $request->validate([
'plan' => ['required', 'in:pro,enterprise'],
'months' => ['required', 'integer', 'in:6,12,24'],
]);
$organization = $this->organization($request);
if ($plans->hasPaidPlan($organization)) {
return redirect()->route('care.pro.index')
->with('success', 'Your organization already has an active paid plan.');
}
$plan = $validated['plan'];
$months = (int) $validated['months'];
if ($plan === 'enterprise' && ! $plans->canSubscribeEnterprise($organization)) {
$min = (int) config('care.enterprise.min_branches', 2);
return redirect()->route('care.pro.index')
->with('error', "Enterprise billing requires at least {$min} active branches.");
}
$monthlyMinor = $plan === 'enterprise'
? $plans->enterprisePriceMinor($organization)
: $plans->proPriceMinor();
$amountMinor = $monthlyMinor * $months;
$branches = $plan === 'enterprise' ? $plans->activeBranchCount($organization) : null;
try {
$checkout = $billing->initiatePlanCheckout(
$organization->owner_ref,
$plan,
$months,
$amountMinor,
route('care.pro.paystack.callback'),
array_filter([
'organization_id' => $organization->id,
'enterprise_billed_branches' => $branches,
], static fn ($v) => $v !== null),
);
} catch (\Throwable) {
return redirect()->route('care.pro.index')
->with('error', 'Could not start Paystack checkout. Please try again.');
}
$url = trim((string) ($checkout['checkout_url'] ?? ''));
if ($url === '') {
return redirect()->route('care.pro.index')
->with('error', 'Paystack did not return a checkout URL.');
}
return redirect()->away($url);
}
public function paystackCallback(Request $request, BillingClient $billing, PlanService $plans): RedirectResponse
{
$reference = (string) $request->query('reference', '');
if ($reference === '') {
return redirect()->route('care.pro.index')->with('error', 'Missing payment reference.');
}
try {
$result = $billing->verifyPlanCheckout($reference);
} catch (\Throwable) {
return redirect()->route('care.pro.index')
->with('error', 'Could not verify payment. Contact support with reference: '.$reference);
}
if (! ($result['paid'] ?? false)) {
return redirect()->route('care.pro.index')
->with('error', 'Payment was not completed.');
}
$metadata = (array) ($result['metadata'] ?? []);
$organization = Organization::query()->find((int) ($metadata['organization_id'] ?? 0));
if (! $organization) {
return redirect()->route('care.pro.index')
->with('error', 'Organization not found for this payment.');
}
$this->authorizeAbility($request, 'settings.manage');
if ($this->organization($request)->id !== $organization->id) {
abort(403);
}
$plan = (string) ($result['plan'] ?? 'pro');
$months = (int) ($result['months'] ?? 0);
$branches = isset($metadata['enterprise_billed_branches'])
? (int) $metadata['enterprise_billed_branches']
: null;
$this->activatePrepaidPlan($organization, $plan, $months, $branches);
$label = $plan === 'enterprise' ? 'Care Enterprise' : 'Care Pro';
return redirect()->route('care.pro.index')
->with('success', "{$label} is active for {$months} months.");
}
private function chargeMonthlyWallet(
Organization $organization,
BillingClient $billing,
int $priceMinor,
string $plan,
string $billingSource,
string $reference,
string $description,
string $successMessage,
?int $enterpriseBranches = null,
): RedirectResponse {
try {
if (! $billing->canAfford($organization->owner_ref, $priceMinor)) {
return redirect()->route('care.pro.index')
->with('error', 'Insufficient wallet balance. Top up your Ladill wallet to upgrade.');
}
$charged = $billing->debit(
$organization->owner_ref,
$priceMinor,
$billingSource,
$reference,
$description,
);
} catch (\Throwable) {
return redirect()->route('care.pro.index')
->with('error', 'Could not process upgrade. Please try again.');
}
if (! $charged) {
return redirect()->route('care.pro.index')
->with('error', 'Insufficient wallet balance. Top up your Ladill wallet to upgrade.');
}
$settings = $organization->settings ?? [];
$settings['plan'] = $plan;
$settings['auto_renew'] = true;
$settings['billing_method'] = 'wallet_monthly';
$settings['plan_expires_at'] = now()
->addDays((int) config('care.pro.period_days', 30))
->toIso8601String();
if ($enterpriseBranches !== null) {
$settings['enterprise_billed_branches'] = $enterpriseBranches;
}
unset($settings['plan_renewal_error']);
$organization->update(['settings' => $settings]);
return redirect()->route('care.pro.index')->with('success', $successMessage);
}
private function activatePrepaidPlan(
Organization $organization,
string $plan,
int $months,
?int $enterpriseBranches = null,
): void {
$settings = $organization->settings ?? [];
$settings['plan'] = $plan;
$settings['auto_renew'] = false;
$settings['billing_method'] = 'paystack_prepaid';
$settings['plan_expires_at'] = now()->addMonths($months)->toIso8601String();
if ($enterpriseBranches !== null) {
$settings['enterprise_billed_branches'] = $enterpriseBranches;
}
unset($settings['plan_renewal_error']);
$organization->update(['settings' => $settings]);
}
}