Embeddable UI Kit - React.js

Embeddable UI components

The Amberflo UI Kit is a React component library for our customers to be able to consume and make use of principal Amberflo views, for one of their customers, on their own site.

UI Kit components are responsible of making the API calls. To use them you just first need to import the components into your app.

Installation

Run yarn add @amberflo/uikit or npm install @amberflo/uikit to install Amberflo UI Kit in your React project.

📘

Technologies

React >= v17.0.2
Node v16.13.1
Typescript v4.5.5


Available Versions

All versions can be found on npm repository: @amberflo/uikit


Getting Started

Amberflo Provider

The AmberfloProvider is a Provider component that needs to wrap your app, so the components can hit our API. It requires a customer-specific session and a theme. You can check here how to:

<AmberfloProvider
  session="<YOUR_SESSION_ID>"
  theme={{
    brandColor: "<YOUR_BRAND_COLOR>",
    fontSize: <DEFAULT_FONT_SIZE>,
    fontFamily: "<DEFAULT_FONT_FAMILY>"
  }}
>
  ...
</AmberfloProvider>

Imports

To import a single Amberflo UI Kit component into your application (Recommended):

import { CostExplorerBarGraph } from "@amberflo/uikit/compnents/organisms/CostExplorerBarGraph";
import { InvoicesList } from '@amberflo/uikit/components/organisms/InvoiceList'

This will allow to perform tree-shaking so unused components will be dropped from the final bundle that will weight less and load faster.

📘

To make this possible the bundler needs to allow tree shaking.

To import multiple components from the root:

import { CostExplorerBarGraph, InvoicesList } from "@amberflo/ui-kit";

📘

Notice tree shaking won’t be effective if you use this approach.


Theming

To customize the AmberfloProvider above with the theme, we expect this object in the theme prop:

{
  brandColor: string // it can be hex, or color name
  fontSize: number // Basic font size, all rest of font sizes will scale dynamically to this value
  fontFamily: string // name of the font to use. The font must be available on your site. Or you can use a custom font as showed below.
  customFontUrl: string // google font url to import to your site
}

Types

Amberflo UI Kit is heavily typed, which will allow, if you use typescript on your project, to easily see which kind of properties a component receives, or what would return a specific function or hook.


Hooks

We provide a few hooks to access the same data we show on our components, in case you need to render your own component. All hooks can be imported from:

import { ... } from '@amberflo/uikit/hooks`

Available hooks are:

useCost = (startDate: number, endDate: number, period: string) => { data: CostResponse, isFetching: boolean }

useCurrentPricingPlan = () => { data: PricingPlanResponse, isFetching: boolean, handleSelectPlan: (pricingPlanId: string) => void }

useInvoiceDetails = (invoiceDate: string) => { data: InvoiceType, isFetching: boolean }

useInvoices = () => { data: InvoiceType[], isFetching: boolean }

useMeters = () => { data: Meter[], isFetching: boolean }

usePrepaidSummary = () => { data: PrepaidItem[], isFetching: boolean }

useStripeClientSecret = () => { data: string, isFetching: boolean }

useUsage = (meters: string[], startDate: number, endDate: number, period: string, groupBy?: string) => { data: UsageResponse[], isFetching: boolean }


Invoice-related Options

There are a few UI Kit components that display invoice-related data (i.e. Invoice List, Invoice Details, Invoice PDF). There are invoice-related settings a user can update at Amberflo | Customize Invoice which affect how invoices are displayed through UI Kit components (as well as the customer portal and in the main-app).

The current available option/settings are:

  • Displaying cached invoices

    • Invoice data displayed will either be cached data or real-time data.

    • Cached data is used to speed up how quickly invoice data can be retrieved.

  • Group product items on invoices

    • We list all product items and allow user to create categories to group on the invoices.

Common Props

These are props common to all views:

