11import { createContext , useEffect , useState } from 'react' ;
22
3+ const VOUCHERS = {
4+ default : {
5+ code : 'docs-50' ,
6+ value : '50' ,
7+ type : '%' ,
8+ } ,
9+ dedicated : {
10+ code : 'docs-10' ,
11+ value : '10' ,
12+ type : '%' ,
13+ } ,
14+ domain : {
15+ code : 'docs-10' ,
16+ value : '10' ,
17+ type : '%' ,
18+ } ,
19+ } ;
20+
21+ export function getVoucherForServices ( vouchers , services = [ ] ) {
22+ if ( vouchers && vouchers . code && ! vouchers . default ) {
23+ return vouchers ;
24+ }
25+
26+ if ( vouchers && typeof vouchers === 'object' ) {
27+ if ( Array . isArray ( services ) && services . length > 0 ) {
28+ for ( const service of services ) {
29+ if ( vouchers [ service ] ) {
30+ return vouchers [ service ] ;
31+ }
32+ }
33+ }
34+
35+ if ( vouchers . default ) {
36+ return vouchers . default ;
37+ }
38+ }
39+
40+ return VOUCHERS . default ;
41+ }
42+
343export const VoucherContext = createContext ( {
444 loading : false ,
545 found : false ,
6- voucher : null ,
46+ vouchers : { } ,
47+ getVoucherForServices : getVoucherForServices ,
748} ) ;
849
950export const VoucherProvider = props => {
1051 const [
1152 loading ,
1253 setLoading ,
13- ] = useState ( false ) ;
54+ ] = useState ( true ) ;
1455
1556 const [
16- voucher ,
17- setVoucher ,
57+ vouchers ,
58+ setVouchers ,
1859 ] = useState ( { } ) ;
1960
2061 const [
@@ -23,45 +64,17 @@ export const VoucherProvider = props => {
2364 ] = useState ( null ) ;
2465
2566 useEffect ( ( ) => {
26- const voucherRetrieval = async ( ) => {
27- setLoading ( true ) ;
28-
29- try {
30- const voucherResponse = await fetch ( 'https://zap-hosting.com/interface/shop/_ajax/json_getDocsCoupon.php' , {
31- headers : {
32- 'X-Requested-With' : 'XMLHttpRequest' ,
33- } ,
34- } ) ;
35-
36- if ( ! voucherResponse . ok ) {
37- throw new Error ( `HTTP error! Status: ${ voucherResponse . status } ` ) ;
38- }
39-
40- const voucherData = await voucherResponse . json ( ) ;
41-
42- if ( voucherData . message !== 'ok' || voucherData . result !== 'success' ) {
43- throw new Error ( `Successful response code with application level error: ${ voucherData . message } ` ) ;
44- }
45-
46- setFound ( true ) ;
47- setVoucher ( voucherData . data ) ;
48- } catch ( error ) {
49- console . error ( "Not displaying a voucher for this reason:" , error ) ; // Log the error for debugging
50- setFound ( false ) ;
51- setVoucher ( { } ) ;
52- } finally {
53- setLoading ( false ) ;
54- }
55- } ;
56-
57- voucherRetrieval ( ) ;
67+ setVouchers ( VOUCHERS ) ;
68+ setFound ( true ) ;
69+ setLoading ( false ) ;
5870 } , [ ] ) ;
5971
6072 return (
6173 < VoucherContext . Provider value = { {
6274 loading : loading ,
6375 found : found ,
64- voucher : voucher ,
76+ vouchers : vouchers ,
77+ getVoucherForServices : ( services ) => getVoucherForServices ( vouchers , services ) ,
6578 } } >
6679 { props . children }
6780 </ VoucherContext . Provider >
0 commit comments