ZuloOne
English
Sign inTry it
Menu

Report modules

Updated

A report module is the C# code of a standard report — what 1C keeps in a report's object module. Its attributes are values the reader sets in the quick settings panel; OnBeforeRunAsync turns them into the run's settings before every run; its data sets build rows in code that the report reads as a table; its functions are called by the report's formulas; OnAfterRunAsync has the last word on the result; OnDrillAsync decides what a drill-down opens; its commands are buttons on the report window's toolbar.

← Developer wiki

The report itself — variants and reader settings. The module mechanics it reuses — form modules.

Where it lives#

A report module is a form module of a standard report:

Part Where it is stored Workspace file
Attributes and command captions MetaFormLayout.LayoutJson of a shared layout with ObjectType = "Report", ObjectMetaId = the report's id <Model>/Forms/<Name>.form.json
Module a FormModule script linked by ModuleScriptMetaId, class <Name>Form <Name>Form.script.json + <Name>Form.cs

The generated half of the class derives from ReportModuleBase (ZuloOne.Runtime.Forms), which is a FormModuleBase: the typed State, GetService<T>(), questions to the user and the compile cache are a form module's. The layout's nodes stay empty: the report opens in the standard window.

The layout file, Sales/Forms/CustomerOrderAnalysis.Report.form.json:

{
  "kind": "FormLayout",
  "object": {
    "objectType": "Report",
    "objectMetaId": "<the standard report's metaId>",
    "formKind": "Record",
    "moduleScriptMetaId": "<the module script's metaId>",
    "layoutJson": "{\"attributes\":[{\"name\":\"NotPaid\",\"type\":\"Boolean\",\"caption\":{\"en\":\"Not paid\",\"ru\":\"Не оплачено\"}}],\"commands\":[],\"nodes\":[]}",
    "metaId": "<the layout's metaId>",
    "name": "CustomerOrderAnalysis.Report",
    "modelId": "<the model>"
  }
}

Its module is CustomerOrderAnalysisReportForm.cs with the envelope CustomerOrderAnalysisReportForm.script.json: scriptType FormModule, objectType FormLayout, objectName and objectMetaId the layout's — as for any form module.

Attributes#

Declared as a form's attributes (form modules). The quick settings panel shows every scalar type: a Reference as a lookup of its dictionary's records (ref names the dictionary), an Enum as a list of its values (ref names the enum), a Guid as text. Table attributes are not used by reports.

  • The reader's values are part of their settings of the variant (SettingsDelta.attributes); a variant keeps its own (UserReportConfig.attributes).
  • A missing value is the type's default: false, 0, null.
  • A name matches in any case; a value of an attribute the layout does not declare is ignored.

Before every run#

public partial class CustomerOrderAnalysisReportForm
{
    public override Task OnBeforeRunAsync(ReportRunContext ctx)
    {
        var states = new List<string>();
        if (State.NotPaid) states.Add("notPaid");
        if (State.PartlyPaid) states.Add("partlyPaid");
        if (State.Paid) states.Add("paid");
        if (states.Count > 0) ctx.GroupFilterValues("payState", states.ToArray());
        return Task.CompletedTask;
    }
}

payState is the report's condition on groups over the column of the same name, whose values are notPaid, partlyPaid and paid.

OnBeforeRunAsync runs on every run of the report: the window, an export (Excel, PDF, CSV), the assistant, and ctx.Report.RunAsync of a command. What it changes:

Call What it does
ctx.Filter(path, op, value) / ctx.Filter(path, op, values) changes the report's own filter on the field and switches it on; without one, adds a filter the reader cannot switch off
ctx.RemoveFilter(path) switches off every filter on the field
ctx.UseFilter(id, on) switches the filter with this id on or off
ctx.GroupFilterValues(id, …) / ctx.UseGroupFilter(id, on) the texts an «in list» condition on groups keeps / switches it on or off
ctx.ShowColumn(id, visible) shows or hides a column
ctx.Period(from, to) / ctx.Period("LAST_MONTH") the period
ctx.GroupBy(paths…) replaces the row groupings; a grouping the report has keeps its settings, and a condition on groups moves with its grouping
ctx.SourceFilter(sourceId, path, op, value) a filter of an additional source (its facts[].id): its own filter on the path is changed and switched on, or a new one is added; an unknown source is left alone — the price type of a price list read beside the stock
  • The changes land in the run's own copy of the settings; the stored variant is never changed.
  • An item the author locked stays as it is, and so do the report's root and sources.
  • A condition on groups whose grouping GroupBy leaves out is dropped when it is off. When it is on, GroupBy throws: keep its grouping, or switch the condition off first with ctx.UseGroupFilter.
  • What a change refers to is checked when the report compiles: a filter on an unknown field is a validation error.
  • A module that does not compile, or throws, stops the run with an error that names it.
  • ctx.UserId, ctx.Language and ctx.ReportName say who runs what.