NameTypeDescription
withTitlebooleanIf true, will show the widget title (If the container is enabled) see below
withContainerbooleanIf true, a container wrapper will show around the widget
titlestringCustom title for the block
hideLoaderbooleanIf true, Loader won’t show while loading. Useful if you are showing many components with the same data, and you want a single loader. Or to use your own custom loader
callToAction{ text?: string | JSX.Element; onClick?: () => void; type?: "add" | "disabledAdd" | "remove" | "deleteAll"; noIcon?: boolean; disabled?: boolean; }Shows a button link on the title of container, that can be attached any action
onError(error) => voidA event called when there was some kind of error with the component. So it can show the error to customer
onLoadingChange(isLoading: boolean) => voidAn event called each time the component switches the status of loading. So you can show your own loading for instance.

Common Date Picker Props

There are a few props shared by views that have a date picker.

Views with date picker:

Shared props:

NameTypeDefaultDescription
startDatenumberCurrent day minus 7 days.
For month picker, it will be start of current month to current day.
Default value for the start date on the date picker.
For month picker, this value is used to show the number of months in the month ranges dropdown.
periodValue"daily" | "weekly" | "monthly"dailyDefault value for the date picker value.
onPeriodChange(period: string) => voidundefinedFunction to be called when period is changed
onDateChange(startDate: number, endDate: number) => voidundefinedFunction to be called when date is changed
endDatenumberCurrent DayDefault value for the end date on the date picker.
withDatePickerbooleantrueIf false, DatePicker will be hidden.

Common Graph Props

There are a few props shared by views that have a graph.

Views with graphs:

Shared props:

NameTypeDefaultDescription
graphTextColorstringundefinedColor for the axis of graphs
customGraphOptionsChartOptionsundefinedWe use Chart.js for our graphs. This prop allows to customize the graph using all the options they provide. For more info check: https://www.chartjs.org/docs/latest/general/options.html

For example, you could change text colors, lines or bars weight, add animations, etc.

Available Views

Cost Explorer Bar Graph

2028

How to import:

import { CostExplorerBarGraph } from "@amberflo/uikit/components/organisms/CostExplorerBarGraph";

Available Props

There are no specific props for this view. To see common props check ReactJS Integration | Common Props




Cost Table

2022

How to import:

import { CostExplorerTable } from '@amberflo/uikit/components/organisms/CostExplorerTable'

Available Props

To see common props check ReactJS Integration | Common Props

Prop NameTypeDefault ValueDescription
customCurrencyNumberFormatstringdecimalA string value (either decimal or integer) that determines how custom currency is formatted and displayed. For example, if you had a custom currency value (called “Credits”) of 100, it would be displayed as 100.00 Credits if decimal was used. If integer was used, the credits would be displayed as 100 Credits.



Invoice Details

1948

How to import:

import { InvoiceDetails } from '@amberflo/uikit/components/organisms/InvoiceDetails'

Available Props

To see common props check ReactJS Integration | Common Props

Prop NameTypeDefault ValueDescription
dimensionsMapRecord<string, Record<string, string>>undefinedAn object containing the dimension name as key, and another object as value, containing the dimension value and the new dimension name to be replaced with.

For instance if you have a dimension called availability_zone, with a value of dim1, and you want to see it as Dimension 1, you can pass an object like this:

dimensionsMap={{ availability_zone: { dim1: "Dimension 1" } }}

This will apply to dimensions on graph, and to dimension selector on top.
invoiceDatestringundefinedDate of the invoice to show on UTC and in format l
prepaidIdstringundefinedIf you want to view a prepaid transactions invoice details, you can pass a prepaidId. An invoiceDate is also required when using a prepaidId.
hideBreakdownbooleanfalseHide invoices details breakdown
withInvoiceDetailsbooleantrueDecides to show or not the invoice details section, aka top part of invoice
withInvoiceTotalbooleantrueDecides to show or not the invoice total section, aka bottom part of invoice
customCurrencyNumberFormatstringdecimalA string value (either decimal or integer) that determines how custom currency is formatted and displayed. For example, if you had a custom currency value (called “Credits”) of 100, it would be displayed as 100.00 Credits if decimal was used. If integer was used, the credits would be displayed as 100 Credits.

