Orchardcore reports

From CrestApps/CrestApps.AgentSkills · View interactive version

Orchardcore reports is an AI agent skill from the GitHub repository CrestApps/CrestApps.AgentSkills. Skill for building on the CrestApps Orchard Core Reports framework (CrestApps.OrchardCore.Reports, Reports.OpenXml, Reports.Pdf). Covers coded reports with static IReport descriptors and services.AddReport, report families with IReportRunner and ReportDescriptor, ExportPermission and DefaultDateRang

How to use this skill

Skill file

CrestApps Orchard Core Reports

You are an Orchard Core expert. Generate accurate setup, report code, filters, export formats and widgets for the CrestApps Reports framework.

The Reports module is a reusable reporting framework. It adds one admin Reports area and a small contract any module implements to publish a report. Every report shares the same filter form, the same renderer (metric cards, tables, bars, Chart.js charts) and the same exports (CSV built in, Excel with an add-on). Modules such as Omnichannel, Contact Center, Phone Number Verifications, Orders and Inventory contribute their reports through it.

Designed reports that people build in the browser are the Report Builder feature; see the orchardcore-report-builder skill.

Guidelines

Features

| Feature ID | Name | What it adds | Depends on |

| --- | --- | --- | --- |

| CrestApps.OrchardCore.Reports | Reports | Admin Reports area, ReportFilter with the date range filter, renderer, CSV export | CrestApps.OrchardCore.Resources, OrchardCore.Users |

| CrestApps.OrchardCore.Reports.OpenXml | Reports (OpenXml) | Excel .xlsx export (DocumentFormat.OpenXml) | Reports |

| CrestApps.OrchardCore.Reports.Pdf | Reports (PDF) | PDF .pdf export laid out like the page (separate CrestApps.OrchardCore.Reports.Pdf package, uses CrestApps.OrchardCore.Pdf.Core and PdfPig) | Reports |

| CrestApps.OrchardCore.Reports.Subscriptions | Report Subscriptions | Emails any registered report daily, weekly or monthly (in the Reports package) | Reports, OrchardCore.Email |

| CrestApps.OrchardCore.Reports.Builder | Report Builder | Drag-and-drop designed reports (in the Reports package; see orchardcore-report-builder) | Reports, OrchardCore.DataPipelines.Core |

The feature IDs are constants on ReportsConstants (Feature, OpenXmlFeature, PdfFeature, SubscriptionsFeature, BuilderFeature).

{
  "steps": [
    {
      "name": "Feature",
      "enable": [
        "CrestApps.OrchardCore.Reports",
        "CrestApps.OrchardCore.Reports.OpenXml",
        "CrestApps.OrchardCore.Reports.Pdf",
        "CrestApps.OrchardCore.Reports.Subscriptions"
      ]
    }
  ]
}

The AI analytics are reports of this framework too: AI Chat Session Analytics, AI Chat Extracted Data and AI Chat Conversion Goals (AI Chat Session Analytics feature, see orchardcore-ai-chat-analytics), AI Usage Analytics (AI Usage Analytics feature), and the AI QA Dashboard (AI Quality).

Layers and namespaces

Contribute a report

What describes a report is static, like the data sources of Orchard Core's Data Pipelines: Name, DisplayName and Description (both LocalizationSource), Category and Permission. RunAsync comes from IReportRunner. The framework lists, routes to and authorizes reports from their descriptors, and creates a report only to run it.

using CrestApps.OrchardCore.Reports;
using CrestApps.OrchardCore.Reports.Models;
using Microsoft.Extensions.Localization;
using OrchardCore.Localization;
using OrchardCore.Security.Permissions;

namespace MyModule.Reports;

public sealed class OrderVolumeReport : IReport
{
    private readonly IOrderReportStore _store;

    internal readonly IStringLocalizer S;

    public OrderVolumeReport(IOrderReportStore store, IStringLocalizer<OrderVolumeReport> stringLocalizer)
    {
        _store = store;
        S = stringLocalizer;
    }

