calculateSummary function

List<SummaryLine> calculateSummary(
  1. ReportElement table,
  2. Map<String, dynamic> data, {
  3. String locale = 'de-DE',
})

Calculates aggregates, subtotal, discount, taxes, and total for table.

Implementation

List<SummaryLine> calculateSummary(
  ReportElement table,
  Map<String, dynamic> data, {
  String locale = 'de-DE',
}) {
  final source = resolvePath(table.dataSource, data);
  final rows = source is List ? source : const [];
  final subtotal = rows.fold<double>(
    0,
    (sum, row) => sum + rowAmount(row, table.amountExpression),
  );
  final discount = subtotal * table.discountPercent / 100;
  final factorAfterDiscount = subtotal == 0
      ? 1.0
      : (subtotal - discount) / subtotal;
  final lines = <SummaryLine>[];
  if (table.showSummary && table.showSubtotal) {
    lines.add(SummaryLine(_localizeLabel(table.subtotalLabel, locale), subtotal));
  }
  for (final rule in table.aggregateRules) {
    lines.add(
      SummaryLine(
        _localizeLabel(rule.label, locale),
        calculateAggregate(rule, rows.cast<dynamic>()),
        bold: rule.bold,
        format: rule.format,
        targetColumnField: rule.targetColumnField,
      ),
    );
  }
  if (table.showSummary && table.discountPercent != 0) {
    lines.add(
      SummaryLine(
        '${_localizeLabel(table.discountLabel, locale)} (${formatCell(table.discountPercent, ColumnFormat.number, locale: locale)} %)',
        -discount,
      ),
    );
  }
  var taxes = 0.0;
  if (table.showSummary && table.showTaxes) {
    for (final rule in table.taxRules) {
      final matchingBase = rows
          .where((row) {
            if (rule.filterField.isEmpty) return true;
            return resolvePath(rule.filterField, row)?.toString() ==
                rule.filterValue;
          })
          .fold<double>(
            0,
            (sum, row) => sum + rowAmount(row, table.amountExpression),
          );
      final tax = matchingBase * factorAfterDiscount * rule.rate / 100;
      taxes += tax;
      lines.add(SummaryLine(_localizeLabel(rule.label, locale), tax));
    }
  }
  if (table.showSummary) {
    lines.add(
      SummaryLine(_localizeLabel(table.totalLabel, locale), subtotal - discount + taxes, bold: true),
    );
  }
  return lines;
}