Note: Invoice data displayed in this component is affected by Invoice-related options.




Invoices List

2006

How to import:

import { InvoicesList } from '@amberflo/uikit/components/organisms/InvoiceList'

Available Props

To see common props check ReactJS Integration | Common Props

Prop NameTypeDefault ValueDescription
onRowClick(invoice: Invoice) => nullundefinedData for the invoice clicked
hasExportActionbooleantrueboolean value used to determine if the "Export As" column is displayed which gives you the ability to export invoices to PDF.
paymentStatusBlockListstring[]undefinedArray of strings that list the payment statuses of invoices you do not want to display.
showPrepaidInvoicesbooleantrueWhen set to true, prepaid transactions will be included in your invoices list.
customCurrencyNumberFormatstringdecimalA string value (either decimal or integer) that determines how custom currency is formatted and displayed. For example, if you had a custom currency value (called “Credits”) of 100, it would be displayed as 100.00 Credits if decimal was used. If integer was used, the credits would be displayed as 100 Credits.

Note: Invoice data displayed in this component is affected by Invoice-related options.




Invoice PDF

202

How to import:

import { InvoicePdf } from '@amberflo/uikit/components/organisms/InvoicePdf'

Available Props

To see common props check ReactJS Integration | Common Props

NameTypeDefaultDescription
dimensionsMapRecord<string, Record<string, string>>undefinedAn object containing the dimension name as key, and another object as value, containing the dimension value and the new dimension name to be replaced with.

For instance if you have a dimension called availability_zone, with a value of dim1, and you want to see it as Dimension 1, you can pass an object like this:

dimensionsMap={{ availability_zone: { dim1: "Dimension 1" } }}

This will apply to dimensions on graph, and to dimension selector on top.
invoiceDatestringundefinedDate of the invoice to show on UTC and in format l
prepaidIdstringundefinedIf you want to export a PDF of a prepaid transaction's invoice, you can pass a prepaidId. An invoiceDate is also required when using a prepaidId.
hideBreakdownbooleanfalseHide invoices details breakdown
invoiceDataRecord<string,any>undefinedThis is an object of invoice details. This is the individual invoice data returned by this API, /customer-portal/invoice/.
planIdstringundefinedThis is a string of the plan id that is associated with the invoice you want to export.
customCurrencyNumberFormatstringdecimalA string value (either decimal or integer) that determines how custom currency is formatted and displayed. For example, if you had a custom currency value (called “Credits”) of 100, it would be displayed as 100.00 Credits if decimal was used. If integer was used, the credits would be displayed as 100 Credits.

Note: Invoice data displayed in this component is affected by Invoice-related options.




Prepaid Summary Graph

1762

How to import:

import { PrepaidSummaryGraph } from '@amberflo/uikit/PrepaidSummaryGraph'

Available Props

To see common props check ReactJS Integration | Common Props

Prop NameTypeDefault ValueDescription
customCurrencyNumberFormatstringdecimalA string value (either decimal or integer) that determines how custom currency is formatted and displayed. For example, if you had a custom currency value (called “Credits”) of 100, it would be displayed as 100.00 Credits if decimal was used. If integer was used, the credits would be displayed as 100 Credits.



Prepaid Summary Table

1954

How to import:

import { PrepaidSummaryTable } from '@amberflo/uikit/PrepaidSummaryTable'

Available Props

To see common props check ReactJS Integration | Common Props

Prop NameTypeDefault ValueDescription
customCurrencyNumberFormatstringdecimalA string value (either decimal or integer) that determines how custom currency is formatted and displayed. For example, if you had a custom currency value (called “Credits”) of 100, it would be displayed as 100.00 Credits if decimal was used. If integer was used, the credits would be displayed as 100 Credits.



