Merge branch 'master' of github.com:Budibase/budibase into form-builder

This commit is contained in:
Andrew Kingston 2021-01-14 09:10:41 +00:00
commit cdfcff4bbb
15 changed files with 428 additions and 40 deletions

View File

@ -42,6 +42,7 @@ services:
environment: environment:
MINIO_ACCESS_KEY: ${MINIO_ACCESS_KEY} MINIO_ACCESS_KEY: ${MINIO_ACCESS_KEY}
MINIO_SECRET_KEY: ${MINIO_SECRET_KEY} MINIO_SECRET_KEY: ${MINIO_SECRET_KEY}
MINIO_BROWSER: "off"
command: server /data command: server /data
healthcheck: healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:9000/minio/health/live"] test: ["CMD", "curl", "-f", "http://localhost:9000/minio/health/live"]

View File

@ -56,4 +56,13 @@ export default class Automation {
steps.splice(stepIdx, 1) steps.splice(stepIdx, 1)
this.automation.definition.steps = steps this.automation.definition.steps = steps
} }
constructBlock(type, stepId, blockDefinition) {
return {
...blockDefinition,
inputs: blockDefinition.inputs || {},
stepId,
type,
}
}
} }

View File

@ -2,6 +2,7 @@ import { writable } from "svelte/store"
import api from "../../api" import api from "../../api"
import Automation from "./Automation" import Automation from "./Automation"
import { cloneDeep } from "lodash/fp" import { cloneDeep } from "lodash/fp"
import analytics from "analytics"
const automationActions = store => ({ const automationActions = store => ({
fetch: async () => { fetch: async () => {
@ -93,6 +94,9 @@ const automationActions = store => ({
state.selectedBlock = newBlock state.selectedBlock = newBlock
return state return state
}) })
analytics.captureEvent("Added Automation Block", {
name: block.name,
})
}, },
deleteAutomationBlock: block => { deleteAutomationBlock: block => {
store.update(state => { store.update(state => {

View File

@ -49,16 +49,9 @@
} }
function addBlockToAutomation(stepId, blockDefinition) { function addBlockToAutomation(stepId, blockDefinition) {
const newBlock = { const newBlock = $automationStore.selectedAutomation.constructBlock(
...blockDefinition, selectedTab, stepId, blockDefinition)
inputs: blockDefinition.inputs || {},
stepId,
type: selectedTab,
}
automationStore.actions.addBlockToAutomation(newBlock) automationStore.actions.addBlockToAutomation(newBlock)
analytics.captureEvent("Added Automation Block", {
name: blockDefinition.name,
})
closePopover() closePopover()
if (stepId === "WEBHOOK") { if (stepId === "WEBHOOK") {
webhookModal.show() webhookModal.show()

View File

@ -1,6 +1,7 @@
<script> <script>
import TableSelector from "./TableSelector.svelte" import TableSelector from "./TableSelector.svelte"
import RowSelector from "./RowSelector.svelte" import RowSelector from "./RowSelector.svelte"
import SchemaSetup from "./SchemaSetup.svelte"
import { Button, Input, Select, Label } from "@budibase/bbui" import { Button, Input, Select, Label } from "@budibase/bbui"
import { automationStore } from "builderStore" import { automationStore } from "builderStore"
import WebhookDisplay from "../Shared/WebhookDisplay.svelte" import WebhookDisplay from "../Shared/WebhookDisplay.svelte"
@ -70,6 +71,8 @@
<RowSelector bind:value={block.inputs[key]} {bindings} /> <RowSelector bind:value={block.inputs[key]} {bindings} />
{:else if value.customType === 'webhookUrl'} {:else if value.customType === 'webhookUrl'}
<WebhookDisplay value={block.inputs[key]} /> <WebhookDisplay value={block.inputs[key]} />
{:else if value.customType === 'triggerSchema'}
<SchemaSetup bind:value={block.inputs[key]} />
{:else if value.type === 'string' || value.type === 'number'} {:else if value.type === 'string' || value.type === 'number'}
<BindableInput <BindableInput
type="string" type="string"

View File

@ -0,0 +1,133 @@
<script>
import { Input, Select } from "@budibase/bbui"
export let value = {}
$: fieldsArray = Object.entries(value).map(([name, type]) => ({
name,
type,
}))
function addField() {
const newValue = { ...value }
newValue[""] = "string"
value = newValue
}
function removeField(name) {
const newValues = { ...value }
delete newValues[name]
value = newValues
}
const fieldNameChanged = originalName => e => {
// reconstruct using fieldsArray, so field order is preserved
let entries = [...fieldsArray]
const newName = e.target.value
if (newName) {
entries.find(f => f.name === originalName).name = newName
} else {
entries = entries.filter(f => f.name !== originalName)
}
value = entries.reduce((newVals, current) => {
newVals[current.name] = current.type
return newVals
}, {})
}
</script>
<div class="root">
<div class="add-field">
<i class="ri-add-line" on:click={addField} />
</div>
<div class="spacer" />
{#each fieldsArray as field}
<div class="field">
<Input
value={field.name}
secondary
on:change={fieldNameChanged(field.name)} />
<Select
secondary
extraThin
value={field.type}
on:blur={e => (value[field.name] = e.target.value)}>
<option>string</option>
<option>number</option>
<option>boolean</option>
<option>datetime</option>
</Select>
<i class="remove-field ri-delete-bin-line"
on:click={() => removeField(field.name)} />
</div>
{/each}
</div>
<style>
.root {
position: relative;
max-width: 100%;
overflow-x: auto;
/* so we can show the "+" button beside the "fields" label*/
top: -26px;
}
.spacer {
height: var(--spacing-s);
}
.field {
max-width: 100%;
background-color: var(--grey-2);
margin-bottom: var(--spacing-m);
border-style: solid;
border-width: 1px;
border-color: var(--grey-4);
display: grid;
/*grid-template-rows: auto auto;
grid-template-columns: auto;*/
position: relative;
overflow: hidden;
}
.field :global(select) {
padding: var(--spacing-xs) 2rem var(--spacing-m) var(--spacing-s) !important;
font-size: var(--font-size-xs);
color: var(--grey-7);
}
.field :global(.pointer) {
padding-bottom: var(--spacing-m) !important;
color: var(--grey-2);
}
.field :global(input) {
padding: var(--spacing-m) var(--spacing-xl) var(--spacing-xs) var(--spacing-m);
font-size: var(--font-size-s);
font-weight: bold;
}
.remove-field {
cursor: pointer;
color: var(--grey-6);
position: absolute;
top: var(--spacing-m);
right: 3px;
}
.remove-field:hover {
color: var(--black);
}
.add-field {
text-align: right;
}
.add-field > i {
cursor: pointer;
}
</style>

View File

@ -0,0 +1,131 @@
<script>
import { Select, Label, Input } from "@budibase/bbui"
import { automationStore } from "builderStore"
import SaveFields from "./SaveFields.svelte"
export let parameters = {}
let newOrExisting = parameters.automationId ? "existing" : "new"
$: automations = $automationStore.automations
.filter(a => a.definition.trigger?.stepId === "APP")
.map(automation => {
const schema = Object.entries(
automation.definition.trigger.inputs.fields
).map(([name, type]) => ({ name, type }))
return {
name: automation.name,
_id: automation._id,
schema,
}
})
$: hasAutomations = automations && automations.length > 0
$: selectedAutomation =
parameters &&
parameters.automationId &&
automations.find(a => a._id === parameters.automationId)
const onFieldsChanged = e => {
parameters.fields = e.detail
}
const setNew = () => {
newOrExisting = "new"
parameters.automationId = undefined
}
const setExisting = () => {
newOrExisting = "existing"
parameters.newAutomationName = ""
}
</script>
<div class="root">
<div class="radio-container" on:click={setNew}>
<input
type="radio"
value="new"
bind:group={newOrExisting}
disabled={!hasAutomations}>
<Label disabled={!hasAutomations}>Create a new automation </Label>
</div>
<div class="radio-container" on:click={setExisting}>
<input
type="radio"
value="existing"
bind:group={newOrExisting}
disabled={!hasAutomations}>
<Label disabled={!hasAutomations}>Use an existing automation </Label>
</div>
<Label size="m" color="dark">Automation</Label>
{#if newOrExisting=== "existing"}
<Select secondary bind:value={parameters.automationId} placeholder="Choose automation">
<option value="" />
{#each automations as automation}
<option value={automation._id}>{automation.name}</option>
{/each}
</Select>
{:else}
<Input secondary bind:value={parameters.newAutomationName} placeholder="Enter automation name" />
{/if}
<SaveFields
parameterFields={parameters.fields}
schemaFields={newOrExisting === "existing" && selectedAutomation && selectedAutomation.schema}
fieldLabel="Field"
on:fieldschanged={onFieldsChanged} />
</div>
<style>
.root {
display: grid;
column-gap: var(--spacing-s);
row-gap: var(--spacing-s);
grid-template-columns: auto 1fr auto 1fr auto;
align-items: baseline;
}
.root :global(> div:nth-child(4)) {
grid-column: 2 / span 4;
}
.radio-container {
display: grid;
grid-template-columns: auto 1fr;
}
.radio-container:nth-child(1) {
grid-column: 1 / span 2;
}
.radio-container:nth-child(2) {
grid-column: 3 / span 3;
}
.radio-container :global(> label) {
margin-left: var(--spacing-m);
}
.radio-container > input {
margin-bottom: var(--spacing-s);
}
.radio-container > input:focus {
outline: none;
}
</style>

View File

@ -3,6 +3,7 @@
import { AddIcon, ArrowDownIcon } from "components/common/Icons/" import { AddIcon, ArrowDownIcon } from "components/common/Icons/"
import actionTypes from "./actions" import actionTypes from "./actions"
import { createEventDispatcher } from "svelte" import { createEventDispatcher } from "svelte"
import { automationStore } from "builderStore"
const dispatch = createEventDispatcher() const dispatch = createEventDispatcher()
const eventTypeKey = "##eventHandlerType" const eventTypeKey = "##eventHandlerType"
@ -13,17 +14,11 @@
let addActionDropdown let addActionDropdown
let selectedAction let selectedAction
let draftEventHandler = { parameters: [] }
$: actions = event || [] $: actions = event || []
$: selectedActionComponent = $: selectedActionComponent =
selectedAction && selectedAction &&
actionTypes.find(t => t.name === selectedAction[eventTypeKey]).component actionTypes.find(t => t.name === selectedAction[eventTypeKey]).component
const updateEventHandler = (updatedHandler, index) => {
actions[index] = updatedHandler
}
const deleteAction = index => { const deleteAction = index => {
actions.splice(index, 1) actions.splice(index, 1)
actions = actions actions = actions
@ -44,8 +39,43 @@
selectedAction = action selectedAction = action
} }
const saveEventData = () => { const saveEventData = async () => {
dispatch("change", actions) // e.g. The Trigger Automation action exposes beforeSave, so it can
// create any automations it needs to
for (let action of actions) {
if (action[eventTypeKey] === "Trigger Automation") {
await createAutomation(action.parameters)
}
}
dispatch("change", actions)
}
// called by the parent modal when actions are saved
const createAutomation = async parameters => {
if (parameters.automationId || !parameters.newAutomationName) return
await automationStore.actions.create({name: parameters.newAutomationName})
const appActionDefinition = $automationStore.blockDefinitions.TRIGGER.APP
const newBlock = $automationStore.selectedAutomation.constructBlock(
"TRIGGER", "APP", appActionDefinition)
newBlock.inputs = {
fields: Object.entries(parameters.fields).reduce((fields, [key, value]) => {
fields[key] = value.type
return fields
}, {})
}
automationStore.actions.addBlockToAutomation(newBlock)
await automationStore.actions.save(
$automationStore.selectedAutomation)
parameters.automationId = $automationStore.selectedAutomation.automation._id
delete parameters.newAutomationName
} }
</script> </script>

View File

@ -1,6 +1,6 @@
<script> <script>
// accepts an array of field names, and outputs an object of { FieldName: value } // accepts an array of field names, and outputs an object of { FieldName: value }
import { DataList, Label, TextButton, Spacer, Select } from "@budibase/bbui" import { DataList, Label, TextButton, Spacer, Select, Input } from "@budibase/bbui"
import { store, backendUiStore, currentAsset } from "builderStore" import { store, backendUiStore, currentAsset } from "builderStore"
import fetchBindableProperties from "builderStore/fetchBindableProperties" import fetchBindableProperties from "builderStore/fetchBindableProperties"
import { CloseCircleIcon, AddIcon } from "components/common/Icons" import { CloseCircleIcon, AddIcon } from "components/common/Icons"
@ -14,6 +14,7 @@
export let parameterFields export let parameterFields
export let schemaFields export let schemaFields
export let fieldLabel="Column"
const emptyField = () => ({ name: "", value: "" }) const emptyField = () => ({ name: "", value: "" })
@ -59,7 +60,7 @@
// value and type is needed by the client, so it can parse // value and type is needed by the client, so it can parse
// a string into a correct type // a string into a correct type
newParameterFields[field.name] = { newParameterFields[field.name] = {
type: schemaFields.find(f => f.name === field.name).type, type: schemaFields ? schemaFields.find(f => f.name === field.name).type : "string",
value: readableToRuntimeBinding(bindableProperties, field.value), value: readableToRuntimeBinding(bindableProperties, field.value),
} }
} }
@ -73,13 +74,17 @@
{#if fields} {#if fields}
{#each fields as field} {#each fields as field}
<Label size="m" color="dark">Column</Label> <Label size="m" color="dark">{fieldLabel}</Label>
<Select secondary bind:value={field.name} on:blur={rebuildParameters}> {#if schemaFields}
<option value="" /> <Select secondary bind:value={field.name} on:blur={rebuildParameters}>
{#each schemaFields as schemaField} <option value="" />
<option value={schemaField.name}>{schemaField.name}</option> {#each schemaFields as schemaField}
{/each} <option value={schemaField.name}>{schemaField.name}</option>
</Select> {/each}
</Select>
{:else}
<Input secondary bind:value={field.name} on:blur={rebuildParameters}/>
{/if}
<Label size="m" color="dark">Value</Label> <Label size="m" color="dark">Value</Label>
<DataList secondary bind:value={field.value} on:blur={rebuildParameters}> <DataList secondary bind:value={field.value} on:blur={rebuildParameters}>
<option value="" /> <option value="" />
@ -100,7 +105,7 @@
<Spacer small /> <Spacer small />
<TextButton text small blue on:click={addField}> <TextButton text small blue on:click={addField}>
Add Field Add {fieldLabel}
<div style="height: 20px; width: 20px;"> <div style="height: 20px; width: 20px;">
<AddIcon /> <AddIcon />
</div> </div>

View File

@ -1,6 +1,7 @@
import NavigateTo from "./NavigateTo.svelte" import NavigateTo from "./NavigateTo.svelte"
import SaveRow from "./SaveRow.svelte" import SaveRow from "./SaveRow.svelte"
import DeleteRow from "./DeleteRow.svelte" import DeleteRow from "./DeleteRow.svelte"
import TriggerAutomation from "./TriggerAutomation.svelte"
// defines what actions are available, when adding a new one // defines what actions are available, when adding a new one
// the component is the setup panel for the action // the component is the setup panel for the action
@ -20,4 +21,8 @@ export default [
name: "Navigate To", name: "Navigate To",
component: NavigateTo, component: NavigateTo,
}, },
{
name: "Trigger Automation",
component: TriggerAutomation,
},
] ]

View File

@ -0,0 +1,10 @@
import API from "./api"
/**
* Executes an automation. Must have "App Action" trigger.
*/
export const triggerAutomation = async (automationId, fields) => {
return await API.post({
url: `/api/automations/${automationId}/trigger`,
body: { fields },
})
}

View File

@ -7,3 +7,4 @@ export * from "./views"
export * from "./relationships" export * from "./relationships"
export * from "./routes" export * from "./routes"
export * from "./app" export * from "./app"
export * from "./automations"

View File

@ -1,6 +1,6 @@
import { enrichDataBinding } from "./enrichDataBinding" import { enrichDataBinding } from "./enrichDataBinding"
import { routeStore } from "../store" import { routeStore } from "../store"
import { saveRow, deleteRow } from "../api" import { saveRow, deleteRow, triggerAutomation } from "../api"
const saveRowHandler = async (action, context) => { const saveRowHandler = async (action, context) => {
let draft = context[`${action.parameters.contextPath}_draft`] let draft = context[`${action.parameters.contextPath}_draft`]
@ -21,6 +21,17 @@ const deleteRowHandler = async (action, context) => {
}) })
} }
const triggerAutomationHandler = async (action, context) => {
const params = {}
for (let field in action.parameters.fields) {
params[field] = enrichDataBinding(
action.parameters.fields[field].value,
context
)
}
await triggerAutomation(action.parameters.automationId, params)
}
const navigationHandler = action => { const navigationHandler = action => {
routeStore.actions.navigate(action.parameters.url) routeStore.actions.navigate(action.parameters.url)
} }
@ -29,6 +40,7 @@ const handlerMap = {
["Save Row"]: saveRowHandler, ["Save Row"]: saveRowHandler,
["Delete Row"]: deleteRowHandler, ["Delete Row"]: deleteRowHandler,
["Navigate To"]: navigationHandler, ["Navigate To"]: navigationHandler,
["Trigger Automation"]: triggerAutomationHandler,
} }
/** /**

View File

@ -2,6 +2,7 @@ const CouchDB = require("../db")
const emitter = require("../events/index") const emitter = require("../events/index")
const InMemoryQueue = require("../utilities/queue/inMemoryQueue") const InMemoryQueue = require("../utilities/queue/inMemoryQueue")
const { getAutomationParams } = require("../db/utils") const { getAutomationParams } = require("../db/utils")
const { coerceValue } = require("../utilities")
let automationQueue = new InMemoryQueue("automationQueue") let automationQueue = new InMemoryQueue("automationQueue")
@ -119,6 +120,37 @@ const BUILTIN_DEFINITIONS = {
}, },
type: "TRIGGER", type: "TRIGGER",
}, },
APP: {
name: "App Action",
event: "app:trigger",
icon: "ri-window-fill",
tagline: "Automation fired from the frontend",
description: "Trigger an automation from an action inside your app",
stepId: "APP",
inputs: {},
schema: {
inputs: {
properties: {
fields: {
type: "object",
customType: "triggerSchema",
title: "Fields",
},
},
required: [],
},
outputs: {
properties: {
fields: {
type: "object",
description: "Fields submitted from the app frontend",
},
},
required: ["fields"],
},
},
type: "TRIGGER",
},
} }
async function queueRelevantRowAutomations(event, eventType) { async function queueRelevantRowAutomations(event, eventType) {
@ -200,12 +232,19 @@ async function fillRowOutput(automation, params) {
module.exports.externalTrigger = async function(automation, params) { module.exports.externalTrigger = async function(automation, params) {
// TODO: replace this with allowing user in builder to input values in future // TODO: replace this with allowing user in builder to input values in future
if ( if (automation.definition != null && automation.definition.trigger != null) {
automation.definition != null && if (automation.definition.trigger.inputs.tableId != null) {
automation.definition.trigger != null && params = await fillRowOutput(automation, params)
automation.definition.trigger.inputs.tableId != null }
) { if (automation.definition.trigger.stepId === "APP") {
params = await fillRowOutput(automation, params) // values are likely to be submitted as strings, so we shall convert to correct type
const coercedFields = {}
const fields = automation.definition.trigger.inputs.fields
for (let key in fields) {
coercedFields[key] = coerceValue(params.fields[key], fields[key])
}
params.fields = coercedFields
}
} }
automationQueue.add({ automation, event: params }) automationQueue.add({ automation, event: params })

View File

@ -144,6 +144,23 @@ exports.walkDir = (dirPath, callback) => {
} }
} }
/**
* This will coerce a value to the correct types based on the type transform map
* @param {object} row The value to coerce
* @param {object} type The type fo coerce to
* @returns {object} The coerced value
*/
exports.coerceValue = (value, type) => {
// eslint-disable-next-line no-prototype-builtins
if (TYPE_TRANSFORM_MAP[type].hasOwnProperty(value)) {
return TYPE_TRANSFORM_MAP[type][value]
} else if (TYPE_TRANSFORM_MAP[type].parse) {
return TYPE_TRANSFORM_MAP[type].parse(value)
}
return value
}
/** /**
* This will coerce the values in a row to the correct types based on the type transform map and the * This will coerce the values in a row to the correct types based on the type transform map and the
* table schema. * table schema.
@ -159,12 +176,7 @@ exports.coerceRowValues = (row, table) => {
const field = table.schema[key] const field = table.schema[key]
if (!field) continue if (!field) continue
// eslint-disable-next-line no-prototype-builtins clonedRow[key] = exports.coerceValue(value, field.type)
if (TYPE_TRANSFORM_MAP[field.type].hasOwnProperty(value)) {
clonedRow[key] = TYPE_TRANSFORM_MAP[field.type][value]
} else if (TYPE_TRANSFORM_MAP[field.type].parse) {
clonedRow[key] = TYPE_TRANSFORM_MAP[field.type].parse(value)
}
} }
return clonedRow return clonedRow
} }