npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

protect-group-dynamic-refundable-react

v1.4.3

Published

React component to display Protect Group Dynamic Refundable Content, and write transactions

Downloads

817

Readme

Protect Group Dynamic Refundable React Component

This component is designed to place our Refundable Content (served via our dynamic api) on your React app, and allow you to also send transactions into our platform using a simple hook.

Installation

npm i --save protect-group-dynamic-refundable-react

Usage

RefundableProvider

Add the provider somewhere near the root of your application

import {
	RefundableOptions,
	RefundableProvider
} from 'protect-group-dynamic-refundable-react'

function MyApp() {
	const options: RefundableOptions = {
        currencyCode: 'GBP',
        environment: 'test',
        languageCode: 'en',
        vendorCode: '<YOUR-VENDOR-CODE>',
        eventDateFormat: 'DD/MM/YYYY', // optional
        containerSize: 'medium', //optional
        useSaleAction: true, // optional, set this to false if you intend to call our sale endpoint manually
        nonce: '[nonce code for the inline script, if you have a CSP set up on your site]', //optional
        salesTax: 10 // optional, apply sales tax to the refundable booking cost
      
    }

	return (
		<RefundableProvider options={options}>
			<TheRestOfYourApp/>
		</RefundableProvider>
	)
}

updateQuoteData

The useRefudableActions hook provides a function to update the quote data at any point on your app

import {useRefundableActions} from 'protect-group-dynamic-refundable-react'

function MyTicketTypeSelector(){
  const {updateQuoteData} = useRefundableActions()
  const {myInternalState} = useMyInternalStateContext()
  
  useEffect(() => {
    const {bookingCost, numberOfTickets, eventDate} = myInternalState
    updateQuoteData({
      totalValue: bookingCost, 
      numberOfTickets, 
      eventTravelDateTime: eventDate,
      nonce: '[nonce code can also be provided here, if required]'
    })
  }, [myInternalState])
  
  const handleChange = event => updateQuoteData({
    totalValue: myInternalState.bookingCost,
    numberOfTickets: myInternalState.numberOfTickets,
    eventTravelDateTime: myInternalState.eventDate,
    ticketType: event.target.value,
    nonce: '[nonce code can also be provided here, if required]',
    salesTax: 5 // sales tax can also be applied here, if required
  })
  
  return (
    <div>
      <label>Select a ticket type</label>
      <select onChange={handleChange}>
        <option value="standard">Standard</option>
        <option value="premium">Premium</option>
        <option value="vip">VIP</option>
      </select>
    </div>
  )
}

RefundableContent

Add the RefundableContent component where you would like our Refundable Content to be placed on your page. Use the writeSale function on the useRefundableActions hook to write a transaction into our platform

import {
	ApiRequestFailedEventArgs,
	ProtectionChangeEventArgs,
	RefudableContent,
	SaleData,
	useRefundableActions
} from 'protect-group-dynamic-refundable-react'

function MyCheckoutPage() {
	const {writeSale} = useRefundableActions()

	const handleProtectionChange = (args: ProtectionChangeEventArgs) => {
		//Do something with the args
	}

	const handleApiError = (args: ApiRequestFailedEventArgs) => {
		// Maybe some invalid data was supplied?
	}

	const handleMakePayment = async () => {
		// Do your sale thing

		const request: SaleData = {
			bookingReference: '<YOUR-BOOKING-REFERENCE>',
			customers: [
				{firstName: 'Test', lastName: 'Test'}
			]
		}

		try {
			const response = await writeSale(request)
			// Do something with the response
		} catch (e: any) {
			const {data: {error}} = e
			// Something went wrong
		}
	}

	return (
		<MyPageWrapper>
			//some components
			<RefundableContent
				onApiError={handleApiError}
				onProtectionChange={handleProtectionChange}
			/>
			//some components
			<MakePaymentButton onClick={handleMakePayment}></MakePaymentButton>
		</MyPageWrapper>
	)
}

Types

  • Environment - 'test' | 'prod'
  • ContainerSize - 'small' | 'medium' | 'large'

RefundableProvider Props