Pricing Plan

561

How to import:

import { PricingPlan } from '@amberflo/uikit/PricingPlan'

Available Props

To see common props check ReactJS Integration | Common Props

Prop NameTypeDefault ValueDescription
pricestring""Text to show under the title
titlestring""Title of pricing plan
productItemsstring[][]Array un strings to show as product items
pricingPlanId*stringundefinedId of the pricing plan, to call correct endpoints
onClick(pricingPlanId: string) => voidundefinedFunction to be called when button is pressed



Pricing Plan Summary

1610

How to import:

import { PricingPlanSummary } from '@amberflo/uikit/components/organisms/PricingPlanSummary'

Available Props

To see common props check ReactJS Integration | Common Props

Prop NameTypeDefault ValueDescription
titlestring"Current Plan"Display title for component
customCurrencyNumberFormatstringdecimalA string value (either decimal or integer) that determines how custom currency is formatted and displayed. For example, if you had a custom currency value (called “Credits”) of 100, it would be displayed as 100.00 Credits if decimal was used. If integer was used, the credits would be displayed as 100 Credits.



Usage Graph

1962

How to import:

import { UsageByMeterLineGraph } from '@amberflo/uikit/components/organisms/UsageByMeterLineGraph'

Available Props

To see common props check ReactJS Integration | Common Props

Prop NameTypeDefault ValueDescription
meterstring""Meter ApiName of the meter to show on the graph
dimensionsMapRecord<string, string>undefinedAn object to map dimensions to a new name.

For instance if you have a dimension called 'Dim1' and want to show dimension 1 instead, you can pass this prop as

dimensionsMap={{ dim1: 'Dimension 1' }}

