]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/Application/Trigger/Reactor.pm
Merge remote-tracking branch 'eg-working/user/dbs/lp894052-version-upgrade'
[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     # returns the org unit setting value
129     get_org_setting => sub {
130         my($org_id, $setting) = @_;
131         return $U->ou_ancestor_setting_value($org_id, $setting);
132     },
133
134     # This basically greps/maps out ths isbn string values, but also promotes the first isbn-13 to the
135     # front of the line (so that the EDI translator takes it as primary) if there is one.
136     get_li_isbns => sub {
137         my $attrs = shift;
138         my @isbns;
139         my $primary;
140         foreach (@$attrs) {
141             $_->attr_name eq 'isbn' or next;
142             my $val = $_->attr_value;
143             if (! $primary and length($val) == 13) {
144                 $primary = $val;
145             } else {
146                 push @isbns, $val;
147             }
148         }
149         $primary and unshift @isbns, $primary;
150         $logger->debug("get_li_isbns returning isbns: " . join(', ', @isbns));
151         return @isbns;
152     },
153
154     # helpers.get_li_attr('isbn_13', li.attributes)
155     # returns matching line item attribute, or undef
156     get_li_attr => \&get_li_attr,
157
158     get_li_attr_jedi => sub {
159         # This helper has to mangle data in at least three interesting ways.
160         #
161         # 1) We'll be receiving data that may already have some \-escaped
162         # characters.
163         #
164         # 2) We need our output to be valid JSON.
165         #
166         # 3) We need our output to yield valid and unproblematic EDI when
167         # passed through edi4r by the edi_pusher.pl script.
168
169         my $value = get_li_attr(@_);
170         if ($value) {
171             # Here we can add any number of special case transformations to
172             # avoid problems with the EDI translator (or bad JSON).
173
174             # The ? character, if in the final position of a string, breaks
175             # the translator. + or ' or : could be problematic, too.
176             if ($value =~ /[\?\+':]$/) {
177                 chop $value;
178             }
179
180             # Typical vendors dealing with EDIFACT would seem not to want
181             # any unicode characters, so trash them. Yes, they're already
182             # in the data escaped like this at this point even though we
183             # haven't JSON-escaped things yet.
184             $value =~ s/\\u[0-9a-f]{4}//g;
185
186             # What the heck, get rid of [ ] too (although I couldn't get them
187             # to cause any problems for me, problems have been reported. See
188             # LP #812593).
189             $value =~ s/[\[\]]//g;
190         }
191
192         $value = OpenSRF::Utils::JSON->perl2JSON($value);
193
194         # Existing action/trigger templates expect an unquoted string.
195         $value =~ s/^"//g;
196         chop $value;
197
198         return $value;
199     },
200
201     get_queued_bib_attr => sub {
202         my $name = shift or return;     # the first arg is always the name
203         my ($attr) = @_;
204         # use Data::Dumper; $logger->warn("get_queued_bib_attr: " . Dumper($attr));
205         ($name and @$attr) or return;
206
207         my $query = {
208             select => {'vqbrad' => ['id']},
209             from => 'vqbrad',
210             where => {code => $name}
211         };
212
213         my $def_ids = new_editor()->json_query($query);
214         @$def_ids or return;
215
216         my $length;
217         $name =~ s/^(\D+)_(\d+)$/$1/ and $length = $2;
218         foreach (@$attr) {
219             $_->field eq @{$def_ids}[0]->{id} or next;
220             next if $length and $length != length($_->attr_value);
221             return $_->attr_value;
222         }
223         return;
224     },
225
226     get_queued_auth_attr => sub {
227         my $name = shift or return;     # the first arg is always the name
228         my ($attr) = @_;
229         # use Data::Dumper; $logger->warn("get_queued_auth_attr: " . Dumper($attr));
230         ($name and @$attr) or return;
231
232         my $query = {
233             select => {'vqarad' => ['id']},
234             from => 'vqarad',
235             where => {code => $name}
236         };
237
238         my $def_ids = new_editor()->json_query($query);
239         @$def_ids or return;
240
241         my $length;
242         $name =~ s/^(\D+)_(\d+)$/$1/ and $length = $2;
243         foreach (@$attr) {
244             $_->field eq @{$def_ids}[0]->{id} or next;
245             next if $length and $length != length($_->attr_value);
246             return $_->attr_value;
247         }
248         return;
249     },
250
251     csv_datum => sub {
252         my ($str) = @_;
253
254         if ($str =~ /\,/ || $str =~ /"/) {
255             $str =~ s/"/""/g;
256             $str = '"' . $str . '"';
257         }
258
259         return $str;
260     },
261
262
263     bre_open_hold_count => sub {
264         my $bre_id = shift;
265         return 0 unless $bre_id;
266         return $U->simplereq(
267             'open-ils.circ',
268             'open-ils.circ.bre.holds.count', $bre_id);
269     },
270
271     xml_doc => sub {
272         my ($str) = @_;
273         return $str ? (new XML::LibXML)->parse_string($str) : undef;
274     },
275
276     unapi_bre => sub {
277         my ($bre_id, $unapi_args) = @_;
278         $unapi_args ||= {};
279         $unapi_args->{flesh} ||= '{}',
280
281         my $query = { 
282             from => [
283                 'unapi.bre', $bre_id, 'marcxml','record', 
284                 $unapi_args->{flesh}, 
285                 $unapi_args->{site}, 
286                 $unapi_args->{depth}, 
287                 $unapi_args->{flesh_depth}, 
288             ]
289         };
290
291         my $unapi = new_editor()->json_query($query);
292         return undef unless @$unapi;
293         return $_TT_helpers->{xml_doc}->($unapi->[0]->{'unapi.bre'});
294     }
295 };
296
297
298 # processes templates.  Returns template output on success, undef on error
299 sub run_TT {
300     my $self = shift;
301     my $env = shift;
302     my $nostore = shift;
303     return undef unless $env->{template};
304
305     my $error;
306     my $output = '';
307     my $tt = Template->new;
308     # my $tt = Template->new(ENCODING => 'utf8');   # ??
309     $env->{helpers} = $_TT_helpers;
310
311     unless( $tt->process(\$env->{template}, $env, \$output) ) {
312         $output = undef;
313         ($error = $tt->error) =~ s/\n/ /og;
314         $logger->error("Error processing Trigger template: $error");
315     }
316
317     if ( $error or (!$nostore && $output) ) {
318         my $t_o = Fieldmapper::action_trigger::event_output->new;
319         $t_o->data( ($error) ? $error : $output );
320         $t_o->is_error( ($error) ? 't' : 'f' );
321         $logger->info("trigger: writing " . length($t_o->data) . " bytes to template output");
322
323         $env->{EventProcessor}->editor->xact_begin;
324         $t_o = $env->{EventProcessor}->editor->create_action_trigger_event_output( $t_o );
325
326         my $state = (ref $$env{event} eq 'ARRAY') ? $$env{event}->[0]->state : $env->{event}->state;
327         my $key = ($error) ? 'error_output' : 'template_output';
328         $env->{EventProcessor}->update_state( $state, { $key => $t_o->id } );
329     }
330         
331     return $output;
332 }
333
334
335 1;