Data sets in code#

A data set is rows the module builds in code — 1C's object data set. The report reads them as it reads a table: the engine groups, filters, totals, sorts, draws the charts, drills down, exports and mails them, and the report's formulas, conditions on groups, conditional appearance and additional sources work on them as on any table. A reference field reaches the fields of its record: a set that returns an Item gives the report Item.ItemGroup too.

public partial class StandardCostVarianceReportForm
{
    public sealed class VarianceRow
    {
        [ReportField("Date", Ru = "Дата")]
        public DateTime Date { get; set; }

        [ReportField("Document", Ru = "Документ", Document = "*")]
        public Guid Document { get; set; }

        [ReportField("Item", Ru = "Номенклатура", Dictionary = "Item")]
        public Guid Item { get; set; }

        [ReportField("Variance", Ru = "Отклонение")]
        public decimal Variance { get; set; }
    }

    [ReportDataSet("<a GUID of its own>", "WriteOffs", Caption = "Write-offs against the standard", Ru = "Списания против норматива")]
    public async Task<List<VarianceRow>> WriteOffsAsync(ReportDataSetContext ctx)
    {
        var rows = new List<VarianceRow>();
        // … read what the report needs, compute, add rows …
        return rows;
    }
}

The report names the set by its id, as its root or as an additional source:

{ "root": { "kind": "DataSet", "metaId": "<the set's GUID>" }, "period": { "path": "Date", "relative": "THIS_MONTH" } }
  • A data set is a public method of the module marked [ReportDataSet(metaId, name)] that takes a ReportDataSetContext and returns the rows: Task<List<TRow>> (any task of an enumerable), IEnumerable<TRow> or IAsyncEnumerable<TRow>. The id never changes once a report names it; the name is letters, digits and underscores.
  • Every public readable property of TRow is a field, in the order it is declared. [ReportField] gives it a caption per language (Caption in English, Ru, Uk, Ar), says what a Guid points at, or keeps it out:
Property type Field Notes
string, char text longer than 4 000 characters is cut
decimal, double, int, long… number kept to 10 decimal places
DateTime, DateTimeOffset, DateOnly date DateOnly = true compares by the calendar date, never shifted to the reader's time zone
bool yes / no
Guid a record of Dictionary = "Item", a document of Document = "SalesInvoice" (or "*" — any type), or a plain id an empty Guid is no value
an enum a value from a list, captioned by its member names

Hidden = true keeps a field out of the field lists (a layout may still name it); Ignore = true makes the property no field at all. Any other type stops the set with an error that names the property.

  • The module runs as for OnBeforeRunAsync: State holds the report's attribute values (a variant's, then the reader's), GetService<T>() reaches the services.
  • The catalog of New report lists the sets under their report, as Data sets in code: a reader builds a report of their own on one as on a register.

What the method gets in ctx:

ctx.PeriodFrom, ctx.PeriodTo the report's period, the first and the last day in the reader's calendar; null when the period is open at that end
ctx.Filters, ctx.Filter(field) the run's switched-on filters on the set's own fields, the values typed as the fields are — none when the filters are not all joined with AND. The engine applies them anyway; a set uses them to read less
ctx.QueryAsync(query) reads other data through the report engine, as the caller (below)
ctx.UserId, ctx.Language, ctx.ReportName, ctx.DataSet who runs what
ctx.CancellationToken cancelled when the reader goes away or the run's time is up

The period. The report's period is on a date field of the set, and the engine keeps the rows inside it. A set whose rows are not dated — balances at the period's end, one line per batch — puts the period's last day (ctx.PeriodTo ?? DateTime.Today) in a date field and the report's period is on that field.

Reading other data through the engine#

var sold = await ctx.QueryAsync(ReportQuery.Register("Revenue")
    .GroupBy("Item")
    .Sum("Amount", "Qty")
    .Where("Customer.Region", "eq", regionId)
    .Period("MovementDate", ctx.PeriodFrom, ctx.PeriodTo));