    public static string Name => "my-order-volume";

    public static LocalizationSource DisplayName { get; } = LocalizationSource.Create<OrderVolumeReport>("Order volume");

    public static LocalizationSource Description { get; } = LocalizationSource.Create<OrderVolumeReport>("Orders and revenue per day.");

    public static string Category => ReportsConstants.Categories.Commerce;

    public static Permission Permission => MyPermissions.ViewOrderReports;

    public async Task<ReportDocument> RunAsync(ReportContext context, CancellationToken cancellationToken = default)
    {
        // The period is a filter like any other. Bounds are UTC and null when no date range filter ran.
        var range = context.Filter.GetDateRange();
        var channel = context.Filter.GetOrDefault<string>("Channel");

        var days = await _store.GetDailyTotalsAsync(range.FromUtc, range.ToUtc, channel, cancellationToken);

        var rows = days
            .Select(day => new ReportRow([day.Date.ToString("d"), ReportFormat.Number(day.Orders), day.Revenue.ToString("C")]))
            .ToList();

        rows.Add(new ReportRow(
            [S["Total"].Value, ReportFormat.Number(days.Sum(day => day.Orders)), days.Sum(day => day.Revenue).ToString("C")],
            ReportRowKind.GrandTotal));

        return new ReportDocument()
            .Add(ReportSection.ForMetrics(S["Summary"].Value,
            [
                new ReportMetric(S["Orders"].Value, ReportFormat.Number(days.Sum(day => day.Orders))),
                new ReportMetric(S["Days"].Value, ReportFormat.Number(days.Count)),
            ]))
            .Add(ReportSection.ForChart(S["Orders per day"].Value, new ReportChart
            {
                Type = ReportChartType.Line,
                Labels = days.Select(day => day.Date.ToString("d")).ToList(),
                Datasets = [new ReportChartDataset(S["Orders"].Value, days.Select(day => (double)day.Orders))],
            }, width: 12))
            .Add(ReportSection.ForTable(S["Daily totals"].Value,
            [
                new ReportColumn(S["Day"].Value),
                new ReportColumn(S["Orders"].Value, ReportColumnAlign.End),
                new ReportColumn(S["Revenue"].Value, ReportColumnAlign.End),
            ], rows));
    }
}

Register it in a startup that runs only when Reports is enabled. AddReport<TReport>() registers the class as scoped and adds its descriptor to ReportOptions:

using CrestApps.OrchardCore.Reports;
using Microsoft.Extensions.DependencyInjection;
using OrchardCore.Modules;

namespace MyModule;

[RequireFeatures(ReportsConstants.Feature)]
public sealed class ReportsStartup : StartupBase
{
    public override void ConfigureServices(IServiceCollection services)
    {
        services.AddReport<OrderVolumeReport>();
    }
}

Rules:

Two static members are optional (static virtual on IReport, null by default). ReportDescriptor.Create<TReport>() copies them, and a family of reports sets them on each ReportDescriptor with init:

// Needed beside Permission to export: the page hides its export buttons without it, ReportsController.Export
// refuses, and a subscription can neither be saved with a file format nor attach the file.
public static Permission ExportPermission => MyPermissions.ExportOrderReports;

// The period the report opens on (see "The built-in date range").
public static ReportDefaultDateRange DefaultDateRange => ReportDefaultDateRange.LastDays(30);

ReportContext, run mode and user

ReportContext carries the Filter, the Mode and the User:

// Inside RunAsync: keep only the queues the person the report runs for may supervise.
// _queueStore is your module's own store; MyPermissions.SuperviseQueue is checked per queue as a resource.
var visible = new List<Queue>();

foreach (var queue in await _queueStore.ListAsync(cancellationToken))
{
    if (context.User is not null &&
        await _authorizationService.AuthorizeAsync(context.User, MyPermissions.SuperviseQueue, queue))
    {
        visible.Add(queue);
    }
}

The report document

