index.ts
9 months ago
useDonationsBySubscription.ts
9 months ago
useSubscriptionAmounts.ts
9 months ago
useSubscriptionCancel.ts
9 months ago
useSubscriptionSync.tsx
9 months ago
useSubscriptionSync.tsx
78 lines
| 1 | import { useState } from "react"; |
| 2 | import { getSubscriptionOptionsWindowData } from "../utils"; |
| 3 | |
| 4 | export interface SubscriptionSyncResponse { |
| 5 | details: SyncDetails; |
| 6 | missingTransactions: SyncTransaction[]; |
| 7 | presentTransactions: SyncTransaction[]; |
| 8 | notice: string; |
| 9 | } |
| 10 | |
| 11 | export interface SyncDetails { |
| 12 | currentStatus: string; |
| 13 | gatewayStatus: string; |
| 14 | currentPeriod: string; |
| 15 | gatewayPeriod: string; |
| 16 | currentCreatedAt: string; |
| 17 | gatewayCreatedAt: string; |
| 18 | } |
| 19 | |
| 20 | export interface SyncTransaction { |
| 21 | id: number; |
| 22 | gatewayTransactionId: string; |
| 23 | amount: string; |
| 24 | createdAt: string; |
| 25 | status: string; |
| 26 | type: 'renewal' | 'subscription'; |
| 27 | } |
| 28 | |
| 29 | /** |
| 30 | * @since 4.8.0 |
| 31 | */ |
| 32 | export default function useSubscriptionSync() { |
| 33 | const { syncSubscriptionNonce } = getSubscriptionOptionsWindowData(); |
| 34 | |
| 35 | const [isLoading, setIsLoading] = useState(false); |
| 36 | const [hasResolved, setHasResolved] = useState(false); |
| 37 | const [syncResult, setSyncResult] = useState<SubscriptionSyncResponse | null>(null); |
| 38 | |
| 39 | const syncSubscription = async (subscription: any) => { |
| 40 | setIsLoading(true); |
| 41 | setHasResolved(false); |
| 42 | |
| 43 | try { |
| 44 | const response = await fetch('/wp-admin/admin-ajax.php', { |
| 45 | method: 'POST', |
| 46 | headers: { |
| 47 | 'Content-Type': 'application/x-www-form-urlencoded', |
| 48 | }, |
| 49 | body: new URLSearchParams({ |
| 50 | action: 'give_recurring_sync_subscription_details', |
| 51 | subscription_id: String(subscription?.id), |
| 52 | 'give-form-id': String(subscription?.donationFormId), |
| 53 | security: syncSubscriptionNonce, |
| 54 | }), |
| 55 | }); |
| 56 | |
| 57 | const json = await response.json(); |
| 58 | |
| 59 | setSyncResult(json?.data); |
| 60 | setHasResolved(true); |
| 61 | return json?.data; |
| 62 | } catch (error) { |
| 63 | console.error('Sync failed:', error); |
| 64 | setHasResolved(false); |
| 65 | throw error; |
| 66 | } finally { |
| 67 | setIsLoading(false); |
| 68 | } |
| 69 | }; |
| 70 | |
| 71 | return { |
| 72 | syncSubscription, |
| 73 | isLoading, |
| 74 | hasResolved, |
| 75 | syncResult: syncResult, |
| 76 | }; |
| 77 | } |
| 78 |