]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/Application/Trigger/Reactor.pm
Additional action/trigger helper functions
[Evergreen.git] / Open-ILS / src / perlmods / lib / OpenILS / Application / Trigger / Reactor.pm
1 package OpenILS::Application::Trigger::Reactor;
2 use strict; use warnings;
3 use Encode qw/ encode /;
4 use Template;
5 use DateTime;
6 use DateTime::Format::ISO8601;
7 use Unicode::Normalize;
8 use XML::LibXML;
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';
15
16 sub fourty_two { return 42 }
17 sub NOOP_True  { return  1 }
18 sub NOOP_False { return  0 }
19
20
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.
23 sub get_li_attr {
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;
29     my $length;
30     $name =~ s/^(\D+)_(\d+)$/$1/ and $length = $2;
31     foreach (@$attr) {
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;
35     }
36     return;
37 }
38
39 # helper functions inserted into the TT environment
40 my $_TT_helpers; # define first so one helper can use another
41 $_TT_helpers = {
42
43     # turns a date into something TT can understand
44     format_date => sub {
45         my $date = shift;
46         $date = DateTime::Format::ISO8601->new->parse_datetime(cleanse_ISO8601($date));
47         return sprintf(
48             "%0.2d:%0.2d:%0.2d %0.2d-%0.2d-%0.4d",
49             $date->hour,
50             $date->minute,
51             $date->second,
52             $date->day,
53             $date->month,
54             $date->year
55         );
56     },
57
58     # escapes a string for inclusion in an XML document.  escapes &, <, and > characters
59     escape_xml => sub {
60         my $str = shift;
61         $str =~ s/&/&amp;/sog;
62         $str =~ s/</&lt;/sog;
63         $str =~ s/>/&gt;/sog;
64         return $str;
65     },
66
67     escape_json => sub {
68         my $str = shift;
69         $str =~ s/([\x{0080}-\x{fffd}])/sprintf('\u%0.4x',ord($1))/sgoe;
70         return $str;
71     },
72
73     # encode email headers in UTF-8, per RFC2231
74     escape_email_header => sub {
75         my $str = shift;
76         $str = encode("MIME-Header", $str);
77         return $str;
78     },
79
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 {
83         my $str = shift;
84         $str = NFD($str);
85         $str =~ s/[\x{0080}-\x{fffd}]//g;
86         return $str;
87     },
88
89     # returns the calculated user locale
90     get_user_locale => sub { 
91         my $user_id = shift;
92         return $U->get_user_locale($user_id);
93     },
94
95     # returns the calculated copy price
96     get_copy_price => sub {
97         my $copy_id = shift;
98         return $U->get_copy_price(new_editor(xact=>1), $copy_id);
99     },
100
101     get_org_unit => sub {
102         my $org_id = shift;
103         return $org_id if ref $org_id;
104         return new_editor()->retrieve_actor_org_unit($org_id);
105     },
106
107     # given a copy, returns the title and author in a hash
108     get_copy_bib_basics => sub {
109         my $copy_id = shift;
110         my $copy = new_editor(xact=>1)->retrieve_asset_copy([
111             $copy_id,
112             {
113                 flesh => 2,
114                 flesh_fields => {
115                     acp => ['call_number'],
116                     acn => ['record']
117                 }
118             }
119         ]);
120         if($copy->call_number->id == -1) {
121             return {
122                 title  => $copy->dummy_title,
123                 author => $copy->dummy_author,
124             };
125         } else {
126             my $mvr = $U->record_to_mvr($copy->call_number->record);
127             return {
128                 title  => $mvr->title,
129                 author => $mvr->author
130             };
131         }
132     },
133
134     # given a call number, returns the copy location with the most copies
135     get_most_populous_location => sub {
136         my $acn_id = shift;
137
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([
140             $acn_id,
141             {
142                 flesh => 1,
143                 flesh_fields => {
144                     acn => ['copies']
145                 }
146             }
147         ]);
148         my %location_count = (); my $winning_location; my $winning_total;
149         use Data::Dumper;
150         foreach my $copy (@{$call_number->copies()}) {
151             if (! defined $location_count{ $copy->location() }) {
152                 $location_count{ $copy->location() } = 1;
153             } else {
154                 $location_count{ $copy->location() } += 1;
155             }
156             if ($location_count{ $copy->location() } > $winning_total) {
157                 $winning_total = $location_count{ $copy->location() };
158                 $winning_location = $copy->location();
159             }
160         }
161
162         my $location = new_editor(xact=>1)->retrieve_asset_copy_location([
163             $winning_location, {}
164         ]);
165         return $location;
166     },
167
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);
172     },
173
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);  
180     },
181
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 {
185         my $attrs = shift;
186         my @isbns;
187         my $primary;
188         foreach (@$attrs) {
189             $_->attr_name eq 'isbn' or next;
190             my $val = $_->attr_value;
191             if (! $primary and length($val) == 13) {
192                 $primary = $val;
193             } else {
194                 push @isbns, $val;
195             }
196         }
197         $primary and unshift @isbns, $primary;
198         $logger->debug("get_li_isbns returning isbns: " . join(', ', @isbns));
199         return @isbns;
200     },
201
202     # helpers.get_li_attr('isbn_13', li.attributes)
203     # returns matching line item attribute, or undef
204     get_li_attr => \&get_li_attr,
205
206     # get_li_attr_jedi() returns a JSON-encoded string without the enclosing
207     # quotes.  The function also removes other characters from the string
208     # that the EDI translator doesn't like.
209     #
210     # This *always* return a string, so don't use this in conditional
211     # expressions in your templates unless you really mean to.
212     get_li_attr_jedi => sub {
213         # This helper has to mangle data in at least three interesting ways.
214         #
215         # 1) We'll be receiving data that may already have some \-escaped
216         # characters.
217         #
218         # 2) We need our output to be valid JSON.
219         #
220         # 3) We need our output to yield valid and unproblematic EDI when
221         # passed through edi4r by the edi_pusher.pl script.
222
223         my $value = get_li_attr(@_);
224
225         {
226             no warnings 'uninitialized';
227             $value .= "";   # force to string
228         };
229
230         # Here we can add any number of special case transformations to
231         # avoid problems with the EDI translator (or bad JSON).
232
233         # Typical vendors dealing with EDIFACT (or is the problem with
234         # our EDI translator itself?) would seem not to want
235         # any characters outside the ASCII range, so trash them.
236         $value =~ s/[^[:ascii:]]//g;
237
238         # Remove anything somehow already JSON-escaped as a Unicode
239         # character. (even though for our part, we haven't JSON-escaped
240         # anything yet).
241         $value =~ s/\\u[0-9a-f]{4}//g;
242
243         # What the heck, get rid of [ ] too (although I couldn't get them
244         # to cause any problems for me, problems have been reported. See
245         # LP #812593).
246         $value =~ s/[\[\]]//g;
247
248         $value = OpenSRF::Utils::JSON->perl2JSON($value);
249
250         # Existing action/trigger templates expect an unquoted string.
251         $value =~ s/^"//g;
252         $value =~ s/"$//g;
253
254         # The ? character, if in the final position of a string, breaks
255         # the translator. + or ' or : could be problematic, too. And we must
256         # avoid leaving a hanging \.
257         while ($value =~ /[\\\?\+':]$/) {
258             chop $value;
259         }
260
261         return $value;
262     },
263
264     get_queued_bib_attr => sub {
265         my $name = shift or return;     # the first arg is always the name
266         my ($attr) = @_;
267         # use Data::Dumper; $logger->warn("get_queued_bib_attr: " . Dumper($attr));
268         ($name and @$attr) or return;
269
270         my $query = {
271             select => {'vqbrad' => ['id']},
272             from => 'vqbrad',
273             where => {code => $name}
274         };
275
276         my $def_ids = new_editor()->json_query($query);
277         @$def_ids or return;
278
279         my $length;
280         $name =~ s/^(\D+)_(\d+)$/$1/ and $length = $2;
281         foreach (@$attr) {
282             $_->field eq @{$def_ids}[0]->{id} or next;
283             next if $length and $length != length($_->attr_value);
284             return $_->attr_value;
285         }
286         return;
287     },
288
289     get_queued_auth_attr => sub {
290         my $name = shift or return;     # the first arg is always the name
291         my ($attr) = @_;
292         # use Data::Dumper; $logger->warn("get_queued_auth_attr: " . Dumper($attr));
293         ($name and @$attr) or return;
294
295         my $query = {
296             select => {'vqarad' => ['id']},
297             from => 'vqarad',
298             where => {code => $name}
299         };
300
301         my $def_ids = new_editor()->json_query($query);
302         @$def_ids or return;
303
304         my $length;
305         $name =~ s/^(\D+)_(\d+)$/$1/ and $length = $2;
306         foreach (@$attr) {
307             $_->field eq @{$def_ids}[0]->{id} or next;
308             next if $length and $length != length($_->attr_value);
309             return $_->attr_value;
310         }
311         return;
312     },
313
314     csv_datum => sub {
315         my ($str) = @_;
316
317         if ($str =~ /\,/ || $str =~ /"/) {
318             $str =~ s/"/""/g;
319             $str = '"' . $str . '"';
320         }
321
322         return $str;
323     },
324
325
326     bre_open_hold_count => sub {
327         my $bre_id = shift;
328         return 0 unless $bre_id;
329         return $U->simplereq(
330             'open-ils.circ',
331             'open-ils.circ.bre.holds.count', $bre_id);
332     },
333
334     xml_doc => sub {
335         my ($str) = @_;
336         return $str ? (new XML::LibXML)->parse_string($str) : undef;
337     },
338
339     # returns an email addresses derived from sms_carrier and sms_notify
340     get_sms_gateway_email => sub {
341         my $sms_carrier = shift;
342         my $sms_notify = shift;
343
344         if (! defined $sms_notify || $sms_notify eq '') {
345             return '';
346         }
347
348         my $query = {
349             select => {'csc' => ['id','name','email_gateway']},
350             from => 'csc',
351             where => {id => $sms_carrier}
352         };
353         my $carriers = new_editor()->json_query($query);
354
355         # If this looks like a pretty-formatted number drop the pretty-formatting
356         # Otherwise assume it may be a literal alias instead of a real number
357         if ($sms_notify =~ m/^[- ()0-9]*$/) {
358             $sms_notify =~ s/[- ()]//g;
359         }
360
361         my @addresses = ();
362         foreach my $carrier ( @{ $carriers } ) {
363             my $address = $carrier->{email_gateway};
364             $address =~ s/\$number/$sms_notify/g;
365             push @addresses, $address;
366         }
367
368         return join(',',@addresses);
369     },
370
371     unapi_bre => sub {
372         my ($bre_id, $unapi_args) = @_;
373         $unapi_args ||= {};
374         $unapi_args->{flesh} ||= '{}',
375
376         my $query = { 
377             from => [
378                 'unapi.bre', $bre_id, 'marcxml','record', 
379                 $unapi_args->{flesh}, 
380                 $unapi_args->{site}, 
381                 $unapi_args->{depth}, 
382                 $unapi_args->{flesh_depth}, 
383             ]
384         };
385
386         my $unapi = new_editor()->json_query($query);
387         return undef unless @$unapi;
388         return $_TT_helpers->{xml_doc}->($unapi->[0]->{'unapi.bre'});
389     },
390
391     # escapes quotes in csv string values
392     escape_csv => sub {
393         my $string = shift;
394         $string =~ s/"/""/og;
395         return $string;
396     }
397 };
398
399
400 # processes templates.  Returns template output on success, undef on error
401 sub run_TT {
402     my $self = shift;
403     my $env = shift;
404     my $nostore = shift;
405     return undef unless $env->{template};
406
407     my $error;
408     my $output = '';
409     my $tt = Template->new;
410     # my $tt = Template->new(ENCODING => 'utf8');   # ??
411     $env->{helpers} = $_TT_helpers;
412
413     unless( $tt->process(\$env->{template}, $env, \$output) ) {
414         $output = undef;
415         ($error = $tt->error) =~ s/\n/ /og;
416         $logger->error("Error processing Trigger template: $error");
417     }
418
419     if ( $error or (!$nostore && $output) ) {
420         my $t_o = Fieldmapper::action_trigger::event_output->new;
421         $t_o->data( ($error) ? $error : $output );
422         $t_o->is_error( ($error) ? 't' : 'f' );
423         $logger->info("trigger: writing " . length($t_o->data) . " bytes to template output");
424
425         $env->{EventProcessor}->editor->xact_begin;
426         $t_o = $env->{EventProcessor}->editor->create_action_trigger_event_output( $t_o );
427
428         my $state = (ref $$env{event} eq 'ARRAY') ? $$env{event}->[0]->state : $env->{event}->state;
429         my $key = ($error) ? 'error_output' : 'template_output';
430         $env->{EventProcessor}->update_state( $state, { $key => $t_o->id } );
431     }
432         
433     return $output;
434 }
435
436
437 1;