Skip to content

dashboard_builder

dashboard_builder

Dashboard builder for creating Domo pages with card layouts.

Follows the same builder pattern as kpi_builder.py and alert_builder.py.

Workflow
  1. Build a DashboardDefinition with card placements and optional headers
  2. Call build_dashboard() to get the page creation + layout body
  3. Use create_page() route to create the page
  4. Use bulk_add_cards_to_pages() to add cards
  5. Use create_page_layout() to create the layout
  6. Use update_page_layout() to set the final card positions

Or use the convenience function create_dashboard() which does all steps.

Example

from crew_dcs.classes.dashboard_builder import ( DashboardDefinition, CardPlacement, SectionHeader, create_dashboard ) from crew_dcs.auth import DomoTokenAuth

dashboard = DashboardDefinition( title="P&L Dashboard", cards=[ CardPlacement(card_id=533357453, x=0, y=0, width=60, height=30), CardPlacement(card_id=1604966475, x=0, y=30, width=30, height=30), CardPlacement(card_id=123456789, x=30, y=30, width=30, height=30), ], headers=[ SectionHeader(text="Revenue Overview", x=0, y=0, width=60, height=5), ], )

auth = DomoTokenAuth(domo_access_token="...", domo_instance="datacrew-space") result = await create_dashboard(auth=auth, dashboard=dashboard)

result.page_id, result.layout_id

CardPlacement dataclass

CardPlacement(
    card_id: int,
    x: int,
    y: int,
    width: int,
    height: int,
    hide_title: bool = False,
    hide_border: bool = False,
    hide_description: bool = True,
    hide_footer: bool = True,
    hide_timeframe: bool = False,
    accept_filters: bool = True,
    accept_date_filter: bool = True,
    accept_segments: bool = True,
    fit_to_frame: bool = False,
    compact_x: int | None = None,
    compact_y: int | None = None,
    compact_width: int = 12,
    compact_height: int = 6,
)

Placement of a card on the dashboard grid.

The Domo standard grid is 60 units wide. Height units are arbitrary (the grid auto-sizes based on aspect ratio). Common patterns: - Full width: x=0, width=60 - Half width: x=0 or x=30, width=30 - Third width: x=0/20/40, width=20 - Quarter width: x=0/15/30/45, width=15

Parameters:

Name Type Description Default
card_id int

The Domo card ID

required
x int

Horizontal position (0-59)

required
y int

Vertical position (0+)

required
width int

Card width (1-60)

required
height int

Card height (typical: 30 for standard, 7 for compact)

required
hide_title bool

Hide the card title

False
hide_border bool

Hide the card border

False
hide_description bool

Hide the card description

True
hide_footer bool

Hide the card footer

True
hide_timeframe bool

Hide the timeframe selector

False
accept_filters bool

Accept dashboard filter interactions

True
accept_date_filter bool

Accept date filter interactions

True
accept_segments bool

Accept segment interactions

True
fit_to_frame bool

Fit card to frame (removes margins)

False
compact_x int | None

Override compact layout x position

None
compact_y int | None

Override compact layout y position

None
compact_width int

Override compact layout width (default: 12)

12
compact_height int

Override compact layout height (default: 6)

6

DashboardCreationResult dataclass

DashboardCreationResult(
    page_id: int,
    layout_id: str,
    page_response: dict,
    layout_response: dict,
    layout_update_response: dict | None,
)

Result of create_dashboard() — holds all the IDs from the workflow.

DashboardDefinition dataclass

DashboardDefinition(
    title: str,
    cards: list[CardPlacement] = list(),
    headers: list[SectionHeader] = list(),
    parent_page_id: int = 0,
    background_color: str = "#FFFFFF",
    text_color: str = "#4A4A4A",
    locked: bool = False,
    standard_width: int = 60,
    standard_aspect_ratio: float = 1.67,
    compact_width: int = 12,
    compact_aspect_ratio: float = 1.0,
)

Complete dashboard definition: page + layout + card placements.

Parameters:

Name Type Description Default
title str

Dashboard (page) title

required
cards list[CardPlacement]

List of CardPlacement objects

list()
headers list[SectionHeader]

List of SectionHeader objects (optional)

list()
parent_page_id int

Parent page ID (0 for top-level)

0
background_color str

