Sisense Community logo
    • Community Feedback
    • Chapters
    • Events
    • Forums
      • Help and How To
      • Product Feedback Forum
      • Strategy & Use Cases
    • Blogs
    • KB Docs
      • KB Docs
      • Add-Ons & Plug-Ins
      • APIs
      • Best Practices
      • Blox
      • CDT
      • Cloud Managed Service
      • Data Models
      • Data Sources
      • Embedding Analytics
      • How-Tos & FAQs
      • Onboarding
      • PySisense
      • Security
      • Sisense Administration
      • Sisense Intelligence & AI
      • Troubleshooting
      • Widget & Dashboard Scripts
    • Support
    • Learning
      • Sisense Academy: Free Courses and Certifications
      • Official Developer Documentation
      • Official Product Documentation
      • Official Sisense Youtube Channel
      • Sisense Compose SDK Playground
    • Use Case Gallery
    All PostsDiscussionsBlogsIdeasQuestions
    Leaderboards
    •                    
    •                    
    •                    
    •                    
    •                    
    •                    
    •                    
    •                    
    •                    
    •                    
    •                    
    •                    
    •                    
    •                    
    •                    
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   
    Discussions
    • TagsChevronRightIcon
    Configuration & Design Tips
    • Blog banner
      • Embedding AnalyticsChevronRightIcon

      Using ComposeSDK Planning Documents: Guiding an AI Coding Assistant with a Written Planning Document

                                                                       

      Using ComposeSDK Planning Documents: Guiding an AI Coding Assistant with a Written Planning Document From Zero to ComposeSDK describes building a ComposeSDK application one prompt at a time, and that approach scales well. Adding one page, one widget, one filter at a time, each described on its own and confirmed before moving to the next, works for a small dashboard and for a larger one, provided each addition is independent and the person directing the assistant is already thinking through the pieces one at a time. This article describes a different way of working with an AI coding assistant. It is not strictly better than the approach in that article, simply different. Rather than prompting through a ComposeSDK build step by step, the assistant drafts a written plan first. That plan gets revised over a few rounds while nothing has been built yet, and only then does the assistant implement most or all of it in one longer working session. It is a more involved process than the one in From Zero to ComposeSDK, worth using when enough of a project is already decided in advance that writing it down once is less effort than describing it prompt by prompt, not a step every ComposeSDK build needs. Any modern LLM based coding assistant can drive this workflow the same way it drives the one described in From Zero to ComposeSDK . It needs the same two capabilities, editing files in the project folder and running terminal commands. This article mostly describes Claude Code as an example, but nothing about a written planning document is specific to it, and the same steps apply with another agentic editor, a standalone CLI assistant, or a desktop app with terminal access. This article does not cover installing the editor, the assistant, Node, or ComposeSDK itself, and it assumes the setup from From Zero to ComposeSDK is already in place, a scaffolded React project with the ComposeSDK packages installed and a .env file holding the Sisense instance URL and API token. It builds on that setup rather than repeating it. A planning document does not remove the need to review the assistant's work. It moves most of that review earlier, into the document, before the assistant starts writing code against it, rather than after each small step. A plan reviewed carefully before implementation catches a wrong field name or a missing page as a one line edit. The same mistake caught after a long stretch of implementation can require changes in many different places, and costs considerably more time to fix. What goes Into the Planning Document A planning document for a ComposeSDK build works best as a plain markdown file kept in the project, for example plan.md in the project root, rather than something that only exists in the chat history. As a file on disk, it can be opened and edited directly, referenced again in a later session, and it survives a long session's context being condensed in a way that conversation history alone does not. The document does not need a fixed template, but it generally works better when it covers a few things beyond a page and widget list. What the application is for, who uses it, and what habit or decision it supports. Which ComposeSDK flavor the project uses, React, Angular, or Vue, since that decides the package names and component syntax everything else in the plan assumes. The data model involved, referencing the .ts file already generated by the ComposeSDK CLI, or naming the data source if it still needs generating, along with why the fields involved matter to that audience, not just their names. Each page or view and its widgets, specific enough to build from, naming the chart type, the dimensions and measures, and any filters. Interactivity between widgets or pages, such as a filter or a click on one page affecting another. Layout and visual style, to whatever level of detail is already decided, colors, branding, density. Where the Sisense URL and token is and how the assistant checks its own connection without viewing or saving the authentication token, covered in its own section below. A milestone checklist, ordered the way the build should proceed, written as markdown checkboxes so the assistant can mark each one complete as it finishes. Anything explicitly out of scope, so the assistant does not add it unasked while working through a long stretch unsupervised. The checklist carries the most weight during implementation. A long LLM working session eventually has its earlier history summarized, and a agent's summarization keeps only a handful of the most recently read files in full alongside the summary. A checklist file the assistant is instructed to re-open at the start of each milestone stays accurate regardless of how much of the conversation itself has been condensed, because the current state of the build lives in the file rather than in memory of the conversation. Drafting the plan The first cycle is a conversation, not a single prompt. Describing the project and asking for a draft is enough to start. The prompts throughout this article are rough examples of the general tone and type of instruction, not meant to be copied directly. The right wording depends on the specific ComposeSDK application being built. Draft a planning document for a new React ComposeSDK application in this folder, save it as plan.md. It's for the regional sales team, replacing three spreadsheets they currently cross-reference by hand before the weekly pipeline review, built on the Sample ECommerce data model, which mirrors what's in those spreadsheets. Use ComposeSDK's ExecuteQuery function to look at the actual values in a column if that would help, not just the field names in the schema file. The token for authentication is in .env. Cover the purpose, why the data matters to this audience, each page and its filters, any interactivity between pages, a rough visual style, and a milestone checklist. List anything you're unsure of as open questions in its own section rather than guessing. That last instruction matters. An assistant asked to draft a plan will otherwise fill a gap with a guess that sounds reasonable rather than flagging it, and a guess buried in a paragraph of prose is easy to miss on a first read. A dedicated "Open questions" section in the draft is easy to scan and resolve before moving on. Revising the plan across cycles The draft is rarely final on the first pass. Revising it happens either by editing the markdown file directly, or by describing the change and letting the assistant update the file. In plan.md, change the regional breakdown page to a map visualization instead of a bar chart, and add a country filter UI that applies across all pages. Update the milestone checklist to match. Either editing style works, and most planning sessions mix both, a person adjusting a sentence directly while asking the assistant to work out the consequences elsewhere in the document, such as keeping the checklist in sync with a changed page list. As many cycles as needed happen before implementation starts. Nothing has been built yet, so a revision at this stage costs a paragraph, not a refactor. Keeping the connection working while the build runs The plan should note where the Sisense URL and token live, .env , and that the assistant's own read access to it is denied, the setup already covered in From Zero to ComposeSDK. That protection does not need re-explaining here, the plan only needs to point at it. What is worth adding for a longer, less supervised run is two different checks, since they answer different questions. Rotating the token or changing the URL is the only thing that actually requires re-testing whether the assistant can still reach Sisense at all. Reusing the same ComposeSDK CLI command already used to generate the data model file, pointed at a throwaway output path, is a reasonable way to confirm that without the assistant ever seeing the token value, since the script reads .env at run time on its own rather than through a tool call the assistant's file permissions would block. // scripts/check-credentials.mjs // Confirms Sisense credentials still authenticate, without printing // the token. Run with: node --env-file=.env scripts/check-credentials.mjs import { execFileSync } from 'node:child_process'; const url = process.env.VITE_SISENSE_URL; const token = process.env.VITE_SISENSE_TOKEN; try { execFileSync( 'npx', [ '@sisense/sdk-cli', 'get-data-model', '--url', url, '--token', token, '--dataSource', 'Sample ECommerce', '--output', 'scratch/credential-check.ts', ], { stdio: 'ignore' }, ); console.log('Sisense credentials OK'); } catch { console.log('Sisense credential check FAILED'); } This is worth running once after setup, and again only if the plan notes that .env has changed. Running it after an ordinary milestone, like adding a widget, confirms nothing new, since nothing about the credentials changed either. This is for the assistant to run on its own, a person does not need to run it by hand. What the assistant will almost certainly check on its own, once there is a widget to look at, is whether it renders the way the plan describes, and that is a visual check, not a credential check. If the session has a browser automation tool connected, a Playwright MCP server is a common example, the assistant can open the running dev server itself, take a screenshot, and confirm the new chart or page looks right. Asked to verify a milestone and given a way to see the running app, most assistants will reach for exactly this on their own, without needing the mechanism spelled out. Without a connected browser tool, this check still means a person glancing at the running app in a browser, the same as the smoke test described in From Zero to ComposeSDK. If the assistant asks partway through to install a browser automation tool, whether as a yes or no prompt or a plain request, it is usually worth approving. Iterative development goes far better when the assistant can see what its own code produces instead of just describing it. The plan's connection section can state this plainly, without prescribing how. URL and token in .env, read access denied per project settings. Re-run scripts/check-credentials.mjs only if these values change. After each milestone, confirm the change actually renders correctly in the browser. Choosing a permission mode for the implementation run Claude Code, used here as the concrete example, cycles through a few permission modes with Shift+Tab, and the mode in use during implementation determines how often the assistant stops to ask before acting. Manual (the default) asks before every file edit and most shell commands. It suits the planning cycles above, where little is being written yet, but is not practical for a long implementation run, since it interrupts constantly. Accept Edits auto-approves file edits and common filesystem commands, while still asking before other shell commands, such as installing a package or running a build, unless those have already been allow-listed. It is a reasonable default for working through a reviewed plan. Code changes stop interrupting, while a command run for the first time still gets a look. Auto goes further, approving tool calls generally with a background safety check evaluating each action against what was asked, rather than a person reviewing each one. It suits a long stretch of implementation against a plan that has already been reviewed carefully, since there are fewer opportunities to catch a problem as it happens. Bypass Permissions ( --dangerously-skip-permissions at startup) skips prompts almost entirely. It is documented as intended for use inside a container or VM the assistant cannot otherwise damage, not on a developer's own machine. Since the setup this article builds on keeps a live Sisense token in .env on that same machine, this mode is out of scope here. Other LLM's have very similar permission modes. Whichever mode is active, deny rules are checked before any mode grants approval, so the .env protection from From Zero to ComposeSDK stays in effect through Accept Edits and Auto mode as well. Commands already known to be safe and expected by the plan, running the dev server, running tests, regenerating the data model, can be allow-listed directly in .claude/settings.json (or equivalent for your LLM) so they stop prompting even once, while everything else continues to ask. { "permissions": { "allow": [ "Bash(npm run *)", "Bash(npm test *)" ], "deny": [ "Read(./.env)", "Read(./.env.*)" ] } } A Stop hook, configured the same way in settings.json , is a further option worth knowing about. It runs a chosen shell command each time the assistant finishes responding, which can be pointed at the credential check script so it runs automatically after any milestone that touches .env , rather than depending on the assistant remembering the instruction in the plan. The Claude Code hooks documentation is linked below. Other LLM code assistants have similar features. Handing off the finished plan Once the plan reads correctly end to end, implementation itself is one request. Work through plan.md from top to bottom. After finishing each item on the milestone checklist, check it off in the file, confirm the change renders correctly in the browser, and report the result before starting the next item. Re-read plan.md at the start of each milestone rather than relying on memory of earlier parts of this conversation. Stop and ask only when a decision is not covered by the plan. The instruction to re-read the file matters on a long session. It is what keeps the assistant's sense of what is done and what remains accurate even after earlier parts of the conversation have been condensed. Resuming and checking status Because the plan and its checklist live on disk, a new session, or the same session after a break, can pick up where the last one left off. Read plan.md and tell me which milestones are checked off, what remains, and whether any of the finished ones still need a browser check before I can consider them done. This works whether the pause was intentional or the result of the assistant stopping to ask about something the plan did not cover. Example planning document The following is a shortened example of what a finished plan looks like before implementation begins, for a small internal ComposeSDK app. # Regional Sales Pulse *Sisense ComposeSDK Planning Document* ## Purpose Built as a React ComposeSDK application for the regional sales managers who currently pull this picture together from three spreadsheets before the weekly pipeline review. The app should answer, at a glance, whether a region or category is trending up or down. It exists specifically for that meeting, and is meant to make it faster and more informative. ## Data model and what it contains Sample ECommerce (src/models/sample-ecommerce.ts). Revenue and Units are the two figures managers actually watch weekly. Category and Country are the two dimensions they currently cross-reference by hand for trends. Condition (New/Used) does not matter here and should not appear on any page unless someone asks for it later. ## Pages, filters, and interactivity 1. Overview. Revenue and Units by month, column chart. This is the page a manager opens first, so it should load with the current calendar year already selected. 2. Regional Breakdown. Revenue by Country, map visualization. 3. Product Performance. Revenue by Category, ranked bar chart, highest to lowest. Two filters sit at the top of the app and apply across all three pages, a date range defaulting to the last two weeks, and a country selector. Both should be visible without opening a menu. ## Visual style Matches the internal tools intranet look, navy header, white background, no dark mode needed for this audience. Cards with some padding around each chart rather than charts running edge to edge. Nothing more elaborate than that is expected here. ## Connection and verification URL and token in .env, read access denied per project settings. Re-run scripts/check-credentials.mjs only if these values change. After each milestone, confirm the change actually renders correctly in the browser. ## Milestones - [x] Scaffold three page routes with placeholder headers and the shared filters wired to nothing yet - [ ] Overview page with Revenue and Units by month - [ ] Regional Breakdown page with Revenue by Country as a map - [ ] Product Performance page with Category ranked by Revenue - [ ] Shared date range and country filters applied across all three pages - [ ] Navigation between the three pages - [ ] Visual pass matching the style notes above ## Testing Add unit and integration tests where they make sense, and skip them where they don't. Use headless browser screenshots for visual checks, the same way each milestone gets confirmed in the browser. Confirm at least once, early on, that a real query actually returns data, since the credential check script only proves the token authenticates, not that a query returns rows. ## Out of scope No user accounts or role management beyond what Sisense already provides. No PDF export or scheduled email in this version. Condition does not appear anywhere unless a later request asks for it. ## Open questions - Should the country filter support selecting more than one country at once? Left single select for now, since that already matches what the spreadsheets show today. Prompt library Drafting and revising. Draft a planning document for [project description] as a [React/Angular/Vue] ComposeSDK application, saved as plan.md. Cover the purpose, why the data matters, which ComposeSDK flavor it uses, each page and its filters, any interactivity, a rough visual style, and a milestone checklist, with open questions listed separately. Use ExecuteQuery to check the actual values in [columns] before finalizing that page in the plan, not just the field names in the schema file. In plan.md, change [specific details] and update the milestone checklist to match. Review plan.md and flag anything ambiguous enough that you would have to guess during implementation. Connection and verification. Add scripts/check-credentials.mjs as described in plan.md, and note that it only needs to run again if the .env values change. After this milestone, confirm it renders correctly in the browser before checking it off. Settings for a longer run. Add an allow rule to .claude/settings.json (or equivalent for the LLM Code Assistant you or using) for [command], so it stops prompting for that one going forward. Add a Stop hook in settings.json that runs scripts/check-credentials.mjs automatically whenever .env changes. Handoff and resumption. Work through plan.md from top to bottom, checking off each milestone as it's finished, confirming each one in the browser, and re-reading plan.md at the start of the next. Stop only for decisions the plan does not cover. Read plan.md and report which milestones are done, what remains, and which finished ones still need a browser check. Useful links From Zero to ComposeSDK ComposeSDK documentation ComposeSDK ExecuteQuery reference Claude Code permissions documentation Claude Code hooks documentation ComposeSDK Github Monorepo Sisense CSDK Github Skills Examples Sisense MCP Github Server Sisense REST API and authentication documentation A written planning document is worthwhile when a application design and purpose is already decided in enough detail to write down once. A application still being thought out piece by piece is usually still faster to build the direct way, one prompt, one page, one widget at a time.

      Jeremy Friedel
      Jeremy FriedelPosted 3 weeks ago
      0
               
      • TroubleshootingChevronRightIcon

      Resolving resize widget Issue when the Tabber Widget is in use

                               

      Introduction When using the Tabber widget, you may encounter issues where other widgets cannot be resized. This guide provides a step-by-step solution to resolve the problem by temporarily removing and recreating the Tabber widget while ensuring all widgets remain functional. Step-by-Step Guide Identify the Problem: Confirm that the issue is with the Tabber widget not allowing the resizing of other widgets on the dashboard. Delete the Tabber Widget: Before deleting the Tabber widget, copy any scripts associated with it. Remove the Tabber widget from the dashboard. Resize the Widgets: Resize the other widgets on the dashboard as needed. Ensure that the widgets are properly sized before re-adding the Tabber widget. Recreate the Tabber Widget: Add the Tabber widget back to the dashboard. Paste the previously copied script into the new Tabber widget. Verify the Solution: Check if the resizing issue is resolved in the duplicated dashboard. Ensure that the Tabber widget and other widgets are functioning correctly. Troubleshooting Tips Edit Mode Issues: If you cannot change the size of widgets in edit mode, try adding another widget next to the one you want to resize. This can sometimes resolve resizing issues. Conclusion By following the steps, you can restore full resizing functionality. If issues persist, try adding another widget nearby as a workaround. This ensures a smooth and flexible dashboard layout.

      Sisense User
      Sisense UserPosted 2 years ago • Last reply Aug 14, 2026 at 6:00 PM
      3
               
    • Blog banner
      • PySisenseChevronRightIcon

      Modifying Sisense Widgets With PySisense

                                                                                                                                       

      Modifying Sisense Widgets With PySisense Overview A chart widget's metadata, including the dimension driving its category axis and the measures driving its values, lives inside the widget's own JSON definition rather than on a separate settings screen. Changing one, through the widget's Edit panel, can be done quickly. Mass modifying the same field across many widgets, or repeating the same change every time a dashboard is rebuilt from a template, is not something the Sisense UI is built to do in bulk. This article describes swap_widget_dimension.py , a Python command-line tool that reads a Sisense chart widget, replaces the field used by one item on a named panel, and writes the result back using the pySisense library. By default it targets the categories panel, a bar chart's category axis, but the same get_widget_by_id and update_widget calls apply to any panel in the widget's metadata.panels structure, including values , so the tool also works for swapping a measure. The worked example throughout is a bar chart with two versions on a dashboard that differ only in their measure: one totals Revenue, the other totals Cost. The script changes only the field of one panel item on one widget per run. It is meant primarily as an example, and can be adapted to cover other widget attributes as needed. The full source is available on GitHub in this repository . About PySisense PySisense is a Python SDK for the Sisense REST API, installed via pip . It provides wrappers around common Sisense operations and handles authentication, session management, and request errors internally. This script uses three methods from pySisense's Dashboard class: get_widget_by_id , which retrieves a widget's full current definition; update_widget , which writes a modified definition back and strips the fields Sisense manages internally ( oid , owner , created , and so on) before sending the request; and, through Dashboard 's access_mgmt attribute, get_my_user , which identifies the Sisense user the API token belongs to. Note: The current release of PySisense on PyPI does not yet include get_widget_by_id , update_widget , or find_widgets_by_type . This functionality is planned for the next PySisense release. The development branch of the PySisense repository already contains it and can be installed directly from there: pip install "git+https://github.com/sisense/pysisense.git@dev" How a chart widget stores its fields A Sisense chart widget's configuration lives under metadata.panels , a list of panel objects. For a bar chart, the panel named categories holds the dimension shown on the category axis, and the panel named values holds the measures. Each panel has an items list, and each item carries a jaql object identifying one field, with table , column , and dim keys ( dim in the form [Table.Column] ), plus a title and other fields, such as datatype or agg , that vary by field type. Panel names and item order can differ by widget type and by how a chart was originally built, so it's worth confirming the structure on the specific widget being changed rather than assuming it. Running the script with --show prints a widget's current panels for exactly this purpose, before anything is changed: python swap_widget_dimension.py --show Prerequisites Python 3.10 or later pySisense (for now, currently the dev branch, this will be merged into the main branch shortly) and PyYAML Network access to the Sisense instance A Sisense API token: Admin > REST API > v1.0 > GET /authentication/tokens/api Only a dashboard's owner can write to its widgets. If the API token's user does not own the dashboard being changed, use a token belonging to the dashboard's owner, or transfer ownership first with pySisense's change_dashboard_owner . Setup pip install "git+https://github.com/sisense/pysisense.git@dev" pyyaml Create a config.yaml with the Sisense instance details, the widget to change, and the field to switch to: sisense: domain: https://your-instance.sisense.com token: YOUR_API_TOKEN_HERE is_ssl: true widget: dashboard_id: YOUR_DASHBOARD_ID widget_id: YOUR_WIDGET_ID dimension: table: Commerce column: Region title: Region Run with --show first to confirm the widget has the panel expected, then continue with the sequence in Usage. Configuration reference sisense.domain , sisense.token , sisense.is_ssl : connection details for the Sisense instance. widget.dashboard_id , widget.widget_id : the widget to change. Both can be overridden for a single run with --dashboard-id and --widget-id without editing config.yaml . widget.admin_access : left unset by default, which auto-detects the right setting (see Troubleshooting below). Set to true or false , or pass --admin-access or --no-admin-access , only to skip that auto-detection. dimension.panel : the metadata.panels entry to change. categories for a bar chart's category axis, values for its measures. Defaults to categories if unset. Can be overridden with --panel . dimension.table , dimension.column , dimension.title : the new field to apply. table and column identify it; title is the label shown on the widget and defaults to column when omitted. All three can be overridden with --table , --column , and --title . Usage Inspect the widget's current panels before changing anything: python swap_widget_dimension.py --show Preview the change without writing it: python swap_widget_dimension.py Apply the change: python swap_widget_dimension.py --apply If the result is not correct, revert to the widget's prior state: python swap_widget_dimension.py --undo Troubleshooting Whether adminAccess is needed depends on ownership, not the Sisense version. get_widget_by_id can fail with a schema validation error mentioning adminAccess , on Sisense instances that reject the parameter outright, or with a permission error, on instances that require it for a widget the API token's user doesn't own. Rather than have the caller guess which applies, the script tries without admin access first, and only retries with admin access if that fails. It also prints a line identifying the token's user and whether that user owns the widget, so the reason either attempt succeeded is visible. --admin-access and --no-admin-access are still available to force one path and skip the auto-detection. Worked example: swapping a measure from Revenue to Cost A dashboard can have two versions of the same bar chart widget that differ only in their values panel, one totaling Commerce.Revenue , the other Commerce.Cost . Pointing the script at the Revenue widget and targeting the values panel swaps it to Cost, keeping its sum aggregation intact: python swap_widget_dimension.py \ --dashboard-id YOUR_DASHBOARD_ID --widget-id YOUR_WIDGET_ID \ --panel values --table Commerce --column Cost --title "Total Cost" \ --apply Running --show against the widget beforehand returns: { "table": "Commerce", "column": "Revenue", "dim": "[Commerce.Revenue]", "datatype": "numeric", "columnTitle": "Revenue", "tableTitle": "Commerce", "agg": "sum", "title": "Total Revenue" } and after --apply : { "table": "Commerce", "column": "Cost", "dim": "[Commerce.Cost]", "datatype": "numeric", "columnTitle": "Cost", "tableTitle": "Commerce", "agg": "sum", "title": "Total Cost" } table , column , dim , columnTitle , tableTitle , and title all changed to Cost; datatype and the sum aggregation in agg carried over unchanged, exactly as build_new_jaql is designed to do. Common use cases Reusing one chart across dashboard variants A bar chart that should show a different measure, or a different category dimension, on each of several dashboards can be built once and adjusted per dashboard with a single command instead of being rebuilt in the widget editor each time. Correcting a field after templating Dashboards built from a template sometimes carry the template's placeholder field. Rather than reopening every affected widget by hand, each one can be pointed at the correct field directly. Working with more than one item on a panel A widget with more than one item on the panel being changed, such as a grouped bar chart with two category dimensions, needs --match-column to identify which one to replace: python swap_widget_dimension.py --apply --match-column Category Full option reference usage: swap_widget_dimension.py [-h] [--config FILE] [--dashboard-id ID] [--widget-id ID] [--panel PANEL] [--table TABLE] [--column COLUMN] [--title TITLE] [--match-column COLUMN] [--show] [--apply] [--undo] [--backup-file FILE] [--admin-access | --no-admin-access] Swap the field used by one item on a Sisense chart widget panel. options: -h, --help show this help message and exit --config FILE Path to config.yaml. --dashboard-id ID Overrides widget.dashboard_id from config.yaml. --widget-id ID Overrides widget.widget_id from config.yaml. --panel PANEL Name of the metadata.panels entry to change, for example categories (a bar chart's category axis) or values (its measures). Overrides dimension.panel from config.yaml. Defaults to 'categories' if neither is set. --table TABLE Overrides dimension.table from config.yaml. --column COLUMN Overrides dimension.column from config.yaml. --title TITLE Overrides dimension.title from config.yaml. --match-column COLUMN Column name of the item to replace within --panel, if it has more than one item. Defaults to the first item. --show Print the widget's current metadata.panels and exit. Use this to confirm panel names and item order before swapping anything. --apply Write the change to Sisense. Without this flag, only a preview is printed. --undo Restore the widget to the state recorded in --backup- file, then exit. --backup-file FILE Where the widget's prior state is saved before a change, and read back from during --undo. --admin-access Always fetch with adminAccess=true, skipping auto- detection. Needed when the API token's user does not own the widget. --no-admin-access Always fetch without adminAccess=true, skipping auto- detection. Needed on Sisense instances that reject adminAccess as an unrecognized query parameter. Use case Using swap_widget_dimension.py instead of manual widget edits offers several advantages: Applies a field change to a widget directly through its JSON definition, without opening the widget editor Works on either a chart's category dimension or its measures, through the same --panel option Provides a way to confirm a widget's panel structure with --show before any change is made Auto-detects whether admin access is needed, rather than requiring the caller to know their token's relationship to the widget in advance Provides a backup of the widget's prior state before every applied change, with --undo to restore it Demonstrates how pySisense's get_widget_by_id and update_widget can be used together to read, modify, and write back any field in a widget's definition, not only its dimension Summary swap_widget_dimension.py gives Sisense administrators and developers a way to change the field used by a chart widget's category axis or its measures from the command line, with a preview step, a way to inspect the widget's actual structure first, auto-detection of whether admin access is needed, and a backup that makes any applied change reversible. The same get_widget_by_id and update_widget pattern used here, fetch the widget, modify the field that needs to change, write it back, applies to other widget fields beyond the ones shown in this example. """swap_widget_dimension.py: swap the field used by one item on a Sisense chart widget panel. Reads a widget with ``Dashboard.get_widget_by_id()``, replaces the field used by one item in a named ``metadata.panels`` entry, such as ``categories`` (a bar chart's category axis) or ``values`` (its measures), and writes the result back with ``Dashboard.update_widget()``. "Dimension" is used loosely here, the way most readers of this script will mean it: the field dropped into that panel, whether it is technically a dimension or a measure. This is a worked example of pySisense's widget read and write functions, not a general purpose widget editor: it changes one field on one panel item on one widget per run, and does not touch anything else on the widget. Note: get_widget_by_id, update_widget, and find_widgets_by_type are not yet in the pySisense release on PyPI. Install from the dev branch to use this script: pip install "git+https://github.com/sisense/pysisense.git@dev" Usage ----- python swap_widget_dimension.py --show # print the widget's panels, change nothing python swap_widget_dimension.py # preview the swap, change nothing python swap_widget_dimension.py --apply # write the change to Sisense python swap_widget_dimension.py --undo # restore from the backup file python swap_widget_dimension.py --panel values --apply # swap a measure instead of the category axis Whether a widget fetch needs adminAccess=true depends on whether the API token's own user already owns the widget. Rather than requiring the caller to know that in advance, fetch_widget() below tries without admin access first and only escalates if that fails. """ from __future__ import annotations import argparse import json import sys from pathlib import Path from typing import Any import yaml from pysisense import Dashboard, SisenseClient SCRIPT_DIR = Path(__file__).parent DEFAULT_CONFIG_PATH = SCRIPT_DIR / "config.yaml" DEFAULT_BACKUP_PATH = SCRIPT_DIR / "widget_backup.json" # The metadata.panels entry this script targets when --panel and # dimension.panel are both left unset: a bar chart's category axis. DEFAULT_PANEL_NAME = "categories" def load_config(path: Path) -> dict[str, Any]: """Load and parse the YAML configuration file. Parameters ---------- path : Path Location of the config.yaml file to read. Returns ------- dict[str, Any] The parsed configuration. Empty dict if the file is empty. Raises ------ SystemExit If no file exists at ``path``. """ if not path.exists(): sys.exit( f"Config file not found: {path}\n" "Copy config.example.yaml to config.yaml and fill in the instance URL, " "token, and widget details." ) with path.open() as config_file: return yaml.safe_load(config_file) or {} def build_client(config: dict[str, Any]) -> SisenseClient: """Construct a SisenseClient from the ``sisense`` section of config.yaml. Parameters ---------- config : dict[str, Any] The full parsed configuration, as returned by :func:`load_config`. Returns ------- SisenseClient A client ready to use with pySisense's Dashboard class. Raises ------ SystemExit If ``sisense.domain`` or ``sisense.token`` is missing. """ sisense_config = config.get("sisense", {}) domain = sisense_config.get("domain", "") token = sisense_config.get("token", "") if not domain or not token: sys.exit("config.yaml must include sisense.domain and sisense.token.") return SisenseClient(domain=domain, token=token, is_ssl=sisense_config.get("is_ssl", True)) def describe_current_user(dashboard: Dashboard) -> dict[str, Any] | None: """Look up the Sisense user the API token belongs to. Used only to print a diagnostic line explaining whether the token's own user already owns the widget being changed, which is what actually determines whether admin access is needed (see :func:`fetch_widget`). A failed lookup here is not fatal to the rest of the script. Parameters ---------- dashboard : Dashboard A pySisense Dashboard instance, whose ``access_mgmt`` attribute exposes ``get_my_user()``. Returns ------- dict[str, Any] | None The logged-in user object (``GET /api/users/loggedin``), or ``None`` if the lookup failed for any reason. """ try: user = dashboard.access_mgmt.get_my_user() except Exception: return None if isinstance(user, dict) and "error" not in user: return user return None def fetch_widget( dashboard: Dashboard, dashboard_id: str, widget_id: str, *, admin_access: bool | None, ) -> tuple[dict[str, Any], bool]: """Fetch a widget, auto detecting whether admin access is required. Whether a fetch needs ``adminAccess=true`` depends on whether the API token's own user already owns the widget, not on the Sisense version. On top of that, some Sisense versions reject ``adminAccess`` outright as an unrecognized query parameter, which looks identical from here to "not the owner". Rather than have the caller guess, this tries the cheaper, no-admin-access request first, and only escalates if that fails. Parameters ---------- dashboard : Dashboard A pySisense Dashboard instance. dashboard_id : str The ``oid`` of the dashboard that contains the widget. widget_id : str The ``oid`` of the widget to fetch. admin_access : bool | None ``True`` or ``False`` forces that mode and skips auto-detection. ``None`` tries without admin access first, then retries with admin access only if the first attempt fails. Returns ------- tuple[dict[str, Any], bool] The fetched widget, and whether admin access was actually used to retrieve it. Raises ------ SystemExit If the widget cannot be fetched in the requested mode(s). """ if admin_access is not None: widget = dashboard.get_widget_by_id(dashboard_id, widget_id, admin_access=admin_access) if "error" in widget: sys.exit(f"Could not fetch widget: {widget['error']}") return widget, admin_access widget = dashboard.get_widget_by_id(dashboard_id, widget_id, admin_access=False) if "error" not in widget: return widget, False error_without_admin_access = widget["error"] widget = dashboard.get_widget_by_id(dashboard_id, widget_id, admin_access=True) if "error" not in widget: return widget, True sys.exit( "Could not fetch widget, with or without admin access.\n" f" Without admin access: {error_without_admin_access}\n" f" With admin access: {widget['error']}" ) def print_fetch_diagnostics(dashboard: Dashboard, widget: dict[str, Any], admin_access_used: bool) -> None: """Print a line explaining whether the token's user owns this widget. Purely informational: makes the reason admin access was, or was not, needed for this particular widget visible, instead of leaving the ``True``/``False`` in ``admin_access_used`` unexplained. Printed to stderr, not stdout, so it never lands in ``--show``'s JSON output and can be piped straight into something like ``jq``. Parameters ---------- dashboard : Dashboard A pySisense Dashboard instance, used to look up the current user. widget : dict[str, Any] The widget returned by :func:`fetch_widget`. admin_access_used : bool Whether the fetch that retrieved ``widget`` used admin access. Returns ------- None """ access_note = "with admin access" if admin_access_used else "without admin access" current_user = describe_current_user(dashboard) if current_user is None: print(f"Fetched widget {access_note} (could not look up the current user for comparison).", file=sys.stderr) return identity = current_user.get("email") or current_user.get("userName") or current_user.get("_id") owns_widget = current_user.get("_id") == widget.get("owner") ownership_note = "owns this widget" if owns_widget else "does not own this widget" print(f"Fetched widget {access_note}. Authenticated as {identity!r}, who {ownership_note}.", file=sys.stderr) def find_panel_item( widget: dict[str, Any], panel_name: str, match_column: str | None, ) -> tuple[list[dict[str, Any]], int]: """Locate the panel item to change. Parameters ---------- widget : dict[str, Any] The full widget object, as returned by ``get_widget_by_id``. panel_name : str The ``metadata.panels`` entry to search, for example ``"categories"`` (a bar chart's category axis) or ``"values"`` (its measures). match_column : str | None If given, selects the item whose current ``jaql.column`` equals it. If ``None``, the first item in the panel is used, which is correct whenever that panel only has one item, such as a simple bar chart's single category dimension or single measure. Returns ------- tuple[list[dict[str, Any]], int] The panel's ``items`` list, and the index within it of the item to change. Raises ------ SystemExit If the widget has no panel named ``panel_name``, the panel has no items, or ``match_column`` does not match any item in it. """ panels = widget.get("metadata", {}).get("panels", []) panel = next((candidate for candidate in panels if candidate.get("name") == panel_name), None) if panel is None or not panel.get("items"): sys.exit(f"No {panel_name!r} panel with items found on this widget. Run --show to inspect its structure.") items = panel["items"] if match_column is None: return items, 0 for index, item in enumerate(items): if item.get("jaql", {}).get("column") == match_column: return items, index sys.exit(f"No item with column {match_column!r} found in the {panel_name!r} panel. Run --show to see the current items.") def build_new_jaql(existing_jaql: dict[str, Any], table: str, column: str, title: str | None) -> dict[str, Any]: """Return a copy of ``existing_jaql`` with its field swapped. ``table``, ``column``, and ``dim`` always change. ``title`` changes to ``title`` or, if that is ``None``, to ``column``. ``columnTitle`` and ``tableTitle`` (Sisense's own display-label mirrors of ``column`` and ``table``, confirmed by inspecting a live widget) are updated to match whenever the existing jaql already had them, so nothing about the field still points at the old one under a different key. ``agg`` and every other key already present (``datatype``, and so on) are carried over unchanged. Preserving ``agg`` in particular is what makes this safe to use on a ``values`` panel item, not only a ``categories`` one: swapping Revenue for Cost keeps the sum aggregation the widget already had, instead of resetting it. Parameters ---------- existing_jaql : dict[str, Any] The jaql object currently on the panel item being replaced. table : str The table of the new field. column : str The column of the new field. title : str | None The label to show on the widget for the new field. Defaults to ``column`` when ``None``. Returns ------- dict[str, Any] A new jaql object with the field swapped. """ new_jaql = dict(existing_jaql) new_jaql["table"] = table new_jaql["column"] = column new_jaql["dim"] = f"[{table}.{column}]" new_jaql["title"] = title or column if "columnTitle" in new_jaql: new_jaql["columnTitle"] = column if "tableTitle" in new_jaql: new_jaql["tableTitle"] = table return new_jaql def write_widget(dashboard: Dashboard, dashboard_id: str, widget_id: str, payload: dict[str, Any]) -> None: """Write ``payload`` back to Sisense via ``Dashboard.update_widget()``. Parameters ---------- dashboard : Dashboard A pySisense Dashboard instance. dashboard_id : str The ``oid`` of the dashboard that contains the widget. widget_id : str The ``oid`` of the widget being written. payload : dict[str, Any] The full widget object to write back. Returns ------- None Raises ------ SystemExit If the API reports a write failure. """ result = dashboard.update_widget(dashboard_id, widget_id, payload) if "error" in result: sys.exit(f"Update failed: {result['error']}") def parse_args() -> argparse.Namespace: """Define and parse this script's command-line arguments. Returns ------- argparse.Namespace The parsed arguments. """ parser = argparse.ArgumentParser(description="Swap the field used by one item on a Sisense chart widget panel.") parser.add_argument("--config", default=str(DEFAULT_CONFIG_PATH), metavar="FILE", help="Path to config.yaml.") parser.add_argument("--dashboard-id", metavar="ID", help="Overrides widget.dashboard_id from config.yaml.") parser.add_argument("--widget-id", metavar="ID", help="Overrides widget.widget_id from config.yaml.") parser.add_argument( "--panel", help="Name of the metadata.panels entry to change, for example categories (a bar " "chart's category axis) or values (its measures). Overrides dimension.panel from " f"config.yaml. Defaults to {DEFAULT_PANEL_NAME!r} if neither is set.", ) parser.add_argument("--table", help="Overrides dimension.table from config.yaml.") parser.add_argument("--column", help="Overrides dimension.column from config.yaml.") parser.add_argument("--title", help="Overrides dimension.title from config.yaml.") parser.add_argument( "--match-column", metavar="COLUMN", help="Column name of the item to replace within --panel, if it has more than one item. " "Defaults to the first item.", ) parser.add_argument( "--show", action="store_true", help="Print the widget's current metadata.panels and exit. Use this to confirm panel " "names and item order before swapping anything.", ) parser.add_argument( "--apply", action="store_true", help="Write the change to Sisense. Without this flag, only a preview is printed.", ) parser.add_argument( "--undo", action="store_true", help="Restore the widget to the state recorded in --backup-file, then exit.", ) parser.add_argument( "--backup-file", default=str(DEFAULT_BACKUP_PATH), metavar="FILE", help="Where the widget's prior state is saved before a change, and read back from during --undo.", ) admin_access_group = parser.add_mutually_exclusive_group() admin_access_group.add_argument( "--admin-access", dest="admin_access", action="store_true", default=None, help="Always fetch with adminAccess=true, skipping auto-detection. Needed when the API " "token's user does not own the widget.", ) admin_access_group.add_argument( "--no-admin-access", dest="admin_access", action="store_false", help="Always fetch without adminAccess=true, skipping auto-detection. Needed on Sisense " "instances that reject adminAccess as an unrecognized query parameter.", ) return parser.parse_args() def main() -> None: """Entry point: parse arguments, then fetch, inspect, swap, or restore a widget's dimension.""" args = parse_args() config = load_config(Path(args.config)) client = build_client(config) dashboard = Dashboard(api_client=client) widget_config = config.get("widget", {}) dashboard_id = args.dashboard_id or widget_config.get("dashboard_id") widget_id = args.widget_id or widget_config.get("widget_id") if not dashboard_id or not widget_id: sys.exit( "dashboard_id and widget_id are required, either in config.yaml under 'widget' " "or via --dashboard-id/--widget-id." ) admin_access = args.admin_access if args.admin_access is not None else widget_config.get("admin_access") if args.undo: backup_path = Path(args.backup_file) if not backup_path.exists(): sys.exit(f"No backup file found at {backup_path}. Nothing to undo.") original_widget = json.loads(backup_path.read_text()) write_widget(dashboard, dashboard_id, widget_id, original_widget) print(f"Widget {widget_id} restored from {backup_path}.") return widget, admin_access_used = fetch_widget(dashboard, dashboard_id, widget_id, admin_access=admin_access) print_fetch_diagnostics(dashboard, widget, admin_access_used) if args.show: print(json.dumps(widget.get("metadata", {}).get("panels", []), indent=2)) return dimension_config = config.get("dimension", {}) panel_name = args.panel or dimension_config.get("panel") or DEFAULT_PANEL_NAME table = args.table or dimension_config.get("table") column = args.column or dimension_config.get("column") title = args.title or dimension_config.get("title") if not table or not column: sys.exit("table and column are required, either in config.yaml under 'dimension' or via --table/--column.") items, index = find_panel_item(widget, panel_name, args.match_column) old_jaql = items[index].get("jaql", {}) new_jaql = build_new_jaql(old_jaql, table, column, title) print(f"\nWidget: {widget.get('title') or widget_id!r} ({widget.get('type')})") print(f" {'Panel:':<15}{panel_name!r}") print(f" {'Current field:':<15}{old_jaql.get('table')}.{old_jaql.get('column')} (title: {old_jaql.get('title')!r})") print(f" {'New field:':<15}{table}.{column} (title: {new_jaql['title']!r})") if not args.apply: print("\n[PREVIEW] No changes made. Re-run with --apply to write this change to Sisense.") return backup_path = Path(args.backup_file) backup_path.write_text(json.dumps(widget, indent=2)) print(f"\nBacked up current widget state to {backup_path}.") items[index]["jaql"] = new_jaql write_widget(dashboard, dashboard_id, widget_id, widget) print(f"Widget {widget_id} updated. To revert: python {Path(__file__).name} --undo --backup-file {backup_path}") if __name__ == "__main__": main()

      Before and After Change Via Tool
      Disclaimer: This post outlines a potential custom workaround for a specific use case or provides instructions regarding a specific task. The solution may not work in all scenarios or Sisense versions, so we strongly recommend testing it in your environment before deployment. If you need further assistance with this, please let us know.

      Jeremy Friedel
      Jeremy FriedelPosted 1 month ago
      0
               
    • Blog banner
      • Embedding AnalyticsChevronRightIcon

      From Zero to ComposeSDK: Building a Sisense React Application with an AI Coding Assistant

                                                                                                                                       

      From Zero to ComposeSDK: Building a Sisense React Application with an AI Coding Assistant A computer with no development related setup, no code editor application, no programming languages or runtimes such as Node installed, no development tooling of any kind, can create a running ComposeSDK React application in a single development session, connected to a live Sisense instance and ready for continued iteration. The computer can be a laptop, desktop, or server, and the finished app can be served from localhost, a local IP address, or a domain. Almost none of this development and setup has to be done by hand. An AI coding assistant installs the tooling, runs the commands, and writes the code, while the developer describes what should happen and confirms the results along the way. This style of development is sometimes called vibe coding, which refers to working conversationally and letting the AI handle the mechanics. Any modern LLM based coding assistant can drive this workflow. It needs two capabilities, editing code files in the project folder and running terminal commands. This article uses Claude Code in VS Code as the concrete example, but the same steps work in other editors with agentic assistants, in a standalone CLI tool like Claude CLI, or in a desktop app with terminal access like Claude Desktop. The prompts translate directly and are not specific to Claude. Only two steps require manual installation. The first is installing the text editor with its AI assistant, and the second is generating an API token inside the Sisense web interface. Everything else happens through conversation, from installing Node.js to creating the project, configuring credentials, generating the .ts representation of a Sisense data model, and building the widgets, dashboards, and other visualizations themselves. The starting point on the Sisense side is a modern Linux instance with at least one data model, either an ElastiCube or a live model, and permission to generate an API bearer token on it. Prerequisites A modern Linux Sisense instance with at least one data model Permission to generate an API bearer token on that instance A computer with the ability to install programs and CLI access Access to an LLM like Claude, or similar Getting Started An editor and an AI assistant have to be installed before anything can be done conversationally, so the first two steps are done manually. Download and install Visual Studio Code . Open the Extensions view in VS Code, search for the assistant of choice, install it, and sign in. For Claude Code, see the Claude Code documentation . Other agentic assistants with file editing and terminal access work the same way. One behavior is worth knowing about before the first prompt. Agentic assistants ask for approval before running each terminal command, so expect to click Yes regularly during setup, and read each command before approving it. The approval step exists so the developer always knows what is about to run on the machine, and it only provides that protection if the commands are actually read. Most assistants also offer an option to allow certain commands without asking again, which becomes convenient once a pattern has been reviewed a few times. Editing files inside the project folder is a sensible thing to approve universally. Commands that reach outside the project folder, or that install programs system wide, should be reviewed every time and not auto approved. How Granular to Be The sections below proceed step by step, with each prompt doing one focused thing. That structure is deliberate. It makes each step verifiable before the next is added, and it gives the reader a chance to learn what is happening at every stage. It is not a limitation of the LLM. In practice, an agentic assistant handles much larger requests comfortably. Given an empty folder and little else, a single prompt can carry the project most of the way. Set up a new ComposeSDK React application in this folder. Install Node if it is missing, create a React TypeScript Vite project, add the Sisense ComposeSDK packages, and start the dev server. My Sisense instance is at https://example.sisense.com and I will provide an API token in the file where it is needed, tell me where it is. The assistant works through the chain on its own, installing what is missing, flagging where the token goes, and reporting back when the dev server is running. Granular prompts tend to be the better choice while learning. Broad prompts work better once the process is familiar. Most real sessions mix both freely. If any errors are visible, pasting the error message into the LLM chat will often allow the LLM to resolve the issue. Checking the browser developer tools console for error messages to copy can also be helpful. Handing the Environment to the Assistant From this point forward, work happens in the assistant's chat panel. The first task is the development environment itself. To open the Claude VS Code UI, click the orange flower icon in the top right corner when a text file is open in VS Code. Open VS Code in a new empty folder that will hold the project (File, Open Folder, then create or select a directory. Name the folder appropriately, to match the name of the ComposeSDK (CSDK) application). Create an empty text file if the Claude VS Code icon (or the equivalent for the LLM in use) is hidden. Then open the LLM chat panel and ask the assistant to set up the toolchain. Install the latest LTS version of Node on this machine, make sure it is on the path, then verify that node and npm both work from the terminal. The assistant detects the operating system, picks an appropriate install method for that platform, runs it, and confirms the versions. If the path changed during installation, the assistant will usually mention that the terminal or VS Code may need a restart before the change takes effect. Node.js can also be installed manually for the relevant OS from the Node.js website download section , if the LLM struggles to install it via CLI. This first exchange establishes the pattern for everything that follows. State the goal, let the LLM assistant run the commands, confirm the result, move to the next step. Creating the Project With the toolchain verified, the next request creates the application. Create a new React TypeScript app in this folder using Vite, install the dependencies, and start the dev server so I can confirm the default page loads. The assistant plans and sets up the project, installs packages, and starts the Vite dev server, usually at http://localhost:5173 . Open that URL in a browser and confirm the default Vite page renders. Confirming each layer before adding the next is a habit worth keeping. If a later step fails, a verified baseline makes it obvious where the problem was introduced. Installing ComposeSDK ComposeSDK ships as npm packages, so adding it is one request. Add the Sisense ComposeSDK packages to this project: sdk-ui and sdk-data as dependencies, and the SDK CLI as a dev dependency. The three packages serve distinct purposes. @sisense/sdk-ui provides the React components, the charts, dashboards, and filter UI. @sisense/sdk-data provides the query construction layer, including dimensions, measures, and filter factories. @sisense/sdk-cli is a development tool used to generate the TypeScript data model files covered later in this article, and never ships with the application. Full ComposeSDK documentation is available on developer.sisense.com. Connecting to the Sisense Instance Two values connect and authenticate the CSDK application to Sisense, the instance URL and an API bearer token. Generate the token in the Sisense web interface, from the user profile menu under API Token ( Sisense documentation on generating API tokens ). Copy it once generated. The recommended approach keeps the token out of the LLM chat entirely, so the LLM never has access to it. The assistant builds the configuration with the token left blank. Create a .env file with VITE_SISENSE_URL set to https://example.sisense.com and VITE_SISENSE_TOKEN left blank. Add .env to .gitignore, deny your own read access to .env in your permission settings, wrap the app in SisenseContextProvider using those environment variables, and tell me where to paste my token. The assistant creates the .env file with the relevant keys, excludes it from both version control and its own file access, and points to where the token goes. Editing the URL and pasting the token into .env directly in the editor completes the setup. From that point the application can read the bearer token value but the assistant cannot. In Claude Code specifically, the mechanism for blocking its own access is a permission deny rule rather than an ignore file. The rule lives in .claude/settings.json at the project level, or in ~/.claude/settings.json to apply across all projects. { "permissions": { "deny": ["Read(./.env)", "Read(./.env.*)"] } } The /permissions command in Claude Code can also add this rule interactively, saving it to .claude/settings.local.json . Other assistants have their own equivalents, whether ignore files or access controls. Whichever tool is in use, it is worth verifying the block before pasting the real token. Put a dummy value in .env , ask the assistant to read the file, and confirm it refuses. Pasting the token straight into the chat and letting the assistant write the whole file also works, but is not recommended, since it means trusting the chat tool with a credential. Either way, keep .env out of version control and rotate the token if exposure is suspected. Clicking the refresh icon in the Profile bearer token page rotates the token. A token from a viewer role user is all that is required for CSDK, as long as that user has access to every dashboard and data source the application uses. Bearer tokens are also not the only option. ComposeSDK can authenticate with Web Access Tokens (WAT) and SSO as well, which are worth considering beyond initial development ( ComposeSDK authentication documentation ). The resulting setup looks approximately like this in main.tsx , the entry file Vite generates. Wrapping inside App.tsx works just as well, as long as the provider sits above every ComposeSDK component. import { createRoot } from 'react-dom/client'; import { SisenseContextProvider } from '@sisense/sdk-ui'; import App from './App.tsx'; // The provider supplies the connection to every ComposeSDK component below it. // Values come from .env so credentials stay out of source control. createRoot(document.getElementById('root')!).render( <SisenseContextProvider url={import.meta.env.VITE_SISENSE_URL} token={import.meta.env.VITE_SISENSE_TOKEN} > <App /> </SisenseContextProvider> ); Smoke Testing the Connection Before building further, it is worth confirming the application can reach and authenticate with the Sisense instance. There are two reasonable ways to do it. The fastest is DashboardById , which renders an existing Sisense dashboard and requires no data model work in the project. Open any dashboard in Sisense and copy its OID from the browser URL. Render the dashboard with OID 65a1b2c3d4e5f6a7b8c9d0e1 from my Sisense instance on the main page using DashboardById, replacing the default Vite content. The alternative is a minimal chart against a known data model, which previews the widget workflow used in the rest of this article. Either one confirms the same thing, that the URL and token work and the instance is reachable from the browser. A rendered dashboard means the connection is established. A blank or broken one usually traces back to one of these common causes. The token is invalid or belongs to a user without access to the dashboard or data source. Regenerate the token and confirm the user can open the dashboard in Sisense directly. The URL is incorrect, commonly a missing https:// or a trailing path. The value should be the bare instance origin. The browser blocks the request with a CORS error. ComposeSDK typically works without any CORS configuration, but if the console shows a CORS error, an administrator can add http://localhost:5173 to the allowed origins in the Sisense Admin section under Security Settings ( Sisense documentation on CORS configuration ). Browser console errors generally identify which of these applies, and the error output can be pasted straight into the chat for diagnosis. Generating the TypeScript Data Model ComposeSDK includes a built in tool for this step. The SDK CLI installed earlier generates a .ts file that describes the data model, listing its tables, dimensions, and measures as typed TypeScript objects, so widget code references real fields with autocomplete rather than hand typed strings. It works the same way whether the model is an ElastiCube or a live model. Being specific in the prompt matters here. Naming the goal, a .ts file generated by the SDK's own CLI, steers the assistant toward the right tool, there otherwise being the possibility it would try to create or hallucinate its own representation. Use the ComposeSDK CLI (the get-data-model command from @sisense/sdk-cli) to generate a .ts file describing my data model named Sample ECommerce, and save it to src/models. Use the token in .env. Under the hood this runs a command of the following form. # Generates a .ts file describing the data model's tables, dimensions, and measures. # The token and URL are the same values used by the app itself. npx @sisense/sdk-cli get-data-model \ --url https://example.sisense.com \ --token <token> \ --dataSource "Sample ECommerce" \ --output src/models/sample-ecommerce.ts The generated .ts file exports a typed object, conventionally imported as DM , containing every table, dimension, and measure in the model. Everything built from this point on references fields through that object, which means typos become compile errors instead of silently empty charts. Building the First Widget With the .ts model file in place, building the first real chart is a single request. Using the generated Sample ECommerce data model in src/models, add a column chart below the dashboard showing total Revenue by Condition. The assistant writes a component along these lines. import { Chart } from '@sisense/sdk-ui'; import { measureFactory } from '@sisense/sdk-data'; import * as DM from './models/sample-ecommerce'; // A minimal ComposeSDK chart: one category dimension, one aggregated measure. <Chart dataSet={DM.DataSource} chartType="column" dataOptions={{ category: [DM.Commerce.Condition], value: [measureFactory.sum(DM.Commerce.Revenue, 'Total Revenue')], }} /> Once it renders, iteration can be done through continued conversation or manual code editing. The Vite application will auto update with any changes, without requiring manual refreshes. Change it to a bar chart, break it down by Gender, and only include 2024 data. The assistant adds the breakBy entry to the data options and a date filter to the chart, and the result appears on the next hot reload. Describe a change, see it render, refine. That loop is the core of the workflow, and it is the same whether the change is a chart type, a filter, or a layout adjustment. Styling and Structuring the Application The same conversational approach turns the result from a test page into something that looks like an application. Add a professional looking header and footer to the application, including the title [app title], and lay out the dashboard and the chart in cards. What this prompt actually says will vary by user and project. The card layout here is just one option, and the assistant follows whatever visual direction it is given, from minimal to fully branded. One distinction is worth knowing. Application CSS and widget theming are separate layers. Page layout, headers, and footers are ordinary React and CSS. The appearance of the ComposeSDK widgets themselves, including chart colors, fonts, and backgrounds, is controlled through the SDK's ThemeProvider component ( ComposeSDK theming documentation ). Asking for "a dark theme on the charts" versus "a dark background on the page" will, correctly, touch different code. Working with Live Data The ComposeSDK application itself does not typically contain or store data, though exceptions exist, a point that is often misunderstood. Every widget sends a JAQL query to the Sisense instance at render time, so the CSDK application always reflects the current state of the data model. For an ElastiCube that means fresh data appears after each build, and for a live model queries hit the source directly. In neither case does updated data require rebuilding or redeploying the application. The generated .ts model file only needs regeneration when the schema changes, such as new fields, renamed columns, or restructured tables. Data refreshes do not affect it. When the schema does change, regeneration is one request. My data model schema changed. Use the ComposeSDK CLI to regenerate the .ts model file and tell me if any existing widget code references fields that no longer exist. Because the model file is typed, removed fields surface as compile errors, and the assistant can identify and fix the affected components in the same exchange. Prompt Library The prompts below are starting points, not strings that need to be copied exactly. Everything in this article was done conversationally, and describing the goal in natural language as it comes to mind is usually faster than locating a prompt to paste. What makes these prompts work is their specificity, with actual field names, file locations, and a clear definition of when the task is finished. Those qualities carry over to any phrasing, including a single broad prompt that covers several steps at once. Setup and environment: Install the latest LTS version of Node, make sure it is on the path, and verify node and npm from the terminal. Create a React TypeScript Vite app here, install dependencies, and start the dev server. Set up a complete ComposeSDK React app in this folder: install anything missing, create the project, add the SDK packages, and get the dev server running. ComposeSDK installation and connection: Add the ComposeSDK packages: sdk-ui and sdk-data as dependencies and the SDK CLI as a dev dependency. Create a .env with my Sisense URL and a blank token, add it to .gitignore, deny your own read access to it, wire up SisenseContextProvider from those variables, and tell me where to paste my token. The dashboard component shows a network error. Here is the browser console output: [paste]. Diagnose whether this is CORS, the token, the URL, or something else. Data and widgets: Use the ComposeSDK CLI to generate a .ts file for the data model named [name] into src/models. Render the dashboard with OID [oid] using DashboardById. Add a line chart of [measure] by [date dimension] at month granularity, with a member filter on [dimension] limited to [values]. Add breakBy on [dimension] to the existing column chart and move the legend to the bottom. Advanced: Use useExecuteQuery to fetch [measure] grouped by [dimension] and render the result in a plain HTML table instead of an SDK chart component. Use onBeforeRender on the line chart to set the line width to 3 and enable data labels through the underlying Highcharts options. The advanced prompts reference real ComposeSDK extension points. useExecuteQuery runs a query directly and returns rows for custom rendering, and onBeforeRender exposes the underlying Highcharts options object before a chart draws, allowing customization beyond the SDK's own props ( useExecuteQuery reference , chart customization reference ). Useful Links ComposeSDK documentation ComposeSDK quickstart for React Claude Code documentation Sisense REST API and authentication documentation The techniques in this article generalize. Any capability in the ComposeSDK documentation, from dashboard filters to custom widget types, is reachable the same way. Describe it to the assistant with enough specificity, confirm the result in the browser, and refine conversationally.

      Jeremy Friedel
      Jeremy FriedelPosted 3 months ago • Last reply 2 months ago
      3
               
    • Blog banner
      • Widget & Dashboard ScriptsChevronRightIcon

      Hiding Widgets if a Widget Has No Results [Linux]

                                                                                                               

      Hiding Widgets if a Widget Has No Results [Linux] Introduction A common dashboard design requirement is hiding widgets that have no data. This article includes a widget script that conditionally hides an indicator widget when its primary value is empty or represents an N/A like value. This behavior is commonly requested when dashboard filters or formulas result in no meaningful value and the widget should be visually hidden rather than showing an empty or zero indicator. The article also includes an alternative dashboard-level approach that hides widgets based on filter selections, without inspecting widget query results. This alternative is derived from the linked external blog post . This is applicable to both on-cloud and on-prem Sisense in all recent Sisense versions. Use Case Customers often want indicator widgets to disappear when their calculated value is not meaningful. Common examples include: Filters resulting in no matching data Calculations returning N/A, null, or empty values Conditional metrics that only apply to certain filter selections Rather than showing an empty indicator, this approach hides the widget entirely and restores it automatically when the value becomes valid again. Layout Considerations For best visual results, it is ideal to use one of these two layouts for the indicator widgets that may be hidden: Place the indicator widget in its own dashboard row Place it at the end of a row Hiding a widget via a script does not automatically resize or reflow other widgets on the same row. Step by Step Guide Widget Script to Hide Widget Based on Indicator Value This widget script is applied directly to the indicator widget. It evaluates the widget’s primary value after each render and hides or shows the widget accordingly. Behavior If the primary value is null, empty, or an N/A like string, the widget container is set to display: none. When the value becomes valid and not null again, the widget is restored to visibility and redrawn to ensure correct indicator rendering. A guard variable prevents infinite redraw loops, since a redraw triggers the widget ready event. A debug flag allows optional console logging when needed. Widget Script /** * Hide widget when its primary indicator value is empty or N/A-like. * * Behavior: * - If the value is empty, set the widget container to display "none". * - If the returned value becomes a number or valid value, restore display style to original and redraw * - A redraw triggers "ready" again, so a guard variable prevents a redraw loop. * * Debug: * - Set debug variable = true to enable console logging to track script status. * * For best results use on indicator in own row or at end of row, if other widgets exist on row, empty space will appear in dashboard */ widget.on("ready", function () { function run() { var debug; var suppressNextReady; var hideValues; debug = false; suppressNextReady = false; hideValues = [ "n/a", "#n/a", "na", "none", "null", "undefined" ]; // Function to turn console logging on or off function log(message, data) { if (!debug) { return; } if (data === undefined) { console.log("[hide-empty-indicator] " + message); return; } console.log("[hide-empty-indicator] " + message, data); } // Widget CSS selector function getWidgetElement() { return document.querySelector('widget[widgetid="' + widget.oid + '"]'); } // Get value of primary indicator value function getPrimaryValue() { if ( widget.queryResult && widget.queryResult.value && widget.queryResult.value.data !== undefined ) { return widget.queryResult.value.data; } try { if ( widget.queryResult && widget.queryResult.data && widget.queryResult.data.length ) { return widget.queryResult.data[0][0]; } } catch (e) { log("Value read failed for data[0][0].", e); } if (widget.queryResult && Array.isArray(widget.queryResult)) { if (widget.queryResult.length && widget.queryResult[0].length) { if (widget.queryResult[0][0]) { return widget.queryResult[0][0].Value; } } } return null; } function shouldHide(value) { var text; var normalized; if (value === null || value === undefined) { return true; } text = String(value).trim(); if (!text) { return true; } normalized = text.replace(/\\/g, "/").toLowerCase(); return hideValues.indexOf(normalized) !== -1; } function isElementHidden(element) { if (!element) { return false; } return element.style.display === "none"; } function hideWidget(element) { if (!element) { return; } if (element.style.display === "none") { return; } element.style.display = "none"; log("Hid widget due to empty/N/A-like value."); } function showWidgetAndRedrawIfNeeded(element) { var wasHidden; if (!element) { return; } wasHidden = isElementHidden(element); element.style.display = ""; if (!wasHidden) { log("Widget already visible."); return; } if (typeof widget.redraw !== "function") { log("Widget restored, redraw not available."); return; } suppressNextReady = true; log("Widget restored, triggering redraw."); widget.redraw(); } function applyRule() { var element; var primaryValue; element = getWidgetElement(); if (!element) { log("Widget container element not found."); return; } if (widget.queryResult === undefined) { log("queryResult is not available yet, keeping widget visible."); element.style.display = ""; return; } primaryValue = getPrimaryValue(); log("Primary value evaluated.", primaryValue); if (shouldHide(primaryValue)) { hideWidget(element); return; } showWidgetAndRedrawIfNeeded(element); } function onReady() { if (suppressNextReady) { suppressNextReady = false; log("Ready fired after redraw, applying rule without redraw."); applyRule(); return; } applyRule(); } onReady(); } run(); }); Notes The script uses display: none instead of jQuery hide or show to avoid layout and rendering issues with indicator widgets. Redraw is triggered only when restoring visibility, not when hiding. The script relies only on the widget ready event, which fires again after redraw and filter changes. Dashboard Script to Hide Widgets Based on Filter Selections As an alternative, widgets can be hidden purely based on filter selections, without checking whether the widget returns data. This approach is useful when visibility rules are deterministic based on filters. This method uses a dashboard script and CSS classes to hide widget containers. Example Dashboard Script dashboard.on('filterschanged', function (se, ev) { let filterName = 'Region' //mapping of filter items and widgets to be hidden. //if selected filter item is not available in the list, widgets in 'default' key will be hidden let itemWidgetMapping = { 'Midwest':['6390b5a285a029002e9e2ad6'], 'South': ['6238887ba77683002ea4425b'], 'West':['6390b5a285a029002e9e2ad6', '6238887ba77683002ea4425b'], 'default':[] } selectedFilter = ev.items.find(el=>el.jaql.title == filterName) let selectedItem = 'default' if(selectedFilter && selectedFilter.jaql.filter.members) selectedItem = selectedFilter.jaql.filter.members[0] //unhide all widgets first and then hide widgets based on selected filter $(`widget`).closest('.dashboard-layout-subcell-host').removeClass('dontshowme-parent') if(selectedItem in itemWidgetMapping){ for (const [key, value] of Object.entries(itemWidgetMapping)) { if(key == selectedItem){ itemWidgetMapping[key].forEach(function (item, index) { $(`widget[widgetid="${item}"]`).closest('.dashboard-layout-subcell-host').addClass('dontshowme-parent') }); } } } else{ itemWidgetMapping['default'].forEach(function (item, index) { $(`widget[widgetid="${item}"]`).closest('.dashboard-layout-subcell-host').addClass('dontshowme-parent') }); } }); Choosing the Right Approach Generally the widget script is best suited when: Visibility depends on whether data is returned The indicator value can be empty due to calculations or filters Generally the dashboard script is best suited when: Visibility depends only on filter selections Centralized control over multiple widgets is required These approaches are alternatives and should not be used simultaneously for the same widgets. Conclusion Hiding indicator widgets based on their returned value can potentially improve dashboard clarity and user experience. The widget script approach provides result aware behavior, while the dashboard script approach offers deterministic, filter based control. Both methods are powerful tools for customizing dashboard widget visibility. Two Full Row Indicator Widgets, both visible First Row Indicator Widget is now hidden, by script, due to no data Two Indicators in one row, both visible Second Indicator is now hidden by script, due to no data Disclaimer: This post outlines a potential custom workaround for a specific use case or provides instructions regarding a specific task. The solution may not work in all scenarios or Sisense versions, so we strongly recommend testing it in your environment before deployment. If you need further assistance with this, please let us know.

      Jeremy Friedel
      Jeremy FriedelPosted 3 months ago
      0
               
    • Blog banner
      • APIsChevronRightIcon

      Connection Tool - Programmatically Remove Unused Datasource Connections, and List All Connections

                                                                                                                                                                       

      Connection Tool - A Tool to Programmatically Remove Unused Datasource Connections, and List All Connections     Managing connections within your Sisense server can become complex over time, if there are a large number of connections, and connections are often added, and replace earlier datasource connections. In some scenarios unused connections can accumulate, potentially cluttering the Connection Manager UI with no longer relevant connections. Although unused connections typically represent minimal direct security risk, it's considered best practice to maintain a clean, organized list of connections, and in some scenarios it can be desired to remove all unused connections. Sisense prevents the deletion of connections actively used in datasources, safeguarding your dashboards and datasources from disruptions. However, inactive or "orphaned" connections remain after datasources are deleted or a connection is replaced, potentially contributing to unnecessary UI complexity in the connection manager UI. Connections can be of any type Sisense supports, common types include various SQL connections, Excel files, and CSV files, as well as many data providers, such as Big Panda. This tool can also be used to list all connections, with no automatic deletion of unused connections. Introducing the Sisense Connection Prune Tool The Sisense Connection Prune Tool is a Python-based Sisense API based tool designed to programmatically identify and delete unused connections. It generates a CSV report listing all connections and their associated datasources, streamlining your connection management process. If desired, it can automatically remove all unused connections automatically from a Sisense server.   Using the Tool, sourcing the Virtual Environment, generating the Connection CSV   CSV Output of Used Connections and Associated Datasources   CSV opened visually to view as Table, Excel and other programs and text editors can open CSV files   Sisense Connection Prune Tool README Here's the full README included with the tool: # Sisense Connection Prune Tool A command-line tool to list used data connections and prune unused Sisense connections via CSV. It allows you to generate a CSV file of all connections and their dependencies, then delete those connections if needed, after removing the connections to keep from the CSV. ## Features - **Dry Run Mode**: Simulate deletions without making any changes. - **CSV-Based Flow**: Easily inspect and list connections to remove before deletion. - **Logging**: Extensive logs if needed. - **Error Handling**: Clear and descriptive messages for issues encountered during execution. ## Usage 1. **Activate the Virtual Environment** After downloading this project folder, activate the Python virtual environment bundled with it that includes all Python dependencies. - **Windows**: `venv\Scripts\activate` - **macOS/Linux**: `source venv/bin/activate` 2. **Configure the Tool** Open the `config.yaml` file and set your Sisense server URL, bearer token, CSV file path, and log file path. For example: ```yaml server_url: "https://your.sisense.server" bearer_token: "your_bearer_token_here" dry_run: true csv_file_path: "connections.csv" log_file_path: "connection_tool.log" ``` - **server_url**: The URL of your Sisense instance. - **bearer_token**: Your Sisense API token for authentication. - **dry_run**: If set to `true`, deletions will be simulated (no real deletions). - **csv_file_path**: Where the CSV file should be created and read from. - **log_file_path**: Where log file will be stored. 3. **Run the Tool** ```bash python3 ConnectionPruneTool.py ``` You will be prompted to choose an option: 1. **Generate connection CSV** - Fetches all Sisense connections. - Immediately removes (or simulates removing, if `dry_run` is `true`) any connection with no dependencies. - Writes all remaining connections and their dependencies to the CSV file. - **Important**: Inspect the CSV file and remove lines for any connections you want to **keep**. 2. **Delete connections from CSV list** - Reads the CSV file. - Removes or simulates removing each connection still listed. - Provides a summary report of which connections were deleted or bypassed. 4. **Review the Logs** Check the file specified in `log_file_path` for a record of all actions taken or simulated if needed. This is helpful for understanding what happened during each run and diagnosing any issues. ## Example Workflow 1. **Generate CSV** ```bash python3 ConnectionPruneTool.py # Choose option 1 when prompted ``` After generation, open the CSV file and **delete rows** corresponding to any connections you want to **keep**. 2. **Delete Connections** ```bash python3 ConnectionPruneTool.py # Choose option 2 when prompted ``` The tool will read the CSV and delete the remaining listed connections (or simulate deletion, if `dry_run` is enabled). ## Notes - Unused connections are removed automatically in step 1, without a CSV step - To keep a connection, remove its line from the CSV before proceeding with deletion. - If `dry_run` is set to `true`, no actual deletions will occur, only simulated logs and printed messages. - The log file will be cleared at the start of each run, so be sure to review or archive logs (or change log file name in config), if needed. ​ This is a command-line tool to list used data connections and prune unused Sisense connections, in general and via a CSV list. It allows a user with a data admin or higher bearer token to generate a CSV file of all connections and their dependencies, then delete those connections if needed, from the remaining connections in the CSV. Example Output: Deleted unused connection: Old_DB_Connection (ID: 123abc) CSV file generated at connections.csv. It contains 25 row(s) of active connections. Please review and remove lines for connections you want to keep before running deletion step by running tool again. Remaining lines will be deleted in deletion mode. Summary Report: Total lines in CSV (active used connections): 25 Deleted Unused Connections: - Old_DB_Connection No connections were bypassed.   API Endpoints Used Retrieve connections: GET /api/v2/connections Retrieve dependencies: GET /api/v2/connections/{connection_id}/getAllDependencies Delete connection: DELETE /api/v2/connections/{connection_id} Full Code connections.py - Uses Sisense API endpoints to: Fetch all connections (GET /api/v2/connections). Retrieve datasource dependencies for a specific connection (GET /api/v2/connections/{connection_id}/getAllDependencies). Delete a specific connection (DELETE /api/v2/connections/{connection_id}).     from helperFunctions import load_config, api_get, api_delete config = load_config() headers = {"Authorization": f"Bearer {config['bearer_token']}"} base_url = config["server_url"] # Retrieve all connections from Sisense def get_all_connections(): endpoint = f"{base_url}/api/v2/connections" return api_get(endpoint, headers) # Retrieve dependencies of a specific connection def get_connection_dependencies(connection_id): endpoint = f"{base_url}/api/v2/connections/{connection_id}/getAllDependencies" return api_get(endpoint, headers) # Delete a specific connection def delete_connection(connection_id): endpoint = f"{base_url}/api/v2/connections/{connection_id}" return api_delete(endpoint, headers) helperFunctions.py - Uses the Requests library to handle API requests (GET/DELETE). Catches and logs API errors. Uses PyYAML to read the config.yaml file for configuration.     import yaml import requests import logging # Load configuration from YAML file def load_config(): with open("config.yaml", "r") as file: return yaml.safe_load(file) # Configure logging settings def setup_logging(log_file): logging.basicConfig( filename=log_file, level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s", ) # Perform a GET request with error handling def api_get(endpoint, headers): try: response = requests.get(endpoint, headers=headers, verify=False) response.raise_for_status() return response.json() except requests.RequestException as e: logging.error(f"GET request failed: {e}") print(f"Error during GET request: {e}") return None # Perform a DELETE request with error handling def api_delete(endpoint, headers): try: response = requests.delete(endpoint, headers=headers, verify=False) response.raise_for_status() return response except requests.RequestException as e: logging.error(f"DELETE request failed: {e}") print(f"Error during DELETE request: {e}") return None ConnectionPruneTool.py - Serves as the entry point for the entire tool. Implements a CLI for user interaction. Invokes connections.py and helperFunctions.py to retrieve, analyze, and optionally delete Sisense connections. Uses Pandas to build a DataFrame of connection details and writes the results to a CSV file. Reads back the CSV file to remove selected connections after manual edits. Manages logs and prints summary reports to the terminal. import pandas as pd import logging import os from connections import ( get_all_connections, get_connection_dependencies, delete_connection, ) from helperFunctions import load_config, setup_logging # Load config yaml config = load_config() setup_logging(config["log_file_path"]) # Clear log file at start open(config["log_file_path"], "w").close() dry_run = config["dry_run"] csv_path = config["csv_file_path"] def generate_connections_csv(): """ Retrieves all connections from Sisense, deletes any that have no dependencies (unless in dry_run mode), and writes the remaining used connections and their dependent data models to a CSV file. """ # Create or clear existing CSV open(csv_path, "w").close() connections = get_all_connections() if connections is None: logging.error("Failed to retrieve connections.") print("Failed to retrieve connections.") return data = [] deleted = [] bypassed = [] # Go through each connection returned from the API for conn in connections: dependencies = get_connection_dependencies(conn["oid"]) if dependencies is None: logging.warning( f"Failed to retrieve dependencies for: {conn['name']} ({conn['oid']})" ) print( f"Failed to retrieve dependencies for: {conn['name']} ({conn['oid']})" ) bypassed.append(conn["name"]) continue # If no dependencies, optionally delete the connection (not in dry-run) if not dependencies: action_msg = "[Dry Run] Would delete" if dry_run else "Deleted" log_str = ( f"{action_msg} unused connection: {conn['name']} (ID: {conn['oid']})" ) print(log_str) logging.info(log_str) if not dry_run: try: response = delete_connection(conn["oid"]) # If response is None, treat it as a failed deletion if response is None: logging.error( f"Failed to delete unused connection: {conn['name']} ({conn['oid']})." ) print( f"Error deleting unused connection: {conn['name']} ({conn['oid']})" ) bypassed.append(conn["name"]) else: deleted.append(conn["name"]) except Exception as e: logging.error( f"Exception while deleting unused connection: {conn['name']} ({conn['oid']}) - {e}" ) print( f"Error deleting unused connection: {conn['name']} ({conn['oid']})" ) bypassed.append(conn["name"]) else: # If the connection is used, add each dependency row to CSV. # Use a fallback value if 'title' or 'oid' is missing. for dep in dependencies: dep_title = dep.get( "title", "NULL TITLE Share Datasource with associated Bearer Token user to include in CSV", ) dep_oid = dep.get("oid", "NULL OID") data.append( { "Connection Name": conn["name"], "Connection ID": conn["oid"], "Elasticube/Data Model Name": dep_title, "Elasticube/Data Model ID": dep_oid, } ) # Create a DataFrame of only the used connections (with datasource dependencies) df = pd.DataFrame(data) df.to_csv(csv_path, index=False) row_count = len(df) logging.info(f"Generated CSV at {csv_path}") print( f"CSV file generated at {csv_path}. " f"It contains {row_count} row(s) of used connections.\n" "Please review and remove lines for connections you want to keep " "before running deletion step by running tool again. Remaining lines will be deleted in deletion mode." ) # Summaries for auto-deleted (unused) connections print("\nSummary Report:") print(f"Total lines in CSV (active used connections): {row_count}") if deleted: print("\nDeleted Unused Connections:") for d in deleted: print(f" - {d}") else: print("\nNo connections were deleted in this step.") if bypassed: print("\nBypassed Connections:") for b in bypassed: print(f" - {b}") else: print("\nNo connections were bypassed in this step.") def delete_connections_from_csv(): """ Reads the CSV (remaining lines after user review, removing lines for connections to keep), then deletes each connection listed. If a delete fails or returns None, the connection is logged and added to 'bypassed'. """ if not os.path.exists(csv_path): print( "CSV file does not exist. Please generate it first or fix the config path." ) return df = pd.read_csv(csv_path) deleted = [] bypassed = [] for _, row in df.iterrows(): conn_id = row["Connection ID"] conn_name = row["Connection Name"] action_msg = "[Dry Run] Would delete" if dry_run else "Deleted" log_str = f"{action_msg} connection: {conn_name} ({conn_id})" print(log_str) logging.info(log_str) if not dry_run: try: response = delete_connection(conn_id) if response is None: logging.error( f"Failed to delete connection: {conn_name} ({conn_id})" ) print(f"Error deleting connection: {conn_name} ({conn_id})") bypassed.append(conn_name) else: deleted.append(conn_name) except Exception as e: logging.error( f"Exception while deleting connection: {conn_name} ({conn_id}) - {e}" ) print(f"Error deleting connection: {conn_name} ({conn_id})") bypassed.append(conn_name) # Print summary report print("\nSummary Report:") if deleted: print("Deleted Connections:") for d in deleted: print(f" - {d}") else: print("No connections were deleted.") if bypassed: print("\nBypassed:") for b in bypassed: print(f" - {b}") else: print("No connections were bypassed.") if __name__ == "__main__": # If there is no CSV file found, select step 1 automatically if not os.path.exists(csv_path): print( "No CSV file found; defaulting to generating connections CSV. " "Correct config if CSV file name has changed." ) generate_connections_csv() else: choice = input( "Choose an option:\n" "1 - Generate connection CSV\n" "2 - Delete connections from CSV list\n" "Enter your choice (1 or 2): " ) if choice == "1": generate_connections_csv() elif choice == "2": delete_connections_from_csv() else: print("Invalid option. Please enter '1' or '2'.") Conclusion By automating the detection of inactive connections and simplifying their removal, the Sisense Connection Prune Tool reduces clutter in the Sisense server Connection Manager UI while minimizing the risk of unintentionally impacting active datasources. Whether you opt for a dry-run mode to review potential deletions in a generated CSV file, or to simply list connections, or proceed with the full removal of unused connections, this tool offers a clear, flexible, and reliable approach to keeping your connections organized. A full copy of the tool, is attached below.        

      Jeremy Friedel
      Jeremy FriedelPosted 1 year ago • Last reply 6 months ago
      4
               
    • Blog banner
      • Add-ons & Plug-InsChevronRightIcon

      Customizing the Sisense User Interface with Interactive Buttons and Icons

                                                                                                               

      Customizing the Sisense User Interface with Interactive Buttons and Icons Sisense plugins  and scripts enable extensive customization of the Sisense user interface, allowing developers to add interactive elements such as buttons and icons to enhance functionality and user experience. A common use case of plugins involves adding clickable icons or buttons that trigger specific plugin features or open custom UI elements. This article outlines the process for adding these interactive elements using a practical example.   Icon Example Key Steps for Adding Clickable Buttons Follow this general flow to successfully add a custom clickable buttons or icon into the Sisense UI: Choose the UI placement:   Determine the exact area of the Sisense UI where the button or icon will appear. Identify the target parent container:   Find the appropriate parent element in the DOM that will contain the new button. Prevent duplication:   Implement checks to avoid adding duplicate buttons, if Sisense dashboard or prism event used fires more than once. Create the HTML button element:   Construct the button programmatically and apply necessary styling, adding either button text or icon image. Attach Click Listener:   Use JavaScript event listeners to define the button or icon interactive behavior. Practical Example: Adding a Button to the Filter Header Below is a clear and reusable example demonstrating the process of adding a clickable button to the filters header in a Sisense dashboard. This can easily be adapted for different parts of the dashboard or various plugin functionalities.   function addCustomButton() { // Step 1: Locate the UI container (in this example, the header to the right hand filter panel) const filtersContainer = document.querySelector('.filters-headline'); // Step 2: Avoid duplicate button addition if (filtersContainer && !filtersContainer.querySelector('.custom-btn')) { // Identify placement context, in this example next to the spacer element to the right of the filters label const spacerElement = filtersContainer.querySelector('.spacer'); if (spacerElement) { // Step 3: Create the button with appropriate classes const customButton = document.createElement('button'); customButton.classList.add('btn', 'btn--icon', 'btn--dark', 'btn--on-grey', 'custom-btn'); // Insert an SVG icon (example provided) customButton.innerHTML = ` <svg xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" width="100" height="100" viewBox="0,0,256,256"> <g fill="#5b6372" fill-rule="nonzero" stroke="none" stroke-width="1" stroke-linecap="butt" stroke-linejoin="miter" stroke-miterlimit="10" stroke-dasharray="" stroke-dashoffset="0" font-family="none" font-weight="none" font-size="none" text-anchor="none" style="mix-blend-mode: normal"> <g transform="scale(8,8)"> <path d="M9,4c-1.64453,0 -3,1.35547 -3,3v18c0,1.64453 1.35547,3 3,3h17v-24zM9,6h3v11.41406l4,-4l4,4v-11.41406h4v16h-15c-0.35156,0 -0.68359,0.07422 -1,0.1875v-15.1875c0,-0.56641 0.43359,-1 1,-1zM14,6h4v6.58594l-2,-2l-2,2zM9,24h15v2h-15c-0.56641,0 -1,-0.43359 -1,-1c0,-0.56641 0.43359,-1 1,-1z"></path> </g> </g> </svg> `; = ` <!-- Your SVG icon here --> `; // Step 4: Define button functionality customButton.addEventListener('click', function () { // Replace with your plugin's custom action yourPlugin.action(); }); // Insert button into UI spacerElement.insertAdjacentElement('afterend', customButton); } } } // Add button upon dashboard load prism.on("dashboardloaded", function (e, args) { args.dashboard.on("widgetinitialized", addCustomButton); }); By following these principles and adapting the provided example, you can effectively enrich the Sisense interface, tailoring the UI to specific custom workflows and interactions.

      Jeremy Friedel
      Jeremy FriedelPosted 1 year ago
      0
               
    • Blog banner
      • Add-ons & Plug-InsChevronRightIcon

      Loading Amchart5 and Other External Libraries via Script Tags in Plugins

                                                                                                               

      This article explains how to load external libraries, such as Amchart5 , into Sisense plugins , such as plugins that create new custom widget visualization types, by dynamically adding script tags to the page header to load the library. This method can avoid potential issues associated with other loading techniques but also offers flexibility such as using an external CDN to reduce plugin size and file count. Previous articles  have discussed how to load external libraries and modules for Sisense plugins via adding the file to the plugin folder, and adding the file to the "source" parameter array in the plugin.json.   What Is a Script Tag?   A  script tag  is an HTML element (<script>) used to embed or reference JavaScript code in an HTML document. When you include a script tag with a src attribute, the browser downloads and executes the external JavaScript file.   Why Use Script Tags for Loading External Libraries? For certain JavaScript libraries, especially visualization libraries like Amchart5, loading the library via a script tag can help avoid issues that might arise from bundling the files directly into the plugin. The script tag method provides several benefits: Flexibility:  It allows the option of using an external CDN. This can reduce the size of the plugin package and the number of files you need to manage. Auto-Updating:  When using a CDN, the external library can be updated automatically without modifying the plugin. Self-Hosting Option:  Alternatively, you can set the src parameter to a local path of JavaScript files uploaded within the plugin, ensuring that the plugin remains fully self-hosted and independent of any CDN. Loading External Libraries: Self-Hosted or Using a CDN Self-Hosted:  The script’s src is set to point to the files within the plugin folder. This follows this very specific format: /plugins/${name_of_plugin_folder}/{Any_subfolders_if_needed}/{full_name_of_the_file} This approach makes the plugin self-contained and avoids external dependencies. The src path must follow this format. CDN-Hosted:  The src parameter is set to the URL of the external CDN, such as: https://cdn.amcharts.com/lib/5/xy.js Using a CDN can reduce the plugin’s file size and benefit from auto-updating libraries, though it introduces a dependency on the CDN’s availability. Example Loader Script Below is an example of a loader file (loader.6.js) that dynamically adds script tags to the page header to load Amchart5 and its modules (AM5 is loaded in this example, as well as additional AM5 modules dealing with axises and animation, this is a self-hosted example and does not rely on a CDN). // List of script URLs to add to the page header const scriptUrls = [ "/plugins/am5Example/am5/index.js", "/plugins/am5Example/am5/xy.js", "/plugins/am5Example/am5/themes/Animation.js" ]; // Function to add a script tag to the header function addScriptToHeader(url) { const script = document.createElement("script"); script.src=url; // Optionally set async or defer attributes if needed script.async = false; document.head.appendChild(script); } // Loop through each URL and add it to the header scriptUrls.forEach(url => addScriptToHeader(url));   This can be modified to occur on a specific prism and dashboard event, as opposed to immediately when the plugin loads. In this script: document.createElement("script"):  Creates a new script tag. script.src:  Specifies the source of the JavaScript file. document.head.appendChild(script):  Adds the script tag to the Sisense page header. The async attribute is set to false to ensure that scripts load in the order they are added. Configuring plugin.json In your plugin’s plugin.json, reference the loader file and the library file itself. The loader file then adds the necessary external scripts. An example plugin.json configuration is shown below: { "name": "am5Example", "pluginInfraVersion": 2, "isEnabled": true, "source": [ "am5/loader.6.js" ], "folderName": "am5Example", "version": "1.0.0" } This setup makes the external library (Amchart5, in this case) available to your plugin without bundling the entire library directly into the main codebase. Conclusion Using script tags to load external libraries like Amchart5 provides a flexible method for managing dependencies in Sisense plugins. Whether the libraries are self-hosted or rely on an external CDN, this method simplifies the management of external scripts and can lead to more efficient plugin development, and avoid issues with specific libraries such as Amchart5 that work best when loaded as a script element. The example plugin that demonstrates this type of loading is available for download below.    

      Jeremy Friedel
      Jeremy FriedelPosted 1 year ago • Last reply 1 year ago
      1
               
      • Sisense AdministrationChevronRightIcon

      How to make a dashboard as the first page of the analytics tab

                                       

      Introduction:  How to add the dashboard/site as the first page of the Analytics tab with the help of the Branding. Step-by-step guide:  Create a dashboard based on the BLOX, for example Share this dashboard with the group Everyone Press 3 dots on the top right of the dashboard, select Embed code, and select the following checkboxes on the float window [ALT Text: The image shows the "Embed Dashboard" settings for a Sisense dashboard. It includes options to customize the embed settings, such as toggling the right panel, left panel, toolbar, and header. The URL code at the bottom updates based on the selected options. The unchecked options suggest that the embed link is being customized to hide specific UI elements in the embedded dashboard.] Copy the URL Code Paste it to the Admin - App configuration - White labeling - Analytics & Data Main pages  -  Analytics Home Page or  Admin - Server & Hardware - Management - Configuration - Branding - Home Page  (Be sure that toggle Enable Branding is enabled) Press the Save button to save the changes Check with a user who has Viewer permission To add the site, you should just paste the URL of the site into the Home Page field. Just remember that, based on the security, that site should allow use if with Iframe from other domains - X-Frame-Options: ALLOW-FROM origin ( https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/X-Frame-Options ) Sisense Docs 

      OleksandrB
      OleksandrBPosted 1 year ago
      0
               
      • Add-ons & Plug-InsChevronRightIcon

      Exploring the Potential of Sisense Jump to Dashboard Filter Configurations

                                                                       

      Exploring the Potential of Sisense Jump to Dashboard Filter Configurations Introduction: Sisense Jump to Dashboard offers a powerful way to enhance the user experience and streamline data exploration with the help of different filter configurations. By default, all the filters from the parent dashboard, measured values, and widget filters are passed and replaced in the drill dashboard. This guide explains and provides examples of how you can customize the way filters impact the drill dashboard. We'll delve into multiple filter configuration options and provide a step-by-step guide on how to implement them effectively. The Default Behaviour & Description: The default settings of the Jump to Dashboard add-on do not require any JavaScript configuration. You can use the plugin with the default configuration right after it’s enabled. The default filter behavior configuration is the following: displayFilterPane : true This parameter determines if to display a filter pane in the target dashboard window. The default value is true which means that the filters pane shall be displayed. excludeFilterDims : [] Dimensions to exclude from the drilled dashboard filter. An empty array means that no dimensions are excluded. includeFilterDims : [] Dimensions to include in the drilled dashboard filter. An empty array means that all dimensions are included. resetDashFilterAfterJTD : false Resets the filters of a target dashboard. Combine this with mergeTargetDashboardFilters if you want your dashboard filters to be displayed in the target dashboard. mergeTargetDashboardFilters : false Determines if you want your dashboard filters to be displayed in the target dashboard (usually combined with resetDashFilterAfterJTD) Configuration Methods: A detailed explanation can be found here: https://community.sisense.com/t5/knowledge/jumptodashboard-plugin-how-to-use-and-customize/ta-p/17375 config.js method: it’s a system-wide configuration and takes effect for the entire Sisense installation. To edit the default system-wide JTD filters configuration set in the config.js navigate with the help of File Manager to plugins -> jumpToDashboard -> js -> config.js Adjust the configuration required by modifying the file and saving the changes - the changes will take effect after the plugin rebuild process which is initiated right after the config changes are saved. Once the user refreshes the dashboard and obtains the last build of the plugins, the new configuration will be in place across all the dashboards. Widget script method: It’s used to override the default system-wide config and can change the behavior of a particular widget Not all configuration parameters are supported for this method - check the “Configured In” field of the specification table located on the Technical Details tab of the JTD Marketplace Page: Jump to Dashboard - Sisense Configuration can be applied by adding the Widget JavaScript Extension to the particular widget The changes take effect right after the script is saved and the dashboard containing the widget is reloaded. Configurable Filters Behavior + Script Examples: displayFilterPane The filter panel is visible by default: If you want to hide it in the drill dashboard, just change row 4 in config.js like:   displayFilterPane : false   OR add the following script to configure it for the particular JTD widget   prism.jumpToDashboard(widget, { displayFilterPane: false});​   The result will look like this: excludeFilterDims By default, all the filters from the parent dashboard, measured values, and widget filters are passed to the drill dashboard, but you can exclude particular dimensions from being passed. In Sisense, a "dimension" is a qualitative attribute used to categorize and filter quantitative data (measures). In most cases, it will be represented as the table_name.column_name identifying the data location in the elasticube or live model. A few things to note: excludeFilterDims is an array so even when the single filter dimension is used, it should be enclosed in square brackets []. This configuration can be modified both on a system-wide level via config.js, or via the widget script When excluding the date dimension using the parameter excludeFilterDims, (Calendar) must be used or the exclusion will not work.  Example: [Table.Dimension(Calendar)] An example if you use excludeFilterDims with Dimension B: Parent Dash FIlters Drill Dash Filters Resulting Filters Dimension A - Value A1 Dimension A - Value A2 Dimension A - Value A1 Dimension B - Value B1 Dimension B - Value B2 No Dimension C - Value C1 Dimension C - Value C2 Dimension C - Value C1 Widget script Example:   prism.jumpToDashboard(widget, { excludeFilterDims: ["[divisions.Divison_name]", "[Admissions.Admission_Time (Calendar)]", "[doctors.Specialty]" ] });   includeFilterDims It’s the opposite of the excludeFilterDims described above. includeFilterDims is intended to explicitly set the filter's dimensions you want to pass to the drill dashboard. All other filter dims will be ignored . The same usage notes apply here as for the excludeFilterDims. Example if you use includeFilterDims with Dimension B: Parent Dash FIlters Drill Dash Filters Resulting Filters Dimension A - Value A1 Dimension A - Value A2 No Dimension B - Value B1 Dimension B - Value B2 Dimension B - Value B1 Dimension C - Value C1 Dimension C - Value C2 No Widget script Example:   prism.jumpToDashboard(widget, { includeFilterDims: ["[country.Country]", "[brand.Brand]" ] });   resetDashFilterAfterJTD Note: Configurable in config,js file only By default, after we open the dashboard with the help of JTD, the filters passed to this drill dashboard by JTD are saved for the user. This behavior can be changed with the help of resetDashFilterAfterJTD config. Once set to true, the filters of the drill dashboard will be preserved (in the temporary storage inside the dashboard object ​​prism.activeDashboard.filtersToRestore) and restored during the next dashboard opening. config.js example:   resetDashFilterAfterJTD: true   mergeTargetDashboardFilters By default, when the drill dashboard is opened with the help of JTD, the filters of the drill dashboard are replaced with the filters from the parent dashboard. If you’d like to compliment the dashboard filters with the original ones from the drill dashboard, you can enable this parameter. Usage Example: Parent Dash FIlters Drill Dash Filters mergeTargetDashboardFilters: false mergeTargetDashboardFilters: true No Dimension A - Value A2 No Dimension A - Value A2 Dimension B - Value B1 Dimension B - Value B2 Dimension B - Value B1 Dimension B - Value B1 No Dimension C - Value C2 No Dimension C - Value C2 Widget Script Example:   prism.jumpToDashboard(widget, { mergeTargetDashboardFilters: true });   Locating the correct dimension for the config: There is a simple way of finding out the correct filter dims for the configuration scripts. When the source dashboard is open, open the Browser Development Console. Here are the common shortcuts to open the browser developer console: Chrome: Ctrl + Shift + J (Windows/Linux) or Cmd + Option + J (Mac) Firefox: Ctrl + Shift + K (Windows/Linux) or Cmd + Option + K (Mac) Edge: Ctrl + Shift + I (Windows/Linux) or Cmd + Option + I (Mac) Safari: Cmd + Option + C (Mac) (Enable "Show Develop menu in menu bar" in Preferences first) Opera: Ctrl + Shift + I (Windows/Linux) or Cmd + Option + I (Mac) In the console type in the following to list the active dashboard filters’ dimensions:   prism.activeDashboard.filters.$$items.forEach((item)=>console.log(JSON.stringify(item.jaql.dim)));   The list of active dashboard filter dimensions should be returned like below, so you can use them in your configurations: Hope the above helps you understand the Jump to Dashboard filter settings better and I wish you good luck with setting up your JTD customizations!

      Taras Skvarko
      Taras SkvarkoPosted 2 years ago • Last reply 1 year ago
      2