ReportDocument is an ordered list of ReportSections, added with Add (fluent). Each section has a Title, an optional Description (shown under the title), an optional EmptyMessage (shown instead of the content when there is none, such as how to start collecting the data), and a Width on the shared twelve-column grid (default 12; ForChart defaults to 6). Exports leave Description and EmptyMessage out.

| Factory | Content |

| --- | --- |

| ReportSection.ForMetrics(title, metrics) | ReportMetric(label, value, hint) cards |

| ReportSection.ForTable(title, columns, rows) | ReportColumn(label, align, headerStyle) and ReportRow(cells, kind) |

| ReportSection.ForBars(title, bars) | Horizontal ReportBar(label, value, ratio) with ratio from 0 to 1 |

| ReportSection.ForChart(title, chart, width) | ReportChart with Type, Labels, Datasets, Stacked, ShowLegend, PercentageScale |

Color-coded cells with ReportStyle

ReportStyle.Create(color, backgroundColor, bold) styles a header (ReportColumn.HeaderStyle), a row (ReportRow.WithStyle) or a single cell (ReportRow.WithCellStyle(index, style), which wins over the row style). Use hexadecimal colors such as #2563EB: the HTML renderer also accepts simple named colors, but only hexadecimal colors reach the Excel and PDF exports. The PDF also shades subtotal and grand-total rows as the page does. CSV never carries styles.

var columns = new[]
{
    new ReportColumn(S["Queue"].Value, ReportColumnAlign.Start, ReportStyle.Create("#FFFFFF", "#2563EB", bold: true)),
    new ReportColumn(S["Completed"].Value, ReportColumnAlign.End),
};

var rows = new List<ReportRow>
{
    new ReportRow(["Support", "18"]).WithCellStyle(1, ReportStyle.Create("#B91C1C")),
    new ReportRow(["All queues", "18"], ReportRowKind.GrandTotal).WithStyle(ReportStyle.Create(backgroundColor: "#EFF6FF")),
};

Filters

ReportFilter is an Entity with a ReportName and a Properties bag. A report declares no fixed filter dimensions: every filter, including the date range, is a DisplayDriver<ReportFilter> that writes into the bag. Browser display and export build the filter the same way, so values apply to both.

Typed helpers from ReportFilterExtensions:

The built-in date range

ReportDateRangeFilterDisplayDriver renders for every report at Content:1. It uses the shared DateRangePicker view component and date-range-picker resource from CrestApps Resources (see orchardcore-crestapps-resources), with presets (Today, Yesterday, Last 24 Hours, Last 7/30/90 Days, This/Last Week, Month, Quarter, Year, Last 3/6/12 Months), Custom Range, On or before and On or after.

A report-specific filter

Gate the driver to your report with filter.ReportName, and write the value with Set. The full driver, view model and view are in references/reports-examples.md.

public sealed class ChannelFilterDisplayDriver : DisplayDriver<ReportFilter>
{
    public override IDisplayResult Edit(ReportFilter filter, BuildEditorContext context)
    {
        if (filter.ReportName != OrderVolumeReport.Name)
        {
            return null;
        }

        return Initialize<ChannelFilterViewModel>("ChannelFilter_Edit", model =>
        {
            model.Channel = filter.GetOrDefault<string>("Channel");
        }).Location("Content:2");
    }

    public override async Task<IDisplayResult> UpdateAsync(ReportFilter filter, UpdateEditorContext context)
    {
        if (filter.ReportName != OrderVolumeReport.Name)
        {
            return null;
        }

        var model = new ChannelFilterViewModel();
        await context.Updater.TryUpdateModelAsync(model, Prefix);
        filter.Set("Channel", model.Channel);

        return Edit(filter, context);
    }
}

Register it with services.AddDisplayDriver<ReportFilter, ChannelFilterDisplayDriver>() in the same [RequireFeatures(ReportsConstants.Feature)] startup. A driver shared by many reports can instead check whether the report implements IReportFilterMetadata and lists the driver's filter name in FilterNames (_reportManager.GetReport(filter.ReportName) is IReportFilterMetadata metadata), as the Omnichannel and Contact Center filters do.