Background color hex (default: #FFFFFF)

'#FFFFFF'
text_color str

Text color hex (default: #4A4A4A)

'#4A4A4A'
locked bool

Lock the dashboard

False
standard_width int

Grid width (default: 60, don't change unless you know why)

60
standard_aspect_ratio float

Card aspect ratio (default: 1.67)

1.67
compact_width int

Compact grid width (default: 12)

12
compact_aspect_ratio float

Compact card aspect ratio (default: 1.0)

1.0

SectionHeader dataclass

SectionHeader(
    text: str,
    x: int,
    y: int,
    width: int,
    height: int = 5,
    compact_x: int | None = None,
    compact_y: int | None = None,
    compact_width: int = 12,
    compact_height: int = 2,
)

A section header on the dashboard.

Headers are text labels that group cards visually. They take up grid space but don't display data.

Parameters:

Name Type Description Default
text str

Header text

required
x int

Horizontal position

required
y int

Vertical position

required
width int

Header width

required
height int

Header height (typically 5)

5
compact_x int | None

Override compact x

None
compact_y int | None

Override compact y

None
compact_width int

Override compact width (default: 12)

12
compact_height int

Override compact height (default: 2)

2

build_dashboard_layout_body

build_dashboard_layout_body(
    dashboard: DashboardDefinition,
    layout_id: str | None = None,
    page_urn: str | None = None,
) -> dict

Build the layout body for a dashboard definition.

This produces the body for PUT /content/v4/pages/layouts/{layoutId}. The layout_id and page_urn are required for an update — they come from the create_page_layout() response.

Parameters:

Name Type Description Default
dashboard DashboardDefinition

DashboardDefinition with card placements and headers

required
layout_id str | None

Layout ID (from create_page_layout response)

None
page_urn str | None

Page ID (same as page_id)

None

Returns:

Type Description
dict

Layout body dict for the PUT API call

Source code in src/crew_dcs/classes/dashboard_builder.py
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
def build_dashboard_layout_body(
    dashboard: DashboardDefinition,
    layout_id: str | None = None,
    page_urn: str | None = None,
) -> dict:
    """Build the layout body for a dashboard definition.

    This produces the body for PUT /content/v4/pages/layouts/{layoutId}.
    The layout_id and page_urn are required for an update — they come from
    the create_page_layout() response.

    Args:
        dashboard: DashboardDefinition with card placements and headers
        layout_id: Layout ID (from create_page_layout response)
        page_urn: Page ID (same as page_id)

    Returns:
        Layout body dict for the PUT API call
    """
    content = []
    standard_template = []
    compact_template = []

    # Add headers first, then cards — this matches the Domo UI pattern
    # where headers appear above their card sections

    # Sort all items by y position, then x position
    all_items: list[tuple[int, int, str, Any]] = []
    for header in dashboard.headers:
        all_items.append((header.y, header.x, "header", header))
    for card in dashboard.cards:
        all_items.append((card.y, card.x, "card", card))

    all_items.sort(key=lambda item: (item[0], item[1]))

    for content_key, (_, _, item_type, item) in enumerate(all_items):
        tmpl_type = "HEADER" if item_type == "header" else "CARD"
        if item_type == "header":
            content.append(_build_header_content(content_key, item))
        else:
            content.append(_build_card_content(content_key, item))

        standard_template.append(
            _build_template_item(
                content_key, item.x, item.y, item.width, item.height, tmpl_type
            )
        )
        # Use explicit None checks: a compact position of 0 is valid and must
        # not fall through to the default (falsy-zero bug).
        compact_x = item.compact_x if item.compact_x is not None else 0
        compact_y = item.compact_y if item.compact_y is not None else item.y
        compact_template.append(
            _build_template_item(
                content_key,
                compact_x,
                compact_y,
                item.compact_width,
                item.compact_height,
                tmpl_type,
            )
        )

    body: dict[str, Any] = {
        "printFriendly": True,
        "enabled": True,
        "isDynamic": False,
        "hasPageBreaks": False,
        "content": content,
        "standard": {
            "aspectRatio": dashboard.standard_aspect_ratio,
            "width": dashboard.standard_width,
            "frameMargin": None,
            "framePadding": None,
            "type": "STANDARD",
            "template": standard_template,
        },
        "compact": {
            "aspectRatio": dashboard.compact_aspect_ratio,
            "width": dashboard.compact_width,
            "frameMargin": None,
            "framePadding": None,
            "type": "COMPACT",
            "template": compact_template,
        },
        "background": {
            "selectedColor": dashboard.background_color,
            "textColor": dashboard.text_color,
            "type": "COLOR",
            "darkMode": False,
            "alpha": 1.0,
        },
    }

    if layout_id is not None:
        body["layoutId"] = layout_id
    if page_urn is not None:
        body["pageUrn"] = str(page_urn)

    return body

create_dashboard async

create_dashboard(
    auth: DomoAuth,
    dashboard: DashboardDefinition,
    *,
    context: RouteContext | None = None,
    **context_kwargs
) -> DashboardCreationResult

Create a complete dashboard: page + cards + layout.

This is the convenience function that does the full workflow: 1. Create the page (POST /content/v1/pages) 2. Bulk add cards to the page (PUT /content/v1/cards/bulk/pages) 3. Create the layout (POST /content/v4/pages/layouts) 4. Update the layout with proper card positions (PUT /content/v4/pages/layouts/{id})

Parameters:

Name Type Description Default
auth DomoAuth

DomoAuth object

required
dashboard DashboardDefinition

DashboardDefinition with card placements

required
context RouteContext | None

Optional RouteContext

None
**context_kwargs

Additional context parameters

{}

Returns:

Type Description
DashboardCreationResult

DashboardCreationResult with page_id, layout_id, and raw responses

Source code in src/crew_dcs/classes/dashboard_builder.py
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
async def create_dashboard(
    auth: DomoAuth,
    dashboard: DashboardDefinition,
    *,
    context: RouteContext | None = None,
    **context_kwargs,
) -> DashboardCreationResult:
    """Create a complete dashboard: page + cards + layout.

    This is the convenience function that does the full workflow:
    1. Create the page (POST /content/v1/pages)
    2. Bulk add cards to the page (PUT /content/v1/cards/bulk/pages)
    3. Create the layout (POST /content/v4/pages/layouts)
    4. Update the layout with proper card positions (PUT /content/v4/pages/layouts/{id})

    Args:
        auth: DomoAuth object
        dashboard: DashboardDefinition with card placements
        context: Optional RouteContext
        **context_kwargs: Additional context parameters

    Returns:
        DashboardCreationResult with page_id, layout_id, and raw responses
    """
    import httpx

    context = RouteContext.build_context(context=context, **context_kwargs)

    # Step 1: Create the page
    page_res = await create_page(
        auth=auth,
        title=dashboard.title,
        parent_page_id=dashboard.parent_page_id,
        context=context,
        return_raw=True,
    )
    if not page_res.is_success:
        raise RuntimeError(
            f"Failed to create page: {page_res.status} - {page_res.response}"
        )

    page_id = page_res.response.get("pageId")
    if not page_id:
        raise RuntimeError(
            f"Page creation response missing pageId: {page_res.response}"
        )

    # Step 2: Bulk add cards to the page
    if dashboard.cards:
        card_ids = [str(c.card_id) for c in dashboard.cards]
        add_res = await bulk_add_cards_to_pages(
            auth=auth,
            card_ids=card_ids,
            destination_page_ids=[int(page_id)],
            context=context,
            return_raw=True,
        )
        if not add_res.is_success:
            raise RuntimeError(
                f"Failed to bulk add cards: {add_res.status} - {add_res.response}"
            )

    # Step 3: Create the layout (auto-populates with card content items)
    layout_res = await create_page_layout(
        auth=auth,
        page_id=str(page_id),
        context=context,
        return_raw=True,
    )
    if not layout_res.is_success:
        raise RuntimeError(
            f"Failed to create layout: {layout_res.status} - {layout_res.response}"
        )

    layout_id = layout_res.response.get("layoutId")
    if not layout_id:
        raise RuntimeError(
            f"Layout creation response missing layoutId: {layout_res.response}"
        )

    # Step 4: Update the layout with proper card positions
    layout_body = build_dashboard_layout_body(
        dashboard=dashboard,
        layout_id=str(layout_id),
        page_urn=str(page_id),
    )

    # Resolve the acting user id for the write lock. Fail loudly rather than
    # silently locking as user "0" (which Domo may reject, leaving the layout
    # un-positioned while the workflow still reports success).
    user_id = getattr(auth, "user_id", None)
    if not user_id:
        await auth.who_am_i(context=context)
        user_id = getattr(auth, "user_id", None)
    if not user_id:
        raise RuntimeError(
            "Could not resolve the acting user id (auth.who_am_i returned no id); "
            "a write lock is required to position dashboard cards."
        )

    lock_url = (
        f"https://{auth.domo_instance}.domo.com"
        f"/api/content/v4/pages/layouts/{layout_id}/writelock"
    )

    async def _apply_layout_with_lock(lock_ctx: RouteContext) -> rgd.ResponseGetData:
        """Acquire the write lock, update the layout, and always release it."""
        now_epoch = dmcv.convert_datetime_to_epoch_millisecond(dt.datetime.now())
        lock_body = {
            "layoutId": str(layout_id),
            "lockHeartbeat": now_epoch,
            "lockTimestamp": now_epoch,
            "userId": user_id,
        }
        await gd.get_data(
            auth=auth, url=lock_url, method="PUT", body=lock_body, context=lock_ctx
        )
        try:
            return await update_page_layout(
                auth=auth,
                layout_id=str(layout_id),
                body=layout_body,
                context=lock_ctx,
                return_raw=True,
            )
        finally:
            # Release the lock even if the update raised, so the page is not
            # left write-locked for the lock TTL.
            await gd.get_data(
                auth=auth, url=lock_url, method="DELETE", context=lock_ctx
            )

    # Reuse the caller's session when it's still open; otherwise open a temp one.
    session = context.session
    if session is None or getattr(session, "is_closed", False):
        async with httpx.AsyncClient(timeout=30.0) as temp_session:
            update_res = await _apply_layout_with_lock(
                RouteContext.build_context(session=temp_session)
            )
    else:
        update_res = await _apply_layout_with_lock(context)

    layout_update_response = update_res.response if update_res.is_success else None

    return DashboardCreationResult(
        page_id=page_id,
        layout_id=str(layout_id),
        page_response=page_res.response,
        layout_response=layout_res.response,
        layout_update_response=layout_update_response,
    )