Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Custom expressions for billing metrics #1825

Merged
merged 29 commits into from
Nov 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
14af593
chore(translations): add required translations
stephenlago99 Oct 24, 2024
bbec46f
feat(JsonEditor): add support for different modes
stephenlago99 Oct 24, 2024
380e1f6
feat(Drawer): enable passing a classname to StickyBottomBar
stephenlago99 Oct 24, 2024
8bd4e74
feat(billableMetrics): create Custom Expression drawer
stephenlago99 Oct 24, 2024
0fe21f5
feat(CreateBillableMetric): create new section - Aggregate on
stephenlago99 Oct 24, 2024
57075fa
feat(CreateBillableMetric): integrate Custom Expression drawer
stephenlago99 Oct 24, 2024
05c0a6b
chore(translations): update translations
stephenlago99 Oct 25, 2024
a1e6b7c
chore(graphql): generate types
stephenlago99 Oct 25, 2024
0e87a3c
refactor(CustomExpressionDrawer): improve closeDrawer, fix timestamp …
stephenlago99 Oct 25, 2024
c5f06b7
refactor(CreateBillableMetric): embed aggregateOn in formik, remove u…
stephenlago99 Oct 25, 2024
47b20ac
chore(translations): update translations
stephenlago99 Oct 25, 2024
09dc585
feat(JsonEditor): add support for custom validations / rendering help…
stephenlago99 Oct 25, 2024
e913d4d
feat(CustomExpressionDrawer): pass custom validation to editor, bette…
stephenlago99 Oct 25, 2024
ace119d
fix(CreateBillableMetric): empty expression for unique field / fix ta…
stephenlago99 Oct 28, 2024
3b152a7
feat(webpack): enable async wasm
stephenlago99 Oct 31, 2024
27fb3d8
feat(lago-expression): embed lago-expression
stephenlago99 Oct 31, 2024
341200a
feat(billableMetrics): create utils for parsing and evaluating
stephenlago99 Oct 31, 2024
6bffb3f
refactor(JsonEditor): remove async
stephenlago99 Oct 31, 2024
f6bfd0c
refactor(CustomExpressionDrawer): use utils file / improve error hand…
stephenlago99 Oct 31, 2024
f1fb06b
fix(linting): ignore lago-expression files
stephenlago99 Oct 31, 2024
c1ce6cd
fix(translations): fix translations
stephenlago99 Oct 31, 2024
8e6b82f
fix(CustomExpressionDrawer): fix translation
stephenlago99 Nov 2, 2024
18a9204
refactor(CustomExpressionDrawer): use event instead of events
stephenlago99 Nov 2, 2024
98928f2
refactor(Chip): remove beta / variant, className props
stephenlago99 Nov 4, 2024
551bf4b
refactor(CustomExpression): use Chip instead of Typography
stephenlago99 Nov 4, 2024
a175b0b
feat(JsonEditor): add readOnlyWithoutStyles prop
stephenlago99 Nov 4, 2024
622158d
fix(CreateBillableMetric): prevent editing after tabbing
stephenlago99 Nov 4, 2024
1b31280
feat(lago-expression): update to latest version
stephenlago99 Nov 5, 2024
955ad1f
refactor(billableMetricUtils): pass bigint to binary
stephenlago99 Nov 5, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .eslintignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@ dist
.github
globals.d.ts
generated
cypress/*
cypress/*
src/lago-expression/*
3 changes: 2 additions & 1 deletion .prettierignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,5 @@ generated
globals.d.ts
ci
cypress/downloads
cypress/screenshots
cypress/screenshots
/src/lago-expression/*
262 changes: 262 additions & 0 deletions src/components/billableMetrics/CustomExpressionDrawer.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,262 @@
import { Typography } from '@mui/material'
import { useFormik } from 'formik'
import { forwardRef, useImperativeHandle, useRef, useState } from 'react'
import { mixed, object, string } from 'yup'

import {
isValidJSON,
wrappedEvaluateExpression,
wrappedParseExpression,
} from '~/components/billableMetrics/utils'
import { Button, Chip, Drawer, DrawerRef, Icon } from '~/components/designSystem'
import { JsonEditorField } from '~/components/form/JsonEditor'
import { useInternationalization } from '~/hooks/core/useInternationalization'
import { Divider } from '~/styles/mainObjectsForm'

type CustomExpressionDrawerState = {
expression?: string | null
billableMetricCode?: string | null
isEditable?: boolean
}

export interface CustomExpressionDrawerRef extends DrawerRef {
openDrawer: (data?: CustomExpressionDrawerState) => unknown
closeDrawer: () => unknown
}

type CustomExpressionDrawerProps = {
onSave: (expression: string) => void
}

export type EventPayload = {
event: {
transaction_id: string
external_subscription_id: string
code: string
timestamp: number
properties: {
[key: string]: string
}
}
}

type CustomExpressionInput = {
expression: string
eventPayload: EventPayload
}

export type ValidationResult = {
result?: string | null
error?: string | null
}

const CUSTOM_EXPRESSION_EXAMPLES = [
'event.properties.tokens * event.properties.replicas',
'concat(event.properties.user_id, ‘-‘ , event.properties.app_id)',
'(event.properties.ended_at - event.timestamp) / 3600',
]

const TIMESTAMP = new Date().getTime()

export const CustomExpressionDrawer = forwardRef<
CustomExpressionDrawerRef,
CustomExpressionDrawerProps
>(({ onSave }, ref) => {
const { translate } = useInternationalization()

const drawerRef = useRef<DrawerRef>(null)
const [localData, setLocalData] = useState<CustomExpressionDrawerState>()
const [validationResult, setValidationResult] = useState<ValidationResult>()

const closeDrawer = () => {
formikProps.resetForm()
setValidationResult({})
drawerRef.current?.closeDrawer()
}

const formikProps = useFormik<CustomExpressionInput>({
initialValues: {
expression: localData?.expression || '',
eventPayload: {
event: {
transaction_id: 'trx_id_123456789',
external_subscription_id: 'sub_id_123456789',
code: localData?.billableMetricCode || '__BILLABLE_METRIC_CODE__',
timestamp: TIMESTAMP,
properties: {
property_name: '__YOUR__VALUE__',
},
},
},
},
validationSchema: object().shape({
expression: string().test((value) => wrappedParseExpression(value)),
eventPayload: mixed().test((value) => isValidJSON(value)),
}),
validateOnMount: true,
enableReinitialize: true,
onSubmit: (values) => {
if (values?.expression) {
onSave(values.expression)

closeDrawer()
}
},
})

const onValidateExpression = async () => {
const result = wrappedEvaluateExpression(
formikProps.values.expression,
formikProps.values.eventPayload,
)

setValidationResult(result)
}

useImperativeHandle(ref, () => ({
openDrawer: (data) => {
setLocalData(data)
drawerRef.current?.openDrawer()
},
closeDrawer: () => drawerRef.current?.closeDrawer(),
}))

const hasErrors = !!(formikProps.errors.expression || formikProps.errors.eventPayload)

return (
<Drawer
className="px-12 pt-12"
ref={drawerRef}
title={translate('text_1729771640162lug0w6ztlyr')}
onClose={closeDrawer}
stickyBottomBarClassName="z-10"
stickyBottomBar={() => {
return (
<div className="flex justify-end gap-3">
<Button
size="large"
variant="secondary"
onClick={onValidateExpression}
disabled={hasErrors}
>
{translate('text_1729773655417m826qhyr465')}
</Button>

{localData?.isEditable ? (
<Button
size="large"
onClick={formikProps.submitForm}
disabled={!validationResult?.result}
>
{translate('text_17297736554176g6clgo34du')}
</Button>
) : (
<Button size="large" onClick={() => drawerRef?.current?.closeDrawer()}>
{translate('text_62f50d26c989ab03196884ae')}
</Button>
)}
</div>
)
}}
>
<div>
<div className="mb-12">
<Typography className="mb-1 text-2xl font-semibold text-grey-700">
{translate('text_1729771640162lug0w6ztlyr')}
</Typography>

<Typography className="text-base font-normal text-grey-600">
{translate('text_1729771640162z7ndqn1ju9h')}
</Typography>
</div>

<Typography className="mb-6 text-lg font-semibold text-grey-700">
{translate('text_1729771640162c0o1estqusi')}
</Typography>

<JsonEditorField
name="expression"
disabled={!localData?.isEditable}
label={translate('text_17297736554164pkbpqi0ke8')}
editorMode="text"
customInvalidError={translate('text_1729864793151rrlucly2t6d')}
showHelperOnError={true}
formikProps={formikProps}
placeholder={translate('text_1729771640162kaf49b93e20') + '\n'}
helperText={
<div className="mt-1">
<Typography className="text-sm font-normal text-grey-600">
{translate('text_1729773655417n5w5fu02lbm')}
</Typography>

<div className="mt-1 flex flex-col items-start gap-1">
{CUSTOM_EXPRESSION_EXAMPLES.map((example, index) => (
<Chip
key={`ce-drawer-${index}`}
className="!px-2 !py-0.5"
size="small"
variant="captionCode"
color="grey600"
label={example}
/>
))}
</div>
</div>
}
/>

<div className="my-12">
<Divider />
</div>

<div className="mb-6">
<Typography className="mb-2 text-lg font-semibold text-grey-700">
{translate('text_1729773655417vo5dm6vqzpu')}
</Typography>
<Typography className="text-sm font-normal text-grey-600">
{translate('text_1729773655417khuj828ti9j')}
</Typography>
</div>

<JsonEditorField
name="eventPayload"
height="300px"
label={translate('text_1729773655417k0y7nxt5c5j')}
formikProps={formikProps}
customInvalidError={translate('text_6638a3538de76801ac2f451b')}
placeholder={translate('text_17297753616921jc1iyf6mke')}
/>

<div className="mt-6">
<Typography className="mb-1 text-sm font-normal text-grey-600">
{translate('text_1729773655417b4y4j7oatnq')}
</Typography>

{validationResult?.error && (
<div className="flex items-center gap-2">
<Icon name="warning-filled" color="warning" />

<Typography className="text-base font-normal text-grey-600">
{validationResult?.error}
</Typography>
</div>
)}

{!validationResult?.result && !validationResult?.error && (
<Typography className="text-base font-normal text-grey-500">
{translate('text_17297736554178ifm0gd8093')}
</Typography>
)}

{validationResult?.result && !validationResult?.error && (
<Typography className="text-base font-normal text-grey-700">
{validationResult?.result}
</Typography>
)}
</div>
</div>
</Drawer>
)
})

CustomExpressionDrawer.displayName = 'CustomExpressionDrawer'
65 changes: 65 additions & 0 deletions src/components/billableMetrics/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import { EventPayload, ValidationResult } from '~/components/billableMetrics/CustomExpressionDrawer'

import { evaluateExpression, parseExpression } from '../../lago-expression/expression_js'

export const wrappedEvaluateExpression = (
expression: string,
payload: EventPayload,
): ValidationResult => {
try {
let eventPayload = payload

if (typeof payload === 'string') {
eventPayload = JSON.parse(payload)
}

const res = evaluateExpression(
parseExpression(expression),
eventPayload.event.code,
BigInt(eventPayload.event.timestamp),
eventPayload.event.properties,
)

return {
result: res,
}
} catch (e) {
return {
error: e as string,
}
}
}

export const wrappedParseExpression = (expression?: string | null): boolean => {
if (!expression) {
return false
}

try {
parseExpression(expression)

return true
} catch (e) {
return false
}
}

export const isValidJSON = (json?: unknown) => {
if (!json) {
return false
}

try {
if (typeof json === 'object') {
return true
}

if (typeof json === 'string') {
JSON.parse(json)
}

return true
} catch (e) {
return false
}
}
Loading
Loading