Database-BI
view release on metacpan or search on metacpan
lib/Database/BI/Controller/Dashboard.pm view on Meta::CPAN
my ($level) = $fn =~ /\Ap(\d{1,3})\z/;
return undef unless defined $level;
return ($level >= 1 && $level <= 100) ? $level + 0 : undef;
}
# _measure_fn_ok($fn) -> bool
#
# True for every function _grouped_totals can compute: the named ones and any
# percentile level. This is the single answer to "is this a measure function?"
# for the parser, and the vocabulary the 400 message prints comes from the same
# two lists, so a message can never list a function the fold cannot compute.
sub _measure_fn_ok {
my $fn = shift;
return 0 unless defined $fn && length $fn;
return 1 if $MEASURE_FN_OK{$fn};
return defined _measure_percentile($fn) ? 1 : 0;
}
# ---------------------------------------------------------------------------
# Relative time ranges
#
# A relative time range is a named window worked out from the clock when the
# request arrives -- "the last 30 days", "this quarter" -- so a link, a
# bookmark or a saved canvas that carries one keeps meaning the same thing
# every time it is opened instead of freezing the dates it first resolved to.
#
# The range is named in the URL (?range=<name>&rcol=<column>) and resolved to
# two f= filters on that column, which every data route already applies, so the
# table view, the charts, the pivot, the stats page, the insights page, the
# exports and a saved canvas all see the same rows.
#
# The vocabulary is day-granular except last_24_hours, which is to the second.
# ---------------------------------------------------------------------------
Readonly my @TIME_RANGES => (
{ name => 'last_24_hours', label => 'Last 24 hours', hours => 24 },
{ name => 'today', label => 'Today', day => 0 },
{ name => 'yesterday', label => 'Yesterday', day => -1 },
{ name => 'last_7_days', label => 'Last 7 days', days => 7 },
{ name => 'last_30_days', label => 'Last 30 days', days => 30 },
{ name => 'last_90_days', label => 'Last 90 days', days => 90 },
{ name => 'this_month', label => 'This month', month => 0 },
{ name => 'last_month', label => 'Last month', month => -1 },
{ name => 'this_quarter', label => 'This quarter', quarter => 0 },
{ name => 'last_quarter', label => 'Last quarter', quarter => -1 },
{ name => 'this_year', label => 'This year', year => 0 },
{ name => 'last_year', label => 'Last year', year => -1 },
);
Readonly my %TIME_RANGE => map { $_->{name} => $_ } @TIME_RANGES;
# The operators an f= filter may name (_apply_filter_spec), as written: an
# operator in capitals is refused with the rest, not read as another one.
# differ (the Delta button) is the one whose value is another column's name:
# f=a:differ:b keeps the rows where a and b do not hold identical text.
Readonly my @FILTER_OPS => qw(eq ne contains starts lt le gt ge empty notempty between in differ);
Readonly my %FILTER_OP => map { $_ => 1 } @FILTER_OPS;
# How many column names a refusal lists before it says how many more there are.
Readonly my $FILTER_COLUMNS_LISTED => 20;
# Allowed strptime-style date format patterns for the /dates/save endpoint, and
# the two time patterns that may be given beside one of them for a column that
# holds a clock time as well as a date.
Readonly my %ALLOWED_DATE_PATTERNS => map { $_ => 1 }
qw(%m/%d/%Y %d/%m/%Y %d-%b-%Y);
Readonly my %ALLOWED_TIME_PATTERNS => map { $_ => 1 }
qw(%H:%M %H:%M:%S);
# Default share token lifetime: 30 days in seconds.
Readonly my $SHARE_TOKEN_TTL => 30 * 86_400;
# The AI routes spend the configured ai_api_key on every call. A question is
# at most this long, and each server process makes at most ai_calls_per_hour
# provider calls in any hour (0: no limit).
Readonly my $ASK_MAX_QUESTION => 500;
Readonly my $AI_CALLS_PER_HOUR => 60;
Readonly my $AI_WINDOW_S => 3600;
# ---------------------------------------------------------------------------
# Protected helpers
# ---------------------------------------------------------------------------
# _whole_number($value) -> $integer | undef
#
# A request parameter as an integer, or undef if it does not spell one. int()
# on the raw text warns on 'abc' and turns it into 0, and reads a long run of
# digits or '1e400' as infinity, which no LIMIT or OFFSET can use.
sub _whole_number {
my $value = $_[0];
return undef unless defined($value) && $value =~ /\A-?[0-9]{1,$MAX_WHOLE_NUMBER_DIGITS}\z/;
return $value + 0;
}
# _categorical_scheme($name) -> $name
# _sequential_scheme($name) -> $name
#
# A colour scheme the chart can use, or the default. These must be checked here:
# HTML::D3 writes a categorical name into its script as SCHEMES['name'], so an
# unchecked value is script on the page, and it dies on a sequential name it does
# not know, which is a 500. An unknown name has always drawn the default colours.
sub _categorical_scheme {
my $name = $_[0];
return (defined($name) && !ref($name) && $SCATTER_SCHEMES{$name}) ? $name : $DEFAULT_CATEGORICAL_SCHEME;
}
sub _sequential_scheme {
my $name = $_[0];
return (defined($name) && !ref($name) && $SEQUENTIAL_SCHEMES{$name}) ? $name : $DEFAULT_SEQUENTIAL_SCHEME;
}
# _optional_scheme($name) -> $name | undef
#
# A categorical scheme for a chart that draws its own colours without one:
# a histogram's bars are steelblue, a combo's bars and line steelblue and red,
# and a scheme replaces them with its first colours. Unlike
# _categorical_scheme there is no scheme by default, so a name that is not one
# of the five is undef and the chart keeps the colours it had before scheme=
# existed. /histogram, /combo and their canvas cards all read it here.
sub _optional_scheme {
my $name = $_[0];
return (defined($name) && !ref($name) && $SCATTER_SCHEMES{$name}) ? $name : undef;
lib/Database/BI/Controller/Dashboard.pm view on Meta::CPAN
otherwise $spec unchanged (other kinds of spec, remote /../host paths,
missing files, a name holding a newline, undef)
=cut
=head2 extract_list / extract_save / extract_delete
C<GET /extract/list>, C<POST /extract/save>, C<POST /extract/delete> -- Manage
the stored field extractions of a dataset: C<models.json>
C<extractions.E<lt>specE<gt>.E<lt>nameE<gt>>. Each is applied by
C<_apply_extractions> straight after the lookups, so every later stage can read
the columns it adds.
=head3 API SPECIFICATION
=head4 extract_list (GET /extract/list)
INPUT: l=<spec> (required)
OUTPUT: 200 application/json
{ "extractions": { "<name>": { "col": "<col>", "pattern": "<re>",
"fields": ["<group>", ...] }, ... } }
400 application/json { "error": "l= required" }
=head4 extract_save (POST /extract/save)
INPUT: l=<spec>, name=<identifier>, col=<col>, pattern=<regular expression>
optional: fields=<group>[,<group>...] (repeatable; default every named group)
OUTPUT: 200 application/json { "ok": 1, "fields": ["<group>", ...] }
400 application/json { "error": "..." } -- l=, name=, col= or pattern=
missing or invalid; the pattern too long, using a refused
construct, not compiling or naming no group; a field not a group
=head4 extract_delete (POST /extract/delete)
INPUT: l=<spec>, name=<identifier> (omit name= to delete every extraction of the spec)
OUTPUT: 200 application/json { "ok": 1 }
400 application/json { "error": "l= required" }
=head3 EXAMPLE
POST /extract/save l=table:invoices&name=parts&col=ref
&pattern=^(?<country>[A-Z]{2})-(?<year>\d{4})-
-> 200 { "ok": 1, "fields": ["country", "year"] }
GET /export?l=table:invoices&format=json
-> 200 [ { "ref": "GB-2026-001", "country": "GB", "year": "2026", ... },
{ "ref": "unknown", "country": "(unparseable)", "year": "(unparseable)", ... } ]
=head3 NOTES
The column the extraction reads is checked on every request; one the dataset
does not have is a 400 (C<error_extract_col_unknown>). A row that does not
match is C<(unparseable)> in every column; a group that took no part is C<''>.
The pattern is compiled by L<Database::BI::Calc/Regular expressions>, which
has no timeout.
=cut
=head1 DESCRIPTION
All user-facing routes in C<Database::BI> are handled by this controller.
See the individual action POD above for per-endpoint documentation.
=head2 Filter operators and the quick-filter bar
Filters are expressed as C<f=col:op:val> query parameters and are applied
server-side after all joins. Multiple C<f=> params are applied in order
(AND semantics).
The colon separator is split with a limit of 3, so values may themselves
contain colons (e.g. C<f=sale_date:eq:2025-01-15>, or a time value like
C<f=start_time:eq:14:30:00>).
B<Supported operators:>
eq case-insensitive string equality
ne case-insensitive string inequality
contains case-insensitive substring match
starts case-insensitive prefix match
lt numeric less-than
le numeric less-than-or-equal
gt numeric greater-than
ge numeric greater-than-or-equal
empty cell is undef or empty string (val ignored)
notempty cell is defined and non-empty (val ignored)
in case-insensitive equality with any value of a JSON array of
strings, e.g. C<f=place:in:["Paris","Rome"]>; a value that is
not such an array matches no row
B<Quick-filter bar (table view):>
A filter row below the toolbar lets the user pick a column, operator, and
value and press "Apply filter" (or Enter) to add a condition without
opening any panel. The current URL is updated with the new C<f=> param
and the page reloads; all other URL parameters (joins, dedup, etc.) are
preserved automatically via the browser C<URL> API.
Active filter chips appear in the toolbar. Each chip has an individual
x-button to remove just that condition. The "x Clear filters" link
removes all C<f=> params at once.
B<Drill-down from pie chart:>
Clicking a pie slice or legend entry on C</pie> navigates to the table
view with C<f=cat_col:eq:label> appended, so the user can inspect the
rows behind any slice without manually typing a filter.
=head2 Cross-row columns
A measure folds a group into one number, a calculated field computes one row
from that row, and C<cs=> is the third shape: one row worked out from many,
written back beside every row of the view.
cs=<column>:<function>:<alias> write a column of that name
cs=<column>:<function>:<alias>:<count> a moving window needs its width
by=<column>[,<column>...] partition; without it there is one
order=<column>[:asc|desc] the order the rows are read in
B<Functions:> C<pct_of_total>, C<rank> and C<zscore> are order-free. They
answer a whole-partition question: a row's share of the partition total (the
shares sum to 1), its rank with ties sharing a rank and the next rank
skipping (as SQL C<RANK()> does), and its z-score against the same sample
( run in 1.880 second using v1.01-cache-2.11-cpan-eb134014566 )