shoving editor into ctx so others can use it or roll it back
[Evergreen.git] / Open-ILS / src / perlmods / OpenILS / Application / Circ / ScriptBuilder.pm
1 package OpenILS::Application::Circ::ScriptBuilder;
2 use strict; use warnings;
3 use OpenILS::Utils::ScriptRunner;
4 use OpenILS::Utils::CStoreEditor qw/:funcs/;
5 use OpenILS::Application::AppUtils;
6 use OpenILS::Application::Actor;
7 use OpenSRF::Utils::Logger qw/$logger/;
8 use OpenILS::Application::Circ::Holds;
9 use DateTime::Format::ISO8601;
10 use OpenSRF::Utils qw/:datetime/;
11 use Scalar::Util qw/weaken/;
12 my $U = "OpenILS::Application::AppUtils";
13 use Data::Dumper;
14
15 my $holdcode = "OpenILS::Application::Circ::Holds";
16
17 my $evt = "environment";
18 my %GROUP_SET;
19 my $GROUP_TREE;
20 my $ORG_TREE;
21 my @ORG_LIST;
22 my @OU_TYPES;
23
24
25 # -----------------------------------------------------------------------
26 # Possible Args:
27 #  copy
28 #  copy_id
29 #  copy_barcode
30 #
31 #  patron
32 #  patron_id
33 #  patron_barcode
34 #
35 #  fetch_patron_circ_info - load info on items out, overdues, and fines.
36 #
37 #  _direct - this is a hash of key/value pairs to shove directly into the 
38 #  script runner.  Use this to cover data not covered by this module
39 # -----------------------------------------------------------------------
40 sub build {
41         my( $class, $args ) = @_;
42
43         my $evt;
44         my @evts;
45
46         my $editor = $$args{editor} || new_editor(xact => 1);
47
48         $args->{_direct} = {} unless $args->{_direct};
49         $args->{editor} = $editor;
50         
51         $evt = fetch_bib_data($editor, $args);
52         push(@evts, $evt) if $evt;
53         $evt = fetch_user_data($editor, $args);
54         push(@evts, $evt) if $evt;
55
56         if(@evts) {
57                 my @e;
58                 push( @e, $_->{textcode} ) for @evts;
59                 $logger->info("script_builder: some events occurred: @e");
60                 $logger->debug("script_builder: some events occurred: " . Dumper(\@evts));
61                 $args->{_events} = \@evts;
62         }
63
64         return build_runner($editor, $args);
65 }
66
67
68 sub build_runner {
69         my $editor      = shift;
70         my $ctx         = shift;
71
72         my $runner = OpenILS::Utils::ScriptRunner->new;
73
74         my $gt = $GROUP_TREE;
75         $runner->insert( "$evt.groupTree",      $gt, 1);
76
77
78         $runner->insert( "$evt.patron",         $ctx->{patron}, 1);
79         $runner->insert( "$evt.copy",                   $ctx->{copy}, 1);
80         $runner->insert( "$evt.volume",         $ctx->{volume}, 1);
81         $runner->insert( "$evt.title",          $ctx->{title}, 1);
82
83         if( ref $ctx->{requestor} ) {
84                 $runner->insert( "$evt.requestor",      $ctx->{requestor}, 1);
85                 if($ctx->{requestor}->ws_ou) {
86                         $runner->insert( "$evt.location",       
87                                 $editor->retrieve_actor_org_unit($ctx->{requestor}->ws_ou), 1);
88                 }
89         }
90
91         $runner->insert( "$evt.patronItemsOut", $ctx->{patronItemsOut}, 1 );
92         $runner->insert( "$evt.patronOverdueCount", $ctx->{patronOverdue}, 1 );
93         $runner->insert( "$evt.patronFines", $ctx->{patronFines}, 1 );
94
95         $runner->insert("$evt.$_", $ctx->{_direct}->{$_}, 1) for keys %{$ctx->{_direct}};
96
97         insert_org_methods( $editor, $runner );
98         insert_copy_methods( $editor, $ctx, $runner );
99
100         return $runner;
101 }
102
103 sub fetch_bib_data {
104         my $e = shift;
105         my $ctx = shift;
106
107         if(!$ctx->{copy}) {
108
109                 my $flesh = { flesh => 1, flesh_fields => { acp => [ 'location', 'status', 'circ_lib' ] } };
110
111                 if($ctx->{copy_id}) {
112                         $ctx->{copy} = $e->retrieve_asset_copy(
113                                 [$ctx->{copy_id}, $flesh ]) or return $e->event;
114
115                 } elsif( $ctx->{copy_barcode} ) {
116
117                         $ctx->{copy} = $e->search_asset_copy(
118                                 [{barcode => $ctx->{copy_barcode}, deleted => 'f'}, $flesh ])->[0]
119                                 or return $e->event;
120                 }
121         }
122
123         return undef unless my $copy = $ctx->{copy};
124
125         $copy->location($e->retrieve_asset_copy_location($copy->location))
126                 unless( ref $copy->location );
127
128         $copy->status($e->retrieve_config_copy_status($copy->status))
129                 unless( ref $copy->status );
130
131         $copy->circ_lib( 
132                 $e->retrieve_actor_org_unit($copy->circ_lib)) 
133                 unless ref $copy->circ_lib;
134
135         $ctx->{volume} = $e->retrieve_asset_call_number(
136                 $ctx->{copy}->call_number) or return $e->event;
137
138         $ctx->{title} = $e->retrieve_biblio_record_entry(
139                 $ctx->{volume}->record) or return $e->event;
140
141         $copy->age_protect(
142                 $e->retrieve_config_rules_age_hold_protect($copy->age_protect))
143                 if $ctx->{flesh_age_protect} and $copy->age_protect;
144
145         return undef;
146 }
147
148
149
150 sub fetch_user_data {
151         my( $e, $ctx ) = @_;
152         
153         if(!$ctx->{patron}) {
154
155                 if( $ctx->{patron_id} ) {
156                         $ctx->{patron} = $e->retrieve_actor_user($ctx->{patron_id});
157
158                 } elsif( $ctx->{patron_barcode} ) {
159
160                         my $card = $e->search_actor_card( 
161                                 { barcode => $ctx->{patron_barcode} } )->[0] or return $e->event;
162
163                         $ctx->{patron} = $e->search_actor_user( 
164                                 { card => $card->id })->[0] or return $e->event;
165
166                 } elsif( $ctx->{fetch_patron_by_circ_copy} ) {
167
168                         if( my $copy = $ctx->{copy} ) {
169                                 my $circs = $e->search_action_circulation(
170                                         { target_copy => $copy->id, checkin_time => undef });
171
172                                 if( my $circ = $circs->[0] ) {
173                                         $ctx->{patron} = $e->retrieve_actor_user($circ->usr)
174                                                 or return $e->event;
175                                 }
176                         }
177                 }
178         }
179
180         return undef unless my $patron = $ctx->{patron};
181
182         unless( $ctx->{ignore_user_status} ) {
183                 return OpenILS::Event->new('PATRON_INACTIVE')
184                         unless $U->is_true($patron->active);
185         
186                 $patron->card($e->retrieve_actor_card($patron->card))
187                         unless ref $patron->card;
188         
189                 return OpenILS::Event->new('PATRON_CARD_INACTIVE')
190                         unless $U->is_true($patron->card->active);
191         
192                 my $expire = DateTime::Format::ISO8601->new->parse_datetime(
193                         clense_ISO8601($patron->expire_date));
194         
195                 return OpenILS::Event->new('PATRON_ACCOUNT_EXPIRED')
196                         if( CORE::time > $expire->epoch ) ;
197         }
198
199         $patron->home_ou( 
200                 $e->retrieve_actor_org_unit($patron->home_ou) ) 
201                 unless ref $patron->home_ou;
202
203         $patron->home_ou->ou_type(
204                 $patron->home_ou->ou_type->id) 
205                 if ref $patron->home_ou->ou_type;
206
207         if(!%GROUP_SET) {
208                 $GROUP_TREE = $e->search_permission_grp_tree(
209                         [
210                                 { parent => undef }, 
211                                 { 
212                                         flesh => 100,
213                                         flesh_fields => { pgt => ['children'] }
214                                 } 
215                         ]
216                 )->[0];
217
218                 flatten_groups($GROUP_TREE);
219         }
220
221         $patron->profile( $GROUP_SET{$patron->profile} )
222                 unless ref $patron->profile;
223
224
225         $ctx->{requestor} = $ctx->{requestor} || $e->requestor;
226
227         # this could alter the requestor object within the editor..
228         #if( my $req = $ctx->{requestor} ) {
229         #       $req->home_ou( $e->retrieve_actor_org_unit($requestor->home_ou) );      
230         #       $req->ws_ou( $e->retrieve_actor_org_unit($requestor->ws_ou) );  
231         #}
232
233         if( $ctx->{fetch_patron_circ_info} ) {
234                 my $circ_counts = 
235                         OpenILS::Application::Actor::_checked_out(1, $e, $patron->id);
236
237                 $ctx->{patronOverdue} = $circ_counts->{overdue} || 0;
238                 $ctx->{patronItemsOut} = $ctx->{patronOverdue} + $circ_counts->{out};
239                 $logger->debug("script_builder: patron overdue count is " . $ctx->{patronOverdue});
240         }
241
242         if( $ctx->{fetch_patron_money_info} ) {
243                 # Grab the fines
244 #               my $fxacts = $e->search_money_billable_transaction_summary(
245 #                       { usr => $patron->id, balance_owed => { "!=" => 0 }, xact_finish => undef });
246 #
247 #               my $fines = 0;
248 #               $fines += $_->balance_owed for @$fxacts;
249 #               $ctx->{patronFines} = $fines;
250                 $ctx->{patronFines} = $U->patron_money_owed($patron->id);
251                 $logger->debug("script_builder: patron fines determined to be ".$ctx->{patronFines});
252         }
253
254         return undef;
255 }
256
257
258 sub flatten_groups {
259         my $tree = shift;
260         return undef unless $tree;
261         $GROUP_SET{$tree->id} = $tree;
262         if( $tree->children ) {
263                 flatten_groups($_) for @{$tree->children};
264         }
265 }
266
267 sub flatten_org_tree {
268         my $tree = shift;
269         return undef unless $tree;
270         push( @ORG_LIST, $tree );
271         if( $tree->children ) {
272                 flatten_org_tree($_) for @{$tree->children};
273         }
274 }
275
276
277
278 sub insert_org_methods {
279         my ( $editor, $runner ) = @_;
280
281         if(!$ORG_TREE) {
282                 $ORG_TREE = $editor->search_actor_org_unit(
283                         [
284                                 {"parent_ou" => undef },
285                                 {
286                                         flesh                           => 2,
287                                         flesh_fields    => { aou =>  ['children'] },
288                                         order_by                        => { aou => 'name'}
289                                 }
290                         ]
291                 )->[0];
292                 flatten_org_tree($ORG_TREE);
293         }
294
295         my $r = $runner;
296         weaken($r);
297
298         $r->insert(__OILS_FUNC_isOrgDescendent  => 
299                 sub {
300                         my( $write_key, $sname, $id ) = @_;
301                         my ($parent)    = grep { $_->shortname eq $sname } @ORG_LIST;
302                         my ($child)             = grep { $_->id == $id } @ORG_LIST;
303                         my $val = is_org_descendent( $parent, $child );
304                         $logger->debug("script_builder: is_org_desc returned val $val, writing to $write_key");
305                         $r->insert($write_key, $val, 1) if $val;
306                         return $val;
307                 }
308         );
309
310         $r->insert(__OILS_FUNC_hasCommonAncestor  => 
311                 sub {
312                         my( $write_key, $orgid1, $orgid2, $depth ) = @_;
313                         my $val = has_common_ancestor( $orgid1, $orgid2, $depth );
314                         $logger->debug("script_builder: has_common_ancestor resturned $val");
315                         $r->insert($write_key, $val, 1) if $val;
316                         return $val;
317                 }
318         );
319 }
320
321
322 sub is_org_descendent {
323         my( $parent, $child ) = @_;
324         return 0 unless $parent and $child;
325         $logger->debug("script_builder: is_org_desc checking parent=".$parent->id.", child=".$child->id);
326         do {
327                 return 0 unless defined $child->parent_ou;
328                 return 1 if $parent->id == $child->id;
329         } while( ($child) = grep { $_->id == $child->parent_ou } @ORG_LIST );
330         return 0;
331 }
332
333 sub has_common_ancestor {
334         my( $org1, $org2, $depth ) = @_;
335         return 0 unless $org1 and $org2;
336         $logger->debug("script_builder: has_common_ancestor checking orgs $org1 : $org2");
337
338         return 1 if $org1 == $org2;
339         ($org1) = grep { $_->id == $org1 } @ORG_LIST;
340         ($org2) = grep { $_->id == $org2 } @ORG_LIST;
341
342         my $p1 = find_parent_at_depth($org1, $depth);
343         my $p2 = find_parent_at_depth($org2, $depth);
344
345         return 1 if $p1->id == $p2->id;
346         return 0;
347 }
348
349
350 sub find_parent_at_depth {
351         my $org = shift;
352         my $depth = shift;
353         fetch_ou_types();
354         do {
355                 my ($t) = grep { $_->id == $org->ou_type } @OU_TYPES;
356                 return $org if $t->depth == $depth;
357         } while( ($org) = grep { $_->id == $org->parent_ou } @ORG_LIST );
358         return undef;   
359 }
360
361
362 sub fetch_ou_types {
363         return if @OU_TYPES;
364         @OU_TYPES = @{new_editor()->retrieve_all_actor_org_unit_type()};
365 }
366
367 sub insert_copy_methods {
368         my( $e, $ctx,  $runner ) = @_;
369         if( my $copy = $ctx->{copy} ) {
370                 $runner->insert_method( 'environment.copy', '__OILS_FUNC_fetch_best_hold', sub {
371                                 my $key = shift;
372                                 $logger->debug("script_builder: searching for permitted hold for copy ".$copy->barcode);
373                                 my ($hold) = $holdcode->find_nearest_permitted_hold(
374                                         OpenSRF::AppSession->create('open-ils.storage'), $copy, $e->requestor );
375                                 $runner->insert( $key, $hold, 1 );
376                         }
377                 );
378         }
379 }
380
381
382
383
384
385 1;