1 package OpenILS::Application::Trigger::Reactor;
2 use strict; use warnings;
3 use Encode qw/ encode /;
6 use DateTime::Format::ISO8601;
7 use Unicode::Normalize;
9 use OpenSRF::Utils qw/:datetime/;
10 use OpenSRF::Utils::Logger qw(:logger);
11 use OpenSRF::Utils::JSON;
12 use OpenILS::Application::AppUtils;
13 use OpenILS::Utils::CStoreEditor qw/:funcs/;
14 my $U = 'OpenILS::Application::AppUtils';
16 sub fourty_two { return 42 }
17 sub NOOP_True { return 1 }
18 sub NOOP_False { return 0 }
21 # To be used in two places within $_TT_helpers. Without putting the code out
22 # here, we can't really reuse it within that structure.
24 my $name = shift or return; # the first arg is always the name
25 my ($type, $attr) = (scalar(@_) == 1) ? (undef, $_[0]) : @_;
26 # if the next is the last, it's the attributes, otherwise type
27 # use Data::Dumper; $logger->warn("get_li_attr: " . Dumper($attr));
28 ($name and @$attr) or return;
30 $name =~ s/^(\D+)_(\d+)$/$1/ and $length = $2;
32 $_->attr_name eq $name or next;
33 next if $length and $length != length($_->attr_value);
34 return $_->attr_value if (! $type) or $type eq $_->attr_type;
39 # helper functions inserted into the TT environment
40 my $_TT_helpers; # define first so one helper can use another
43 # turns a date into something TT can understand
46 $date = DateTime::Format::ISO8601->new->parse_datetime(cleanse_ISO8601($date));
48 "%0.2d:%0.2d:%0.2d %0.2d-%0.2d-%0.4d",
58 # escapes a string for inclusion in an XML document. escapes &, <, and > characters
61 $str =~ s/&/&/sog;
69 $str =~ s/([\x{0080}-\x{fffd}])/sprintf('\u%0.4x',ord($1))/sgoe;
73 # encode email headers in UTF-8, per RFC2231
74 escape_email_header => sub {
76 $str = encode("MIME-Header", $str);
80 # strip non-ASCII characters after splitting base characters and diacritics
81 # least common denominator for EDIFACT messages using the UNOB character set
82 force_jedi_unob => sub {
85 $str =~ s/[\x{0080}-\x{fffd}]//g;
89 # returns the calculated user locale
90 get_user_locale => sub {
92 return $U->get_user_locale($user_id);
95 # returns the calculated copy price
96 get_copy_price => sub {
98 return $U->get_copy_price(new_editor(xact=>1), $copy_id);
101 get_org_unit => sub {
103 return $org_id if ref $org_id;
104 return new_editor()->retrieve_actor_org_unit($org_id);
107 # given a copy, returns the title and author in a hash
108 get_copy_bib_basics => sub {
110 my $copy = new_editor(xact=>1)->retrieve_asset_copy([
115 acp => ['call_number'],
120 if($copy->call_number->id == -1) {
122 title => $copy->dummy_title,
123 author => $copy->dummy_author,
126 my $mvr = $U->record_to_mvr($copy->call_number->record);
128 title => $mvr->title,
129 author => $mvr->author
134 # given a call number, returns the copy location with the most copies
135 get_most_populous_location => sub {
138 # FIXME - there's probably a more efficient way to do this with json_query/SQL
139 my $call_number = new_editor(xact=>1)->retrieve_asset_call_number([
148 my %location_count = (); my $winning_location; my $winning_total;
150 foreach my $copy (@{$call_number->copies()}) {
151 if (! defined $location_count{ $copy->location() }) {
152 $location_count{ $copy->location() } = 1;
154 $location_count{ $copy->location() } += 1;
156 if ($location_count{ $copy->location() } > $winning_total) {
157 $winning_total = $location_count{ $copy->location() };
158 $winning_location = $copy->location();
162 my $location = new_editor(xact=>1)->retrieve_asset_copy_location([
163 $winning_location, {}
168 # returns the org unit setting value
169 get_org_setting => sub {
170 my($org_id, $setting) = @_;
171 return $U->ou_ancestor_setting_value($org_id, $setting);
174 get_user_setting => sub {
175 my ($user_id, $setting) = @_;
176 my $val = new_editor()->search_actor_user_setting(
177 {usr => $user_id, name => $setting})->[0];
178 return undef unless $val;
179 return OpenSRF::Utils::JSON->JSON2perl($val->value);
182 # This basically greps/maps out ths isbn string values, but also promotes the first isbn-13 to the
183 # front of the line (so that the EDI translator takes it as primary) if there is one.
184 get_li_isbns => sub {
189 $_->attr_name eq 'isbn' or next;
190 my $val = $_->attr_value;
191 if (! $primary and length($val) == 13) {
197 $primary and unshift @isbns, $primary;
198 $logger->debug("get_li_isbns returning isbns: " . join(', ', @isbns));
202 get_li_order_ident => sub {
205 # preferred identifier
206 my ($attr) = grep { $U->is_true($_->order_ident) } @$attrs;
207 return $attr if $attr;
209 # note we're not using get_li_attr, since we need the
210 # attr object and not just the attr value
214 $_->attr_name eq 'isbn' and
215 $_->attr_type eq 'lineitem_marc_attr_definition' and
216 length($_->attr_value) == 13
218 return $attr if $attr;
220 for my $name (qw/isbn issn upc/) {
222 $_->attr_name eq $name and
223 $_->attr_type eq 'lineitem_marc_attr_definition'
225 return $attr if $attr;
228 # any 'identifier' attr
229 return ( grep { $_->attr_name eq 'identifier' } @$attrs)[0];
232 # helpers.get_li_attr('isbn_13', li.attributes)
233 # returns matching line item attribute, or undef
234 get_li_attr => \&get_li_attr,
236 # get_li_attr_jedi() returns a JSON-encoded string without the enclosing
237 # quotes. The function also removes other characters from the string
238 # that the EDI translator doesn't like.
240 # This *always* return a string, so don't use this in conditional
241 # expressions in your templates unless you really mean to.
242 get_li_attr_jedi => sub {
243 # This helper has to mangle data in at least three interesting ways.
245 # 1) We'll be receiving data that may already have some \-escaped
248 # 2) We need our output to be valid JSON.
250 # 3) We need our output to yield valid and unproblematic EDI when
251 # passed through edi4r by the edi_pusher.pl script.
253 my $value = get_li_attr(@_);
256 no warnings 'uninitialized';
257 $value .= ""; # force to string
260 # Here we can add any number of special case transformations to
261 # avoid problems with the EDI translator (or bad JSON).
263 # Typical vendors dealing with EDIFACT (or is the problem with
264 # our EDI translator itself?) would seem not to want
265 # any characters outside the ASCII range, so trash them.
266 $value =~ s/[^[:ascii:]]//g;
268 # Remove anything somehow already JSON-escaped as a Unicode
269 # character. (even though for our part, we haven't JSON-escaped
271 $value =~ s/\\u[0-9a-f]{4}//g;
273 # What the heck, get rid of [ ] too (although I couldn't get them
274 # to cause any problems for me, problems have been reported. See
276 $value =~ s/[\[\]]//g;
278 $value = OpenSRF::Utils::JSON->perl2JSON($value);
280 # Existing action/trigger templates expect an unquoted string.
284 # The ? character, if in the final position of a string, breaks
285 # the translator. + or ' or : could be problematic, too. And we must
286 # avoid leaving a hanging \.
287 while ($value =~ /[\\\?\+':]$/) {
294 get_queued_bib_attr => sub {
295 my $name = shift or return; # the first arg is always the name
297 # use Data::Dumper; $logger->warn("get_queued_bib_attr: " . Dumper($attr));
298 ($name and @$attr) or return;
301 select => {'vqbrad' => ['id']},
303 where => {code => $name}
306 my $def_ids = new_editor()->json_query($query);
310 $name =~ s/^(\D+)_(\d+)$/$1/ and $length = $2;
312 $_->field eq @{$def_ids}[0]->{id} or next;
313 next if $length and $length != length($_->attr_value);
314 return $_->attr_value;
319 get_queued_auth_attr => sub {
320 my $name = shift or return; # the first arg is always the name
322 # use Data::Dumper; $logger->warn("get_queued_auth_attr: " . Dumper($attr));
323 ($name and @$attr) or return;
326 select => {'vqarad' => ['id']},
328 where => {code => $name}
331 my $def_ids = new_editor()->json_query($query);
335 $name =~ s/^(\D+)_(\d+)$/$1/ and $length = $2;
337 $_->field eq @{$def_ids}[0]->{id} or next;
338 next if $length and $length != length($_->attr_value);
339 return $_->attr_value;
347 if ($str =~ /\,/ || $str =~ /"/) {
349 $str = '"' . $str . '"';
356 bre_open_hold_count => sub {
358 return 0 unless $bre_id;
359 return $U->simplereq(
361 'open-ils.circ.bre.holds.count', $bre_id);
366 return $str ? (new XML::LibXML)->parse_string($str) : undef;
369 # returns an email addresses derived from sms_carrier and sms_notify
370 get_sms_gateway_email => sub {
371 my $sms_carrier = shift;
372 my $sms_notify = shift;
374 if (! defined $sms_notify || $sms_notify eq '') {
379 select => {'csc' => ['id','name','email_gateway']},
381 where => {id => $sms_carrier}
383 my $carriers = new_editor()->json_query($query);
385 # If this looks like a pretty-formatted number drop the pretty-formatting
386 # Otherwise assume it may be a literal alias instead of a real number
387 if ($sms_notify =~ m/^[- ()0-9]*$/) {
388 $sms_notify =~ s/[- ()]//g;
392 foreach my $carrier ( @{ $carriers } ) {
393 my $address = $carrier->{email_gateway};
394 $address =~ s/\$number/$sms_notify/g;
395 push @addresses, $address;
398 return join(',',@addresses);
402 my ($bre_id, $unapi_args) = @_;
404 $unapi_args->{flesh} ||= '{}',
408 'unapi.bre', $bre_id, 'marcxml','record',
409 $unapi_args->{flesh},
411 $unapi_args->{depth},
412 $unapi_args->{flesh_depth},
416 my $unapi = new_editor()->json_query($query);
417 return undef unless @$unapi;
418 return $_TT_helpers->{xml_doc}->($unapi->[0]->{'unapi.bre'});
421 # escapes quotes in csv string values
424 $string =~ s/"/""/og;
430 # processes templates. Returns template output on success, undef on error
435 return undef unless $env->{template};
439 my $tt = Template->new;
440 # my $tt = Template->new(ENCODING => 'utf8'); # ??
441 $env->{helpers} = $_TT_helpers;
443 unless( $tt->process(\$env->{template}, $env, \$output) ) {
445 ($error = $tt->error) =~ s/\n/ /og;
446 $logger->error("Error processing Trigger template: $error");
449 if ( $error or (!$nostore && $output) ) {
450 my $t_o = Fieldmapper::action_trigger::event_output->new;
451 $t_o->data( ($error) ? $error : $output );
452 $t_o->is_error( ($error) ? 't' : 'f' );
453 $logger->info("trigger: writing " . length($t_o->data) . " bytes to template output");
455 $env->{EventProcessor}->editor->xact_begin;
456 $t_o = $env->{EventProcessor}->editor->create_action_trigger_event_output( $t_o );
458 my $state = (ref $$env{event} eq 'ARRAY') ? $$env{event}->[0]->state : $env->{event}->state;
459 my $key = ($error) ? 'error_output' : 'template_output';
460 $env->{EventProcessor}->update_state( $state, { $key => $t_o->id } );
466 # processes message templates. Returns template output on success, undef on error
470 return undef unless $env->{usr_message}{template};
474 my $tt = Template->new;
475 # my $tt = Template->new(ENCODING => 'utf8'); # ??
476 $env->{helpers} = $_TT_helpers;
478 unless( $tt->process(\$env->{usr_message}{template}, $env, \$output) ) {
480 ($error = $tt->error) =~ s/\n/ /og;
481 $logger->error("Error processing Trigger message template: $error");