feat: add graph element (port from dashboard) (#5575)

This commit is contained in:
Jérémie Pardou authored and GitHub committed 2026-09-21 15:18:42 +00:00
1 parent 22a9046f1f
commit 13a0f435b5
46 files changed
+2230 -641

No files matched your search

+1
View File
@@ -106,6 +106,7 @@ backend/media/
.env.local
**/.env.local
.env.docker-dev
mise.local.toml
web-frontend/plugins/
backend/plugins/
@@ -606,12 +606,7 @@ class LocalBaserowTableServiceType(LocalBaserowServiceType):
if service.table_id is None:
return None
properties = global_cache.get(
f"table_{service.table_id}__service_schema",
default=lambda: self._get_table_properties(service),
invalidate_key=f"table_{service.table_id}__service_invalidate_key",
timeout=SCHEMA_CACHE_TTL,
)
properties = self.get_table_properties(service)
# When a schema is being generated, we will exclude properties that the
# Application creator did not actively configure. A configured property
@@ -627,6 +622,32 @@ class LocalBaserowTableServiceType(LocalBaserowServiceType):
return self.get_schema_for_return_type(service, properties)
def get_table_properties(
self, service: ServiceSubClass
) -> Optional[Dict[str, Any]]:
"""
Returns the properties of the service's table, cached globally per table.
Building the properties serializes every field of the table, which costs a
query per field, so anything that needs them more than once per request
must go through this method rather than `_get_table_properties`. The cache
entry is invalidated through `table_{table_id}__service_invalidate_key`
whenever the table or its fields change.
:param service: A `LocalBaserowTableService` subclass.
:return: A schema dictionary, or None if no `Table` has been applied.
"""
if service.table_id is None:
return None
return global_cache.get(
f"table_{service.table_id}__service_schema",
default=lambda: self._get_table_properties(service),
invalidate_key=f"table_{service.table_id}__service_invalidate_key",
timeout=SCHEMA_CACHE_TTL,
)
def _get_table_properties(
self, service: ServiceSubClass
) -> Optional[Dict[str, Any]]:
@@ -3090,12 +3111,7 @@ class LocalBaserowFieldsUpdatedServiceType(LocalBaserowRowsSignalServiceType):
# Reuse the cached, fully-built table properties and then narrow them down
# to just the row `id` and the watched fields.
properties = global_cache.get(
f"table_{service.table_id}__service_schema",
default=lambda: self._get_table_properties(service),
invalidate_key=f"table_{service.table_id}__service_invalidate_key",
timeout=SCHEMA_CACHE_TTL,
)
properties = self.get_table_properties(service)
watched_field_keys = {"id", *(f"field_{field_id}" for field_id in field_ids)}
properties = {
@@ -1144,6 +1144,11 @@ def test_collection_element_type_publicly_searchable_sortable_filterable(
"is_publicly_searchable": True,
"is_publicly_filterable": True,
},
"graph": {
"is_publicly_sortable": False,
"is_publicly_searchable": False,
"is_publicly_filterable": False,
},
"table": {
"is_publicly_sortable": True,
"is_publicly_searchable": True,
@@ -286,10 +286,12 @@ class BaserowEnterpriseConfig(AppConfig):
from baserow_enterprise.builder.elements.element_types import (
AuthFormElementType,
FileInputElementType,
GraphElementType,
)
element_type_registry.register(AuthFormElementType())
element_type_registry.register(FileInputElementType())
element_type_registry.register(GraphElementType())
from baserow.contrib.database.data_sync.registries import (
two_way_sync_strategy_type_registry,
@@ -1,4 +1,5 @@
import mimetypes
import uuid
from typing import Any, Dict, List, Optional
from django.utils.translation import gettext_lazy as _
@@ -6,12 +7,15 @@ from django.utils.translation import gettext_lazy as _
from rest_framework import serializers
from baserow.api.exceptions import RequestBodyValidationException
from baserow.contrib.builder.constants import COLOR_FIELD_MAX_LENGTH
from baserow.contrib.builder.elements.element_types import InputElementType
from baserow.contrib.builder.elements.models import Element
from baserow.contrib.builder.elements.registries import ElementType
from baserow.contrib.builder.pages.handler import PageHandler
from baserow.contrib.builder.types import ElementDict
from baserow.contrib.builder.workflow_actions.models import EventTypes
from baserow.core.formula.field import BASEROW_FORMULA_VERSION_INITIAL
from baserow.core.formula.serializers import FormulaSerializerField
from baserow.core.formula.types import (
BASEROW_FORMULA_MODE_SIMPLE,
BaserowFormula,
@@ -19,11 +23,42 @@ from baserow.core.formula.types import (
)
from baserow.core.services.dispatch_context import DispatchContext
from baserow.core.user_sources.handler import UserSourceHandler
from baserow_enterprise.builder.elements.models import AuthFormElement, FileInputElement
from baserow_enterprise.features import BUILDER_FILE_INPUT
from baserow_enterprise.builder.elements.models import (
AuthFormElement,
FileInputElement,
GraphElement,
)
from baserow_enterprise.features import BUILDER_FILE_INPUT, BUILDER_GRAPH_ELEMENT
from baserow_premium.charts import ChartSeriesChartType
from baserow_premium.license.handler import LicenseHandler
class GraphElementSeriesSerializer(serializers.Serializer):
uid = serializers.UUIDField(format="hex_verbose")
label = FormulaSerializerField(required=False)
values = FormulaSerializerField(required=False)
color = serializers.CharField(
required=False, allow_blank=True, default="", max_length=COLOR_FIELD_MAX_LENGTH
)
chart_type = serializers.ChoiceField(
choices=ChartSeriesChartType.choices,
required=False,
default=ChartSeriesChartType.BAR,
)
def validate(self, attrs):
missing_fields = {
field_name: ["This field is required."]
for field_name in ("label", "values")
if field_name not in attrs
}
if missing_fields:
raise serializers.ValidationError(missing_fields)
attrs.setdefault("uid", uuid.uuid4())
attrs["uid"] = str(attrs["uid"])
return attrs
class AuthFormElementType(ElementType):
"""
Element that use the selected user source to generate the login form/buttons.
@@ -352,3 +387,87 @@ class FileInputElementType(InputElementType):
return self._handle_file(element, value, dispatch_context)
return value
class GraphElementType(ElementType):
type = "graph"
model_class = GraphElement
allowed_fields = ["labels", "series"]
serializer_field_names = ["labels", "series"]
simple_formula_fields = ["labels"]
class SerializedDict(ElementDict):
labels: BaserowFormula
series: list[dict[str, BaserowFormula | str]]
@property
def serializer_field_overrides(self):
from baserow.contrib.builder.api.theme.serializers import (
DynamicConfigBlockSerializer,
)
from baserow.contrib.builder.theme.theme_config_block_types import (
TypographyThemeConfigBlockType,
)
return {
"labels": FormulaSerializerField(
help_text=GraphElement._meta.get_field("labels").help_text,
required=False,
),
"series": serializers.ListSerializer(
child=GraphElementSeriesSerializer(),
required=False,
help_text=GraphElement._meta.get_field("series").help_text,
),
"styles": DynamicConfigBlockSerializer(
required=False,
property_names=["graph"],
theme_config_block_type_names=[
[TypographyThemeConfigBlockType.type],
],
serializer_kwargs={"required": False},
),
}
def is_deactivated(self, workspace) -> bool:
return not LicenseHandler.workspace_has_feature(
BUILDER_GRAPH_ELEMENT, workspace
)
def formula_generator(self, element: Element):
yield from super().formula_generator(element)
for series in element.series:
for formula_field in ["label", "values"]:
new_formula = yield BaserowFormulaObject.to_formula(
series.get(formula_field, "")
)
if new_formula is not None:
series[formula_field] = new_formula
yield element
def get_pytest_params(self, pytest_data_fixture):
return {
"labels": BaserowFormulaObject(
formula="to_array('A,B')",
mode=BASEROW_FORMULA_MODE_SIMPLE,
version=BASEROW_FORMULA_VERSION_INITIAL,
),
"series": [
{
"uid": "61b8a893-d454-47e4-9924-8d8da62a8bd9",
"label": BaserowFormulaObject(
formula="'Count'",
mode=BASEROW_FORMULA_MODE_SIMPLE,
version=BASEROW_FORMULA_VERSION_INITIAL,
),
"values": BaserowFormulaObject(
formula="to_array('1,2')",
mode=BASEROW_FORMULA_MODE_SIMPLE,
version=BASEROW_FORMULA_VERSION_INITIAL,
),
"color": "#2e90fa",
"chart_type": ChartSeriesChartType.BAR,
}
],
}
@@ -3,7 +3,7 @@ from django.db import models
from django.db.models import SET_NULL
from baserow.contrib.builder.elements.models import Element, FormElement
from baserow.core.formula.field import FormulaField
from baserow.core.formula.field import FormulaField, JSONFormulaField
class AuthFormElement(Element):
@@ -63,3 +63,16 @@ class FileInputElement(FormElement):
default=False,
help_text="Whether to show a preview of image files.",
)
class GraphElement(Element):
labels = FormulaField(
default="",
blank=True,
help_text="A formula resolving to the graph labels.",
)
series = JSONFormulaField(
default=list,
properties=["label", "values"],
help_text="The series shown in the graph.",
)
@@ -15,6 +15,7 @@ BUILDER_NO_BRANDING = "application_no_branding"
BUILDER_FILE_INPUT = "builder_file_input"
BUILDER_CUSTOM_CODE = "builder_custom_code"
BUILDER_GROUPED_AGGREGATE_ROWS = "builder_grouped_aggregate_rows"
BUILDER_GRAPH_ELEMENT = "builder_graph_element"
CODE_RUNNER = "code_runner"
XLS_FILE_READER = "xls_file_reader"
@@ -6,6 +6,7 @@ from baserow_enterprise.features import (
AUDIT_LOG,
BUILDER_CUSTOM_CODE,
BUILDER_FILE_INPUT,
BUILDER_GRAPH_ELEMENT,
BUILDER_GROUPED_AGGREGATE_ROWS,
BUILDER_NO_BRANDING,
BUILDER_SSO,
@@ -48,6 +49,7 @@ COMMON_ADVANCED_FEATURES = [
CODE_RUNNER,
XLS_FILE_READER,
BUILDER_GROUPED_AGGREGATE_ROWS,
BUILDER_GRAPH_ELEMENT,
# only self-hosted
SSO,
]
@@ -0,0 +1,51 @@
# Generated by Codex on 2026-06-18
import django.db.models.deletion
from django.db import migrations, models
import baserow.core.formula.field
class Migration(migrations.Migration):
dependencies = [
("baserow_enterprise", "0066_teamsubject_team_created_index"),
("builder", "0070_corecsvfilereaderworkflowaction"),
]
operations = [
migrations.CreateModel(
name="GraphElement",
fields=[
(
"element_ptr",
models.OneToOneField(
auto_created=True,
on_delete=django.db.models.deletion.CASCADE,
parent_link=True,
primary_key=True,
serialize=False,
to="builder.element",
),
),
(
"labels",
baserow.core.formula.field.FormulaField(
blank=True,
default="",
help_text="A formula resolving to the graph labels.",
),
),
(
"series",
models.JSONField(
default=list,
help_text="The series shown in the graph.",
),
),
],
options={
"abstract": False,
},
bases=("builder.element",),
),
]
@@ -3,7 +3,10 @@ from baserow_enterprise.builder.custom_code.models import (
BuilderCustomCode,
BuilderCustomScript,
)
from baserow_enterprise.builder.elements.models import AuthFormElement
from baserow_enterprise.builder.elements.models import (
AuthFormElement,
GraphElement,
)
from baserow_enterprise.builder.workflow_actions.models import CoreCodeWorkflowAction
from baserow_enterprise.data_sync.models import LocalBaserowTableDataSync
from baserow_enterprise.date_dependency.models import DateDependency
@@ -28,6 +31,7 @@ __all__ = [
"RoleAssignment",
"LocalBaserowUserSource",
"AuthFormElement",
"GraphElement",
"LocalBaserowTableDataSync",
"LocalBaserowPasswordAppAuthProvider",
"SamlAppAuthProviderModel",
@@ -1,23 +1,28 @@
import json
from unittest.mock import MagicMock, patch
from uuid import UUID
from django.core.files.uploadedfile import SimpleUploadedFile
from django.urls import reverse
import pytest
from rest_framework.status import HTTP_200_OK
from rest_framework.status import HTTP_200_OK, HTTP_400_BAD_REQUEST
from baserow.api.exceptions import RequestBodyValidationException
from baserow.contrib.builder.data_sources.builder_dispatch_context import (
BuilderDispatchContext,
)
from baserow.contrib.builder.elements.exceptions import ElementTypeDeactivated
from baserow.contrib.builder.elements.registries import element_type_registry
from baserow.contrib.builder.elements.service import ElementService
from baserow.contrib.builder.formula_importer import import_formula
from baserow.contrib.builder.workflow_actions.models import EventTypes
from baserow.test_utils.helpers import AnyInt, AnyStr
from baserow_enterprise.builder.elements.element_types import (
AuthFormElementType,
FileInputElementType,
GraphElementSeriesSerializer,
GraphElementType,
)
@@ -77,6 +82,211 @@ def test_builder_application_import_with_auth_form_referencing_trashed_user_sour
assert imported_element.user_source_id is None
@pytest.mark.django_db
def test_graph_element_import_export_formula_data_sources(
data_fixture, enable_enterprise
):
page = data_fixture.create_builder_page()
data_source_1 = data_fixture.create_builder_local_baserow_get_row_data_source()
data_source_2 = data_fixture.create_builder_local_baserow_get_row_data_source()
element_type = GraphElementType()
exported_element = data_fixture.create_builder_element(
GraphElementType,
page=page,
labels=f"get('data_source.{data_source_1.id}.field_1')",
series=[
{
"uid": "61b8a893-d454-47e4-9924-8d8da62a8bd9",
"label": f"get('data_source.{data_source_1.id}.field_2')",
"values": f"get('data_source.{data_source_1.id}.field_3')",
"color": "#2e90fa",
"chart_type": "BAR",
}
],
)
id_mapping = {"builder_data_sources": {data_source_1.id: data_source_2.id}}
updated_models = element_type.import_formulas(
exported_element, id_mapping, import_formula
)
assert updated_models == {exported_element}
assert (
exported_element.labels["formula"]
== f"get('data_source.{data_source_2.id}.field_1')"
)
assert (
exported_element.series[0]["label"]["formula"]
== f"get('data_source.{data_source_2.id}.field_2')"
)
assert (
exported_element.series[0]["values"]["formula"]
== f"get('data_source.{data_source_2.id}.field_3')"
)
assert exported_element.series[0]["color"] == "#2e90fa"
assert exported_element.series[0]["chart_type"] == "BAR"
assert exported_element.series[0]["uid"] == "61b8a893-d454-47e4-9924-8d8da62a8bd9"
@pytest.mark.django_db
def test_graph_element_update_preserves_series_uid(
api_client, enterprise_data_fixture, enable_enterprise
):
user, token = enterprise_data_fixture.create_user_and_token()
page = enterprise_data_fixture.create_builder_page(user=user)
graph = enterprise_data_fixture.create_builder_element(
GraphElementType,
page=page,
)
series_uid = "61b8a893-d454-47e4-9924-8d8da62a8bd9"
url = reverse("api:builder:element:item", kwargs={"element_id": graph.id})
response = api_client.patch(
url,
{
"series": [
{
"uid": series_uid,
"label": "'Count'",
"values": "to_array('1,2')",
"color": "primary",
"chart_type": "BAR",
}
]
},
format="json",
HTTP_AUTHORIZATION=f"JWT {token}",
)
assert response.status_code == HTTP_200_OK
graph.refresh_from_db()
assert graph.series[0]["uid"] == series_uid
@pytest.mark.django_db
def test_graph_element_update_generates_missing_series_uid(
api_client, enterprise_data_fixture, enable_enterprise
):
"""Ensure older clients can omit a series UID without causing a server error."""
user, token = enterprise_data_fixture.create_user_and_token()
page = enterprise_data_fixture.create_builder_page(user=user)
graph = enterprise_data_fixture.create_builder_element(GraphElementType, page=page)
url = reverse("api:builder:element:item", kwargs={"element_id": graph.id})
response = api_client.patch(
url,
{"series": [{"label": "'Count'", "values": "to_array('1,2')"}]},
format="json",
HTTP_AUTHORIZATION=f"JWT {token}",
)
assert response.status_code == HTTP_200_OK
graph.refresh_from_db()
assert graph.series[0]["uid"] == response.json()["series"][0]["uid"]
assert UUID(graph.series[0]["uid"])
@pytest.mark.django_db
def test_graph_element_create_requires_license(enterprise_data_fixture):
user = enterprise_data_fixture.create_user()
page = enterprise_data_fixture.create_builder_page(user=user)
element_type = element_type_registry.get("graph")
enterprise_data_fixture.delete_all_licenses()
assert element_type.is_deactivated(page.builder.workspace)
with pytest.raises(ElementTypeDeactivated):
ElementService().create_element(user, element_type, page)
@pytest.mark.django_db
@pytest.mark.parametrize(
"series",
[
[{"uid": "61b8a893-d454-47e4-9924-8d8da62a8bd9"}],
[
{
"uid": "61b8a893-d454-47e4-9924-8d8da62a8bd9",
"label": "'Count'",
}
],
[
{
"uid": "61b8a893-d454-47e4-9924-8d8da62a8bd9",
"values": "to_array('1,2')",
}
],
],
)
def test_graph_element_update_rejects_incomplete_series(
api_client, enterprise_data_fixture, enable_enterprise, series
):
"""Ensure every graph series contains both required formula fields."""
user, token = enterprise_data_fixture.create_user_and_token()
page = enterprise_data_fixture.create_builder_page(user=user)
graph = enterprise_data_fixture.create_builder_element(
GraphElementType,
page=page,
)
url = reverse("api:builder:element:item", kwargs={"element_id": graph.id})
response = api_client.patch(
url,
{"series": series},
format="json",
HTTP_AUTHORIZATION=f"JWT {token}",
)
assert response.status_code == HTTP_400_BAD_REQUEST
assert response.json()["error"] == "ERROR_REQUEST_BODY_VALIDATION"
def test_graph_element_series_reports_required_formula_fields():
serializer = GraphElementSeriesSerializer(
data={"uid": "61b8a893-d454-47e4-9924-8d8da62a8bd9"}, partial=True
)
assert not serializer.is_valid()
assert serializer.errors == {
"label": ["This field is required."],
"values": ["This field is required."],
}
@pytest.mark.django_db
def test_public_elements_exclude_unlicensed_graph_element(
api_client, enterprise_data_fixture, enable_enterprise
):
"""Ensure a graph saved before a downgrade isn't exposed publicly afterward."""
user = enterprise_data_fixture.create_user()
source_builder = enterprise_data_fixture.create_builder_application(user=user)
published_builder = enterprise_data_fixture.create_builder_application(
user=user, workspace=None
)
page = enterprise_data_fixture.create_builder_page(builder=published_builder)
heading = enterprise_data_fixture.create_builder_heading_element(page=page)
graph = enterprise_data_fixture.create_builder_element(GraphElementType, page=page)
enterprise_data_fixture.create_builder_custom_domain(
domain_name="test.getbaserow.io",
builder=source_builder,
published_to=published_builder,
)
enterprise_data_fixture.delete_all_licenses()
url = reverse("api:builder:domains:list_elements", kwargs={"page_id": page.id})
response = api_client.get(url, format="json")
assert response.status_code == HTTP_200_OK
assert [element["id"] for element in response.json()] == [heading.id]
assert graph.id not in {element["id"] for element in response.json()}
@pytest.mark.django_db
def test_create_auth_form_with_user_source(data_fixture):
user = data_fixture.create_user()
@@ -21,6 +21,7 @@
@import 'oidc_auth_link';
@import 'file_input_element';
@import 'file_input_element_form';
@import 'graph_element';
@import 'custom_code';
@import 'core_code_service_form';
@import 'assistant';
@@ -0,0 +1,35 @@
.graph-element {
height: 320px;
}
.ab-chart {
color: var(--body-text-color, $palette-neutral-900);
font-size: var(--body-font-size, 12px);
height: 100%;
}
.ab-chart__chart {
height: 100%;
}
.ab-chart__axis-color {
color: color-mix(
in srgb,
var(--body-text-color, $palette-neutral-900) 25%,
var(--element-background-color, transparent)
);
display: none;
}
.graph-element__empty {
align-items: center;
border: 1px dashed var(--body-text-color, $palette-neutral-400);
color: var(--body-text-color, $palette-neutral-900);
display: flex;
height: 100%;
justify-content: center;
}
.graph-element__chart {
height: 100%;
}
@@ -0,0 +1,109 @@
<template>
<div ref="chart" class="ab-chart">
<span ref="axisColor" class="ab-chart__axis-color" aria-hidden="true" />
<Chart :data="data" :options="options" class="ab-chart__chart" />
</div>
</template>
<script>
import Chart from '@baserow_premium/components/Chart'
export default {
name: 'ABChart',
components: { Chart },
props: {
data: {
type: Object,
required: true,
},
themeStyle: {
type: Object,
required: false,
default: () => ({}),
},
},
data() {
return {
themeValues: {},
}
},
computed: {
options() {
return {
plugins: {
legend: {
labels: {
color: this.themeValues.label,
font: {
size: this.themeValues.fontSize,
},
},
},
},
scales: {
x: this.getAxisOptions(),
y: this.getAxisOptions(),
},
}
},
},
mounted() {
this.updateThemeColors()
},
watch: {
themeStyle: {
deep: true,
handler() {
this.updateThemeColorsAfterStyleChange()
},
},
},
methods: {
async updateThemeColorsAfterStyleChange() {
await this.$nextTick()
if (typeof requestAnimationFrame === 'undefined') {
this.updateThemeColors()
} else {
requestAnimationFrame(() => this.updateThemeColors())
}
},
updateThemeColors() {
if (!this.$refs.chart || typeof getComputedStyle === 'undefined') {
return
}
const styles = getComputedStyle(this.$refs.chart)
const axisColorStyles = getComputedStyle(this.$refs.axisColor)
const nextThemeValues = {
axis: axisColorStyles.color,
label: styles.color,
fontSize: Number.parseFloat(styles.fontSize),
}
if (
nextThemeValues.axis !== this.themeValues.axis ||
nextThemeValues.label !== this.themeValues.label ||
nextThemeValues.fontSize !== this.themeValues.fontSize
) {
this.themeValues = nextThemeValues
}
},
getAxisOptions() {
return {
border: {
color: this.themeValues.label,
},
grid: {
color: this.themeValues.axis,
},
ticks: {
color: this.themeValues.label,
font: {
size: this.themeValues.fontSize,
},
},
}
},
},
}
</script>
@@ -0,0 +1,100 @@
<template>
<div class="graph-element" :style="graphStyle">
<ABChart
v-if="chartData.datasets.length > 0"
:data="chartData"
:theme-style="graphStyle"
class="graph-element__chart"
/>
<div v-else class="graph-element__empty">
{{ $t('graphElement.noData') }}
</div>
</div>
</template>
<script>
import { toRefs } from 'vue'
import { useElement } from '@baserow/modules/builder/composables/useElement'
import ABChart from '@baserow_enterprise/builder/components/elements/ABChart'
import { getBaseColors, resolveColor } from '@baserow/modules/core/utils/colors'
import {
ensureArray,
ensureString,
} from '@baserow/modules/core/utils/validator'
export default {
name: 'GraphElement',
components: { ABChart },
props: {
element: {
type: Object,
required: true,
},
applicationContextAdditions: {
type: Object,
required: false,
default: undefined,
},
},
setup(props) {
const { colorVariables, getStyleOverride, resolveFormula } = useElement(
toRefs(props)
)
return {
colorVariables,
getStyleOverride,
resolveFormula,
}
},
computed: {
graphStyle() {
return this.getStyleOverride('graph')
},
chartData() {
const labels = ensureArray(this.resolveFormula(this.element.labels)).map(
ensureString
)
const colors = getBaseColors()
const datasets = (this.element.series || [])
.map((series, index) => {
const color = series.color
? resolveColor(series.color, this.colorVariables)
: colors[index % colors.length]
const data = ensureArray(this.resolveFormula(series.values)).map(
(value) => {
if (value === null || value === undefined || value === '') {
return null
}
const numberValue = Number(value)
return Number.isFinite(numberValue) ? numberValue : null
}
)
return {
type: this.convertChartJsType(series.chart_type),
label:
ensureString(this.resolveFormula(series.label)) ||
this.$t('graphElement.series', { number: index + 1 }),
data,
borderColor: color,
backgroundColor: color,
hoverBackgroundColor: color,
tension: 0.25,
}
})
.filter((series) => series.data.length > 0)
return {
labels,
datasets,
}
},
},
methods: {
convertChartJsType(chartType) {
return chartType === 'LINE' ? 'line' : 'bar'
},
},
}
</script>
@@ -0,0 +1,194 @@
<template>
<form @submit.prevent @keydown.enter.prevent>
<CustomStyleButton
v-model="values.styles"
style-key="graph"
:config-block-types="['typography']"
:theme="builder.theme"
:extra-args="{
onlyBody: true,
noAlignment: true,
noFontSelector: true,
noFontWeight: true,
}"
/>
<FormGroup
small-label
required
class="margin-bottom-2"
:label="$t('graphElementForm.labels')"
:helper-text="$t('graphElementForm.labelsHelper')"
>
<InjectedFormulaInput
v-model="values.labels"
:placeholder="$t('graphElementForm.labelsPlaceholder')"
/>
</FormGroup>
<FormSection
class="margin-bottom-2"
:title="$t('graphElementForm.seriesList')"
>
<template #title-slot>
<ButtonText
type="secondary"
icon="iconoir-plus"
size="small"
@click="addSeries"
>
{{ $t('graphElementForm.addSeries') }}
</ButtonText>
</template>
<div>
<SidebarExpandable
v-for="(series, index) in values.series"
:key="series.uid"
v-sortable="{
id: series.uid,
update: orderSeries,
handle: '[data-sortable-handle]',
}"
toggle-on-click
>
<template #title>
<span>{{ getSeriesTitle(index) }}</span>
</template>
<template #default>
<FormGroup
small-label
required
class="margin-bottom-2"
:label="$t('graphElementForm.seriesLabel')"
>
<InjectedFormulaInput
:value="series.label"
:placeholder="$t('graphElementForm.seriesLabelPlaceholder')"
@input="updateSeries(index, 'label', $event)"
/>
</FormGroup>
<FormGroup
small-label
required
class="margin-bottom-2"
:label="$t('graphElementForm.seriesValues')"
:helper-text="$t('graphElementForm.seriesValuesHelper')"
>
<InjectedFormulaInput
:value="series.values"
:placeholder="$t('graphElementForm.seriesValuesPlaceholder')"
@input="updateSeries(index, 'values', $event)"
/>
</FormGroup>
<FormGroup
small-label
required
class="margin-bottom-2"
:label="$t('graphElementForm.chartType')"
>
<Dropdown
:value="series.chart_type"
:show-search="false"
@input="updateSeries(index, 'chart_type', $event)"
>
<DropdownItem
:name="$t('graphElementForm.barChart')"
value="BAR"
></DropdownItem>
<DropdownItem
:name="$t('graphElementForm.lineChart')"
value="LINE"
></DropdownItem>
</Dropdown>
</FormGroup>
<FormGroup
small-label
required
class="margin-bottom-2"
:label="$t('graphElementForm.seriesColor')"
>
<ColorInput
:value="series.color"
:color-variables="colorVariables"
@input="updateSeries(index, 'color', $event)"
/>
</FormGroup>
</template>
<template #footer>
<ButtonText icon="iconoir-bin" @click="removeSeries(index)">
{{ $t('action.delete') }}
</ButtonText>
</template>
</SidebarExpandable>
</div>
</FormSection>
</form>
</template>
<script>
import InjectedFormulaInput from '@baserow/modules/core/components/formula/InjectedFormulaInput'
import CustomStyleButton from '@baserow/modules/builder/components/elements/components/forms/style/CustomStyleButton'
import elementForm from '@baserow/modules/builder/mixins/elementForm'
import SidebarExpandable from '@baserow/modules/builder/components/SidebarExpandable.vue'
import { uuid } from '@baserow/modules/core/utils/string'
export default {
name: 'GraphElementForm',
components: { CustomStyleButton, InjectedFormulaInput, SidebarExpandable },
mixins: [elementForm],
data() {
return {
allowedValues: ['labels', 'series', 'styles'],
values: {
labels: {},
series: [],
styles: {},
},
}
},
mounted() {
if (this.values.series.length === 0) {
this.addSeries()
}
},
methods: {
addSeries() {
this.values.series.push({
uid: uuid(),
label: '',
values: '',
color: 'primary',
chart_type: 'BAR',
})
},
removeSeries(index) {
this.values.series.splice(index, 1)
},
updateSeries(index, key, value) {
this.values.series.splice(index, 1, {
...this.values.series[index],
[key]: value,
})
},
getSeriesTitle(index) {
return this.$t('graphElementForm.series', { number: index + 1 })
},
orderSeries(newOrder) {
const seriesById = Object.fromEntries(
this.values.series.map((series) => [series.uid, series])
)
const orderedSeriesIds = newOrder.filter(
(seriesId) => seriesById[seriesId]
)
this.values.series = orderedSeriesIds.map(
(seriesId) => seriesById[seriesId]
)
},
},
}
</script>
@@ -6,18 +6,24 @@ import AuthFormElement from '@baserow_enterprise/builder/components/elements/Aut
import AuthFormElementForm from '@baserow_enterprise/builder/components/elements/AuthFormElementForm'
import FileInputElement from '@baserow_enterprise/builder/components/elements/FileInputElement'
import FileInputElementForm from '@baserow_enterprise/builder/components/elements/FileInputElementForm'
import GraphElement from '@baserow_enterprise/builder/components/elements/GraphElement'
import GraphElementForm from '@baserow_enterprise/builder/components/elements/GraphElementForm'
import { uuid } from '@baserow/modules/core/utils/string'
import {
ensureArray,
ensureString,
} from '@baserow/modules/core/utils/validator'
import PaidFeaturesModal from '@baserow_premium/components/PaidFeaturesModal'
import { BuilderFileInputElementPaidFeature } from '@baserow_enterprise/paidFeatures'
import {
BuilderFileInputElementPaidFeature,
BuilderGraphElementPaidFeature,
} from '@baserow_enterprise/paidFeatures'
import { AfterLoginEvent } from '@baserow/modules/builder/eventTypes'
import elementImageAuthForm from '@baserow_enterprise/assets/images/builder/element-auth_form.svg?url'
import elementImageFileInput from '@baserow_enterprise/assets/images/builder/element-file_input.svg?url'
import ChartBarWidgetSvg from '@baserow_premium/assets/images/chart_bar.svg?url'
import EnterpriseFeaturesObject from '@baserow_enterprise/features'
@@ -272,3 +278,87 @@ export class FileInputElementType extends FormElementType {
return null
}
}
export class GraphElementType extends ElementType {
static getType() {
return 'graph'
}
category() {
return 'layoutElement'
}
get name() {
return this.app.$i18n.t('elementType.graph')
}
get description() {
return this.app.$i18n.t('elementType.graphDescription')
}
get iconClass() {
return 'iconoir-graph-up'
}
get image() {
return ChartBarWidgetSvg
}
get component() {
return GraphElement
}
get generalFormComponent() {
return GraphElementForm
}
getDefaultValues(page, values) {
const superValues = super.getDefaultValues(page, values)
return {
...superValues,
labels: "'label 1,label 2,label 3'",
series: [
{
uid: uuid(),
label: "'Series 1'",
values: "'10,20,30'",
color: 'primary',
chart_type: 'BAR',
},
],
}
}
isDeactivatedReason({ workspace }) {
if (!workspace) {
return null
}
if (
!this.app.$hasFeature(
EnterpriseFeaturesObject.BUILDER_GRAPH_ELEMENT,
workspace.id
)
) {
return this.app.$i18n.t('enterprise.deactivated')
}
return super.isDeactivatedReason({ workspace })
}
getDeactivatedClickModal({ workspace }) {
if (
workspace &&
!this.app.$hasFeature(
EnterpriseFeaturesObject.BUILDER_GRAPH_ELEMENT,
workspace.id
)
) {
return [
PaidFeaturesModal,
{
'initial-selected-type': BuilderGraphElementPaidFeature.getType(),
},
]
}
return null
}
}
@@ -11,6 +11,7 @@ const EnterpriseFeatures = {
BUILDER_FILE_INPUT: 'BUILDER_FILE_INPUT',
BUILDER_CUSTOM_CODE: 'BUILDER_CUSTOM_CODE',
BUILDER_GROUPED_AGGREGATE_ROWS: 'builder_grouped_aggregate_rows',
BUILDER_GRAPH_ELEMENT: 'BUILDER_GRAPH_ELEMENT',
CODE_RUNNER: 'CODE_RUNNER',
XLS_FILE_READER: 'XLS_FILE_READER',
ADVANCED_WEBHOOKS: 'ADVANCED_WEBHOOKS',
@@ -21,6 +21,7 @@ const commonAdvancedFeatures = [
EnterpriseFeaturesObject.CODE_RUNNER,
EnterpriseFeaturesObject.XLS_FILE_READER,
EnterpriseFeaturesObject.BUILDER_GROUPED_AGGREGATE_ROWS,
EnterpriseFeaturesObject.BUILDER_GRAPH_ELEMENT,
// Only self-hosted
EnterpriseFeaturesObject.SSO,
]
@@ -457,6 +457,8 @@
"builderBrandingContent": "White label the branding of your application by removing the 'Made with Baserow' branding in the footer of your application.",
"builderFileInputElement": "File input element",
"builderFileInputElementContent": "The file input element allows you to add a field to your application pages for uploading files. Give your users the ability to store important documents or images.",
"builderGraphElement": "Graph element",
"builderGraphElementContent": "Display formula-driven data as a graph in application pages.",
"builderCustomCode": "Custom code for applications",
"builderCustomCodeContent": "You can add custom CSS/JavaScript code to further customize the look and behaviour of your application. For example, you can integrate external services like analytics or social media.",
"codeRunner": "Code runner",
@@ -815,9 +817,32 @@
"crossoriginTypeCredentials": "Use credentials"
},
"elementType": {
"graph": "Graph",
"graphDescription": "Display formula-driven data as a graph.",
"errorUserSourceHasNoLoginOption": "The selected user source has no login option",
"errorUserSourceMissing": "No user source selected"
},
"graphElementForm": {
"labels": "Labels",
"labelsHelper": "The formula must resolve to an array. Each item becomes one label on the graph.",
"labelsPlaceholder": "to_array('Jan,Feb,Mar')",
"seriesList": "Series",
"series": "Series {number}",
"addSeries": "Add series",
"seriesLabel": "Series label",
"seriesLabelPlaceholder": "'Revenue'",
"seriesValues": "Values",
"seriesValuesHelper": "The formula must resolve to one numeric value per label.",
"seriesValuesPlaceholder": "to_array('10,20,30')",
"chartType": "Chart type",
"seriesColor": "Color",
"barChart": "Bar",
"lineChart": "Line"
},
"graphElement": {
"series": "Series {number}",
"noData": "No graph data"
},
"fieldPermissionsMenuItem": {
"label": "Edit field permissions"
},
@@ -260,6 +260,32 @@ export class BuilderFileInputElementPaidFeature extends PaidFeature {
}
}
export class BuilderGraphElementPaidFeature extends PaidFeature {
static getType() {
return 'builder_graph_element'
}
getPlan() {
return 'Advanced'
}
getIconClass() {
return 'iconoir-graph-up'
}
getName() {
return this.app.$i18n.t('enterpriseFeatures.builderGraphElement')
}
getImage() {
return null
}
getContent() {
return this.app.$i18n.t('enterpriseFeatures.builderGraphElementContent')
}
}
export class BuilderCustomCodePaidFeature extends PaidFeature {
static getType() {
return 'builder_custom_code'
@@ -45,6 +45,7 @@ import {
import {
AuthFormElementType,
FileInputElementType,
GraphElementType,
} from '@baserow_enterprise/builder/elementTypes'
import {
EnterpriseAdminRoleType,
@@ -79,6 +80,7 @@ import {
BuilderBrandingPaidFeature,
BuilderCustomCodePaidFeature,
BuilderFileInputElementPaidFeature,
BuilderGraphElementPaidFeature,
CodeRunnerPaidFeature,
CoBrandingPaidFeature,
DataScannerPaidFeature,
@@ -227,6 +229,7 @@ export default defineNuxtPlugin({
$registry.register('element', new AuthFormElementType(context))
$registry.register('element', new FileInputElementType(context))
$registry.register('element', new GraphElementType(context))
$registry.unregister('dataSync', PostgreSQLDataSyncType.getType())
$registry.register('dataSync', new PostgreSQLDataSyncType(context))
@@ -284,6 +287,10 @@ export default defineNuxtPlugin({
'paidFeature',
new BuilderFileInputElementPaidFeature(context)
)
$registry.register(
'paidFeature',
new BuilderGraphElementPaidFeature(context)
)
$registry.register('paidFeature', new CodeRunnerPaidFeature(context))
$registry.register('paidFeature', new XLSFileReaderPaidFeature(context))
@@ -1,3 +1,8 @@
import EnterpriseFeaturesObject from '@baserow_enterprise/features'
import ABChart from '@baserow_enterprise/builder/components/elements/ABChart'
import GraphElement from '@baserow_enterprise/builder/components/elements/GraphElement'
import GraphElementForm from '@baserow_enterprise/builder/components/elements/GraphElementForm'
describe('Enterprise builder element types', () => {
describe('Auth form error message', () => {
const getAuthFormErrorMessage = (
@@ -163,6 +168,173 @@ describe('Enterprise builder element types', () => {
null
)
})
test('graph element is an advanced paid feature', () => {
const testApp = useNuxtApp()
for (const licenseType of [
testApp.$registry.get('license', 'advanced'),
testApp.$registry.get('license', 'enterprise_without_support'),
testApp.$registry.get('license', 'enterprise'),
]) {
expect(licenseType.getFeatures()).toContain(
EnterpriseFeaturesObject.BUILDER_GRAPH_ELEMENT
)
}
expect(
testApp.$registry.get('paidFeature', 'builder_graph_element').getPlan()
).toBe('Advanced')
})
test('graph element defaults use formula series', () => {
const testApp = useNuxtApp()
const elementType = testApp.$registry.get('element', 'graph')
expect(elementType.getDefaultValues({}, {})).toStrictEqual({
labels: "'label 1,label 2,label 3'",
series: [
{
uid: expect.any(String),
label: "'Series 1'",
values: "'10,20,30'",
color: 'primary',
chart_type: 'BAR',
},
],
})
})
test('graph element form uses generic series headers', () => {
expect(
GraphElementForm.methods.getSeriesTitle.call(
{
$t(key, values) {
return `${key} ${values.number}`
},
},
1
)
).toBe('graphElementForm.series 2')
})
test('graph element form accepts theme overrides', () => {
const data = GraphElementForm.data()
expect(data.allowedValues).toContain('styles')
expect(data.values.styles).toStrictEqual({})
})
test('graph chart reads its visual theme from computed styles', () => {
const chartElement = {}
const axisColorElement = {}
const chart = {
$refs: { chart: chartElement, axisColor: axisColorElement },
themeValues: ABChart.data().themeValues,
}
const originalGetComputedStyle = globalThis.getComputedStyle
globalThis.getComputedStyle = vi.fn((element) =>
element === axisColorElement
? { color: 'rgb(217, 219, 222)' }
: { color: 'rgb(32, 33, 40)', fontSize: '14px' }
)
try {
ABChart.methods.updateThemeColors.call(chart)
} finally {
globalThis.getComputedStyle = originalGetComputedStyle
}
expect(chart.themeValues).toStrictEqual({
axis: 'rgb(217, 219, 222)',
label: 'rgb(32, 33, 40)',
fontSize: 14,
})
})
test('graph chart preserves blank values as gaps while retaining zeroes', () => {
const context = {
element: {
labels: ['Blank', 'Undefined', 'Empty', 'Zero', 'String zero'],
series: [
{
values: [null, undefined, '', 0, '0', '2', 'invalid'],
label: 'Series',
color: null,
chart_type: 'LINE',
},
],
},
colorVariables: {},
resolveFormula: (value) => value,
convertChartJsType: GraphElement.methods.convertChartJsType,
$t: (key) => key,
}
const chartData = GraphElement.computed.chartData.call(context)
expect(chartData.datasets[0].data).toStrictEqual([
null,
null,
null,
0,
0,
2,
null,
])
})
test('graph element form keeps series identity after delete, undo, and reorder', () => {
const originalSeries = [
{
uid: 'first',
label: "'First'",
values: "'1'",
color: 'primary',
chart_type: 'BAR',
},
{
uid: 'second',
label: "'Second'",
values: "'2'",
color: 'warning',
chart_type: 'LINE',
},
{
uid: 'third',
label: "'Third'",
values: "'3'",
color: 'error',
chart_type: 'BAR',
},
]
const form = {
values: {
series: [...originalSeries],
},
}
GraphElementForm.methods.removeSeries.call(form, 1)
GraphElementForm.methods.removeSeries.call(form, 1)
form.values.series = [...originalSeries]
GraphElementForm.methods.orderSeries.call(form, [
undefined,
'third',
'second',
'first',
])
expect(form.values.series.map(({ uid }) => uid)).toStrictEqual([
'third',
'second',
'first',
])
expect(form.values.series.map(({ label }) => label)).toStrictEqual([
"'Third'",
"'Second'",
"'First'",
])
})
})
describe('Enterprise automation and workflow action types', () => {
+1
View File
@@ -1,2 +1,3 @@
[tools]
node = "24"
python = "3.14"
@@ -1,7 +1,7 @@
from rest_framework import serializers
from baserow_premium.charts import ChartSeriesChartType
from baserow_premium.dashboard.widgets.models import (
ChartSeriesChartType,
PieChartSeriesChartType,
)
@@ -10,19 +10,33 @@ from baserow_premium.integrations.local_baserow.models import (
class LocalBaserowTableServiceAggregationSeriesSerializer(serializers.ModelSerializer):
id = serializers.IntegerField(required=False)
field_id = serializers.IntegerField(allow_null=True)
trashed = serializers.BooleanField(
source="field.trashed",
read_only=True,
default=False,
help_text="An aggregation series is considered trashed if "
"the field it's associated with is trashed.",
)
class Meta:
model = LocalBaserowTableServiceAggregationSeries
fields = ("id", "aggregation_type", "field_id")
fields = ("id", "aggregation_type", "field_id", "trashed")
class LocalBaserowTableServiceAggregationGroupBySerializer(serializers.ModelSerializer):
field_id = serializers.IntegerField(allow_null=True)
order = serializers.IntegerField(read_only=True)
trashed = serializers.BooleanField(
source="field.trashed",
read_only=True,
default=False,
help_text="An aggregation group by is considered trashed if "
"the field it's associated with is trashed.",
)
class Meta:
model = LocalBaserowTableServiceAggregationGroupBy
fields = ("order", "field_id")
fields = ("order", "field_id", "trashed")
class LocalBaserowTableServiceAggregationSortBySerializer(serializers.ModelSerializer):
@@ -0,0 +1,6 @@
from django.db import models
class ChartSeriesChartType(models.TextChoices):
BAR = "BAR", "Bar"
LINE = "LINE", "Line"
@@ -1,16 +1,12 @@
from django.db import models
from baserow.contrib.dashboard.widgets.models import Widget
from baserow_premium.charts import ChartSeriesChartType
from baserow_premium.integrations.local_baserow.models import (
LocalBaserowTableServiceAggregationSeries,
)
class ChartSeriesChartType(models.TextChoices):
BAR = "BAR", "Bar"
LINE = "LINE", "Line"
class ChartWidget(Widget):
data_source = models.ForeignKey(
"dashboard.DashboardDataSource",
@@ -214,7 +214,7 @@ class LocalBaserowGroupedAggregateRowsUserServiceType(
self,
service: LocalBaserowGroupedAggregateRows,
) -> dict | None:
table_properties = self._get_table_properties(service)
table_properties = self.get_table_properties(service)
if table_properties is None:
return None
@@ -335,6 +335,33 @@ class LocalBaserowGroupedAggregateRowsUserServiceType(
return [human_name, *rest]
@staticmethod
def _get_property_human_name(property_name: str, property_schema: dict) -> str:
if property_name == GROUPED_AGGREGATE_ROW_ID:
return property_name
metadata = property_schema.get("metadata", {})
return (
metadata.get("result_name")
or metadata.get("display_name")
or property_schema.get("title")
or property_name
)
def _get_result_property_human_names(self, service: Service) -> dict[str, str]:
"""
Maps every technical result property key of the service to the human
readable name used in dispatch results. Callers converting many rows or
keys must build this map once instead of resolving names one by one, as
each resolution walks the full result schema.
"""
result_properties = self._get_result_properties(service) or {}
return {
key: self._get_property_human_name(key, property_schema)
for key, property_schema in result_properties.items()
}
def _get_result_property_human_name(self, service: Service, property_name: str):
if property_name == GROUPED_AGGREGATE_ROW_ID:
return property_name
@@ -344,26 +371,21 @@ class LocalBaserowGroupedAggregateRowsUserServiceType(
if property_schema is None:
return property_name
return (
property_schema.get("metadata", {}).get("result_name")
or property_schema.get("metadata", {}).get("display_name")
or property_schema.get("title")
or property_name
)
return self._get_property_human_name(property_name, property_schema)
def _convert_result_property_names_to_human_names(
self, service: Service, result: dict
self,
service: Service,
result: dict,
human_names: dict[str, str] | None = None,
):
return {
self._get_result_property_human_name(service, key): value
for key, value in result.items()
}
if human_names is None:
human_names = self._get_result_property_human_names(service)
return {human_names.get(key, key): value for key, value in result.items()}
def _convert_allowed_field_names(self, service, allowed_fields):
return [
self._get_result_property_human_name(service, field)
for field in allowed_fields
]
human_names = self._get_result_property_human_names(service)
return [human_names.get(field, field) for field in allowed_fields]
def enhance_queryset(self, queryset):
return (
@@ -1047,6 +1069,11 @@ class LocalBaserowGroupedAggregateRowsUserServiceType(
for field in group_by_fields
}
# Resolved once: both helpers query the group by relation and the name
# lookups below run for every result bucket.
name_property = self.get_name_property(service)
name_field_object = self._get_name_field_object(service)
def process_individual_result(result: dict, overflow=False):
"""Finalize aggregates and assign readable group labels before deduplication."""
@@ -1060,13 +1087,12 @@ class LocalBaserowGroupedAggregateRowsUserServiceType(
)
if "total" in result:
del result["total"]
name_property = self.get_name_property(service)
if overflow:
name = "OTHER_VALUES"
elif name_property:
name = self._get_human_readable_result_value(
result.get(name_property),
self._get_name_field_object(service),
name_field_object,
model,
)
else:
@@ -1147,8 +1173,11 @@ class LocalBaserowGroupedAggregateRowsUserServiceType(
if result[GROUPED_AGGREGATE_ROW_ID] == current_record_id
]
human_names = self._get_result_property_human_names(service)
results = [
self._convert_result_property_names_to_human_names(service, result)
self._convert_result_property_names_to_human_names(
service, result, human_names
)
for result in results
]
@@ -2,4 +2,10 @@ from .fields.models import AIField, AIFieldScheduledUpdate
from .license.models import License, LicenseUser
from .row_comments.models import RowComment
__all__ = ["License", "LicenseUser", "RowComment", "AIField", "AIFieldScheduledUpdate"]
__all__ = [
"License",
"LicenseUser",
"RowComment",
"AIField",
"AIFieldScheduledUpdate",
]
@@ -82,17 +82,21 @@ def test_grouped_aggregate_rows_get_dashboard_data_sources(
assert response.status_code == HTTP_200_OK
assert len(response_json) == 2
assert response_json[0] == {
"aggregation_group_bys": [{"field_id": field_3.id, "order": 1}],
"aggregation_group_bys": [
{"field_id": field_3.id, "order": 1, "trashed": False}
],
"aggregation_series": [
{
"aggregation_type": "sum",
"field_id": field.id,
"id": AnyInt(),
"trashed": False,
},
{
"aggregation_type": "sum",
"field_id": field_2.id,
"id": AnyInt(),
"trashed": False,
},
],
"context_data": {
@@ -219,15 +223,17 @@ def test_grouped_aggregate_rows_update_data_source(api_client, premium_data_fixt
"aggregation_type": "sum",
"field_id": field.id,
"id": AnyInt(),
"trashed": False,
},
{
"aggregation_type": "sum",
"field_id": field_2.id,
"id": AnyInt(),
"trashed": False,
},
]
assert response_json["aggregation_group_bys"] == [
{"field_id": field_3.id, "order": 0}
{"field_id": field_3.id, "order": 0, "trashed": False}
]
assert response_json["aggregation_sorts"] == [
{
@@ -26,6 +26,10 @@ from baserow.core.services.exceptions import (
from baserow.core.services.handler import ServiceHandler
from baserow.core.services.registries import service_type_registry
from baserow.test_utils.pytest_conftest import FakeDispatchContext
from baserow_premium.api.integrations.local_baserow.serializers import (
LocalBaserowTableServiceAggregationGroupBySerializer,
LocalBaserowTableServiceAggregationSeriesSerializer,
)
from baserow_premium.integrations.local_baserow.models import (
LocalBaserowGroupedAggregateRows,
LocalBaserowTableServiceAggregationGroupBy,
@@ -4823,3 +4827,105 @@ def test_grouped_aggregate_rows_sanitize_result_does_not_query_per_button_field(
sanitize_queries(1)
assert sanitize_queries(3) == sanitize_queries(1)
@pytest.mark.django_db
def test_grouped_aggregate_rows_dispatch_query_count_is_constant_with_buckets(
data_fixture, mocker
):
"""
Converting result keys to human readable names used to rebuild the full table
schema, at one field constraints query per table field, for every result row
and key. The dispatch query count must not grow with the number of groups, and
the table properties must be built at most once per dispatch.
"""
user = data_fixture.create_user()
dashboard = data_fixture.create_dashboard_application(user=user)
table = data_fixture.create_database_table(user=user)
number_field = data_fixture.create_number_field(table=table)
text_field = data_fixture.create_text_field(table=table)
for _ in range(5):
data_fixture.create_text_field(table=table)
integration = data_fixture.create_local_baserow_integration(
application=dashboard, user=user
)
service = data_fixture.create_service(
LocalBaserowGroupedAggregateRows,
integration=integration,
table=table,
)
LocalBaserowTableServiceAggregationSeries.objects.create(
service=service, field=number_field, aggregation_type="max", order=1
)
LocalBaserowTableServiceAggregationGroupBy.objects.create(
service=service, field=text_field, order=1
)
def create_groups(start, count):
RowHandler().create_rows(
user,
table,
rows_values=[
{
f"field_{number_field.id}": index,
f"field_{text_field.id}": f"Group {index}",
}
for index in range(start, start + count)
],
)
def dispatch():
with CaptureQueriesContext(connection) as context:
result = ServiceHandler().dispatch_service(service, FakeDispatchContext())
return len(context.captured_queries), result.data["results"]
table_properties_spy = mocker.spy(
LocalBaserowGroupedAggregateRowsUserServiceType, "_get_table_properties"
)
create_groups(0, 2)
# Warm the global table schema cache so both measurements compare like for like.
dispatch()
queries_two_groups, results = dispatch()
assert len(results) == 2
create_groups(2, 4)
queries_six_groups, results = dispatch()
assert len(results) == 6
assert queries_six_groups == queries_two_groups
assert table_properties_spy.call_count <= 1
@pytest.mark.django_db
def test_grouped_aggregate_rows_serializes_trashed_configured_fields(data_fixture):
user = data_fixture.create_user()
dashboard = data_fixture.create_dashboard_application(user=user)
table = data_fixture.create_database_table(user=user)
field = data_fixture.create_number_field(table=table, trashed=True)
integration = data_fixture.create_local_baserow_integration(
application=dashboard, user=user
)
service = data_fixture.create_service(
LocalBaserowGroupedAggregateRows,
integration=integration,
table=table,
)
series = LocalBaserowTableServiceAggregationSeries.objects.create(
service=service, field=field, aggregation_type="max", order=1
)
group_by = LocalBaserowTableServiceAggregationGroupBy.objects.create(
service=service, field=field, order=1
)
primary_group_by = LocalBaserowTableServiceAggregationGroupBy.objects.create(
service=service, field=None, order=2
)
assert LocalBaserowTableServiceAggregationSeriesSerializer(series).data["trashed"]
assert LocalBaserowTableServiceAggregationGroupBySerializer(group_by).data[
"trashed"
]
assert not LocalBaserowTableServiceAggregationGroupBySerializer(
primary_group_by
).data["trashed"]
File renamed without changes.

Before

Width:  |  Height:  |  Size: 1.1 KiB

After

Width:  |  Height:  |  Size: 1.1 KiB

@@ -0,0 +1,239 @@
<template>
<template v-if="isClientReady">
<component
:is="chartComponent"
v-if="hasChartData"
id="chart-id"
:key="chartRenderKey"
:options="chartOptions"
:data="data"
class="chart"
/>
<div v-else class="chart__no-data">
<span class="chart__no-data-dashed-line"></span>
<span class="chart__no-data-dashed-line"></span>
<span class="chart__no-data-dashed-line"></span>
<span class="chart__no-data-dashed-line"></span>
<span class="chart__no-data-dashed-line"></span>
<span class="chart__no-data-plain-line"></span>
</div>
</template>
</template>
<script>
import { Bar, Pie } from 'vue-chartjs'
import {
Chart as ChartJS,
ArcElement,
LineElement,
BarElement,
PointElement,
BarController,
BubbleController,
DoughnutController,
LineController,
PieController,
PolarAreaController,
RadarController,
ScatterController,
CategoryScale,
LinearScale,
LogarithmicScale,
RadialLinearScale,
TimeScale,
TimeSeriesScale,
Decimation,
Filler,
Legend,
Title,
Tooltip,
SubTitle,
} from 'chart.js'
import { convertChartJsType } from '@baserow_premium/utils/chart'
ChartJS.register(
ArcElement,
LineElement,
BarElement,
PointElement,
BarController,
BubbleController,
DoughnutController,
LineController,
PieController,
PolarAreaController,
RadarController,
ScatterController,
CategoryScale,
LinearScale,
LogarithmicScale,
RadialLinearScale,
TimeScale,
TimeSeriesScale,
Decimation,
Filler,
Legend,
Title,
Tooltip,
SubTitle
)
export default {
name: 'Chart',
components: { Bar, Pie },
props: {
data: {
type: Object,
required: false,
default: () => ({ datasets: [] }),
},
options: {
type: Object,
required: false,
default: null,
},
},
emits: ['rendered'],
data() {
return {
isClientReady: false,
}
},
computed: {
chartComponent() {
const firstDatasetType = convertChartJsType(this.data.datasets?.[0]?.type)
return ['pie', 'doughnut'].includes(firstDatasetType) ? 'Pie' : 'Bar'
},
hasChartData() {
return this.data.datasets.length > 0
},
chartRenderKey() {
return `${this.chartComponent}-${JSON.stringify(this.data)}`
},
chartOptions() {
const options = {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: {
display: true,
align: 'start',
position: 'bottom',
labels: {
usePointStyle: true,
boxWidth: 14,
pointStyle: 'circle',
padding: 20,
generateLabels: function (chart) {
if (chart.config.type === 'bar') {
return Legend.defaults.labels.generateLabels(chart)
} else {
const original =
ChartJS.overrides.pie.plugins.legend.labels.generateLabels
if (chart.data.datasets.length <= 1) {
return original.call(this, chart)
}
const originalLabels = original.call(this, chart)
const datasetColors = chart.data.datasets.map(function (e) {
return e.backgroundColor
})
let datasetIndex = 0
const newLabels = []
for (const dataset of chart.data.datasets) {
originalLabels.forEach((label) => {
const newLabel = JSON.parse(JSON.stringify(label))
if (label.text) {
newLabel.text = `${label.text} - ${dataset.label}`
} else {
newLabel.text = dataset.label
}
newLabel.fillStyle =
datasetColors[datasetIndex]?.[label.index % 10] ||
label.fillStyle
newLabels.push(newLabel)
})
datasetIndex += 1
}
return newLabels
}
},
},
},
tooltip: {
backgroundColor: '#202128',
padding: 10,
bodyFont: {
size: 12,
},
titleFont: {
size: 12,
},
},
},
elements: {
bar: {
borderRadius: {
topLeft: 4,
topRight: 4,
bottomLeft: 0,
bottomRight: 0,
},
borderWidth: 1,
borderColor: '#5190ef',
backgroundColor: '#5190ef',
hoverBackgroundColor: '#5190ef',
},
},
}
return this.mergeOptions(options, this.options)
},
},
mounted() {
this.isClientReady = true
this.emitRendered()
},
updated() {
if (this.isClientReady) {
this.emitRendered()
}
},
methods: {
mergeOptions(base, override) {
if (!override) {
return base
}
return Object.entries(override).reduce(
(result, [key, value]) => {
if (
value &&
typeof value === 'object' &&
!Array.isArray(value) &&
result[key] &&
typeof result[key] === 'object' &&
!Array.isArray(result[key])
) {
result[key] = this.mergeOptions(result[key], value)
} else {
result[key] = value
}
return result
},
{ ...base }
)
},
emitRendered() {
this.$nextTick(() => {
const emitRendered = () => this.$emit('rendered')
if (typeof window !== 'undefined' && window.requestAnimationFrame) {
window.requestAnimationFrame(emitRendered)
} else {
emitRendered()
}
})
},
},
}
</script>
@@ -0,0 +1,344 @@
import { colorPalette, getBaseColors } from '@baserow/modules/core/utils/colors'
import { convertChartJsType } from '@baserow_premium/utils/chart'
function getIndividualSeriesConfig(seriesConfig, seriesId) {
return seriesConfig.find((item) => item.series_id === seriesId) || {}
}
function getChartSeries(dataSource) {
return (dataSource.aggregation_series || []).map((item) => {
return {
id: item.id,
fieldName: `field_${item.field_id}`,
aggregationType: item.aggregation_type,
}
})
}
function getAggregationTitle($registry, aggregationType) {
return $registry.get('groupedAggregation', aggregationType).getName()
}
function getServiceType({ dataSource, $registry }) {
if (!dataSource.type || !$registry.exists('service', dataSource.type)) {
return null
}
return $registry.get('service', dataSource.type)
}
function getResultPropertyName({ dataSource, $registry, propertyName }) {
return getServiceType({ dataSource, $registry }).getResultPropertyName(
dataSource,
propertyName
)
}
function hasResultValue({ item, resultFieldName, fallbackFieldName = null }) {
return (
item[resultFieldName] !== undefined ||
(fallbackFieldName !== null && item[fallbackFieldName] !== undefined)
)
}
function getResultValue({ item, resultFieldName, fallbackFieldName = null }) {
if (item[resultFieldName] !== undefined) {
return item[resultFieldName]
}
if (fallbackFieldName !== null) {
return item[fallbackFieldName]
}
return undefined
}
function getFieldTitle({ dataSource, $registry, series }) {
const resultFieldName = `${series.fieldName}_${series.aggregationType}`
const resultField = dataSource.schema.items.properties[resultFieldName]
return (
getServiceType({ dataSource, $registry })?.getSchemaPropertyDisplayName(
dataSource,
resultFieldName
) || resultField?.title
)
}
function getLabel({ dataSource, $registry, series }) {
const label = getAggregationTitle($registry, series.aggregationType)
const fieldTitle = getFieldTitle({ dataSource, $registry, series })
if (fieldTitle) {
return `${fieldTitle} (${label})`
}
return label
}
function getGroupByValue({
dataSource,
$registry,
$t,
fieldName,
resultFieldName,
item,
}) {
const serializedField = dataSource.context_data.fields[fieldName]
const fieldType = serializedField.type
const value = getResultValue({
item,
resultFieldName,
fallbackFieldName: fieldName,
})
if (value === 'OTHER_VALUES') {
return $t('chart.other')
}
if ($registry.exists('chartFieldFormatting', fieldType)) {
const fieldFormatter = $registry.get('chartFieldFormatting', fieldType)
return fieldFormatter.formatGroupByFieldValue(serializedField, value)
}
if (value === true) {
return $t('chart.true')
}
if (value === false) {
return $t('chart.false')
}
return value ?? ''
}
function getSeriesColors() {
return getBaseColors().map((color) => {
return {
backgroundColor: color,
borderColor: color,
hoverBackgroundColor: color,
}
})
}
function getValuesColors() {
return colorPalette.map((palette) => {
return [
palette[4].color,
palette[6].color,
palette[8].color,
palette[0].color,
palette[2].color,
palette[9].color,
palette[7].color,
palette[5].color,
palette[3].color,
palette[1].color,
]
})
}
function getChartColorsSeriesOrValues({ colorSeries, seriesIndex }) {
if (colorSeries) {
return getSeriesColors()[seriesIndex]
} else {
return {
backgroundColor: getValuesColors()[seriesIndex],
}
}
}
function getChartDataGrouping({
dataSource,
results,
seriesConfig,
$registry,
$t,
colorSeries,
}) {
const groupByFieldId = dataSource.aggregation_group_bys[0].field_id
const primaryField = Object.values(dataSource.schema.items.properties).find(
(item) => item.metadata?.primary === true
)
const labels = results.map((item) => {
const groupByFieldName = `field_${groupByFieldId}`
const groupByResultName = getResultPropertyName({
dataSource,
$registry,
propertyName: groupByFieldName,
})
if (
hasResultValue({
item,
resultFieldName: groupByResultName,
fallbackFieldName: groupByFieldName,
})
) {
return getGroupByValue({
dataSource,
$registry,
$t,
fieldName: groupByFieldName,
resultFieldName: groupByResultName,
item,
})
}
const primaryFieldName = `field_${primaryField.metadata.id}`
const primaryResultName = getResultPropertyName({
dataSource,
$registry,
propertyName: primaryFieldName,
})
return getGroupByValue({
dataSource,
$registry,
$t,
fieldName: primaryFieldName,
resultFieldName: primaryResultName,
item,
})
})
const datasets = []
for (const [index, series] of getChartSeries(dataSource).entries()) {
const technicalResultFieldName = `${series.fieldName}_${series.aggregationType}`
const resultFieldName = getResultPropertyName({
dataSource,
$registry,
propertyName: technicalResultFieldName,
})
const seriesData = results.map((item) => {
return getResultValue({
item,
resultFieldName,
fallbackFieldName: technicalResultFieldName,
})
})
const label = getLabel({ dataSource, $registry, series })
const individualSeriesConfig = getIndividualSeriesConfig(
seriesConfig,
series.id
)
datasets.push({
type:
convertChartJsType(individualSeriesConfig.series_chart_type) || 'bar',
data: seriesData,
label,
...getChartColorsSeriesOrValues({ colorSeries, seriesIndex: index }),
})
}
return {
labels,
datasets,
}
}
function getChartDataNoGrouping({
dataSource,
results,
seriesConfig,
$registry,
firstChartType,
}) {
const result = results[0] || {}
if (['pie', 'doughnut'].includes(firstChartType)) {
const labels = []
const data = []
for (const series of getChartSeries(dataSource)) {
const technicalResultFieldName = `${series.fieldName}_${series.aggregationType}`
const resultFieldName = getResultPropertyName({
dataSource,
$registry,
propertyName: technicalResultFieldName,
})
labels.push(getLabel({ dataSource, $registry, series }))
data.push(
getResultValue({
item: result,
resultFieldName,
fallbackFieldName: technicalResultFieldName,
})
)
}
return {
labels,
datasets: [
{
type: firstChartType,
data,
backgroundColor: getValuesColors()[0],
},
],
}
}
const labels = ['']
const datasets = []
for (const [index, series] of getChartSeries(dataSource).entries()) {
const technicalResultFieldName = `${series.fieldName}_${series.aggregationType}`
const resultFieldName = getResultPropertyName({
dataSource,
$registry,
propertyName: technicalResultFieldName,
})
const seriesData = [
getResultValue({
item: result,
resultFieldName,
fallbackFieldName: technicalResultFieldName,
}),
]
const label = getLabel({ dataSource, $registry, series })
const individualSeriesConfig = getIndividualSeriesConfig(
seriesConfig,
series.id
)
datasets.push({
type:
convertChartJsType(individualSeriesConfig.series_chart_type) || 'bar',
data: seriesData,
label,
...getSeriesColors()[index],
})
}
return {
labels,
datasets,
}
}
export function getDashboardChartData({
dataSource,
dataSourceData,
seriesConfig,
$registry,
$t,
}) {
const results = dataSourceData?.results
if (!results) {
return {
datasets: [],
}
}
const firstSeriesConfig = getIndividualSeriesConfig(
seriesConfig,
getChartSeries(dataSource)[0]?.id
)
const firstChartType = convertChartJsType(firstSeriesConfig.series_chart_type)
const colorSeries = !['pie', 'doughnut'].includes(firstChartType)
if (!dataSource.aggregation_group_bys?.length) {
return getChartDataNoGrouping({
dataSource,
results,
seriesConfig,
$registry,
firstChartType,
})
}
return getChartDataGrouping({
dataSource,
results,
seriesConfig,
$registry,
$t,
colorSeries,
})
}
@@ -1,464 +0,0 @@
<template>
<component
:is="chartComponent"
v-if="hasChartData"
id="chart-id"
:key="chartRenderKey"
:options="chartOptions"
:data="chartData"
class="chart"
/>
<div v-else class="chart__no-data">
<span class="chart__no-data-dashed-line"></span>
<span class="chart__no-data-dashed-line"></span>
<span class="chart__no-data-dashed-line"></span>
<span class="chart__no-data-dashed-line"></span>
<span class="chart__no-data-dashed-line"></span>
<span class="chart__no-data-plain-line"></span>
</div>
</template>
<script>
import { colorPalette, getBaseColors } from '@baserow/modules/core/utils/colors'
import { Bar, Pie } from 'vue-chartjs'
import {
Chart as ChartJS,
ArcElement,
LineElement,
BarElement,
PointElement,
BarController,
BubbleController,
DoughnutController,
LineController,
PieController,
PolarAreaController,
RadarController,
ScatterController,
CategoryScale,
LinearScale,
LogarithmicScale,
RadialLinearScale,
TimeScale,
TimeSeriesScale,
Decimation,
Filler,
Legend,
Title,
Tooltip,
SubTitle,
} from 'chart.js'
ChartJS.register(
ArcElement,
LineElement,
BarElement,
PointElement,
BarController,
BubbleController,
DoughnutController,
LineController,
PieController,
PolarAreaController,
RadarController,
ScatterController,
CategoryScale,
LinearScale,
LogarithmicScale,
RadialLinearScale,
TimeScale,
TimeSeriesScale,
Decimation,
Filler,
Legend,
Title,
Tooltip,
SubTitle
)
export default {
name: 'Chart',
components: { Bar, Pie },
emits: ['rendered'],
props: {
dataSource: {
type: Object,
required: true,
},
dataSourceData: {
type: Object,
required: true,
},
seriesConfig: {
type: Array,
required: true,
},
},
mounted() {
this.emitRendered()
},
updated() {
this.emitRendered()
},
computed: {
chartComponent() {
if (this.chartSeries.length > 0) {
const firstSeriesConfig = this.getIndividualSeriesConfig(
this.chartSeries[0].id
)
const chartType = this.convertChartJsType(
firstSeriesConfig.series_chart_type
)
if (['pie', 'doughnut'].includes(chartType)) {
return 'Pie'
}
}
return 'Bar'
},
colorSeries() {
return this.chartComponent === 'Bar'
},
chartOptions() {
return {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: {
display: true,
align: 'start',
position: 'bottom',
labels: {
usePointStyle: true,
boxWidth: 14,
pointStyle: 'circle',
padding: 20,
generateLabels: function (chart) {
if (chart.config.type === 'bar') {
return Legend.defaults.labels.generateLabels(chart)
} else {
const original =
ChartJS.overrides.pie.plugins.legend.labels.generateLabels
if (chart.data.datasets.length <= 1) {
return original(chart)
}
const originalLabels = original(chart)
const datasetColors = chart.data.datasets.map(function (e) {
return e.backgroundColor
})
let datasetIndex = 0
const newLabels = []
for (const dataset of chart.data.datasets) {
originalLabels.forEach((label) => {
const newLabel = JSON.parse(JSON.stringify(label))
if (label.text) {
newLabel.text = `${label.text} - ${dataset.label}`
} else {
newLabel.text = dataset.label
}
newLabel.fillStyle =
datasetColors[datasetIndex]?.[label.index % 10] ||
label.fillStyle
newLabels.push(newLabel)
})
datasetIndex += 1
}
return newLabels
}
},
},
},
tooltip: {
backgroundColor: '#202128',
padding: 10,
bodyFont: {
size: 12,
},
titleFont: {
size: 12,
},
},
},
elements: {
bar: {
borderRadius: {
topLeft: 4,
topRight: 4,
bottomLeft: 0,
bottomRight: 0,
},
borderWidth: 1,
borderColor: '#5190ef',
backgroundColor: '#5190ef',
hoverBackgroundColor: '#5190ef',
},
},
}
},
results() {
return this.dataSourceData.results
},
hasGrouping() {
return (this.dataSource.aggregation_group_bys || []).length > 0
},
chartData() {
if (!this.results) {
return {
datasets: [],
}
}
if (!this.hasGrouping) {
return this.chartDataNoGrouping
}
return this.chartDataGrouping
},
hasChartData() {
return this.chartData.datasets.length > 0
},
chartRenderKey() {
return `${this.chartComponent}-${JSON.stringify(this.chartData)}`
},
serviceType() {
if (!this.dataSource.type) {
return null
}
return this.$registry.get('service', this.dataSource.type)
},
chartDataGrouping() {
const groupByFieldId = this.dataSource.aggregation_group_bys[0].field_id
const primaryField = Object.values(
this.dataSource.schema.items.properties
).find((item) => item.metadata?.primary === true)
const labels = this.results.map((item) => {
const groupByFieldName = `field_${groupByFieldId}`
const groupByResultName = this.getResultPropertyName(groupByFieldName)
if (this.hasResultValue(item, groupByResultName, groupByFieldName)) {
return this.getGroupByValue(groupByFieldName, groupByResultName, item)
}
const primaryFieldName = `field_${primaryField.metadata.id}`
const primaryResultName = this.getResultPropertyName(primaryFieldName)
return this.getGroupByValue(primaryFieldName, primaryResultName, item)
})
const datasets = []
for (const [index, series] of this.chartSeries.entries()) {
const technicalResultFieldName = `${series.fieldName}_${series.aggregationType}`
const resultFieldName = this.getResultPropertyName(
technicalResultFieldName
)
const seriesData = this.results.map((item) => {
return this.getResultValue(
item,
resultFieldName,
technicalResultFieldName
)
})
const label = this.getLabel(series)
const seriesConfig = this.getIndividualSeriesConfig(series.id)
datasets.push({
type:
this.convertChartJsType(seriesConfig.series_chart_type) || 'bar',
data: seriesData,
label,
...this.chartColorsSeriesOrValues(index),
})
}
return {
labels,
datasets,
}
},
chartDataNoGrouping() {
const result = this.results[0] || {}
if (this.chartComponent === 'Pie') {
const labels = []
const data = []
for (const series of this.chartSeries) {
const technicalResultFieldName = `${series.fieldName}_${series.aggregationType}`
const resultFieldName = this.getResultPropertyName(
technicalResultFieldName
)
labels.push(this.getLabel(series))
data.push(
this.getResultValue(
result,
resultFieldName,
technicalResultFieldName
)
)
}
return {
labels,
datasets: [
{
data,
backgroundColor: this.valuesColors[0],
},
],
}
}
const labels = ['']
const datasets = []
for (const [index, series] of this.chartSeries.entries()) {
const technicalResultFieldName = `${series.fieldName}_${series.aggregationType}`
const resultFieldName = this.getResultPropertyName(
technicalResultFieldName
)
const seriesData = [
this.getResultValue(
result,
resultFieldName,
technicalResultFieldName
),
]
const label = this.getLabel(series)
const seriesConfig = this.getIndividualSeriesConfig(series.id)
datasets.push({
type:
this.convertChartJsType(seriesConfig.series_chart_type) || 'bar',
data: seriesData,
label,
...this.seriesColors[index],
})
}
return {
labels,
datasets,
}
},
chartSeries() {
return this.dataSource.aggregation_series.map((item) => {
return {
id: item.id,
fieldId: item.field_id,
fieldName: `field_${item.field_id}`,
aggregationType: item.aggregation_type,
}
})
},
seriesColors() {
return getBaseColors().map((color) => {
return {
backgroundColor: color,
borderColor: color,
hoverBackgroundColor: color,
}
})
},
valuesColors() {
return colorPalette.map((palette) => {
return [
palette[4].color,
palette[6].color,
palette[8].color,
palette[0].color,
palette[2].color,
palette[9].color,
palette[7].color,
palette[5].color,
palette[3].color,
palette[1].color,
]
})
},
},
methods: {
chartColorsSeriesOrValues(seriesIndex) {
if (this.colorSeries) {
return this.seriesColors[seriesIndex]
} else {
return {
backgroundColor: this.valuesColors[seriesIndex],
}
}
},
convertChartJsType(chartType) {
if (!chartType) {
return null
}
return chartType.toLowerCase()
},
getAggregationTitle(aggregationType) {
return this.$registry.get('groupedAggregation', aggregationType).getName()
},
getResultField(series) {
const resultFieldName = `${series.fieldName}_${series.aggregationType}`
return this.dataSource.schema.items.properties[resultFieldName]
},
getFieldTitle(series) {
const resultFieldName = `${series.fieldName}_${series.aggregationType}`
return (
this.serviceType?.getSchemaPropertyDisplayName(
this.dataSource,
resultFieldName
) || this.getResultField(series)?.title
)
},
getLabel(series) {
const label = this.getAggregationTitle(series.aggregationType)
const fieldTitle = this.getFieldTitle(series)
if (fieldTitle) {
return `${fieldTitle} (${label})`
}
return label
},
getResultPropertyName(propertyName) {
return this.serviceType.getResultPropertyName(
this.dataSource,
propertyName
)
},
hasResultValue(item, resultFieldName, fallbackFieldName = null) {
return (
item[resultFieldName] !== undefined ||
(fallbackFieldName !== null && item[fallbackFieldName] !== undefined)
)
},
getResultValue(item, resultFieldName, fallbackFieldName = null) {
if (item[resultFieldName] !== undefined) {
return item[resultFieldName]
}
if (fallbackFieldName !== null) {
return item[fallbackFieldName]
}
return undefined
},
getGroupByValue(fieldName, resultFieldName, item) {
const serializedField = this.dataSource.context_data.fields[fieldName]
const fieldType = serializedField.type
const value = this.getResultValue(item, resultFieldName, fieldName)
if (value === 'OTHER_VALUES') {
return this.$t('chart.other')
}
if (this.$registry.exists('chartFieldFormatting', fieldType)) {
const fieldFormatter = this.$registry.get(
'chartFieldFormatting',
fieldType
)
return fieldFormatter.formatGroupByFieldValue(serializedField, value)
}
if (value === true) {
return this.$t('chart.true')
}
if (value === false) {
return this.$t('chart.false')
}
return value ?? ''
},
getIndividualSeriesConfig(seriesId) {
return this.seriesConfig.find((item) => item.series_id === seriesId) || {}
},
emitRendered() {
this.$nextTick(() => {
this.$emit('rendered')
})
},
},
}
</script>
@@ -50,9 +50,7 @@
<Chart
v-if="chartReady"
:key="chartKey"
:data-source="dataSource"
:data-source-data="dataForDataSource"
:series-config="widget.series_config"
:data="chartData"
@rendered="chartRendered = true"
>
</Chart>
@@ -65,7 +63,8 @@
<script>
import WidgetContextMenu from '@baserow/modules/dashboard/components/widget/WidgetContextMenu'
import Chart from '@baserow_premium/dashboard/components/widget/Chart'
import Chart from '@baserow_premium/components/Chart'
import { getDashboardChartData } from '@baserow_premium/dashboard/chartData'
export default {
name: 'ChartWidget',
@@ -126,6 +125,15 @@ export default {
this.dataForDataSource?.results || []
)}`
},
chartData() {
return getDashboardChartData({
dataSource: this.dataSource || {},
dataSourceData: this.dataForDataSource,
seriesConfig: this.widget.series_config || [],
$registry: this.$registry,
$t: (...args) => this.$t(...args),
})
},
isEditMode() {
return this.$store.getters[
`${this.storePrefix}dashboardApplication/isEditMode`
@@ -50,9 +50,7 @@
<Chart
v-if="chartReady"
:key="chartKey"
:data-source="dataSource"
:data-source-data="dataForDataSource"
:series-config="widget.series_config"
:data="chartData"
@rendered="chartRendered = true"
>
</Chart>
@@ -65,7 +63,8 @@
<script>
import WidgetContextMenu from '@baserow/modules/dashboard/components/widget/WidgetContextMenu'
import Chart from '@baserow_premium/dashboard/components/widget/Chart'
import Chart from '@baserow_premium/components/Chart'
import { getDashboardChartData } from '@baserow_premium/dashboard/chartData'
export default {
name: 'PieChartWidget',
@@ -126,6 +125,15 @@ export default {
this.dataForDataSource?.results || []
)}`
},
chartData() {
return getDashboardChartData({
dataSource: this.dataSource || {},
dataSourceData: this.dataForDataSource,
seriesConfig: this.widget.series_config || [],
$registry: this.$registry,
$t: (...args) => this.$t(...args),
})
},
isEditMode() {
return this.$store.getters[
`${this.storePrefix}dashboardApplication/isEditMode`
@@ -2,7 +2,7 @@ import { WidgetType } from '@baserow/modules/dashboard/widgetTypes'
import ChartWidget from '@baserow_premium/dashboard/components/widget/ChartWidget'
import PieChartWidget from '@baserow_premium/dashboard/components/widget/PieChartWidget'
import ChartWidgetSettings from '@baserow_premium/dashboard/components/widget/ChartWidgetSettings'
import ChartBarWidgetSvg from '@baserow_premium/assets/images/dashboard/widgets/chart_widget_bar.svg?url'
import ChartBarWidgetSvg from '@baserow_premium/assets/images/chart_bar.svg?url'
import ChartLineWidgetSvg from '@baserow_premium/assets/images/dashboard/widgets/chart_widget_line.svg?url'
import ChartPieWidgetSvg from '@baserow_premium/assets/images/dashboard/widgets/chart_widget_pie.svg?url'
import ChartDonutWidgetSvg from '@baserow_premium/assets/images/dashboard/widgets/chart_widget_donut.svg?url'
@@ -76,7 +76,7 @@ export class LocalBaserowGroupedAggregateRowsServiceType extends DataSourceLocal
}
parseRecordId(value) {
return value
return value === '' ? null : value
}
getRecordIdDataType(service) {
@@ -149,6 +149,13 @@ export class LocalBaserowGroupedAggregateRowsServiceType extends DataSourceLocal
if (incompleteSeries) {
return this.app.$i18n.t('serviceType.errorIncompleteAggregationSeries')
}
const configuredFieldsInError = [
...service.aggregation_series,
...(service.aggregation_group_bys || []),
].some((item) => item.trashed)
if (configuredFieldsInError) {
return this.app.$i18n.t('serviceType.errorTrashedAggregationField')
}
const filtersInError = service.filters?.some((filter) => filter.trashed)
if (filtersInError) {
return this.app.$i18n.t('serviceType.errorFilterInError')
@@ -393,7 +393,8 @@
"localBaserowGroupedAggregateRows": "Group and summarize rows",
"localBaserowGroupedAggregateRowsDescription": "Group rows from a Baserow table and calculate summaries.",
"errorNoAggregationSeriesDefined": "No summary series defined.",
"errorIncompleteAggregationSeries": "One or more summary series are incomplete."
"errorIncompleteAggregationSeries": "One or more summary series are incomplete.",
"errorTrashedAggregationField": "At least one configured field has been trashed."
},
"aggregationSeriesForm": {
"aggregationFieldLabel": "Field",
@@ -0,0 +1,7 @@
export function convertChartJsType(chartType) {
if (!chartType) {
return null
}
return chartType.toLowerCase()
}
@@ -1,5 +1,6 @@
import { PremiumTestApp } from '@baserow_premium_test/helpers/premiumTestApp'
import Chart from '@baserow_premium/dashboard/components/widget/Chart'
import Chart from '@baserow_premium/components/Chart'
import { getDashboardChartData } from '@baserow_premium/dashboard/chartData'
describe('Premium dashboard Chart component', () => {
let testApp = null
@@ -12,44 +13,60 @@ describe('Premium dashboard Chart component', () => {
await testApp.afterEach()
})
const mountComponent = async ({
dataSourceData,
dataSource = {},
seriesConfig = [{ series_id: 1, series_chart_type: 'BAR' }],
}) => {
return await testApp.mount(Chart, {
props: {
dataSource: {
type: 'local_baserow_grouped_aggregate_rows',
aggregation_series: [
{ id: 1, field_id: 10, aggregation_type: 'sum' },
],
aggregation_group_bys: [],
schema: {
items: {
properties: {
field_10_sum: {
title: 'Amount sum',
metadata: {
display_name: 'Amount sum',
source_field: {
display_name: 'Amount',
},
aggregation: {
type: 'sum',
},
},
},
const dataSource = (overrides = {}) => ({
type: 'local_baserow_grouped_aggregate_rows',
aggregation_series: [{ id: 1, field_id: 10, aggregation_type: 'sum' }],
aggregation_group_bys: [],
schema: {
items: {
properties: {
field_10_sum: {
title: 'Amount sum',
metadata: {
display_name: 'Amount sum',
source_field: {
display_name: 'Amount',
},
aggregation: {
type: 'sum',
},
},
},
context_data: {
fields: {},
},
...dataSource,
},
dataSourceData,
seriesConfig,
},
},
context_data: {
fields: {},
},
...overrides,
})
const chartData = ({
source = dataSource(),
data = {},
seriesConfig = [{ series_id: 1, series_chart_type: 'BAR' }],
} = {}) => {
return getDashboardChartData({
dataSource: source,
dataSourceData: {
results: [
{
field_10_sum: 20,
},
],
...data,
},
seriesConfig,
$registry: testApp.$registry,
$t: (key) => key,
})
}
const mountComponent = async ({ data, options = null }) => {
return await testApp.mount(Chart, {
props: {
data,
options,
},
global: {
stubs: {
@@ -68,9 +85,9 @@ describe('Premium dashboard Chart component', () => {
})
}
test('renders chart data from grouped aggregation results', async () => {
const wrapper = await mountComponent({
dataSourceData: {
test('builds chart data from grouped aggregation results', async () => {
const data = chartData({
data: {
results: [
{
'Amount sum': 20,
@@ -79,17 +96,15 @@ describe('Premium dashboard Chart component', () => {
},
})
expect(wrapper.find('.chart__no-data').exists()).toBe(false)
const chartData = wrapper.findComponent({ name: 'Bar' }).props('data')
expect(chartData.labels).toEqual([''])
expect(chartData.datasets[0].type).toBe('bar')
expect(chartData.datasets[0].data).toEqual([20])
expect(chartData.datasets[0].label).toBe('Amount (viewAggregationType.sum)')
expect(data.labels).toEqual([''])
expect(data.datasets[0].type).toBe('bar')
expect(data.datasets[0].data).toEqual([20])
expect(data.datasets[0].label).toBe('Amount (viewAggregationType.sum)')
})
test('renders chart data using source field metadata from result fields', async () => {
const wrapper = await mountComponent({
dataSource: {
test('builds chart data when the grouped aggregation schema only exposes result fields', async () => {
const data = chartData({
source: dataSource({
schema: {
items: {
properties: {
@@ -108,8 +123,8 @@ describe('Premium dashboard Chart component', () => {
},
},
},
},
dataSourceData: {
}),
data: {
results: [
{
'Amount sum': 20,
@@ -118,17 +133,15 @@ describe('Premium dashboard Chart component', () => {
},
})
expect(wrapper.find('.chart__no-data').exists()).toBe(false)
const chartData = wrapper.findComponent({ name: 'Bar' }).props('data')
expect(chartData.labels).toEqual([''])
expect(chartData.datasets[0].type).toBe('bar')
expect(chartData.datasets[0].data).toEqual([20])
expect(chartData.datasets[0].label).toBe('Amount (viewAggregationType.sum)')
expect(data.labels).toEqual([''])
expect(data.datasets[0].type).toBe('bar')
expect(data.datasets[0].data).toEqual([20])
expect(data.datasets[0].label).toBe('Amount (viewAggregationType.sum)')
})
test('renders chart label from schema property display name when source field metadata is missing', async () => {
const wrapper = await mountComponent({
dataSource: {
test('builds chart label from schema property display name when source field metadata is missing', async () => {
const data = chartData({
source: dataSource({
schema: {
items: {
properties: {
@@ -141,8 +154,8 @@ describe('Premium dashboard Chart component', () => {
},
},
},
},
dataSourceData: {
}),
data: {
results: [
{
'Amount total': 20,
@@ -151,18 +164,17 @@ describe('Premium dashboard Chart component', () => {
},
})
const chartData = wrapper.findComponent({ name: 'Bar' }).props('data')
expect(chartData.datasets[0].label).toBe(
expect(data.datasets[0].label).toBe(
'Amount total (viewAggregationType.sum)'
)
})
test('renders no-grouping chart data as a single-row list when group config is missing', async () => {
const wrapper = await mountComponent({
dataSource: {
test('builds no-grouping chart data as a single-row list when group config is missing', async () => {
const data = chartData({
source: dataSource({
aggregation_group_bys: undefined,
},
dataSourceData: {
}),
data: {
results: [
{
'Amount sum': 20,
@@ -171,16 +183,37 @@ describe('Premium dashboard Chart component', () => {
},
})
expect(wrapper.find('.chart__no-data').exists()).toBe(false)
const chartData = wrapper.findComponent({ name: 'Bar' }).props('data')
expect(chartData.labels).toEqual([''])
expect(chartData.datasets[0].type).toBe('bar')
expect(chartData.datasets[0].data).toEqual([20])
expect(data.labels).toEqual([''])
expect(data.datasets[0].type).toBe('bar')
expect(data.datasets[0].data).toEqual([20])
})
test('renders no-grouping pie chart data as series slices', async () => {
test('renders chart data with merged options', async () => {
const wrapper = await mountComponent({
dataSource: {
data: {
labels: ['A'],
datasets: [{ type: 'line', label: 'Series', data: [10] }],
},
options: {
plugins: {
legend: {
labels: {
color: '#ff0000',
},
},
},
},
})
const chart = wrapper.findComponent({ name: 'Bar' })
expect(chart.props('data').labels).toEqual(['A'])
expect(chart.props('options').plugins.legend.labels.color).toBe('#ff0000')
expect(chart.props('options').plugins.legend.position).toBe('bottom')
})
test('builds no-grouping pie chart data as series slices', async () => {
const data = chartData({
source: dataSource({
aggregation_series: [
{ id: 1, field_id: 10, aggregation_type: 'sum' },
{ id: 2, field_id: 12, aggregation_type: 'sum' },
@@ -216,8 +249,8 @@ describe('Premium dashboard Chart component', () => {
},
},
},
},
dataSourceData: {
}),
data: {
results: [
{
'Amount sum': 20,
@@ -231,19 +264,19 @@ describe('Premium dashboard Chart component', () => {
],
})
const chartData = wrapper.findComponent({ name: 'Pie' }).props('data')
expect(chartData.labels).toEqual([
expect(data.labels).toEqual([
'Amount (viewAggregationType.sum)',
'Revenue (viewAggregationType.sum)',
])
expect(chartData.datasets).toHaveLength(1)
expect(chartData.datasets[0].data).toEqual([20, 10])
expect(chartData.datasets[0].backgroundColor).toBeInstanceOf(Array)
expect(data.datasets).toHaveLength(1)
expect(data.datasets[0].type).toBe('pie')
expect(data.datasets[0].data).toEqual([20, 10])
expect(data.datasets[0].backgroundColor).toBeInstanceOf(Array)
})
test('renders grouped chart data from human result property names', async () => {
const wrapper = await mountComponent({
dataSource: {
test('builds grouped chart data from human result property names', async () => {
const data = chartData({
source: dataSource({
aggregation_group_bys: [{ field_id: 11 }],
schema: {
items: {
@@ -277,8 +310,8 @@ describe('Premium dashboard Chart component', () => {
},
},
},
},
dataSourceData: {
}),
data: {
results: [
{
'Amount sum': 20,
@@ -288,14 +321,13 @@ describe('Premium dashboard Chart component', () => {
},
})
const chartData = wrapper.findComponent({ name: 'Bar' }).props('data')
expect(chartData.labels).toEqual(['Hardware'])
expect(chartData.datasets[0].data).toEqual([20])
expect(data.labels).toEqual(['Hardware'])
expect(data.datasets[0].data).toEqual([20])
})
test('renders grouped single select labels from human result property names', async () => {
const wrapper = await mountComponent({
dataSource: {
test('builds grouped single select labels from human result property names', async () => {
const data = chartData({
source: dataSource({
aggregation_group_bys: [{ field_id: 11 }],
schema: {
items: {
@@ -333,8 +365,8 @@ describe('Premium dashboard Chart component', () => {
},
},
},
},
dataSourceData: {
}),
data: {
results: [
{
'Amount sum': 20,
@@ -348,29 +380,19 @@ describe('Premium dashboard Chart component', () => {
},
})
const chartData = wrapper.findComponent({ name: 'Bar' }).props('data')
expect(chartData.labels).toEqual(['Hardware', 'Software'])
expect(chartData.datasets[0].data).toEqual([20, 10])
expect(data.labels).toEqual(['Hardware', 'Software'])
expect(data.datasets[0].data).toEqual([20, 10])
})
test('renders chart data from technical result property names as a fallback', async () => {
const wrapper = await mountComponent({
dataSourceData: {
results: [
{
field_10_sum: 20,
},
],
},
})
test('builds chart data from technical result property names as a fallback', async () => {
const data = chartData()
const chartData = wrapper.findComponent({ name: 'Bar' }).props('data')
expect(chartData.datasets[0].data).toEqual([20])
expect(data.datasets[0].data).toEqual([20])
})
test('renders grouped labels from technical group-by property names as a fallback', async () => {
const wrapper = await mountComponent({
dataSource: {
test('builds grouped labels from technical group-by property names as a fallback', async () => {
const data = chartData({
source: dataSource({
aggregation_group_bys: [{ field_id: 11 }],
schema: {
items: {
@@ -415,8 +437,8 @@ describe('Premium dashboard Chart component', () => {
},
},
},
},
dataSourceData: {
}),
data: {
results: [
{
'Amount sum': 20,
@@ -427,8 +449,7 @@ describe('Premium dashboard Chart component', () => {
},
})
const chartData = wrapper.findComponent({ name: 'Bar' }).props('data')
expect(chartData.labels).toEqual(['Hardware'])
expect(chartData.datasets[0].data).toEqual([20])
expect(data.labels).toEqual(['Hardware'])
expect(data.datasets[0].data).toEqual([20])
})
})
@@ -14,6 +14,8 @@ describe('Premium integrations service types', () => {
expect(serviceType.supportsPagination).toBe(false)
expect(serviceType.getIdProperty()).toBe('id')
expect(serviceType.parseRecordId('Selected')).toBe('Selected')
expect(serviceType.parseRecordId('')).toBeNull()
expect(serviceType.parseRecordId('0')).toBe('0')
expect(serviceType.getRecordNameFromId({}, 'Selected')).toBe('Selected')
expect(serviceType.formComponent).toBeDefined()
expect(serviceType.integrationType.getType()).toBe('local_baserow')
@@ -332,6 +334,32 @@ describe('Premium integrations service types', () => {
expect(error).toBeTruthy()
})
test.each(['aggregation_series', 'aggregation_group_bys'])(
'LocalBaserowGroupedAggregateRowsServiceType reports a trashed field in %s',
(configurationKey) => {
const serviceType = useNuxtApp().$registry.get(
'service',
'local_baserow_grouped_aggregate_rows'
)
const service = {
table_id: 1,
aggregation_series: [
{ field_id: 1, aggregation_type: 'sum', trashed: false },
],
aggregation_group_bys: [],
filters: [],
}
service[configurationKey][0] = {
...service[configurationKey][0],
trashed: true,
}
expect(serviceType.getErrorMessage({ service })).toBe(
'serviceType.errorTrashedAggregationField'
)
}
)
test('LocalBaserowGroupedAggregateRowsServiceType resets configuration on table change', () => {
const testApp = useNuxtApp()
const serviceType = testApp.$registry.get(
@@ -154,7 +154,7 @@ export default {
this.element.style_background_color,
this.colorVariables
)
: 'none',
: 'transparent',
'--element-background-image':
this.element.style_background_file !== null
? `url(${this.element.style_background_file.url})`
@@ -0,0 +1,41 @@
import { describe, expect, test, vi } from 'vitest'
import PageElement from '@baserow/modules/builder/components/page/PageElement'
import { BACKGROUND_TYPES } from '@baserow/modules/builder/enums'
describe('PageElement', () => {
const getElementStyles = (styleBackground, styleBackgroundColor = null) => {
const context = {
element: {
style_background: styleBackground,
style_background_color: styleBackgroundColor,
style_background_file: null,
},
colorVariables: {},
border: vi.fn(() => 'none'),
resolveColor: vi.fn(() => '#123456'),
}
return {
context,
styles: PageElement.computed.elementStyles.call(context),
}
}
test('uses transparent as the background color when none is configured', () => {
const { context, styles } = getElementStyles(BACKGROUND_TYPES.NONE)
expect(styles['--element-background-color']).toBe('transparent')
expect(context.resolveColor).not.toHaveBeenCalled()
})
test('uses the resolved configured background color', () => {
const { context, styles } = getElementStyles(
BACKGROUND_TYPES.COLOR,
'primary'
)
expect(styles['--element-background-color']).toBe('#123456')
expect(context.resolveColor).toHaveBeenCalledWith('primary', {})
})
})