foreach (var r in sold)
{
    var item = (Guid?)r["Item"];          // a grouping's key, typed as its field
    var name = (string?)r["Item__label"]; // its shown text
    var amount = (decimal?)r["Amount"];   // a measure by its path
}
  • ReportQuery.Register(name), Balance(register) (balances and turnovers: QtyOpening, QtyIncome, QtyOutcome, QtyClosing), InfoRegister, Dictionary, Document and Lines(document, tablePart) name the object; GroupBy, Sum, Min, Max, Avg, CountDistinct, Where, WhereIn and Period are a report layout in a few calls.
  • One row per lowest group. A path measured twice gets path:Agg for the second aggregate (Qty:Max).
  • It runs as the caller: their permissions and row security apply, as in any report they open.
  • A query that has more groups than a report reads at once (200 000) stops with an error: group by fewer fields or filter it. A set that queries a report built on another set may go 3 levels deep.

Limits#

  • A set returns at most 300 000 rows to a run (50 000 to the builder's preview); past that the run stops with an error that names the set.
  • The run's time limit covers the method: 90 seconds in the window, 300 for an export.
  • A run reads each set it names once, for all its statements; the next run — another click, a drill-down, an export, a mailing — calls it again. A KPI tile that compares another period reads the same rows.
  • A data set root has no related lists and no cross filters: it is no table.
  • Rights: a set is open to whoever may run reports. What its code reads is the code's to guard: ctx.QueryAsync runs as the caller; a service such as ISqlService reads without row security.

After the run#

public override Task OnAfterRunAsync(ReportResultContext ctx)
{
    var total = ctx.Total.Number("amount") ?? 0;
    foreach (var row in ctx.RowsAt(1))
        row["share"] = total == 0 ? null : row.Number("amount") / total;
    ctx.Warn("Shares are of the total for the period");
    return Task.CompletedTask;
}

OnAfterRunAsync runs after every run, on the shaped result, before the reader sees it — 1C's ПриКомпоновкеРезультата after the standard output.

ctx.Total the total line; every group line is under it
ctx.Rows, ctx.RowsAt(level) every group line, outer before inner; the lines of one grouping level (1 = outermost)
row[columnId] a column's value on the line; set it to change what the line shows, a column of the layout or one it hides (a group formula 0 keeps a place for a value the module computes)
row.Number(columnId) the value as a number, or null
row.Level, row.Path, row.Key, row.Label, row.Keys, row.Parent, row.Children where the line is: its grouping, its key and name, the keys of the lines above it
ctx.Warn(text) a note above the result
ctx.Columns, ctx.PeriodFrom, ctx.PeriodTo, ctx.UserId, ctx.Language the result's column ids and who runs what
  • It runs on the window, an export, a mailing and the assistant; the charts are drawn before it and do not see its changes.
  • It runs before the subtotals are blanked (Subtotals off), so it may read them.
  • ctx.Report.RunAsync of a command does not run it: a command gets the engine's figures.
  • The module instance is the one OnBeforeRunAsync ran on, so a value it kept there is still there.

Functions in formulas#

[ReportFunction]
public string Band(decimal? price) => price is null ? "—" : price >= 1000 ? "premium" : price >= 300 ? "middle" : "economy";
{ "id": "band", "kind": "group", "expr": "BAND([avgPrice])", "caption": "Price band" }

A public method marked [ReportFunction] is a function the report's group formulas call — 1C's common-module function in a data composition expression. [ReportFunction("NAME")] gives it another name; case does not matter.

  • It takes numbers (decimal, decimal?, double, int, long), texts, yes/no or object, and returns a number, a text, yes/no or null; a parameter with a default value may be left out.
  • A group formula runs it on every group line and on the total, after the run's figures are summed. A row formula runs in the database and cannot call it.
  • The functions are those of the report being run: its variants and the layouts its drill-down opens have them; a copy saved as one's own report runs without the module, and a formula that calls one is refused with «Unknown function».
  • A function that throws stops the run with an error that names it; a name of a built-in function (ROUND, IF…) is refused.

Drill-down#

public override Task OnDrillAsync(ReportDrillContext ctx)
{
    if (ctx.KeyId("Item") is Guid item && ctx.ColumnId == "amount")
        ctx.OpenReport("StockValue", r => r.Filter("Item", "eq", item), "Stock of the item");
    else if (ctx.KeyId("Customer") is Guid customer && ctx.ColumnId == null)
        ctx.OpenRecord("Customer", customer);
    return Task.CompletedTask;
}

OnDrillAsync decides what a drill-down opens — 1C's drill-down handler (ОбработкаРасшифровки). The window asks the module first whenever the reader drills — a double click, Open, Rows behind the number, Decode by… — and only when the module overrides the handler.

ctx.Action what the window would do: open, rows, decode or report
ctx.Level, ctx.Keys, ctx.Key(path), ctx.KeyId(path) the line: its grouping level (0 = the total) and the keys of it and of the lines above it, by grouping path
ctx.ColumnId, ctx.Value the cell; null on a line's name
ctx.OpenRecord(dictionary, id) / ctx.OpenDocument(id) opens a record's or a document's card
ctx.OpenReport(report, settings, title) opens a standard report, by name or id, in a tab of its own: its own layout changed by settings — filters, the period, groupings, as in OnBeforeRunAsync; that report's module runs on it
ctx.Message(text, level) a message
ctx.StandardProcessing true until the module opens something: then the window's own drill-down does not run. Set it to run both, or to run nothing
  • State holds the window's attribute values, as in the other handlers.
  • A module that throws shows the error; the window's own drill-down does not run then.

Commands#

[FormCommand]
public async Task OrderFromSuppliers(FormContext ctx)
{
    // The order level stays: the payment state is a condition on orders.
    var rows = await ctx.Report!.RunAsync(r => r.GroupBy("Item.DefaultSupplier", "Item", "Owner"));
    // … create one purchase order per supplier from rows …
    ctx.Message($"{rows.Count} lines", "success");
}
  • A command is a public Task Name(FormContext ctx) marked [FormCommand], as on a form. The layout's commands list gives its caption; without one the method name shows.
  • ctx.Report.Selected — the group rows the reader is on, each with its level and the keys of it and the rows above it, by grouping path.
  • ctx.Report.RunAsync(change) — the report run with the window's settings (the module's OnBeforeRunAsync applied) and then change: one row per lowest group, the grouping keys by path, their shown texts by <path>__label and the figures by column id. At most 5 runs per command.
  • Messages, client actions (open what the command created) and questions (ctx.Confirm, ctx.Choose, ctx.Ask) work as on a form.