A family of reports

When one class runs many reports that differ only by what they measure, it cannot describe each with static members. Implement IReportRunner and add a ReportDescriptor per report to ReportOptions, with a factory that creates the runner:

private static readonly ObjectFactory<CatalogReport> _factory =
    ActivatorUtilities.CreateFactory<CatalogReport>([typeof(CatalogReportKind)]);

services.Configure<ReportOptions>(options => options.Add(new ReportDescriptor(
    "my-volume-report",
    LocalizationSource.Create<ReportsStartup>("Volume"),
    LocalizationSource.Create<ReportsStartup>("How much work came in, by day."),
    ReportsConstants.Categories.Operations,
    MyPermissions.ViewReports,
    typeof(CatalogReport),
    services => _factory(services, [CatalogReportKind.Volume]))));

Another feature can add or remove reports of the family through the same options. Omnichannel (enterprise activity reports) and Contact Center (interaction and agent workforce catalogs) use this pattern.

Using reports from code

var descriptor = _reportManager.GetDescriptor("my-order-volume");

if (descriptor is null || !await _authorizationService.AuthorizeAsync(User, descriptor.Permission))
{
    return Forbid();
}

var filter = new ReportFilter { ReportName = descriptor.Name };
filter.SetDateRange(new ReportDateRange { FromUtc = fromUtc, ToUtc = toUtc, Key = "custom" });

var document = await _reportManager.GetReport(descriptor.Name)
    .RunAsync(new ReportContext(filter, ReportRunMode.Export) { User = User }, cancellationToken);

var csv = _exportManager.GetFormat(ReportsConstants.CsvExportFormat).Serialize(document);

The admin pages replace ReportValue.UserDisplayName tokens through ReportDisplayValueResolver (ResolveAsync(document), in the Reports module); call it yourself before serializing when your report writes such tokens.

Export formats

An export format is static too: Name, DisplayName (a LocalizationSource), Extension (with its dot) and ContentType, plus byte[] Serialize(ReportDocument document). Register it with services.AddReportExportFormat<TFormat>(). CSV (csv, ReportsConstants.CsvExportFormat) ships with Reports; Reports (OpenXml) adds xlsx (ReportsConstants.XlsxExportFormat), one worksheet per section group with styles applied; Reports (PDF) adds pdf (ReportsConstants.PdfExportFormat, PdfReportExportFormat). One format renders as an Export button; several render as an Export dropdown. A full example is in references/reports-examples.md.

PDF exports

Admin area

Enabling Reports adds the top-level Reports admin menu (ReportsAdminMenu, shown when at least one report is registered): Reports → {category} → {report}, each item gated by the report's permission. Report Subscriptions add Reports → Subscriptions, and the Report Builder adds Reports → Report Builder, Report Views and Report Groups (see orchardcore-report-builder).

Report subscriptions

CrestApps.OrchardCore.Reports.Subscriptions emails a registered report on a schedule. A ReportSubscription (a catalog item with ReportSubscriptionIndex, declared .ExclusiveToDocumentType().SingleRecordPerDocument()) holds Name, ReportName, Frequency (Daily, Weekly on DayOfWeek, Monthly on DayOfMonth 1 to 28), Hour in the site's time zone, Recipients (comma separated), an optional AttachmentFormat (csv, xlsx, pdf), IsEnabled, and NextRunUtc, LastRunUtc, LastError.

Dashboard widgets

With Orchard Core's Admin Dashboard (OrchardCore.AdminDashboard, ReportWidgetConstants.AdminDashboardFeature) enabled next to Reports, any report can be shown on the admin dashboard; there is no extra feature. Manage Dashboard > Add Widget offers the generic Report widget (ReportWidget type) and every ready-made widget, all built on ReportWidgetPart (ReportName, Period, From, To, Show, MaxRows, CacheMinutes):

| Option | Values |

