Skip to content

Beautiful Open-Source Form Builder

Add refund payment functionality in AdminController and UI components (#841)

Chirag Chhatralabe7729d5fca9
diff --git a/api/app/Http/Controllers/Admin/AdminController.php b/api/app/Http/Controllers/Admin/AdminController.php
index 63cd18269..4ae294158 100644
--- a/api/app/Http/Controllers/Admin/AdminController.php
+++ b/api/app/Http/Controllers/Admin/AdminController.php
@@ -203,22 +203,19 @@ class AdminController extends Controller
{
$request->validate([
'user_id' => 'required',
+ 'subscription_id' => 'required',
'cancellation_reason' => 'required'
]);
$user = User::find($request->get("user_id"));
+ $subscription = $user->subscriptions()->find($request->get("subscription_id"));
- $activeSubscriptions = $user->subscriptions()->where(function ($q) {
- $q->where('stripe_status', 'trialing')
- ->orWhere('stripe_status', 'active');
- })->get();
-
- if ($activeSubscriptions->count() != 1) {
+ if ($subscription && !in_array($subscription->stripe_status, ['active', 'trialing'])) {
return $this->error([
- "message" => "The user has more than one active subscriptions or doesn't have one."
+ "message" => "The subscription is not active or trialing."
]);
}
- $subscription = $activeSubscriptions->first();
+ // Cancel the subscription
$subscription->cancel();
self::log('Cancel Subscription', [
@@ -256,6 +253,62 @@ class AdminController extends Controller
]);
}
+ public function refundPayment(Request $request)
+ {
+ $request->validate([
+ 'user_id' => 'required',
+ 'invoice_id' => 'required',
+ 'refund_reason' => 'required'
+ ]);
+
+ $user = User::findOrFail($request->get('user_id'));
+ $latestInvoice = $user->invoices()->first();
+
+ if (!$latestInvoice) {
+ return $this->error(['message' => 'No invoices found for this user.'], 404);
+ }
+
+ if ($latestInvoice->id !== $request->get('invoice_id')) {
+ return $this->error(['message' => 'You can only refund the last invoice.'], 422);
+ }
+
+ try {
+ // Get the Stripe invoice to find the payment
+ $stripeInvoice = Cashier::stripe()->invoices->retrieve($latestInvoice->id);
+ if (!$stripeInvoice->charge) {
+ return $this->error(['message' => 'It\'s trial period invoice so can not refund.'], 404);
+ }
+
+ $refund = Cashier::stripe()->refunds->create([
+ 'charge' => $stripeInvoice->charge,
+ 'reason' => 'requested_by_customer',
+ 'metadata' => [
+ 'refund_reason' => $request->get('refund_reason'),
+ 'moderator_id' => request()->user()->id,
+ 'user_id' => $user->id
+ ]
+ ]);
+
+ self::log('Refund Payment', [
+ 'user_id' => $user->id,
+ 'invoice_id' => $latestInvoice->id,
+ 'stripe_refund_id' => $refund->id,
+ 'refund_reason' => $request->get('refund_reason'),
+ 'moderator_id' => request()->user()->id,
+ ]);
+ } catch (\Exception $e) {
+ self::log('Refund Error', [
+ 'user_id' => $user->id,
+ 'error' => $e->getMessage(),
+ ]);
+ return $this->error(['message' => 'An error occurred while processing the refund.'], 500);
+ }
+
+ return $this->success([
+ 'message' => "The payment has been successfully refunded."
+ ]);
+ }
+
public static function log($message, $data = [])
{
Log::warning(self::ADMIN_LOG_PREFIX . $message, $data);
diff --git a/api/routes/api.php b/api/routes/api.php
index 2cfea04d2..1de621533 100644
--- a/api/routes/api.php
+++ b/api/routes/api.php
@@ -242,6 +242,10 @@ Route::group(['middleware' => 'auth.multi'], function () {
'cancellation-subscription',
[\App\Http\Controllers\Admin\AdminController::class, 'cancelSubscription']
);
+ Route::patch(
+ 'refund-payment',
+ [\App\Http\Controllers\Admin\AdminController::class, 'refundPayment']
+ );
Route::patch(
'send-password-reset-email',
diff --git a/client/components/pages/admin/CancelSubscription.vue b/client/components/pages/admin/CancelSubscription.vue
deleted file mode 100644
index c8f8d408c..000000000
--- a/client/components/pages/admin/CancelSubscription.vue
+++ /dev/null
@@ -1,68 +0,0 @@
-<template>
- <AdminCard
- v-if="props.user.stripe_id"
- title="Cancel subscription"
- icon="heroicons:trash-16-solid"
- >
- <form
- class="space-y-6 flex flex-col h-full justify-between"
- @submit.prevent="askCancel"
- >
- <p class="text-xs text-neutral-500">
- Ideally customers should cancel subscription themselves via the UI. If
- you cancel the subscription for them, please provide a reason.
- </p>
- <div>
- <TextInput
- name="cancellation_reason"
- :form="form"
- label="Cancellation reason"
- native-type="reason"
- :required="true"
- help="Cancellation reason"
- />
-
- <UButton
- :loading="loading"
- type="submit"
- block
- icon="heroicons:exclamation-triangle-16-solid"
- label="Cancel subscription now"
- />
- </div>
- </form>
- </AdminCard>
-</template>
-
-<script setup>
-const props = defineProps({
- user: { type: Object, required: true }
-})
-
-const alert = useAlert()
-let loading = ref(false)
-const form = useForm({
- user_id: props.user.id,
- cancellation_reason: ''
-})
-
-const askCancel = () => {
- alert.confirm('Are you sure? This will cancel the subscription for this user.', cancelSubscription)
-}
-
-const cancelSubscription = () => {
- if (!props.user.stripe_id) return
- loading = true
- form
- .patch('/moderator/cancellation-subscription')
- .then(async (data) => {
- loading = false
- alert.success(data.message)
- })
- .catch((error) => {
- alert.error(error.data.message)
- loading = false
- })
-}
-
-</script>
diff --git a/client/components/pages/admin/UserPayments.vue b/client/components/pages/admin/UserPayments.vue
index 90c643bb8..5bb320e18 100644
--- a/client/components/pages/admin/UserPayments.vue
+++ b/client/components/pages/admin/UserPayments.vue
@@ -37,6 +37,17 @@
{{ row.original.status }}
</span>
</template>
+ <template #actions-cell="{ row, index }">
+ <UButton
+ v-if="row.original.status == 'paid' && isLastPayment(row.original)"
+ color="error"
+ variant="outline"
+ size="sm"
+ icon="heroicons:arrow-uturn-left-16-solid"
+ label="Refund"
+ @click="openRefundModal(row.original)"
+ />
+ </template>
</UTable>
<div
v-if="payments?.length > pageCount"
@@ -48,6 +59,40 @@
:total="payments?.length"
/>
</div>
+
+ <UModal
+ v-model:open="showRefundModal"
+ :ui="{ content: 'sm:max-w-lg' }"
+ title="Refund payment"
+ >
+ <template #body>
+ <form @submit.prevent="askRefund">
+ <p class="text-xs text-neutral-500">
+ We will not update to user. Please inform them manually. <br/>
+ After refund it will take some time to update this page.
+ </p>
+ <div class="mt-4">
+ <TextInput
+ name="refund_reason"
+ :form="form"
+ label="Refund reason"
+ native-type="reason"
+ :required="true"
+ help="Please provide a clear reason for refunding this payment. This will be logged for future reference."
+ />
+
+ <UButton
+ class="mt-4"
+ :loading="form.busy"
+ type="submit"
+ block
+ icon="heroicons:arrow-uturn-left-16-solid"
+ label="Refund payment now"
+ />
+ </div>
+ </form>
+ </template>
+ </UModal>
</AdminCard>
</template>
@@ -58,6 +103,7 @@ const props = defineProps({
user: {type: Object, required: true}
})
+const alert = useAlert()
const loading = ref(true)
const payments = ref([])
const page = ref(1)
@@ -82,6 +128,17 @@ const getPayments = () => {
})
}
+const isLastPayment = (payment) => {
+ if (!payments.value || payments.value.length === 0) return false
+
+ // Find the most recent payment by creation date
+ const sortedPayments = [...payments.value].sort((a, b) => {
+ return new Date(b.creation_date) - new Date(a.creation_date)
+ })
+
+ return sortedPayments[0].id === payment.id
+}
+
const columns = [{
accessorKey: 'id',
@@ -102,6 +159,45 @@ const columns = [{
accessorKey: 'creation_date',
header: 'Creation date',
sortable: true
+}, {
+ accessorKey: 'actions',
+ header: '',
}]
+const showRefundModal = ref(false)
+const form = useForm({
+ user_id: props.user.id,
+ invoice_id: null,
+ refund_reason: null
+})
+
+watch(showRefundModal, (value) => {
+ if (!value) {
+ form.invoice_id = null
+ form.refund_reason = null
+ }
+})
+
+const openRefundModal = (payment) => {
+ form.invoice_id = payment.id
+ showRefundModal.value = true
+}
+
+const askRefund = () => {
+ alert.confirm('Are you sure? This will refund the payment for this user.', refundPayment)
+}
+
+const refundPayment = () => {
+ if (!props.user.stripe_id) return
+ form
+ .patch('/moderator/refund-payment')
+ .then(async (data) => {
+ alert.success(data.message)
+ showRefundModal.value = false
+ getPayments()
+ })
+ .catch((error) => {
+ alert.error(error.data.message)
+ })
+}
</script>
diff --git a/client/components/pages/admin/UserSubscriptions.vue b/client/components/pages/admin/UserSubscriptions.vue
index 0021690f9..85b25a27f 100644
--- a/client/components/pages/admin/UserSubscriptions.vue
+++ b/client/components/pages/admin/UserSubscriptions.vue
@@ -34,6 +34,16 @@
{{ row.original.status }}
</span>
</template>
+ <template #actions-cell="{ row }">
+ <UButton
+ v-if="row.original.status == 'active' || row.original.status == 'trialing'"
+ color="error"
+ variant="outline"
+ size="sm"
+ icon="heroicons:trash-16-solid"
+ @click="openCancelSubscriptionModal(row.original)"
+ />
+ </template>
</UTable>
<div
v-if="subscriptions?.length > pageCount"
@@ -45,6 +55,41 @@
:total="subscriptions.length"
/>
</div>
+
+ <UModal
+ v-model:open="showCancelSubscriptionModal"
+ :ui="{ content: 'sm:max-w-lg' }"
+ title="Cancel subscription"
+ >
+ <template #body>
+ <form @submit.prevent="askCancel">
+ <p class="text-xs text-neutral-500">
+ Ideally customers should cancel subscription themselves via the UI. If
+ you cancel the subscription for them, please provide a reason.
+ </p>
+ <div class="mt-4">
+ <TextInput
+ name="cancellation_reason"
+ :form="form"
+ label="Cancellation reason"
+ native-type="reason"
+ :required="true"
+ help="Please provide a clear reason for cancelling this subscription. This will be logged for future reference."
+ />
+
+ <UButton
+ class="mt-4"
+ :loading="form.busy"
+ type="submit"
+ block
+ icon="heroicons:exclamation-triangle-16-solid"
+ label="Cancel subscription now"
+ />
+ </div>
+ </form>
+ </template>
+ </UModal>
+
</AdminCard>
</template>
@@ -52,7 +97,7 @@
import { adminApi } from '~/api'
const props = defineProps({
- user: { type: Object, required: true }
+ user: { type: Object, required: true }
})
const loading = ref(true)
@@ -103,6 +148,47 @@ const columns = [{
}, {
accessorKey: 'status',
header: 'Status'
+}, {
+ accessorKey: 'actions',
+ header: '',
}]
+const showCancelSubscriptionModal = ref(false)
+const alert = useAlert()
+const form = useForm({
+ user_id: props.user.id,
+ subscription_id: null,
+ cancellation_reason: null
+})
+
+watch(showCancelSubscriptionModal, (value) => {
+ if (!value) {
+ form.subscription_id = null
+ form.cancellation_reason = null
+ }
+})
+
+const openCancelSubscriptionModal = (subscription) => {
+ form.subscription_id = subscription.id
+ showCancelSubscriptionModal.value = true
+}
+
+const askCancel = () => {
+ alert.confirm('Are you sure? This will cancel the subscription for this user.', cancelSubscription)
+}
+
+const cancelSubscription = () => {
+ if (!props.user.stripe_id) return
+ form
+ .patch('/moderator/cancellation-subscription')
+ .then(async (data) => {
+ alert.success(data.message)
+ showCancelSubscriptionModal.value = false
+ getSubscriptions()
+ })
+ .catch((error) => {
+ alert.error(error.data.message)
+ })
+}
+
</script>
diff --git a/client/pages/admin.vue b/client/pages/admin.vue
index 9620a2e1f..bb74461fd 100644
--- a/client/pages/admin.vue
+++ b/client/pages/admin.vue
@@ -122,9 +122,6 @@
<ExtendTrial
:user="userInfo"
/>
- <CancelSubscription
- :user="userInfo"
- />
<BillingEmail
:user="userInfo"
/>