The report's own window#

A report whose module layout places controls on a canvas (layout version 5) opens in a window laid out by it; one without them opens the standard window. The report's blocks are regions, placed by reference, so a fix in the engine or the standard window reaches every report form:

Region key What it shows
report:toolbar the view bar: variants, settings, the module's command buttons, the period, Generate (for a reader also Make a copy, Export and ⋯)
report:quick the quick settings
report:result the result grid
report:charts the report's charts and KPIs
report:totals the totals of the selected cells

Next to them a field control named like a module attribute edits that attribute: the same value and the same effect as in the quick settings. A button whose command is a module command runs it as the toolbar's button does, with the selected lines. Labels, boxes and pages draw as on a card. A block or an attribute the layout does not place is not shown. Someone who may change the report keeps the builder's tabs above the form.

Edit window layout in the report's ⋯ menu (for those who may change its model, on a report that has a module) opens the canvas designer on the module layout: its palette offers the five blocks, the attributes and the module's commands; an empty layout starts from the toolbar, the quick settings, the charts and the result. A higher model rearranges and extends a vendor's report form in its own layer ([ExtensionOf]), as a card's. Mailing, a dashboard tile and the assistant run the same layout and the same module, so they give the same numbers.

API#

GET api/user-reports/{id} module: attributes (name, caption, type, ref), commands (name, caption), drill (it handles drill-down), functions (their names), formLayoutId (the module layout when it places controls: the report's own window), error when the module does not compile
POST api/user-reports/run, …/export with reportId and config: the module runs on the posted layout; a layout without reportId (the builder's preview) never runs a module
POST api/user-reports/{id}/command { command, config, selection, answers } → a form event result: messages, clientActions, awaitingAnswer
POST api/user-reports/{id}/drill { config, action, level, keys, columnId, value } → standard (the window's own drill-down still runs) and clientActions: OpenRecord, OpenDocument, Message, and OpenReportLayout (title, config, reportId)
GET api/user-reports/catalog the data sets as roots of kind DataSet, under their report (parentCaption)
GET api/user-reports/fields?rootKind=DataSet&rootId=<set> a set's fields; with path, the fields of the record a reference points at

Rights and limits#

  • The module runs as the caller, with the caller's roles and row security; data comes through the engine (ctx.Report.RunAsync, ctx.QueryAsync of a data set) or services.
  • A higher model's extension of the report layout ([ExtensionOf]) may add commands; the attributes, the data sets, the functions and the handlers (OnBeforeRunAsync, OnAfterRunAsync, OnDrillAsync) are the owner's module's.
  • Not yet: writing a module's code in Studio, OnCreateAsync / OnChangeAsync for reports.

Same topic for other readers: User

Was this page helpful?