]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/Application/Trigger/Reactor.pm
f6702ce207d97f85655105d0fc7c08a76a2a2bec
[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     # given a copy, returns the title and author in a hash
102     get_copy_bib_basics => sub {
103         my $copy_id = shift;
104         my $copy = new_editor(xact=>1)->retrieve_asset_copy([
105             $copy_id,
106             {
107                 flesh => 2,
108                 flesh_fields => {
109                     acp => ['call_number'],
110                     acn => ['record']
111                 }
112             }
113         ]);
114         if($copy->call_number->id == -1) {
115             return {
116                 title  => $copy->dummy_title,
117                 author => $copy->dummy_author,
118             };
119         } else {
120             my $mvr = $U->record_to_mvr($copy->call_number->record);
121             return {
122                 title  => $mvr->title,
123                 author => $mvr->author
124             };
125         }
126     },
127
128     # given a call number, returns the copy location with the most copies
129     get_most_populous_location => sub {
130         my $acn_id = shift;
131
132         # FIXME - there's probably a more efficient way to do this with json_query/SQL
133         my $call_number = new_editor(xact=>1)->retrieve_asset_call_number([
134             $acn_id,
135             {
136                 flesh => 1,
137                 flesh_fields => {
138                     acn => ['copies']
139                 }
140             }
141         ]);
142         my %location_count = (); my $winning_location; my $winning_total;
143         use Data::Dumper;
144         foreach my $copy (@{$call_number->copies()}) {
145             if (! defined $location_count{ $copy->location() }) {
146                 $location_count{ $copy->location() } = 1;
147             } else {
148                 $location_count{ $copy->location() } += 1;
149             }
150             if ($location_count{ $copy->location() } > $winning_total) {
151                 $winning_total = $location_count{ $copy->location() };
152                 $winning_location = $copy->location();
153             }
154         }
155
156         my $location = new_editor(xact=>1)->retrieve_asset_copy_location([
157             $winning_location, {}
158         ]);
159         return $location;
160     },
161
162     # returns the org unit setting value
163     get_org_setting => sub {
164         my($org_id, $setting) = @_;
165         return $U->ou_ancestor_setting_value($org_id, $setting);
166     },
167
168     # This basically greps/maps out ths isbn string values, but also promotes the first isbn-13 to the
169     # front of the line (so that the EDI translator takes it as primary) if there is one.
170     get_li_isbns => sub {
171         my $attrs = shift;
172         my @isbns;
173         my $primary;
174         foreach (@$attrs) {
175             $_->attr_name eq 'isbn' or next;
176             my $val = $_->attr_value;
177             if (! $primary and length($val) == 13) {
178                 $primary = $val;
179             } else {
180                 push @isbns, $val;
181             }
182         }
183         $primary and unshift @isbns, $primary;
184         $logger->debug("get_li_isbns returning isbns: " . join(', ', @isbns));
185         return @isbns;
186     },
187
188     # helpers.get_li_attr('isbn_13', li.attributes)
189     # returns matching line item attribute, or undef
190     get_li_attr => \&get_li_attr,
191
192     # get_li_attr_jedi() returns a JSON-encoded string without the enclosing
193     # quotes.  The function also removes other characters from the string
194     # that the EDI translator doesn't like.
195     #
196     # This *always* return a string, so don't use this in conditional
197     # expressions in your templates unless you really mean to.
198     get_li_attr_jedi => sub {
199         # This helper has to mangle data in at least three interesting ways.
200         #
201         # 1) We'll be receiving data that may already have some \-escaped
202         # characters.
203         #
204         # 2) We need our output to be valid JSON.
205         #
206         # 3) We need our output to yield valid and unproblematic EDI when
207         # passed through edi4r by the edi_pusher.pl script.
208
209         my $value = get_li_attr(@_);
210
211         {
212             no warnings 'uninitialized';
213             $value .= "";   # force to string
214         };
215
216         # Here we can add any number of special case transformations to
217         # avoid problems with the EDI translator (or bad JSON).
218
219         # Typical vendors dealing with EDIFACT (or is the problem with
220         # our EDI translator itself?) would seem not to want
221         # any characters outside the ASCII range, so trash them.
222         $value =~ s/[^[:ascii:]]//g;
223
224         # Remove anything somehow already JSON-escaped as a Unicode
225         # character. (even though for our part, we haven't JSON-escaped
226         # anything yet).
227         $value =~ s/\\u[0-9a-f]{4}//g;
228
229         # What the heck, get rid of [ ] too (although I couldn't get them
230         # to cause any problems for me, problems have been reported. See
231         # LP #812593).
232         $value =~ s/[\[\]]//g;
233
234         $value = OpenSRF::Utils::JSON->perl2JSON($value);
235
236         # Existing action/trigger templates expect an unquoted string.
237         $value =~ s/^"//g;
238         $value =~ s/"$//g;
239
240         # The ? character, if in the final position of a string, breaks
241         # the translator. + or ' or : could be problematic, too. And we must
242         # avoid leaving a hanging \.
243         while ($value =~ /[\\\?\+':]$/) {
244             chop $value;
245         }
246
247         return $value;
248     },
249
250     get_queued_bib_attr => sub {
251         my $name = shift or return;     # the first arg is always the name
252         my ($attr) = @_;
253         # use Data::Dumper; $logger->warn("get_queued_bib_attr: " . Dumper($attr));
254         ($name and @$attr) or return;
255
256         my $query = {
257             select => {'vqbrad' => ['id']},
258             from => 'vqbrad',
259             where => {code => $name}
260         };
261
262         my $def_ids = new_editor()->json_query($query);
263         @$def_ids or return;
264
265         my $length;
266         $name =~ s/^(\D+)_(\d+)$/$1/ and $length = $2;
267         foreach (@$attr) {
268             $_->field eq @{$def_ids}[0]->{id} or next;
269             next if $length and $length != length($_->attr_value);
270             return $_->attr_value;
271         }
272         return;
273     },
274
275     get_queued_auth_attr => sub {
276         my $name = shift or return;     # the first arg is always the name
277         my ($attr) = @_;
278         # use Data::Dumper; $logger->warn("get_queued_auth_attr: " . Dumper($attr));
279         ($name and @$attr) or return;
280
281         my $query = {
282             select => {'vqarad' => ['id']},
283             from => 'vqarad',
284             where => {code => $name}
285         };
286
287         my $def_ids = new_editor()->json_query($query);
288         @$def_ids or return;
289
290         my $length;
291         $name =~ s/^(\D+)_(\d+)$/$1/ and $length = $2;
292         foreach (@$attr) {
293             $_->field eq @{$def_ids}[0]->{id} or next;
294             next if $length and $length != length($_->attr_value);
295             return $_->attr_value;
296         }
297         return;
298     },
299
300     csv_datum => sub {
301         my ($str) = @_;
302
303         if ($str =~ /\,/ || $str =~ /"/) {
304             $str =~ s/"/""/g;
305             $str = '"' . $str . '"';
306         }
307
308         return $str;
309     },
310
311
312     bre_open_hold_count => sub {
313         my $bre_id = shift;
314         return 0 unless $bre_id;
315         return $U->simplereq(
316             'open-ils.circ',
317             'open-ils.circ.bre.holds.count', $bre_id);
318     },
319
320     xml_doc => sub {
321         my ($str) = @_;
322         return $str ? (new XML::LibXML)->parse_string($str) : undef;
323     },
324
325     # returns an email addresses derived from sms_carrier and sms_notify
326     get_sms_gateway_email => sub {
327         my $sms_carrier = shift;
328         my $sms_notify = shift;
329
330         if (! defined $sms_notify || $sms_notify eq '') {
331             return '';
332         }
333
334         my $query = {
335             select => {'csc' => ['id','name','email_gateway']},
336             from => 'csc',
337             where => {id => $sms_carrier}
338         };
339         my $carriers = new_editor()->json_query($query);
340
341         my @addresses = ();
342         foreach my $carrier ( @{ $carriers } ) {
343             my $address = $carrier->{email_gateway};
344             $address =~ s/\$number/$sms_notify/g;
345             push @addresses, $address;
346         }
347
348         return join(',',@addresses);
349     },
350
351     unapi_bre => sub {
352         my ($bre_id, $unapi_args) = @_;
353         $unapi_args ||= {};
354         $unapi_args->{flesh} ||= '{}',
355
356         my $query = { 
357             from => [
358                 'unapi.bre', $bre_id, 'marcxml','record', 
359                 $unapi_args->{flesh}, 
360                 $unapi_args->{site}, 
361                 $unapi_args->{depth}, 
362                 $unapi_args->{flesh_depth}, 
363             ]
364         };
365
366         my $unapi = new_editor()->json_query($query);
367         return undef unless @$unapi;
368         return $_TT_helpers->{xml_doc}->($unapi->[0]->{'unapi.bre'});
369     }
370 };
371
372
373 # processes templates.  Returns template output on success, undef on error
374 sub run_TT {
375     my $self = shift;
376     my $env = shift;
377     my $nostore = shift;
378     return undef unless $env->{template};
379
380     my $error;
381     my $output = '';
382     my $tt = Template->new;
383     # my $tt = Template->new(ENCODING => 'utf8');   # ??
384     $env->{helpers} = $_TT_helpers;
385
386     unless( $tt->process(\$env->{template}, $env, \$output) ) {
387         $output = undef;
388         ($error = $tt->error) =~ s/\n/ /og;
389         $logger->error("Error processing Trigger template: $error");
390     }
391
392     if ( $error or (!$nostore && $output) ) {
393         my $t_o = Fieldmapper::action_trigger::event_output->new;
394         $t_o->data( ($error) ? $error : $output );
395         $t_o->is_error( ($error) ? 't' : 'f' );
396         $logger->info("trigger: writing " . length($t_o->data) . " bytes to template output");
397
398         $env->{EventProcessor}->editor->xact_begin;
399         $t_o = $env->{EventProcessor}->editor->create_action_trigger_event_output( $t_o );
400
401         my $state = (ref $$env{event} eq 'ARRAY') ? $$env{event}->[0]->state : $env->{event}->state;
402         my $key = ($error) ? 'error_output' : 'template_output';
403         $env->{EventProcessor}->update_state( $state, { $key => $t_o->id } );
404     }
405         
406     return $output;
407 }
408
409
410 1;