If the value set on the object for a specific dimension is null. The dimension won’t show on the dimension selector.
dimensionsFilterRecord<string,string[]>undefinedUsed to filter the usage data for specific dimension values.
The keys correspond to dimensions defined on the meter and the values are array of strings corresponding to each dimension values.
onDimensonsChange`(dimension: string) => voidundefinedFunction to be called when a dimension is selected using the dimension selector.
withDimensionsSelectorboolean | undefinedundefinedIf true, will enable the dimensions selector to be shown. In addition to this, additional props must be provided to display the selector including a list of dimensions and an onDimensionChange handler.
dimensionstringundefinedIf set, we will group by this dimension.
onMeterChange(meter: string) => voidundefinedFunction to be called when the meter is selected using the dimension selector.
withMeterSelectorboolean | undefinedundefinedIf true, will enable the meter selector to be shown
hideDeprecatedMetersbooleanundefinedIf true, deprecated meters won’t show on the graph
dimensionSelectorListstring[] | undefinedundefinedA list of available dimensions to show on the dimension selector. Only this dimensions will be shown there. To see all available dimensions, do not send this prop.
meterApiNamesstring[] | undefinedundefinedA list of meter api names to show in the meter selector dropdown.
graphViewFunctionUSAGE_GRAPHS_VIEW_FUNCTION where
USAGE_GRAPHS_VIEW_FUNCTION = "linear" | "cumulative"
linearUsed to determine the function used to calculate usage values displayed in the graph. Possible options are linear and cumulative.
allowedChartTypesCHART_TYPE[] where
CHART_TYPE = "line" | "bar" | "horizontalBar" | "stackedBar"
["line", "bar", "horizontalBar", "stackedBar"]Used to determine which chart types should be displayed. Possible chart options are line, bar, horizontalBar and stackedBar. User can send an array of options and these options are used to determine the options displayed in the dropdown. When the array has only one value, the dropdown to select chart type will not be shown.
If this prop is not sent, will use default value.
renderEmptyConfigOnErrorbooleanfalseIf true, the component will be rendered in empty state.
datePickerTypeDatePickerType where
DatePickerType = "date-range" | "month"
date-rangeUsed to determine the type of date picker. For month date picker, the months to be displayed is determined by the startDate prop.
withDimensionValueFilterbooleanundefinedIf true , an input will be displayed to filter the data for a specific dimension value. A dimension should be selected from the dimension selector to see the filter input.



Usage Table

1940

How to import:

import { UsageByMeterTable } from '@amberflo/uikit/components/organisms/UsageByMeterTable'

Available Props

To see common props check ReactJS Integration | Common Props

Prop NameTypeDefault ValueDescription
meterApiNamesstring[] | Array<{ meterApiName: string filter: Record<string, string[]> }>[]List of meter api names to show on the table, or list of objects with meter api name, and filters, such as dimension value and array of possible values
onRowClick(row: Row) => void;undefinedonRowClick is a function. If defined, the onRowClick function will be invoked when clicking on a row of the table. The onRowClick function will receive a Row type object as an argument.



Cost And Billed Usage

1902 1916 1920

How to import:

import { CostAndBilledUsage } from '@amberflo/uikit/components/organisms/CostAndBilledUsage'

Available Props

To see common props check ReactJS Integration | Common Props

Prop NameTypeDefault ValueDescription
withTablebooleanfalseUsed to determine whether the component should display a table or not.
allowedGraphsGraphType[]
where
`GraphType = "cost" | "usage" | "total-cost"
["total-cost","cost", "usage"]Used to determine which graph options should be displayed. Possible graphs options are "usage", "cost" and "total-cost". User can send an array of options and these options are used to determine the options displayed in the dropdown. When the array has only one value, the dropdown to select graph options will not be shown.
showOnlyCurrentBillingPeriodbooleanfalseUsed to determine whether to show only current billing period data or not. If it is false, we show all the billing periods for a specific customer in the dropdown. If it is true, we will not show the dropdown.
productItem
(deprecated from v1.2.45. Use productItemId instead)
stringundefinedIf set, only data corresponding to that
product item will be displayed for options "usage" and "cost". For "total-cost", we will still show all the product items data for the selected billing period.
productItemIdstringundefinedIf passed, only data corresponding to that
product item will be displayed for options "usage" and "cost". For "total-cost", we will still show all the product items data for the selected billing period.
When you send an invalid product item id or send one that is not part of the selected billing period, an error will be thrown.
customGraphOptionsRecord<string, Record<string, string>>undefinedIf defined, customGraphOptions will overwrite the default graph options for the Usage Graph.



At the moment, the customGraphOptions will replace the top level key/values. For example, if the default options are:

{ option1: { value1: "test", value2: "test" }, option2: { value1: "test" } }

and you pass customGraphOptions of:

{ option1: { value3: "test" } }

You will end up with:

{ option1: { value3: "test", }, option2: { value1: "test" } }
customCurrencyNumberFormatstringdecimalA string value (either decimal or integer) that determines how custom currency is formatted and displayed. For example, if you had a custom currency value (called “Credits”) of 100, it would be displayed as 100.00 Credits if decimal was used. If integer was used, the credits would be displayed as 100 Credits.
usageGraphViewFunctionstringcumulativeUsed to determine the function used to calculate usage values displayed in the component. Possible options are linear and cumulative.

Stripe Setup Intent

2530 2538

How to import:

import { StripeSetupIntent } from '@amberflo/uikit/components/organisms/StripeSetupIntent'

Available Props

To see common props check ReactJS Integration | Common Props

Prop NameTypeDefault ValueDescription
publishableKey*stringundefinedPublishable key you can get from stripe. You can see how here
buttonTextstring"Submit"Text to show on the button
returnUrlstringundefinedURL where to go after payment method is saved
showTermsbooleantrueIf true, you allow stripe to show terms below the payment form. In the above image, it is above the Cancel and Submit button
showEditbooleanundefinedIf true, the component will display the stripe payment form, which allows a user to enter their payment info. If false, the component will display the payment details. This prop is helpful if you want to manually control the views and not use the “Edit” button to view the payment form.
onCancel() => voidundefinedonCancel should be a function. If an onCancel function is passed, a Cancel button will appear and invoke the onCancel function when clicked.