| Property | Type | Required? | Default | Description | |:----------------|:-------------:|:---------:|:-------:|:------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | environment | Environment | yes | | Send requests to either our test or production api. Should be either 'test' or 'prod' | | currencyCode | string | yes | | A valid currency code | | languageCode | string | yes | | A valid language code. Currently supported languages are en, ar, de, es, fr, it, ja, ko, pt, ru, tr, zh-CH, zh-TW | | vendorCode | string | yes | | Your vendor code supplied by our commercial team. Please ensure the correct vendor code is supplied for the environment | | eventDateFormat | string | no | | Our api expects a date format of ISO 861 yyyy-MM-ddTHH:mm:ss.FFFFFzzz. If you are unable to supply a date in this format you can optionally configure the format here. The format you supply must match a javascript date format from the moment.js library | | containerSize | ContainerSize | no | 'large' | Display a mobile/tablet layout on a desktop by specifying either 'small' or 'medium'. This is useful if our refundable content is in a smaller area on your desktop layout. Downward media queries are still observed | | useSaleAction | boolean | no | | If you intend to call our sale endpoint at a later time via your back end, set this to false. The change event args will then have two other properties set. quoteId, and products | | nonce | string | no | | The html has a small script block that fires custom events when a CTA is clicked. There is a placeholder for a nonce code if your site has a Content Security Policy set up which would block the script execution | | salesTax | number | no | | Sales tax can be applied to the refundable booking cost, to save you having to calculate it afterwards |

RefundableContent Props

| Property | Type | Required? | Default | Description | |:-------------------|:--------:|:---------:|:---------:|:---------------------------------------------------------------------------| | onProtectionChange | function | yes | | Function that is invoked when any of the components internal state changes | | onApiError | function | | | Function that is invoked if a quote api call fails for whatever reason |

ProtectionChangeEventArgs

The parameter passed into the onProtectionChange function

interface ChangeEventProduct {
  productId: number
  sold?: boolean
}

interface ProtectionChangeEventArgs {
    bookingCost: number
    formattedBookingCost: string
    formattedProtectionValue: string
	formattedProtectionValueNet: string
	formattedProtectionValueTax: string
    formattedTotalValue: string
    products?: ChangeEventProduct[] // only populated when useSaleAction is set to false
    protectionSelected?: boolean
    protectionValue: number
	protectionValueNet: number
	protectionValueTax: number
    quoteId?: string // only populated when useSaleAction is set to false
    totalValue: number
}

quoteId and products will only be set when you set the useSaleAction value to false. These two values are what's required for you to manually make a request to our sale endpoint. You will also need credentials to call our api, which can be provided by your commercial manager.

Interfaces


interface QuoteData {
	accommodationName?: string
	airline?: string
	arrivalAirportCode?: string
	arrivalCountry?: string
	customerDateOfBirth?: string
	customerGender?: string
	departureAirportCode?: string
	departureCountry?: string
	eventName?: string
	eventTravelClass?: string
	eventTravelContinent?: string
	eventTravelCity?: string
	eventTravelCountry?: string
	eventTravelDateTime: string
	eventTravelLatitude?: number
	eventTravelLongitude?: number
	flightType?: string
	nonce?: string
	numberOfTickets: number
	riskType?: string
	salesTax?: number // This will overwrite what was supplied in the provider config
	ticketType?: string
	totalValue: number
	tourOperator?: string
	user?: string
	venue?: string
}

interface Customer {
	firstName: string
	lastName: string
}

interface SaleData {
	bookingReference: string
	customers: Customer[]
}

interface PatchSaleData extends SaleData {
	quoteId: string
	products: SaleProduct[]
}

interface SaleResult {
	data: SaleResponse
	error: any
}

interface SaleResponse {
	saleId: string
	refundableLink?: string // Only returned on a refundable booking
	refundableConfirmationHtml?: string // Only returned on a refunable booking
}

interface RefundableActions {
	updateQuoteData: (data: QuoteData) => void
	writeSale: (request: SaleData) => Promise<SaleResult>
	patchSale: (request: PatchSaleData) => Promise<SaleResponse>
	holdSale: (saleId: string) => Promise<any> // saleId can be either our sale id, from the original sale response OR your booking refernce
	cancelSale: (saleId: string) => Promise<any>
	reset: () => void
}

RefundableActions.reset

This function is for partners who set the useSaleAction prop to false. It's designed to be used after a customer has completed a booking, to clear the session data, which would normally happen automatically during the writeSale process

Release Notes

Version 1.4.1

  • Fixed rounding bug when calculating values on event arguments.
  • Added patchSale function to useRefundableActions hook
  • Added holdSale function to useRefundableActions hook
  • Added cancelSale function to useRefundableActions hook

Version 1.4.2

  • Fixed bug where the protectionSelected event argument field was false when no selection had been made, and neither option is pre-selected. It's now undefined until a selection has been made
  • Added protection value net and tax fields to change event args. Both formatted and numerical. Tax will only have a value if sales tax is supplied on the quote request
  • Updated axios dependency to 1.7.7

Version 1.4.3

  • Version bump, no changes