| 1 |
import {useEntityRecord} from '@wordpress/core-data'; |
| 2 |
import {useState, useEffect} from 'react'; |
| 3 |
import apiFetch from '@wordpress/api-fetch'; |
| 4 |
|
| 5 |
/** |
| 6 |
* @since 4.4.0 |
| 7 |
*/ |
| 8 |
export interface DonorStatistics { |
| 9 |
donations: { |
| 10 |
lifetimeAmount: number; |
| 11 |
highestAmount: number; |
| 12 |
averageAmount: number; |
| 13 |
count: number; |
| 14 |
first: { |
| 15 |
amount: string; |
| 16 |
date: string; |
| 17 |
} | null; |
| 18 |
last: { |
| 19 |
amount: string; |
| 20 |
date: string; |
| 21 |
} | null; |
| 22 |
}; |
| 23 |
donorType: string; |
| 24 |
preferredPaymentMethod: string; |
| 25 |
} |
| 26 |
|
| 27 |
/** |
| 28 |
* @since 4.4.0 |
| 29 |
*/ |
| 30 |
export function useDonorStatistics(donorId: number, mode: 'live' | 'test' = 'live') { |
| 31 |
const [statistics, setStatistics] = useState<DonorStatistics | null>(null); |
| 32 |
const [error, setError] = useState<Error | null>(null); |
| 33 |
const [isResolving, setIsResolving] = useState<boolean>(false); |
| 34 |
const [hasResolved, setHasResolved] = useState<boolean>(false); |
| 35 |
|
| 36 |
useEffect(() => { |
| 37 |
if (!donorId) return; |
| 38 |
|
| 39 |
setIsResolving(true); |
| 40 |
setHasResolved(false); |
| 41 |
setError(null); |
| 42 |
|
| 43 |
apiFetch({ |
| 44 |
path: `/givewp/v3/donors/${donorId}/statistics?mode=${mode}`, |
| 45 |
method: 'GET', |
| 46 |
}) |
| 47 |
.then((data: DonorStatistics) => { |
| 48 |
setStatistics(data); |
| 49 |
setHasResolved(true); |
| 50 |
}) |
| 51 |
.catch((err: Error) => { |
| 52 |
setError(err); |
| 53 |
setHasResolved(true); |
| 54 |
}) |
| 55 |
.finally(() => { |
| 56 |
setIsResolving(false); |
| 57 |
}); |
| 58 |
}, [donorId, mode]); |
| 59 |
|
| 60 |
return { statistics, error, isResolving, hasResolved }; |
| 61 |
} |
| 62 |
|