Included Units

1152

How to import:

import { IncludedUnits } from '@amberflo/uikit/components/organisms/IncludedUnits'

Available Props

To see common props check ReactJS Integration | Common Props

Prop NameTypeDefault ValueDescription
productItemIdstringundefinedProduct Item ID related in the plan. To show how many free units has and how many consumed.
namestringundefinedName or Title to show with the numbers of the progress bar
colorstringundefinedColor for the progress bar.



How To Get Secret Key From Stripe

Call this endpoint:

📘

POST

https://app.amberflo.io/customer-portal/setup-intent

Payload:

{
     "provider": "stripe"
}

Response Body:

{
    "id": "seti_1LIBSbFZnIN3GxYXnNiuvLGe",
    "clientSecret": "seti_3MKDTdHBpKP5IzAZpNiuvLGe_secret_M0BqOmOj5LWcKZ910nPEzRCy1wFfe8M"
}

How to make a payment the default payment method

  1. After creating a new payment method, you’ll get redirected to a new URL with some query string parameters. There is one called setup_intent_client_secret.

  2. You need to retrieve the payment method from Stripe, by running:
    const { setupIntent } = await stripe.retrieveSetupIntent(setupIntentClientSecret);

  3. Submit the payment method to endpoint to set as default payment method:

📘

POST

https://app.amberflo.io/customer-portal/payment-method

Payload

{
  provider: "stripe",
  paymentMethodId: <Payment method ID from Stripe>,
}

Appendix 1: Full Code Example

import { useEffect, useState } from "react";
import {
  AmberfloProvider,
  UsageByMeterLineGraph,
  UsageByMeterTable,
} from "@amberflo/uikit";

function App() {
  const [sessionToken, setSessionToken] = useState(null);

  const getSession = async () => {
    const response = await fetch("https://app.amberflo.io/session", {
      method: "POST",
      body: JSON.stringify({
        // replace customer123 with an actual customer id
        customerId: "customer123",
      }),
      headers: {
        // YOU SHOULD NOT HAVE YOUR API KEY IN YOUR CLIENT SIDE CODE.
        // THIS IS ONLY FOR DEMONSTRATION PURPOSES TO TRY OUT A QUICK WORKING EXAMPLE.
        // Replace your_api_key with your account's API key.
        // Please see this section for more info.
        // (https://docs.amberflo.io/docs/get-session-token)
        "x-api-key": "your_api_key",
      },
    });

    const data = await response.json();

    setSessionToken(data.sessionToken);
  };

  useEffect(() => {
    getSession();
  }, []);

  if (!sessionToken) {
    // You can handle this many different ways (e.g. loaders, etc.), but we will just
    // return null until you have a token for simplicity.
    return null;
  }

  return (
    // When using UI Kit components, they must be a child of the AmberfloProvider.
    // Find out more about the AmberfloProvider here: https://docs.amberflo.io/docs/amberflo-components#getting-started
    // You will give need to provide it the sessionToken we receive from the
    // https://app.amberflo.io/session API.
    <AmberfloProvider session={sessionToken}>
      {/*
          A Usage Graph and Usage Table will be displayed 
          populated with the usage of the customer you selected a session for above.
          Your account must have meters and the selected customer must have usage
          to be able to display any data within the table and graph.
      */}
      <div style={{ display: "flex", flexDirection: "column", gap: "2rem" }}>
        <UsageByMeterLineGraph withTitle withMeterSelector withContainer />
        <UsageByMeterTable withTitle withContainer />
      </div>
    </AmberfloProvider>
  );
}

export default App;