| --- | --- |

| Period (ReportWidgetPeriod) | Today, Yesterday, Last7Days, Last30Days, Last90Days, ThisMonth, LastMonth, ThisYear, Last12Months, AllTime, Custom; all but Custom move with the clock in the site's time zone and become the report's date range filter |

| Show (ReportWidgetContent) | FiguresAndTables (default), FiguresOnly, TablesOnly, ChartsOnly, Everything |

| Rows per table | Rows of each table and bars of each bar list; a total row stays |

| Keep for (minutes) | Result cached in the tenant memory cache per widget, its last change, period, show, rows, language and viewer (NameIdentifier), since a report may show each person only what they may see; ReportWidgetConstants.DefaultCacheMinutes (30) by default; 0 runs on every visit; saving the widget starts over |

A viewer sees a widget's numbers only when they hold the report's permission (checked on every visit, before the cache). The widget runs the report with ReportContext.User set to the viewer. A failing report shows a message in its own tile and is not cached.

Ship a ready-made widget from a migration with DefineReportWidgetAsync, which creates a non-draftable DashboardWidget type with TitlePart and ReportWidgetPart fixed to one report. Register the migration in a startup that requires both features:

using CrestApps.OrchardCore.Reports;
using OrchardCore.ContentManagement.Metadata;
using OrchardCore.Data.Migration;

namespace MyModule.Migrations;

public sealed class OrderReportWidgetMigrations : DataMigration
{
    private readonly IContentDefinitionManager _contentDefinitionManager;

    public OrderReportWidgetMigrations(IContentDefinitionManager contentDefinitionManager)
    {
        _contentDefinitionManager = contentDefinitionManager;
    }

    public async Task<int> CreateAsync()
    {
        await _contentDefinitionManager.DefineReportWidgetAsync(
            "OrderVolumeWidget",
            "Order Volume",
            "Orders and revenue per day.",
            new ReportWidgetPartSettings
            {
                ReportName = "my-order-volume",
                DefaultPeriod = ReportWidgetPeriod.Last30Days,
                DefaultContent = ReportWidgetContent.FiguresOnly,
                DefaultMaxRows = 5,
            });

        return 1;
    }
}
[RequireFeatures(ReportsConstants.Feature, ReportWidgetConstants.AdminDashboardFeature)]
public sealed class ReportWidgetsStartup : StartupBase
{
    public override void ConfigureServices(IServiceCollection services)
    {
        services.AddDataMigration<OrderReportWidgetMigrations>();
    }
}

Orders, Inventory, Reviews, Shipping, Downloads and Subscriptions ship ready-made widgets this way (for example Sales Overview on order-sales, Low Stock on stock-on-hand, Subscription Revenue on subscription-revenue). The Sales Summary and Subscription Summary widgets are not report widgets; they count records directly. With the Report Builder enabled too, the Custom Report widget (ReportDesignWidget, ReportDesignWidgetPart) shows a published designed report or a view; see orchardcore-report-builder.

Upgrading from 2.x

Troubleshooting

Telemetry

Coded report runs, exports, subscriptions and widgets emit spans and metrics on the CrestApps.OrchardCore.Reports source and meter (ReportTelemetry, package CrestApps.OrchardCore.Reports.Core): report.coded.run and crestapps.report.coded.duration (tags crestapps.report.name, crestapps.report.mode, outcome), report.export and crestapps.report.exports, .export.duration, .export.size, .export.rows (tag format), report.subscription.send and crestapps.report.subscription.sends (trigger, outcome, reason), and crestapps.report.widget.requests (crestapps.report.kind, crestapps.report.cache). A coded report that reads a whole index can call ReportTelemetry.RecordCodedIndexRows(Name, rows, logger), which warns (event 14001) from 50,000 rows. Collect it with the CrestApps.OrchardCore.* wildcard (see orchardcore-opentelemetry); the full list of spans, metrics and log ids is in the orchardcore-report-builder skill's large-data and telemetry reference.

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.