Deep UX: 2-column automations, visible appeal cards, platform education, strip model refs
Automations: - 2-column layout: WhatsApp phone LEFT, education RIGHT - Right column: 'How it works' (5 numbered steps), performance stats, timing controls, reply commands, tips - Hero spans full width with photo+dark panel - Improvement CTA is a prominent card, not floating text - No misalignment — phone fills left column naturally Collect: - Appeals shown as visible gap-px grid cards (not hidden dropdown) - Each card shows name, platform, amount raised, pledge count, collection rate - Active appeal has border-l-2 blue indicator - Platform integration clarity: shows 'Donors redirected to JustGiving' etc - Educational section: 'Where to share your link' + 'How payment works' - Explains bank transfer vs JustGiving vs card payment inline AI model: Stripped all model name comments from code (no user-facing references existed)
This commit is contained in:
277
temp_files/care/EditCustomer.php
Normal file
277
temp_files/care/EditCustomer.php
Normal file
@@ -0,0 +1,277 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\CustomerResource\Pages;
|
||||
|
||||
use App\Definitions\PaymentProviders;
|
||||
use App\Filament\Resources\CustomerResource;
|
||||
use App\Filament\Resources\DonationResource;
|
||||
use App\Models\Customer;
|
||||
use App\Services\StripeRefundService;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Components\Textarea;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Resources\Pages\EditRecord;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Illuminate\Support\HtmlString;
|
||||
|
||||
class EditCustomer extends EditRecord
|
||||
{
|
||||
protected static string $resource = CustomerResource::class;
|
||||
|
||||
// ─── Heading: Show who this person IS, not just a name ───────
|
||||
|
||||
public function getHeading(): string|HtmlString
|
||||
{
|
||||
$customer = $this->record;
|
||||
$total = $customer->donations()
|
||||
->whereHas('donationConfirmation', fn ($q) => $q->whereNotNull('confirmed_at'))
|
||||
->sum('amount') / 100;
|
||||
|
||||
$giftAid = $customer->donations()
|
||||
->whereHas('donationPreferences', fn ($q) => $q->where('is_gift_aid', true))
|
||||
->exists();
|
||||
|
||||
$badges = '';
|
||||
if ($total >= 1000) {
|
||||
$badges .= ' <span class="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-amber-100 text-amber-800 ml-2">⭐ Major Donor</span>';
|
||||
}
|
||||
if ($giftAid) {
|
||||
$badges .= ' <span class="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800 ml-2">Gift Aid</span>';
|
||||
}
|
||||
|
||||
$sg = $customer->scheduledGivingDonations()->where('is_active', true)->first();
|
||||
if ($sg) {
|
||||
$amt = '£' . number_format($sg->total_amount / 100, 0);
|
||||
$badges .= ' <span class="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800 ml-2">💙 ' . $amt . '/night</span>';
|
||||
}
|
||||
|
||||
// Monthly donations (reoccurrence=2)
|
||||
$monthly = $customer->donations()
|
||||
->where('reoccurrence', 2)
|
||||
->whereHas('donationConfirmation', fn ($q) => $q->whereNotNull('confirmed_at'))
|
||||
->first();
|
||||
if ($monthly) {
|
||||
$mAmt = '£' . number_format($monthly->amount / 100, 0);
|
||||
$badges .= ' <span class="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-indigo-100 text-indigo-800 ml-2">🔄 ' . $mAmt . '/month</span>';
|
||||
}
|
||||
|
||||
// Recent incomplete donations
|
||||
$incompleteRecent = $customer->donations()
|
||||
->whereDoesntHave('donationConfirmation', fn ($q) => $q->whereNotNull('confirmed_at'))
|
||||
->where('created_at', '>=', now()->subDays(7))
|
||||
->count();
|
||||
if ($incompleteRecent > 0) {
|
||||
$badges .= ' <span class="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800 ml-2">⚠ ' . $incompleteRecent . ' incomplete</span>';
|
||||
}
|
||||
|
||||
return new HtmlString(e($customer->name) . $badges);
|
||||
}
|
||||
|
||||
// ─── Subheading: The one-line story of this donor ────────────
|
||||
|
||||
public function getSubheading(): ?string
|
||||
{
|
||||
$customer = $this->record;
|
||||
$confirmed = $customer->donations()
|
||||
->whereHas('donationConfirmation', fn ($q) => $q->whereNotNull('confirmed_at'));
|
||||
$total = $confirmed->sum('amount') / 100;
|
||||
$count = $confirmed->count();
|
||||
$first = $customer->donations()->oldest()->first();
|
||||
$since = $first ? $first->created_at->format('M Y') : null;
|
||||
|
||||
$parts = [];
|
||||
if ($total > 0) {
|
||||
$parts[] = '£' . number_format($total, 2) . ' donated across ' . $count . ' donations';
|
||||
} else {
|
||||
$parts[] = 'No confirmed donations yet';
|
||||
}
|
||||
if ($since) {
|
||||
$parts[] = 'Supporter since ' . $since;
|
||||
}
|
||||
|
||||
return implode(' · ', $parts);
|
||||
}
|
||||
|
||||
// ─── Header Actions ─────────────────────────────────────────
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
$customer = $this->record;
|
||||
|
||||
// Pre-compute recurring counts for visibility checks
|
||||
$activeScheduled = $customer->scheduledGivingDonations()
|
||||
->where('is_active', true)->count();
|
||||
|
||||
$activeMonthly = $customer->donations()
|
||||
->where('reoccurrence', 2)
|
||||
->where('provider_type', PaymentProviders::STRIPE)
|
||||
->whereHas('donationConfirmation', fn ($q) => $q->whereNotNull('confirmed_at'))
|
||||
->count();
|
||||
|
||||
$hasRecurring = $activeScheduled > 0 || $activeMonthly > 0;
|
||||
|
||||
return array_values(array_filter([
|
||||
|
||||
// ── CANCEL ALL RECURRING ────────────────────────────
|
||||
$hasRecurring ? Action::make('cancel_all_recurring')
|
||||
->label('Cancel All Recurring')
|
||||
->icon('heroicon-o-x-circle')
|
||||
->color('danger')
|
||||
->requiresConfirmation()
|
||||
->modalIcon('heroicon-o-exclamation-triangle')
|
||||
->modalHeading('Cancel All Recurring Giving')
|
||||
->modalDescription(function () use ($customer, $activeScheduled, $activeMonthly) {
|
||||
$parts = [];
|
||||
if ($activeScheduled > 0) {
|
||||
$sgTotal = $customer->scheduledGivingDonations()
|
||||
->where('is_active', true)->sum('total_amount') / 100;
|
||||
$parts[] = $activeScheduled . ' regular giving '
|
||||
. ($activeScheduled === 1 ? 'subscription' : 'subscriptions')
|
||||
. ' (£' . number_format($sgTotal, 2) . ' total)';
|
||||
}
|
||||
if ($activeMonthly > 0) {
|
||||
$parts[] = $activeMonthly . ' monthly '
|
||||
. ($activeMonthly === 1 ? 'donation' : 'donations');
|
||||
}
|
||||
|
||||
return "This will cancel:\n"
|
||||
. implode("\n", array_map(fn ($p) => "• {$p}", $parts))
|
||||
. "\n\nAll Stripe payment methods will be detached. "
|
||||
. "Previously collected payments will NOT be refunded.";
|
||||
})
|
||||
->modalSubmitActionLabel('Cancel All Recurring')
|
||||
->action(function () use ($customer) {
|
||||
$service = app(StripeRefundService::class);
|
||||
$cancelled = 0;
|
||||
|
||||
// Cancel active scheduled giving
|
||||
$activeGiving = $customer->scheduledGivingDonations()
|
||||
->where('is_active', true)->get();
|
||||
foreach ($activeGiving as $sg) {
|
||||
$sg->update(['is_active' => false]);
|
||||
if ($sg->stripe_setup_intent_id) {
|
||||
$service->detachPaymentMethod($sg->stripe_setup_intent_id);
|
||||
}
|
||||
if (method_exists($sg, 'internalNotes')) {
|
||||
$sg->internalNotes()->create([
|
||||
'user_id' => auth()->id(),
|
||||
'body' => 'Cancelled via donor profile "Cancel All Recurring".',
|
||||
]);
|
||||
}
|
||||
$cancelled++;
|
||||
}
|
||||
|
||||
// Cancel monthly Stripe donations
|
||||
$monthlyDonations = $customer->donations()
|
||||
->where('reoccurrence', 2)
|
||||
->where('provider_type', PaymentProviders::STRIPE)
|
||||
->whereHas('donationConfirmation', fn ($q) => $q->whereNotNull('confirmed_at'))
|
||||
->get();
|
||||
foreach ($monthlyDonations as $d) {
|
||||
$ref = $d->provider_reference ?? '';
|
||||
if (str_starts_with($ref, 'seti_')) {
|
||||
$service->detachPaymentMethod($ref);
|
||||
}
|
||||
$d->donationConfirmation?->update(['confirmed_at' => null]);
|
||||
$d->internalNotes()->create([
|
||||
'user_id' => auth()->id(),
|
||||
'body' => 'Monthly giving cancelled via donor profile "Cancel All Recurring".',
|
||||
]);
|
||||
$cancelled++;
|
||||
}
|
||||
|
||||
// Log on the customer too
|
||||
$customer->internalNotes()->create([
|
||||
'user_id' => auth()->id(),
|
||||
'body' => "All recurring giving cancelled ({$cancelled} items). Payment methods detached from Stripe.",
|
||||
]);
|
||||
|
||||
Notification::make()
|
||||
->title("Cancelled {$cancelled} recurring " . ($cancelled === 1 ? 'item' : 'items'))
|
||||
->success()
|
||||
->send();
|
||||
}) : null,
|
||||
|
||||
// ── ADD NOTE ────────────────────────────────────────
|
||||
Action::make('add_note')
|
||||
->label('Add Note')
|
||||
->icon('heroicon-o-chat-bubble-left-ellipsis')
|
||||
->color('gray')
|
||||
->form([
|
||||
Textarea::make('body')
|
||||
->label('Note')
|
||||
->placeholder('e.g. Called on ' . now()->format('d M') . ' — wants to update their address')
|
||||
->required()
|
||||
->rows(3),
|
||||
])
|
||||
->action(function (array $data) use ($customer) {
|
||||
$customer->internalNotes()->create([
|
||||
'user_id' => auth()->id(),
|
||||
'body' => $data['body'],
|
||||
]);
|
||||
Notification::make()->title('Note added')->success()->send();
|
||||
}),
|
||||
|
||||
// ── RESEND RECEIPT ──────────────────────────────────
|
||||
$customer->donations()
|
||||
->whereHas('donationConfirmation', fn ($q) => $q->whereNotNull('confirmed_at'))
|
||||
->exists()
|
||||
? Action::make('resend_receipt')
|
||||
->label('Resend Receipt')
|
||||
->icon('heroicon-o-envelope')
|
||||
->color('info')
|
||||
->form([
|
||||
Select::make('donation_id')
|
||||
->label('Which donation?')
|
||||
->options(function () use ($customer) {
|
||||
return $customer->donations()
|
||||
->whereHas('donationConfirmation', fn ($q) => $q->whereNotNull('confirmed_at'))
|
||||
->latest()
|
||||
->take(10)
|
||||
->get()
|
||||
->mapWithKeys(function ($d) {
|
||||
$label = '£' . number_format($d->amount / 100, 2)
|
||||
. ' on ' . $d->created_at->format('d M Y')
|
||||
. ' — ' . ($d->donationType?->display_name ?? 'Unknown');
|
||||
return [$d->id => $label];
|
||||
});
|
||||
})
|
||||
->required()
|
||||
->helperText('Select the donation to resend the receipt for'),
|
||||
])
|
||||
->action(function (array $data) use ($customer) {
|
||||
$donation = $customer->donations()->find($data['donation_id']);
|
||||
if ($donation) {
|
||||
try {
|
||||
Mail::to($customer->email)
|
||||
->send(new \App\Mail\DonationConfirmed($donation));
|
||||
Notification::make()
|
||||
->title('Receipt sent to ' . $customer->email)
|
||||
->body('For £' . number_format($donation->amount / 100, 2) . ' on ' . $donation->created_at->format('d M Y'))
|
||||
->success()
|
||||
->send();
|
||||
} catch (\Throwable $e) {
|
||||
Notification::make()->title('Failed to send receipt')->body($e->getMessage())->danger()->send();
|
||||
}
|
||||
}
|
||||
}) : null,
|
||||
|
||||
// ── VIEW IN STRIPE ──────────────────────────────────
|
||||
Action::make('view_in_stripe')
|
||||
->label('Stripe')
|
||||
->icon('heroicon-o-arrow-top-right-on-square')
|
||||
->color('gray')
|
||||
->url('https://dashboard.stripe.com/search?query=' . urlencode($customer->email))
|
||||
->openUrlInNewTab(),
|
||||
|
||||
// ── EMAIL ───────────────────────────────────────────
|
||||
$customer->email ? Action::make('email_donor')
|
||||
->label('Email')
|
||||
->icon('heroicon-o-at-symbol')
|
||||
->color('gray')
|
||||
->url('mailto:' . $customer->email)
|
||||
->openUrlInNewTab() : null,
|
||||
]));
|
||||
}
|
||||
}
|
||||
374
temp_files/care/EditDonation.php
Normal file
374
temp_files/care/EditDonation.php
Normal file
@@ -0,0 +1,374 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\DonationResource\Pages;
|
||||
|
||||
use App\Definitions\PaymentProviders;
|
||||
use App\Filament\Resources\CustomerResource;
|
||||
use App\Filament\Resources\DonationResource;
|
||||
use App\Mail\DonationConfirmed;
|
||||
use App\Models\Donation;
|
||||
use App\Services\StripeRefundService;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Resources\Pages\EditRecord;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Illuminate\Support\HtmlString;
|
||||
|
||||
/**
|
||||
* Donation detail page — supporter care command centre.
|
||||
*
|
||||
* Design: read-only view + action buttons. No inline editing of
|
||||
* donation data — all changes go through explicit actions with
|
||||
* confirmation modals and audit logging.
|
||||
*
|
||||
* @property Donation $record
|
||||
*/
|
||||
class EditDonation extends EditRecord
|
||||
{
|
||||
protected static string $resource = DonationResource::class;
|
||||
|
||||
// ── Heading: one-glance context ─────────────────────────────
|
||||
|
||||
public function getHeading(): string|HtmlString
|
||||
{
|
||||
$d = $this->record;
|
||||
|
||||
$status = $d->isConfirmed()
|
||||
? '<span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">✓ Confirmed</span>'
|
||||
: '<span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800">✗ Incomplete</span>';
|
||||
|
||||
$amount = '£' . number_format($d->amount / 100, 2);
|
||||
$provider = PaymentProviders::translate($d->provider_type);
|
||||
|
||||
$badges = $status;
|
||||
$badges .= ' <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800 ml-1">' . $provider . '</span>';
|
||||
|
||||
if ($d->isGiftAid()) {
|
||||
$badges .= ' <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-50 text-green-700 ml-1">Gift Aid</span>';
|
||||
}
|
||||
if ($d->isZakat()) {
|
||||
$badges .= ' <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-purple-50 text-purple-700 ml-1">Zakat</span>';
|
||||
}
|
||||
if ($d->reoccurrence !== -1) {
|
||||
$badges .= ' <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800 ml-1">Recurring</span>';
|
||||
}
|
||||
|
||||
return new HtmlString("{$amount} — " . e($d->customer?->name ?? 'Unknown donor') . '<div class="mt-1">' . $badges . '</div>');
|
||||
}
|
||||
|
||||
public function getSubheading(): ?string
|
||||
{
|
||||
$d = $this->record;
|
||||
$parts = [];
|
||||
$parts[] = $d->donationType?->display_name ?? 'Unknown cause';
|
||||
$parts[] = $d->created_at?->format('d M Y H:i') . ' (' . $d->created_at?->diffForHumans() . ')';
|
||||
if ($d->appeal) {
|
||||
$parts[] = 'Fundraiser: ' . $d->appeal->name;
|
||||
}
|
||||
if ($d->reference_code) {
|
||||
$parts[] = 'Ref: ' . $d->reference_code;
|
||||
}
|
||||
|
||||
return implode(' · ', $parts);
|
||||
}
|
||||
|
||||
// ── Header Actions ──────────────────────────────────────────
|
||||
//
|
||||
// Priority order:
|
||||
// 1. Refund (Stripe PI) — the #1 support request
|
||||
// 2. Cancel Recurring (Stripe SetupIntent monthly)
|
||||
// 3. Confirm / Unconfirm
|
||||
// 4. Resend Receipt
|
||||
// 5. Stripe Status check
|
||||
// 6. Open in Stripe / View Donor / Email
|
||||
//
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
$donation = $this->record;
|
||||
|
||||
$isStripe = $donation->provider_type === PaymentProviders::STRIPE;
|
||||
$isPayPal = $donation->provider_type === PaymentProviders::PAYPAL;
|
||||
$isGoCardless = $donation->provider_type === PaymentProviders::GOCARDLESS;
|
||||
$ref = $donation->provider_reference ?? '';
|
||||
$hasPI = $isStripe && str_starts_with($ref, 'pi_');
|
||||
$hasSI = $isStripe && str_starts_with($ref, 'seti_');
|
||||
|
||||
return array_values(array_filter([
|
||||
|
||||
// ── REFUND (Stripe PaymentIntent) ───────────────────
|
||||
$hasPI && $donation->isConfirmed() ? Action::make('refund')
|
||||
->label('Refund')
|
||||
->icon('heroicon-o-arrow-uturn-left')
|
||||
->color('danger')
|
||||
->requiresConfirmation()
|
||||
->modalIcon('heroicon-o-arrow-uturn-left')
|
||||
->modalHeading('Refund Donation')
|
||||
->modalDescription(
|
||||
'Refund £' . number_format($donation->amount / 100, 2)
|
||||
. ' to ' . e($donation->customer?->name ?? 'donor')
|
||||
. '\'s card via Stripe. This cannot be undone.'
|
||||
)
|
||||
->modalSubmitActionLabel('Process Refund')
|
||||
->form([
|
||||
TextInput::make('refund_amount')
|
||||
->label('Refund amount (£)')
|
||||
->numeric()
|
||||
->default(number_format($donation->amount / 100, 2, '.', ''))
|
||||
->required()
|
||||
->minValue(0.01)
|
||||
->maxValue($donation->amount / 100)
|
||||
->step(0.01)
|
||||
->helperText('Full amount for complete refund. Reduce for partial.'),
|
||||
])
|
||||
->action(function (array $data) {
|
||||
$donation = $this->record;
|
||||
$amountPence = (int) round($data['refund_amount'] * 100);
|
||||
$isPartial = $amountPence < $donation->amount;
|
||||
|
||||
$service = app(StripeRefundService::class);
|
||||
$result = $service->refundPaymentIntent(
|
||||
$donation->provider_reference,
|
||||
$isPartial ? $amountPence : null,
|
||||
'Admin refund by ' . auth()->user()?->name
|
||||
);
|
||||
|
||||
if ($result['success']) {
|
||||
if (! $isPartial) {
|
||||
$donation->donationConfirmation?->update(['confirmed_at' => null]);
|
||||
}
|
||||
|
||||
$donation->internalNotes()->create([
|
||||
'user_id' => auth()->id(),
|
||||
'body' => ($isPartial ? 'Partial' : 'Full') . ' refund of £'
|
||||
. number_format($amountPence / 100, 2)
|
||||
. ' processed via Stripe. Refund ID: ' . $result['refund_id'],
|
||||
]);
|
||||
|
||||
Notification::make()
|
||||
->title('Refund processed')
|
||||
->body('£' . number_format($result['amount'] / 100, 2) . ' refunded. ID: ' . $result['refund_id'])
|
||||
->success()
|
||||
->send();
|
||||
} else {
|
||||
Notification::make()
|
||||
->title('Refund failed')
|
||||
->body($result['error'])
|
||||
->danger()
|
||||
->send();
|
||||
}
|
||||
}) : null,
|
||||
|
||||
// ── CANCEL RECURRING (SetupIntent monthly) ──────────
|
||||
$hasSI && $donation->isConfirmed() ? Action::make('cancel_recurring')
|
||||
->label('Cancel Recurring')
|
||||
->icon('heroicon-o-x-circle')
|
||||
->color('danger')
|
||||
->requiresConfirmation()
|
||||
->modalIcon('heroicon-o-x-circle')
|
||||
->modalHeading('Cancel Monthly Giving')
|
||||
->modalDescription(
|
||||
'This will detach the payment method from Stripe, preventing '
|
||||
. 'all future charges for ' . e($donation->customer?->name ?? 'this donor')
|
||||
. '. Previously collected payments will NOT be refunded.'
|
||||
)
|
||||
->modalSubmitActionLabel('Cancel Monthly Giving')
|
||||
->action(function () {
|
||||
$donation = $this->record;
|
||||
$service = app(StripeRefundService::class);
|
||||
$result = $service->detachPaymentMethod($donation->provider_reference);
|
||||
|
||||
if ($result['success']) {
|
||||
$donation->donationConfirmation?->update(['confirmed_at' => null]);
|
||||
|
||||
$donation->internalNotes()->create([
|
||||
'user_id' => auth()->id(),
|
||||
'body' => 'Monthly giving cancelled. ' . ($result['message'] ?? 'Payment method detached from Stripe.'),
|
||||
]);
|
||||
|
||||
Notification::make()
|
||||
->title('Monthly giving cancelled')
|
||||
->body($result['message'] ?? 'Payment method detached')
|
||||
->success()
|
||||
->send();
|
||||
} else {
|
||||
Notification::make()
|
||||
->title('Cancellation failed')
|
||||
->body($result['error'])
|
||||
->danger()
|
||||
->send();
|
||||
}
|
||||
}) : null,
|
||||
|
||||
// ── OPEN PAYPAL ─────────────────────────────────────
|
||||
$isPayPal && $ref ? Action::make('open_paypal')
|
||||
->label('Open PayPal')
|
||||
->icon('heroicon-o-arrow-top-right-on-square')
|
||||
->color('warning')
|
||||
->url('https://www.paypal.com/activity/payment/' . urlencode($ref))
|
||||
->openUrlInNewTab() : null,
|
||||
|
||||
// ── OPEN GOCARDLESS ─────────────────────────────────
|
||||
$isGoCardless && $ref ? Action::make('open_gocardless')
|
||||
->label('Open GoCardless')
|
||||
->icon('heroicon-o-arrow-top-right-on-square')
|
||||
->color('warning')
|
||||
->url('https://manage.gocardless.com/payments/' . urlencode($ref))
|
||||
->openUrlInNewTab() : null,
|
||||
|
||||
// ── UNCONFIRM ───────────────────────────────────────
|
||||
$donation->isConfirmed() ? Action::make('unconfirm')
|
||||
->label('Unconfirm')
|
||||
->icon('heroicon-o-x-mark')
|
||||
->color('warning')
|
||||
->requiresConfirmation()
|
||||
->modalHeading('Unconfirm Donation')
|
||||
->modalDescription(
|
||||
'Mark this donation as incomplete. This does NOT refund money '
|
||||
. 'on Stripe/PayPal — use the Refund button for that.'
|
||||
)
|
||||
->action(function () {
|
||||
$donation = $this->record;
|
||||
$donation->donationConfirmation?->update(['confirmed_at' => null]);
|
||||
|
||||
$donation->internalNotes()->create([
|
||||
'user_id' => auth()->id(),
|
||||
'body' => 'Donation manually unconfirmed by admin.',
|
||||
]);
|
||||
|
||||
Notification::make()->title('Donation unconfirmed')->warning()->send();
|
||||
}) : null,
|
||||
|
||||
// ── CONFIRM ─────────────────────────────────────────
|
||||
! $donation->isConfirmed() ? Action::make('confirm')
|
||||
->label('Confirm')
|
||||
->icon('heroicon-o-check-circle')
|
||||
->color('success')
|
||||
->requiresConfirmation()
|
||||
->modalHeading('Confirm Donation')
|
||||
->modalDescription(
|
||||
'Mark this donation as confirmed. Only do this if you have '
|
||||
. 'verified the payment was received.'
|
||||
)
|
||||
->action(function () {
|
||||
$donation = $this->record;
|
||||
$donation->confirm();
|
||||
|
||||
$donation->internalNotes()->create([
|
||||
'user_id' => auth()->id(),
|
||||
'body' => 'Donation manually confirmed by admin.',
|
||||
]);
|
||||
|
||||
Notification::make()->title('Donation confirmed')->success()->send();
|
||||
}) : null,
|
||||
|
||||
// ── RESEND RECEIPT ──────────────────────────────────
|
||||
$donation->isConfirmed() && $donation->customer?->email
|
||||
? Action::make('resend_receipt')
|
||||
->label('Receipt')
|
||||
->icon('heroicon-o-envelope')
|
||||
->color('gray')
|
||||
->requiresConfirmation()
|
||||
->modalDescription('Send receipt to ' . $donation->customer->email)
|
||||
->action(function () {
|
||||
$donation = $this->record;
|
||||
try {
|
||||
Mail::to($donation->customer->email)
|
||||
->send(new DonationConfirmed($donation));
|
||||
|
||||
Notification::make()
|
||||
->title('Receipt sent to ' . $donation->customer->email)
|
||||
->success()
|
||||
->send();
|
||||
} catch (\Throwable $e) {
|
||||
Log::error($e);
|
||||
Notification::make()
|
||||
->title('Failed to send receipt')
|
||||
->body($e->getMessage())
|
||||
->danger()
|
||||
->send();
|
||||
}
|
||||
}) : null,
|
||||
|
||||
// ── STRIPE STATUS ───────────────────────────────────
|
||||
($hasPI || $hasSI) ? Action::make('check_stripe')
|
||||
->label('Stripe Status')
|
||||
->icon('heroicon-o-magnifying-glass')
|
||||
->color('gray')
|
||||
->action(function () use ($hasPI) {
|
||||
$donation = $this->record;
|
||||
$service = app(StripeRefundService::class);
|
||||
$details = $hasPI
|
||||
? $service->getPaymentDetails($donation->provider_reference)
|
||||
: $service->getSetupIntentDetails($donation->provider_reference);
|
||||
|
||||
if (! $details) {
|
||||
Notification::make()
|
||||
->title('Could not retrieve Stripe details')
|
||||
->danger()
|
||||
->send();
|
||||
return;
|
||||
}
|
||||
|
||||
$lines = [];
|
||||
foreach ($details as $key => $val) {
|
||||
if ($val === null || $val === '') {
|
||||
continue;
|
||||
}
|
||||
$label = str_replace('_', ' ', ucfirst($key));
|
||||
if (is_bool($val)) {
|
||||
$val = $val ? 'Yes' : 'No';
|
||||
}
|
||||
if ($key === 'amount' || $key === 'amount_refunded') {
|
||||
$val = '£' . number_format($val / 100, 2);
|
||||
}
|
||||
$lines[] = "{$label}: {$val}";
|
||||
}
|
||||
|
||||
Notification::make()
|
||||
->title('Stripe Details')
|
||||
->body(implode("\n", $lines))
|
||||
->info()
|
||||
->persistent()
|
||||
->send();
|
||||
}) : null,
|
||||
|
||||
// ── OPEN IN STRIPE ──────────────────────────────────
|
||||
$isStripe && $ref ? Action::make('open_stripe')
|
||||
->label('Stripe ↗')
|
||||
->icon('heroicon-o-arrow-top-right-on-square')
|
||||
->color('gray')
|
||||
->url('https://dashboard.stripe.com/search?query=' . urlencode($ref))
|
||||
->openUrlInNewTab() : null,
|
||||
|
||||
// ── VIEW DONOR ──────────────────────────────────────
|
||||
$donation->customer_id ? Action::make('view_donor')
|
||||
->label('Donor')
|
||||
->icon('heroicon-o-user')
|
||||
->color('gray')
|
||||
->url(CustomerResource::getUrl('edit', ['record' => $donation->customer_id]))
|
||||
: null,
|
||||
|
||||
// ── EMAIL ───────────────────────────────────────────
|
||||
$donation->customer?->email ? Action::make('email')
|
||||
->label('Email')
|
||||
->icon('heroicon-o-at-symbol')
|
||||
->color('gray')
|
||||
->url('mailto:' . $donation->customer->email)
|
||||
->openUrlInNewTab() : null,
|
||||
]));
|
||||
}
|
||||
|
||||
// Hide save/cancel — donations are not directly editable
|
||||
protected function getSaveFormAction(): Action
|
||||
{
|
||||
return parent::getSaveFormAction()->visible(false);
|
||||
}
|
||||
|
||||
protected function getCancelFormAction(): Action
|
||||
{
|
||||
return parent::getCancelFormAction()->visible(false);
|
||||
}
|
||||
}
|
||||
313
temp_files/care/EditScheduledGivingDonation.php
Normal file
313
temp_files/care/EditScheduledGivingDonation.php
Normal file
@@ -0,0 +1,313 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\ScheduledGivingDonationResource\Pages;
|
||||
|
||||
use App\Filament\Resources\AppealResource\Pages\EditAppeal;
|
||||
use App\Filament\Resources\CustomerResource\Pages\EditCustomer;
|
||||
use App\Filament\Resources\ScheduledGivingDonationResource;
|
||||
use App\Models\ScheduledGivingDonation;
|
||||
use App\Services\StripeRefundService;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Resources\Pages\EditRecord;
|
||||
use Illuminate\Support\HtmlString;
|
||||
|
||||
/**
|
||||
* Scheduled/Regular Giving detail page — supporter care.
|
||||
*
|
||||
* Shows payment progress, card info, and provides cancel/refund
|
||||
* actions that sync with Stripe.
|
||||
*
|
||||
* @property ScheduledGivingDonation $record
|
||||
*/
|
||||
class EditScheduledGivingDonation extends EditRecord
|
||||
{
|
||||
protected static string $resource = ScheduledGivingDonationResource::class;
|
||||
|
||||
// ── Heading: status + progress at a glance ──────────────────
|
||||
|
||||
public function getHeading(): string|HtmlString
|
||||
{
|
||||
$d = $this->record;
|
||||
|
||||
$status = $d->is_active
|
||||
? '<span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">● Active</span>'
|
||||
: '<span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800">● Cancelled</span>';
|
||||
|
||||
$amount = '£' . number_format($d->total_amount / 100, 2);
|
||||
|
||||
// Payment progress
|
||||
$totalPayments = $d->payments()->count();
|
||||
$paidPayments = $d->payments()->where('is_paid', true)->count();
|
||||
$paidTotal = $d->payments()->where('is_paid', true)->sum('amount') / 100;
|
||||
|
||||
$progress = $totalPayments > 0
|
||||
? '<span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800 ml-1">'
|
||||
. $paidPayments . '/' . $totalPayments . ' payments · £' . number_format($paidTotal, 2) . ' collected</span>'
|
||||
: '<span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-600 ml-1">No payments generated</span>';
|
||||
|
||||
if ($d->is_zakat) {
|
||||
$progress .= ' <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-purple-50 text-purple-700 ml-1">Zakat</span>';
|
||||
}
|
||||
if ($d->is_gift_aid) {
|
||||
$progress .= ' <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-50 text-green-700 ml-1">Gift Aid</span>';
|
||||
}
|
||||
|
||||
return new HtmlString(
|
||||
$amount . '/night — ' . e($d->customer?->name ?? 'Unknown')
|
||||
. '<div class="mt-1">' . $status . ' ' . $progress . '</div>'
|
||||
);
|
||||
}
|
||||
|
||||
public function getSubheading(): ?string
|
||||
{
|
||||
$d = $this->record;
|
||||
$parts = [];
|
||||
$parts[] = $d->scheduledGivingCampaign?->title ?? 'Unknown campaign';
|
||||
$parts[] = 'Started ' . $d->created_at?->format('d M Y');
|
||||
if ($d->customer?->email) {
|
||||
$parts[] = $d->customer->email;
|
||||
}
|
||||
if ($d->reference_code) {
|
||||
$parts[] = 'Ref: ' . $d->reference_code;
|
||||
}
|
||||
|
||||
return implode(' · ', $parts);
|
||||
}
|
||||
|
||||
// ── Header Actions ──────────────────────────────────────────
|
||||
//
|
||||
// Priority order:
|
||||
// 1. Cancel (deactivate + detach card)
|
||||
// 2. Cancel & Refund All
|
||||
// 3. Activate
|
||||
// 4. Stripe Status
|
||||
// 5. Open in Stripe / View Donor / View Appeal / Email
|
||||
//
|
||||
|
||||
public function getHeaderActions(): array
|
||||
{
|
||||
$donation = $this->record;
|
||||
$hasStripe = (bool) $donation->stripe_setup_intent_id;
|
||||
|
||||
$paidCount = $donation->payments()
|
||||
->where('is_paid', true)
|
||||
->whereNotNull('stripe_payment_intent_id')
|
||||
->where('stripe_payment_intent_id', '!=', 'SKIPPED')
|
||||
->count();
|
||||
|
||||
$paidTotal = $donation->payments()
|
||||
->where('is_paid', true)
|
||||
->whereNotNull('stripe_payment_intent_id')
|
||||
->where('stripe_payment_intent_id', '!=', 'SKIPPED')
|
||||
->sum('amount') / 100;
|
||||
|
||||
return array_values(array_filter([
|
||||
|
||||
// ── CANCEL ──────────────────────────────────────────
|
||||
$donation->is_active ? Action::make('cancel')
|
||||
->label('Cancel')
|
||||
->icon('heroicon-o-x-circle')
|
||||
->color('danger')
|
||||
->requiresConfirmation()
|
||||
->modalIcon('heroicon-o-x-circle')
|
||||
->modalHeading('Cancel Regular Giving')
|
||||
->modalDescription(
|
||||
'This will deactivate ' . e($donation->customer?->name ?? 'this donor') . '\'s regular giving.'
|
||||
. ($hasStripe ? "\n\nThe payment method will be detached from Stripe, preventing any future charges." : '')
|
||||
. "\n\nPreviously collected payments will NOT be refunded."
|
||||
)
|
||||
->modalSubmitActionLabel('Cancel Regular Giving')
|
||||
->action(function () {
|
||||
$donation = $this->record;
|
||||
$hasStripe = (bool) $donation->stripe_setup_intent_id;
|
||||
|
||||
$donation->update(['is_active' => false]);
|
||||
$stripeMsg = '';
|
||||
|
||||
if ($hasStripe) {
|
||||
$service = app(StripeRefundService::class);
|
||||
$result = $service->detachPaymentMethod($donation->stripe_setup_intent_id);
|
||||
$stripeMsg = $result['success']
|
||||
? ($result['message'] ?? 'Payment method detached.')
|
||||
: 'Warning: ' . ($result['error'] ?? 'Could not detach payment method.');
|
||||
}
|
||||
|
||||
$donation->internalNotes()->create([
|
||||
'user_id' => auth()->id(),
|
||||
'body' => 'Regular giving cancelled by admin. ' . $stripeMsg,
|
||||
]);
|
||||
|
||||
Notification::make()
|
||||
->title('Regular giving cancelled')
|
||||
->body($stripeMsg ?: 'Deactivated')
|
||||
->success()
|
||||
->send();
|
||||
}) : null,
|
||||
|
||||
// ── CANCEL & REFUND ALL ─────────────────────────────
|
||||
$donation->is_active && $paidCount > 0 ? Action::make('cancel_and_refund')
|
||||
->label('Cancel & Refund All')
|
||||
->icon('heroicon-o-arrow-uturn-left')
|
||||
->color('danger')
|
||||
->requiresConfirmation()
|
||||
->modalIcon('heroicon-o-exclamation-triangle')
|
||||
->modalHeading('Cancel & Refund All Payments')
|
||||
->modalDescription(
|
||||
"This will:\n"
|
||||
. "1. Deactivate the regular giving\n"
|
||||
. "2. Detach the payment method from Stripe\n"
|
||||
. "3. Refund all {$paidCount} collected payments (£" . number_format($paidTotal, 2) . ")\n\n"
|
||||
. "This cannot be undone."
|
||||
)
|
||||
->modalSubmitActionLabel('Cancel & Refund Everything')
|
||||
->action(function () {
|
||||
$donation = $this->record;
|
||||
$donation->update(['is_active' => false]);
|
||||
|
||||
$service = app(StripeRefundService::class);
|
||||
|
||||
// Detach card
|
||||
if ($donation->stripe_setup_intent_id) {
|
||||
$service->detachPaymentMethod($donation->stripe_setup_intent_id);
|
||||
}
|
||||
|
||||
// Refund all paid payments
|
||||
$paidPayments = $donation->payments()
|
||||
->where('is_paid', true)
|
||||
->whereNotNull('stripe_payment_intent_id')
|
||||
->where('stripe_payment_intent_id', '!=', 'SKIPPED')
|
||||
->get();
|
||||
|
||||
$refunded = 0;
|
||||
$failed = 0;
|
||||
$totalRefunded = 0;
|
||||
|
||||
foreach ($paidPayments as $payment) {
|
||||
$result = $service->refundPaymentIntent(
|
||||
$payment->stripe_payment_intent_id,
|
||||
null,
|
||||
'Bulk cancel & refund — payment #' . $payment->id
|
||||
);
|
||||
|
||||
if ($result['success']) {
|
||||
$payment->update(['is_paid' => false]);
|
||||
$refunded++;
|
||||
$totalRefunded += $result['amount'];
|
||||
} else {
|
||||
$failed++;
|
||||
}
|
||||
}
|
||||
|
||||
$donation->internalNotes()->create([
|
||||
'user_id' => auth()->id(),
|
||||
'body' => 'Cancelled & refunded all payments. '
|
||||
. $refunded . ' refunded (£' . number_format($totalRefunded / 100, 2) . ')'
|
||||
. ($failed > 0 ? ", {$failed} failed" : ''),
|
||||
]);
|
||||
|
||||
Notification::make()
|
||||
->title('Cancelled & Refunded')
|
||||
->body(
|
||||
$refunded . ' payments refunded (£' . number_format($totalRefunded / 100, 2) . ')'
|
||||
. ($failed > 0 ? ". {$failed} failed — check Stripe." : '')
|
||||
)
|
||||
->success()
|
||||
->send();
|
||||
}) : null,
|
||||
|
||||
// ── REACTIVATE ──────────────────────────────────────
|
||||
! $donation->is_active ? Action::make('activate')
|
||||
->label('Reactivate')
|
||||
->icon('heroicon-o-play')
|
||||
->color('success')
|
||||
->requiresConfirmation()
|
||||
->modalHeading('Reactivate Regular Giving')
|
||||
->modalDescription(
|
||||
'Re-enable payment collection. Note: if the payment method '
|
||||
. 'was previously detached, future charges may fail.'
|
||||
)
|
||||
->action(function () {
|
||||
$donation = $this->record;
|
||||
$donation->update(['is_active' => true]);
|
||||
|
||||
$donation->internalNotes()->create([
|
||||
'user_id' => auth()->id(),
|
||||
'body' => 'Regular giving reactivated by admin.',
|
||||
]);
|
||||
|
||||
Notification::make()->title('Regular giving reactivated')->success()->send();
|
||||
}) : null,
|
||||
|
||||
// ── STRIPE STATUS ───────────────────────────────────
|
||||
$hasStripe ? Action::make('stripe_status')
|
||||
->label('Stripe Status')
|
||||
->icon('heroicon-o-magnifying-glass')
|
||||
->color('gray')
|
||||
->action(function () {
|
||||
$donation = $this->record;
|
||||
$service = app(StripeRefundService::class);
|
||||
$details = $service->getSetupIntentDetails($donation->stripe_setup_intent_id);
|
||||
|
||||
if (! $details) {
|
||||
Notification::make()
|
||||
->title('Could not retrieve Stripe details')
|
||||
->danger()
|
||||
->send();
|
||||
return;
|
||||
}
|
||||
|
||||
$body = 'Status: ' . $details['status'];
|
||||
if ($details['card_brand'] && $details['card_last4']) {
|
||||
$body .= "\nCard: " . ucfirst($details['card_brand']) . ' ····' . $details['card_last4'];
|
||||
}
|
||||
if ($details['card_exp_month'] && $details['card_exp_year']) {
|
||||
$body .= ' (expires ' . $details['card_exp_month'] . '/' . $details['card_exp_year'] . ')';
|
||||
}
|
||||
$body .= "\nCreated: " . $details['created'];
|
||||
if ($details['customer_id']) {
|
||||
$body .= "\nStripe Customer: " . $details['customer_id'];
|
||||
}
|
||||
|
||||
Notification::make()
|
||||
->title('Stripe SetupIntent')
|
||||
->body($body)
|
||||
->info()
|
||||
->persistent()
|
||||
->send();
|
||||
}) : null,
|
||||
|
||||
// ── OPEN IN STRIPE ──────────────────────────────────
|
||||
$hasStripe ? Action::make('open_stripe')
|
||||
->label('Stripe ↗')
|
||||
->icon('heroicon-o-arrow-top-right-on-square')
|
||||
->color('gray')
|
||||
->url('https://dashboard.stripe.com/search?query=' . urlencode($donation->stripe_setup_intent_id))
|
||||
->openUrlInNewTab() : null,
|
||||
|
||||
// ── VIEW DONOR ──────────────────────────────────────
|
||||
$donation->customer ? Action::make('view_customer')
|
||||
->label('Donor')
|
||||
->icon('heroicon-o-user')
|
||||
->color('gray')
|
||||
->url(EditCustomer::getUrl(['record' => $donation->customer->id]))
|
||||
: null,
|
||||
|
||||
// ── VIEW APPEAL ─────────────────────────────────────
|
||||
$donation->appeal ? Action::make('view_appeal')
|
||||
->label('Fundraiser')
|
||||
->icon('heroicon-o-heart')
|
||||
->color('gray')
|
||||
->url(EditAppeal::getUrl(['record' => $donation->appeal->id]))
|
||||
: null,
|
||||
|
||||
// ── EMAIL ───────────────────────────────────────────
|
||||
$donation->customer?->email ? Action::make('email')
|
||||
->label('Email')
|
||||
->icon('heroicon-o-at-symbol')
|
||||
->color('gray')
|
||||
->url('mailto:' . $donation->customer->email)
|
||||
->openUrlInNewTab() : null,
|
||||
]));
|
||||
}
|
||||
}
|
||||
300
temp_files/care/ScheduledGivingDonationPayments.php
Normal file
300
temp_files/care/ScheduledGivingDonationPayments.php
Normal file
@@ -0,0 +1,300 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\ScheduledGivingDonationResource\RelationManagers;
|
||||
|
||||
use App\Jobs\ProcessScheduleGivingDonationPayment;
|
||||
use App\Models\ScheduledGivingPayment;
|
||||
use App\Services\AppealScheduledDonationService;
|
||||
use App\Services\StripeRefundService;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Forms\Form;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Resources\RelationManagers\RelationManager;
|
||||
use Filament\Tables\Actions\Action;
|
||||
use Filament\Tables\Actions\BulkAction;
|
||||
use Filament\Tables\Actions\BulkActionGroup;
|
||||
use Filament\Tables\Columns\IconColumn;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Table;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
|
||||
/**
|
||||
* Payment schedule with per-row charge / refund / skip actions.
|
||||
*
|
||||
* Visual status:
|
||||
* ✓ green = paid via Stripe
|
||||
* ✓ gray = paid (skipped / no PI)
|
||||
* ! red = overdue
|
||||
* ○ gray = upcoming
|
||||
*/
|
||||
class ScheduledGivingDonationPayments extends RelationManager
|
||||
{
|
||||
protected static string $relationship = 'payments';
|
||||
|
||||
protected static ?string $title = 'Payment Schedule';
|
||||
|
||||
public function form(Form $form): Form
|
||||
{
|
||||
return $form;
|
||||
}
|
||||
|
||||
public function table(Table $table): Table
|
||||
{
|
||||
return $table
|
||||
->recordTitleAttribute('amount')
|
||||
->columns([
|
||||
TextColumn::make('expected_at')
|
||||
->label('Date')
|
||||
->date('d M Y')
|
||||
->description(fn ($record) => $record->expected_at?->diffForHumans())
|
||||
->sortable(),
|
||||
|
||||
TextColumn::make('amount')
|
||||
->label('Amount')
|
||||
->money('gbp', divideBy: 100)
|
||||
->sortable(),
|
||||
|
||||
IconColumn::make('is_paid')
|
||||
->label('Status')
|
||||
->icon(fn ($state, $record) => match (true) {
|
||||
(bool) $state && $record->stripe_payment_intent_id === 'SKIPPED' => 'heroicon-o-forward',
|
||||
(bool) $state && (bool) $record->stripe_payment_intent_id => 'heroicon-o-check-circle',
|
||||
(bool) $state => 'heroicon-o-check',
|
||||
$record->expected_at?->isPast() ?? false => 'heroicon-o-exclamation-circle',
|
||||
default => 'heroicon-o-clock',
|
||||
})
|
||||
->color(fn ($state, $record) => match (true) {
|
||||
(bool) $state && $record->stripe_payment_intent_id === 'SKIPPED' => 'warning',
|
||||
(bool) $state => 'success',
|
||||
$record->expected_at?->isPast() ?? false => 'danger',
|
||||
default => 'gray',
|
||||
})
|
||||
->tooltip(fn ($state, $record) => match (true) {
|
||||
(bool) $state && $record->stripe_payment_intent_id === 'SKIPPED' => 'Skipped by admin',
|
||||
(bool) $state && (bool) $record->stripe_payment_intent_id => 'Paid — ' . $record->stripe_payment_intent_id,
|
||||
(bool) $state => 'Marked as paid (no Stripe ref)',
|
||||
$record->expected_at?->isPast() ?? false => 'Overdue — not yet charged',
|
||||
default => 'Upcoming',
|
||||
}),
|
||||
|
||||
TextColumn::make('attempts')
|
||||
->label('Tries')
|
||||
->badge()
|
||||
->color(fn ($state) => match (true) {
|
||||
$state === 0 || $state === null => 'gray',
|
||||
$state === 1 => 'success',
|
||||
default => 'warning',
|
||||
}),
|
||||
|
||||
TextColumn::make('stripe_payment_intent_id')
|
||||
->label('Stripe')
|
||||
->url(fn ($state) => $state && $state !== 'SKIPPED'
|
||||
? "https://dashboard.stripe.com/payments/{$state}"
|
||||
: null)
|
||||
->openUrlInNewTab()
|
||||
->placeholder('—')
|
||||
->limit(18)
|
||||
->fontFamily('mono')
|
||||
->copyable(),
|
||||
])
|
||||
->defaultSort('expected_at', 'asc')
|
||||
|
||||
// ── Row Actions ─────────────────────────────────────
|
||||
->actions([
|
||||
|
||||
// Charge now
|
||||
Action::make('take_payment')
|
||||
->label('Charge')
|
||||
->icon('heroicon-o-banknotes')
|
||||
->color('success')
|
||||
->size('sm')
|
||||
->visible(fn ($record) => ! $record->is_paid && ! $record->stripe_payment_intent_id)
|
||||
->requiresConfirmation()
|
||||
->modalHeading('Charge Payment')
|
||||
->modalDescription(fn ($record) => 'Charge £' . number_format($record->amount / 100, 2)
|
||||
. ' (expected ' . $record->expected_at?->format('d M Y') . ')')
|
||||
->action(function (ScheduledGivingPayment $record) {
|
||||
try {
|
||||
(new ProcessScheduleGivingDonationPayment($record))->handle();
|
||||
(new AppealScheduledDonationService())->syncProcessedPayments(collect([$record]));
|
||||
|
||||
Notification::make()
|
||||
->title('Payment charged')
|
||||
->body('£' . number_format($record->amount / 100, 2) . ' collected')
|
||||
->success()
|
||||
->send();
|
||||
} catch (\Throwable $e) {
|
||||
Notification::make()
|
||||
->title('Payment failed')
|
||||
->body($e->getMessage())
|
||||
->danger()
|
||||
->send();
|
||||
}
|
||||
}),
|
||||
|
||||
// Refund
|
||||
Action::make('refund')
|
||||
->label('Refund')
|
||||
->icon('heroicon-o-arrow-uturn-left')
|
||||
->color('danger')
|
||||
->size('sm')
|
||||
->visible(fn ($record) => $record->is_paid
|
||||
&& $record->stripe_payment_intent_id
|
||||
&& $record->stripe_payment_intent_id !== 'SKIPPED')
|
||||
->requiresConfirmation()
|
||||
->modalHeading('Refund Payment')
|
||||
->modalDescription(fn ($record) => 'Refund £' . number_format($record->amount / 100, 2)
|
||||
. ' for ' . $record->expected_at?->format('d M Y')
|
||||
. ' back to donor\'s card via Stripe.')
|
||||
->form([
|
||||
TextInput::make('refund_amount')
|
||||
->label('Refund amount (£)')
|
||||
->numeric()
|
||||
->default(fn ($record) => number_format($record->amount / 100, 2, '.', ''))
|
||||
->required()
|
||||
->minValue(0.01)
|
||||
->maxValue(fn ($record) => $record->amount / 100)
|
||||
->step(0.01)
|
||||
->helperText('Full amount for complete refund, or reduce for partial.'),
|
||||
])
|
||||
->action(function (ScheduledGivingPayment $record, array $data) {
|
||||
$amountPence = (int) round($data['refund_amount'] * 100);
|
||||
$isPartial = $amountPence < $record->amount;
|
||||
|
||||
$service = app(StripeRefundService::class);
|
||||
$result = $service->refundPaymentIntent(
|
||||
$record->stripe_payment_intent_id,
|
||||
$isPartial ? $amountPence : null,
|
||||
'Admin refund: scheduled payment #' . $record->id
|
||||
);
|
||||
|
||||
if ($result['success']) {
|
||||
if (! $isPartial) {
|
||||
$record->update(['is_paid' => false]);
|
||||
}
|
||||
|
||||
Notification::make()
|
||||
->title('Payment refunded')
|
||||
->body('£' . number_format($result['amount'] / 100, 2) . ' refunded. ID: ' . $result['refund_id'])
|
||||
->success()
|
||||
->send();
|
||||
} else {
|
||||
Notification::make()
|
||||
->title('Refund failed')
|
||||
->body($result['error'])
|
||||
->danger()
|
||||
->send();
|
||||
}
|
||||
}),
|
||||
|
||||
// Skip
|
||||
Action::make('skip')
|
||||
->label('Skip')
|
||||
->icon('heroicon-o-forward')
|
||||
->color('warning')
|
||||
->size('sm')
|
||||
->visible(fn ($record) => ! $record->is_paid && ! $record->stripe_payment_intent_id)
|
||||
->requiresConfirmation()
|
||||
->modalHeading('Skip Payment')
|
||||
->modalDescription(fn ($record) => 'Mark the £' . number_format($record->amount / 100, 2)
|
||||
. ' payment for ' . $record->expected_at?->format('d M Y')
|
||||
. ' as skipped. No charge will be made.')
|
||||
->action(function (ScheduledGivingPayment $record) {
|
||||
$record->update([
|
||||
'is_paid' => true,
|
||||
'stripe_payment_intent_id' => 'SKIPPED',
|
||||
]);
|
||||
|
||||
Notification::make()->title('Payment skipped')->warning()->send();
|
||||
}),
|
||||
])
|
||||
|
||||
// ── Header Actions ──────────────────────────────────
|
||||
->headerActions([
|
||||
Action::make('generate_payments')
|
||||
->label('Generate Payments')
|
||||
->icon('heroicon-o-calculator')
|
||||
->visible(function () {
|
||||
return $this->ownerRecord->payments()->count() == 0
|
||||
&& $this->ownerRecord->isConfirmed();
|
||||
})
|
||||
->requiresConfirmation()
|
||||
->action(fn () => $this->ownerRecord->generatePayments()),
|
||||
])
|
||||
|
||||
// ── Bulk Actions ────────────────────────────────────
|
||||
->bulkActions([
|
||||
BulkActionGroup::make([
|
||||
BulkAction::make('refund_selected')
|
||||
->label('Refund Selected')
|
||||
->icon('heroicon-o-arrow-uturn-left')
|
||||
->color('danger')
|
||||
->requiresConfirmation()
|
||||
->modalHeading('Refund Selected Payments')
|
||||
->modalDescription('Refund all selected paid payments via Stripe. This cannot be undone.')
|
||||
->action(function (Collection $records) {
|
||||
$service = app(StripeRefundService::class);
|
||||
$refunded = 0;
|
||||
$failed = 0;
|
||||
|
||||
foreach ($records as $record) {
|
||||
if (! $record->is_paid
|
||||
|| ! $record->stripe_payment_intent_id
|
||||
|| $record->stripe_payment_intent_id === 'SKIPPED') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$result = $service->refundPaymentIntent(
|
||||
$record->stripe_payment_intent_id,
|
||||
null,
|
||||
'Bulk refund: payment #' . $record->id
|
||||
);
|
||||
|
||||
if ($result['success']) {
|
||||
$record->update(['is_paid' => false]);
|
||||
$refunded++;
|
||||
} else {
|
||||
$failed++;
|
||||
}
|
||||
}
|
||||
|
||||
Notification::make()
|
||||
->title($refunded . ' payments refunded' . ($failed ? ", {$failed} failed" : ''))
|
||||
->success()
|
||||
->send();
|
||||
}),
|
||||
|
||||
BulkAction::make('charge_selected')
|
||||
->label('Charge Selected')
|
||||
->icon('heroicon-o-banknotes')
|
||||
->color('success')
|
||||
->requiresConfirmation()
|
||||
->modalHeading('Charge Selected Payments')
|
||||
->modalDescription('Process all selected unpaid payments now.')
|
||||
->action(function (Collection $records) {
|
||||
$charged = 0;
|
||||
$failed = 0;
|
||||
|
||||
foreach ($records as $record) {
|
||||
if ($record->is_paid || $record->stripe_payment_intent_id) {
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
(new ProcessScheduleGivingDonationPayment($record))->handle();
|
||||
(new AppealScheduledDonationService())->syncProcessedPayments(collect([$record]));
|
||||
$charged++;
|
||||
} catch (\Throwable $e) {
|
||||
$failed++;
|
||||
}
|
||||
}
|
||||
|
||||
Notification::make()
|
||||
->title($charged . ' payments charged' . ($failed ? ", {$failed} failed" : ''))
|
||||
->success()
|
||||
->send();
|
||||
}),
|
||||
]),
|
||||
]);
|
||||
}
|
||||
}
|
||||
157
temp_files/care/StripeRefundService.php
Normal file
157
temp_files/care/StripeRefundService.php
Normal file
@@ -0,0 +1,157 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Stripe\Exception\ApiErrorException;
|
||||
use Stripe\StripeClient;
|
||||
|
||||
/**
|
||||
* Centralised Stripe refund & payment-method management.
|
||||
*
|
||||
* Every action is logged. Every response is a simple array so callers
|
||||
* can show user-friendly notifications without catching exceptions.
|
||||
*/
|
||||
class StripeRefundService
|
||||
{
|
||||
private StripeClient $stripe;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->stripe = new StripeClient(config('paisa.gateways.stripe.secret_key'));
|
||||
}
|
||||
|
||||
// ── Refund a PaymentIntent (full or partial) ────────────────
|
||||
|
||||
public function refundPaymentIntent(string $paymentIntentId, ?int $amountInPence = null, string $reason = ''): array
|
||||
{
|
||||
try {
|
||||
$params = [
|
||||
'payment_intent' => $paymentIntentId,
|
||||
'reason' => 'requested_by_customer',
|
||||
];
|
||||
|
||||
if ($amountInPence !== null && $amountInPence > 0) {
|
||||
$params['amount'] = $amountInPence;
|
||||
}
|
||||
|
||||
$refund = $this->stripe->refunds->create($params);
|
||||
|
||||
Log::info('Stripe refund created', [
|
||||
'refund_id' => $refund->id,
|
||||
'payment_intent' => $paymentIntentId,
|
||||
'amount' => $refund->amount,
|
||||
'status' => $refund->status,
|
||||
'reason' => $reason,
|
||||
]);
|
||||
|
||||
return [
|
||||
'success' => true,
|
||||
'refund_id' => $refund->id,
|
||||
'amount' => $refund->amount,
|
||||
'status' => $refund->status,
|
||||
];
|
||||
} catch (ApiErrorException $e) {
|
||||
Log::error('Stripe refund failed', [
|
||||
'payment_intent' => $paymentIntentId,
|
||||
'error' => $e->getMessage(),
|
||||
'reason' => $reason,
|
||||
]);
|
||||
|
||||
return ['success' => false, 'error' => $e->getMessage()];
|
||||
}
|
||||
}
|
||||
|
||||
// ── Detach payment method from a SetupIntent ────────────────
|
||||
// This is how we "cancel" recurring: remove the card so no
|
||||
// future charges can be made.
|
||||
|
||||
public function detachPaymentMethod(string $setupIntentId): array
|
||||
{
|
||||
try {
|
||||
$si = $this->stripe->setupIntents->retrieve($setupIntentId);
|
||||
|
||||
if (! $si->payment_method) {
|
||||
return ['success' => true, 'message' => 'No payment method attached'];
|
||||
}
|
||||
|
||||
$pmId = is_string($si->payment_method)
|
||||
? $si->payment_method
|
||||
: $si->payment_method->id;
|
||||
|
||||
$this->stripe->paymentMethods->detach($pmId);
|
||||
|
||||
Log::info('Stripe payment method detached', [
|
||||
'setup_intent' => $setupIntentId,
|
||||
'payment_method' => $pmId,
|
||||
]);
|
||||
|
||||
return [
|
||||
'success' => true,
|
||||
'message' => "Payment method {$pmId} detached",
|
||||
'payment_method' => $pmId,
|
||||
];
|
||||
} catch (ApiErrorException $e) {
|
||||
Log::error('Failed to detach payment method', [
|
||||
'setup_intent' => $setupIntentId,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
|
||||
return ['success' => false, 'error' => $e->getMessage()];
|
||||
}
|
||||
}
|
||||
|
||||
// ── Retrieve PaymentIntent details for display ──────────────
|
||||
|
||||
public function getPaymentDetails(string $paymentIntentId): ?array
|
||||
{
|
||||
try {
|
||||
$pi = $this->stripe->paymentIntents->retrieve($paymentIntentId, [
|
||||
'expand' => ['latest_charge'],
|
||||
]);
|
||||
|
||||
$charge = $pi->latest_charge;
|
||||
|
||||
return [
|
||||
'id' => $pi->id,
|
||||
'status' => $pi->status,
|
||||
'amount' => $pi->amount,
|
||||
'currency' => strtoupper($pi->currency),
|
||||
'created' => date('d M Y H:i', $pi->created),
|
||||
'refunded' => $charge?->refunded ?? false,
|
||||
'amount_refunded' => $charge?->amount_refunded ?? 0,
|
||||
'card_brand' => $charge?->payment_method_details?->card?->brand ?? null,
|
||||
'card_last4' => $charge?->payment_method_details?->card?->last4 ?? null,
|
||||
];
|
||||
} catch (ApiErrorException $e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// ── Retrieve SetupIntent details for display ────────────────
|
||||
|
||||
public function getSetupIntentDetails(string $setupIntentId): ?array
|
||||
{
|
||||
try {
|
||||
$si = $this->stripe->setupIntents->retrieve($setupIntentId, [
|
||||
'expand' => ['payment_method'],
|
||||
]);
|
||||
|
||||
$pm = $si->payment_method;
|
||||
|
||||
return [
|
||||
'id' => $si->id,
|
||||
'status' => $si->status,
|
||||
'created' => date('d M Y H:i', $si->created),
|
||||
'payment_method_id' => is_string($pm) ? $pm : ($pm?->id ?? null),
|
||||
'card_brand' => is_object($pm) ? ($pm->card?->brand ?? null) : null,
|
||||
'card_last4' => is_object($pm) ? ($pm->card?->last4 ?? null) : null,
|
||||
'card_exp_month' => is_object($pm) ? ($pm->card?->exp_month ?? null) : null,
|
||||
'card_exp_year' => is_object($pm) ? ($pm->card?->exp_year ?? null) : null,
|
||||
'customer_id' => $si->customer,
|
||||
];
|
||||
} catch (ApiErrorException $e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
134
temp_files/care/deploy.py
Normal file
134
temp_files/care/deploy.py
Normal file
@@ -0,0 +1,134 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Deploy supporter care changes:
|
||||
1. Add HasInternalNotes to ScheduledGivingDonation model
|
||||
2. Add InternalNotesRelationManager to ScheduledGivingDonationResource
|
||||
3. Add refund action to DonationResource table row actions
|
||||
"""
|
||||
import os
|
||||
|
||||
BASE = '/home/forge/app.charityright.org.uk'
|
||||
|
||||
# ── 1. Add HasInternalNotes to ScheduledGivingDonation model ─────
|
||||
|
||||
path = os.path.join(BASE, 'app/Models/ScheduledGivingDonation.php')
|
||||
with open(path, 'r') as f:
|
||||
c = f.read()
|
||||
|
||||
if 'HasInternalNotes' not in c:
|
||||
# Add use import
|
||||
c = c.replace(
|
||||
"use App\\Traits\\Models\\HasBasicAttributions;",
|
||||
"use App\\Traits\\HasInternalNotes;\nuse App\\Traits\\Models\\HasBasicAttributions;"
|
||||
)
|
||||
# Add trait usage
|
||||
c = c.replace(
|
||||
" use HasBasicAttributions,",
|
||||
" use HasInternalNotes,\n HasBasicAttributions,"
|
||||
)
|
||||
with open(path, 'w') as f:
|
||||
f.write(c)
|
||||
print('Added HasInternalNotes to ScheduledGivingDonation model')
|
||||
else:
|
||||
print('ScheduledGivingDonation already has HasInternalNotes')
|
||||
|
||||
# ── 2. Add InternalNotesRelationManager to ScheduledGivingDonationResource ──
|
||||
|
||||
path = os.path.join(BASE, 'app/Filament/Resources/ScheduledGivingDonationResource.php')
|
||||
with open(path, 'r') as f:
|
||||
c = f.read()
|
||||
|
||||
if 'InternalNotesRelationManager' not in c:
|
||||
# Add import
|
||||
c = c.replace(
|
||||
"use App\\Filament\\Resources\\ScheduledGivingDonationResource\\RelationManagers\\ScheduledGivingDonationPayments;",
|
||||
"use App\\Filament\\Resources\\ScheduledGivingDonationResource\\RelationManagers\\ScheduledGivingDonationPayments;\nuse App\\Filament\\RelationManagers\\InternalNotesRelationManager;"
|
||||
)
|
||||
# Add to getRelations
|
||||
c = c.replace(
|
||||
"ScheduledGivingDonationPayments::class,\n ];",
|
||||
"ScheduledGivingDonationPayments::class,\n InternalNotesRelationManager::class,\n ];"
|
||||
)
|
||||
with open(path, 'w') as f:
|
||||
f.write(c)
|
||||
print('Added InternalNotesRelationManager to ScheduledGivingDonationResource')
|
||||
else:
|
||||
print('ScheduledGivingDonationResource already has InternalNotesRelationManager')
|
||||
|
||||
# ── 3. Add refund action to DonationResource table row actions ───
|
||||
|
||||
path = os.path.join(BASE, 'app/Filament/Resources/DonationResource.php')
|
||||
with open(path, 'r') as f:
|
||||
c = f.read()
|
||||
|
||||
# Add StripeRefundService import if missing
|
||||
if 'StripeRefundService' not in c:
|
||||
c = c.replace(
|
||||
"use App\\Models\\Donation;",
|
||||
"use App\\Models\\Donation;\nuse App\\Services\\StripeRefundService;"
|
||||
)
|
||||
|
||||
# Add TextInput import if missing for refund form
|
||||
if 'use Filament\\Forms\\Components\\TextInput;' not in c:
|
||||
c = c.replace(
|
||||
"use Filament\\Forms\\Components\\Select;",
|
||||
"use Filament\\Forms\\Components\\Select;\nuse Filament\\Forms\\Components\\TextInput;"
|
||||
)
|
||||
|
||||
# Add refund action inside the ActionGroup, after ViewAction
|
||||
old_view = " ViewAction::make(),"
|
||||
new_view = """ ViewAction::make(),
|
||||
|
||||
Action::make('refund')
|
||||
->label('Refund')
|
||||
->icon('heroicon-o-arrow-uturn-left')
|
||||
->color('danger')
|
||||
->visible(fn (Donation $d) => $d->isConfirmed()
|
||||
&& $d->provider_type === \\App\\Definitions\\PaymentProviders::STRIPE
|
||||
&& str_starts_with($d->provider_reference ?? '', 'pi_'))
|
||||
->requiresConfirmation()
|
||||
->modalHeading('Refund Donation')
|
||||
->modalDescription(fn (Donation $d) => 'Refund £' . number_format($d->amount / 100, 2) . ' to ' . ($d->customer?->name ?? 'donor') . '\\'s card via Stripe.')
|
||||
->form([
|
||||
TextInput::make('refund_amount')
|
||||
->label('Refund amount (£)')
|
||||
->numeric()
|
||||
->default(fn (Donation $d) => number_format($d->amount / 100, 2, '.', ''))
|
||||
->required()
|
||||
->minValue(0.01)
|
||||
->maxValue(fn (Donation $d) => $d->amount / 100)
|
||||
->step(0.01)
|
||||
->helperText('Full amount for complete refund, or reduce for partial.'),
|
||||
])
|
||||
->action(function (Donation $donation, array $data) {
|
||||
$amountPence = (int) round($data['refund_amount'] * 100);
|
||||
$isPartial = $amountPence < $donation->amount;
|
||||
$service = app(StripeRefundService::class);
|
||||
$result = $service->refundPaymentIntent(
|
||||
$donation->provider_reference,
|
||||
$isPartial ? $amountPence : null,
|
||||
'Table refund by ' . auth()->user()?->name
|
||||
);
|
||||
if ($result['success']) {
|
||||
if (!$isPartial) {
|
||||
$donation->donationConfirmation?->update(['confirmed_at' => null]);
|
||||
}
|
||||
$donation->internalNotes()->create([
|
||||
'user_id' => auth()->id(),
|
||||
'body' => ($isPartial ? 'Partial' : 'Full') . ' refund of £' . number_format($amountPence / 100, 2) . '. Stripe ID: ' . $result['refund_id'],
|
||||
]);
|
||||
Notification::make()->title('£' . number_format($result['amount'] / 100, 2) . ' refunded')->success()->send();
|
||||
} else {
|
||||
Notification::make()->title('Refund failed')->body($result['error'])->danger()->send();
|
||||
}
|
||||
}),"""
|
||||
|
||||
c = c.replace(old_view, new_view)
|
||||
|
||||
with open(path, 'w') as f:
|
||||
f.write(c)
|
||||
print('Added refund action to DonationResource table')
|
||||
else:
|
||||
print('DonationResource already has StripeRefundService')
|
||||
|
||||
print('Done!')
|
||||
27
temp_files/care/revert_vendor.py
Normal file
27
temp_files/care/revert_vendor.py
Normal file
@@ -0,0 +1,27 @@
|
||||
#!/usr/bin/env python3
|
||||
path = '/home/forge/app.charityright.org.uk/vendor/filament/tables/src/Table/Concerns/HasRecords.php'
|
||||
|
||||
with open(path, 'r') as f:
|
||||
lines = f.readlines()
|
||||
|
||||
new_lines = []
|
||||
i = 0
|
||||
while i < len(lines):
|
||||
line = lines[i]
|
||||
if 'public function getModel(): string' in line and 'getModelLabel' not in line:
|
||||
new_lines.append(' public function getModel(): string\n')
|
||||
new_lines.append(' {\n')
|
||||
new_lines.append(' return $this->getQuery()->getModel()::class;\n')
|
||||
new_lines.append(' }\n')
|
||||
# Skip the old method body
|
||||
i += 1
|
||||
while i < len(lines) and lines[i].strip() != '}':
|
||||
i += 1
|
||||
i += 1 # skip closing brace
|
||||
continue
|
||||
new_lines.append(line)
|
||||
i += 1
|
||||
|
||||
with open(path, 'w') as f:
|
||||
f.writelines(new_lines)
|
||||
print('Vendor reverted to original')
|
||||
Reference in New Issue
Block a user