]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/perlmods/OpenILS/Application/AppUtils.pm
added a wait flag to create_events_for_hook() to allow for processing large sets...
[working/Evergreen.git] / Open-ILS / src / perlmods / OpenILS / Application / AppUtils.pm
1 package OpenILS::Application::AppUtils;
2 # vim:noet:ts=4
3 use strict; use warnings;
4 use OpenILS::Application;
5 use base qw/OpenILS::Application/;
6 use OpenSRF::Utils::Cache;
7 use OpenSRF::Utils::Logger qw/$logger/;
8 use OpenILS::Utils::ModsParser;
9 use OpenSRF::EX qw(:try);
10 use OpenILS::Event;
11 use Data::Dumper;
12 use OpenILS::Utils::CStoreEditor;
13 use OpenILS::Const qw/:const/;
14 use Unicode::Normalize;
15 use OpenSRF::Utils::SettingsClient;
16 use UUID::Tiny;
17 use Encode;
18
19 # ---------------------------------------------------------------------------
20 # Pile of utilty methods used accross applications.
21 # ---------------------------------------------------------------------------
22 my $cache_client = "OpenSRF::Utils::Cache";
23
24
25 # ---------------------------------------------------------------------------
26 # on sucess, returns the created session, on failure throws ERROR exception
27 # ---------------------------------------------------------------------------
28 sub start_db_session {
29
30         my $self = shift;
31         my $session = OpenSRF::AppSession->connect( "open-ils.storage" );
32         my $trans_req = $session->request( "open-ils.storage.transaction.begin" );
33
34         my $trans_resp = $trans_req->recv();
35         if(ref($trans_resp) and UNIVERSAL::isa($trans_resp,"Error")) { throw $trans_resp; }
36         if( ! $trans_resp->content() ) {
37                 throw OpenSRF::ERROR 
38                         ("Unable to Begin Transaction with database" );
39         }
40         $trans_req->finish();
41
42         $logger->debug("Setting global storage session to ".
43                 "session: " . $session->session_id . " : " . $session->app );
44
45         return $session;
46 }
47
48 my $PERM_QUERY = {
49     select => {
50         au => [ {
51             transform => 'permission.usr_has_perm',
52             alias => 'has_perm',
53             column => 'id',
54             params => []
55         } ]
56     },
57     from => 'au',
58     where => {},
59 };
60
61
62 # returns undef if user has all of the perms provided
63 # returns the first failed perm on failure
64 sub check_user_perms {
65         my($self, $user_id, $org_id, @perm_types ) = @_;
66         $logger->debug("Checking perms with user : $user_id , org: $org_id, @perm_types");
67
68         for my $type (@perm_types) {
69             $PERM_QUERY->{select}->{au}->[0]->{params} = [$type, $org_id];
70                 $PERM_QUERY->{where}->{id} = $user_id;
71                 return $type unless $self->is_true(OpenILS::Utils::CStoreEditor->new->json_query($PERM_QUERY)->[0]->{has_perm});
72         }
73         return undef;
74 }
75
76 # checks the list of user perms.  The first one that fails returns a new
77 sub check_perms {
78         my( $self, $user_id, $org_id, @perm_types ) = @_;
79         my $t = $self->check_user_perms( $user_id, $org_id, @perm_types );
80         return OpenILS::Event->new('PERM_FAILURE', ilsperm => $t, ilspermloc => $org_id ) if $t;
81         return undef;
82 }
83
84
85
86 # ---------------------------------------------------------------------------
87 # commits and destroys the session
88 # ---------------------------------------------------------------------------
89 sub commit_db_session {
90         my( $self, $session ) = @_;
91
92         my $req = $session->request( "open-ils.storage.transaction.commit" );
93         my $resp = $req->recv();
94
95         if(!$resp) {
96                 throw OpenSRF::EX::ERROR ("Unable to commit db session");
97         }
98
99         if(UNIVERSAL::isa($resp,"Error")) { 
100                 throw $resp ($resp->stringify); 
101         }
102
103         if(!$resp->content) {
104                 throw OpenSRF::EX::ERROR ("Unable to commit db session");
105         }
106
107         $session->finish();
108         $session->disconnect();
109         $session->kill_me();
110 }
111
112 sub rollback_db_session {
113         my( $self, $session ) = @_;
114
115         my $req = $session->request("open-ils.storage.transaction.rollback");
116         my $resp = $req->recv();
117         if(UNIVERSAL::isa($resp,"Error")) { throw $resp;  }
118
119         $session->finish();
120         $session->disconnect();
121         $session->kill_me();
122 }
123
124
125 # returns undef it the event is not an ILS event
126 # returns the event code otherwise
127 sub event_code {
128         my( $self, $evt ) = @_;
129         return $evt->{ilsevent} if( ref($evt) eq 'HASH' and defined($evt->{ilsevent})) ;
130         return undef;
131 }
132
133 # ---------------------------------------------------------------------------
134 # Checks to see if a user is logged in.  Returns the user record on success,
135 # throws an exception on error.
136 # ---------------------------------------------------------------------------
137 sub check_user_session {
138         my( $self, $user_session ) = @_;
139
140         my $content = $self->simplereq( 
141                 'open-ils.auth', 
142                 'open-ils.auth.session.retrieve', $user_session);
143
144     return undef if (!$content) or $self->event_code($content);
145         return $content;
146 }
147
148 # generic simple request returning a scalar value
149 sub simplereq {
150         my($self, $service, $method, @params) = @_;
151         return $self->simple_scalar_request($service, $method, @params);
152 }
153
154
155 sub simple_scalar_request {
156         my($self, $service, $method, @params) = @_;
157
158         my $session = OpenSRF::AppSession->create( $service );
159
160         my $request = $session->request( $method, @params );
161
162         my $val;
163         my $err;
164         try  {
165
166                 $val = $request->gather(1);     
167
168         } catch Error with {
169                 $err = shift;
170         };
171
172         if( $err ) {
173                 warn "received error : service=$service : method=$method : params=".Dumper(\@params) . "\n $err";
174                 throw $err ("Call to $service for method $method \n failed with exception: $err : " );
175         }
176
177         return $val;
178 }
179
180
181
182
183
184 my $tree                                                = undef;
185 my $orglist                                     = undef;
186 my $org_typelist                        = undef;
187 my $org_typelist_hash   = {};
188
189 sub __get_org_tree {
190         
191         # can we throw this version away??
192
193         my $self = shift;
194         if($tree) { return $tree; }
195
196         # see if it's in the cache
197         $tree = $cache_client->new()->get_cache('_orgtree');
198         if($tree) { return $tree; }
199
200         if(!$orglist) {
201                 warn "Retrieving Org Tree\n";
202                 $orglist = $self->simple_scalar_request( 
203                         "open-ils.cstore", 
204                         "open-ils.cstore.direct.actor.org_unit.search.atomic",
205                         { id => { '!=' => undef } }
206                 );
207         }
208
209         if( ! $org_typelist ) {
210                 warn "Retrieving org types\n";
211                 $org_typelist = $self->simple_scalar_request( 
212                         "open-ils.cstore", 
213                         "open-ils.cstore.direct.actor.org_unit_type.search.atomic",
214                         { id => { '!=' => undef } }
215                 );
216                 $self->build_org_type($org_typelist);
217         }
218
219         $tree = $self->build_org_tree($orglist,1);
220         $cache_client->new()->put_cache('_orgtree', $tree);
221         return $tree;
222
223 }
224
225 my $slimtree = undef;
226 sub get_slim_org_tree {
227
228         my $self = shift;
229         if($slimtree) { return $slimtree; }
230
231         # see if it's in the cache
232         $slimtree = $cache_client->new()->get_cache('slimorgtree');
233         if($slimtree) { return $slimtree; }
234
235         if(!$orglist) {
236                 warn "Retrieving Org Tree\n";
237                 $orglist = $self->simple_scalar_request( 
238                         "open-ils.cstore", 
239                         "open-ils.cstore.direct.actor.org_unit.search.atomic",
240                         { id => { '!=' => undef } }
241                 );
242         }
243
244         $slimtree = $self->build_org_tree($orglist);
245         $cache_client->new->put_cache('slimorgtree', $slimtree);
246         return $slimtree;
247
248 }
249
250
251 sub build_org_type { 
252         my($self, $org_typelist)  = @_;
253         for my $type (@$org_typelist) {
254                 $org_typelist_hash->{$type->id()} = $type;
255         }
256 }
257
258
259
260 sub build_org_tree {
261
262         my( $self, $orglist, $add_types ) = @_;
263
264         return $orglist unless ref $orglist; 
265     return $$orglist[0] if @$orglist == 1;
266
267         my @list = sort { 
268                 $a->ou_type <=> $b->ou_type ||
269                 $a->name cmp $b->name } @$orglist;
270
271         for my $org (@list) {
272
273                 next unless ($org);
274
275                 if(!ref($org->ou_type()) and $add_types) {
276                         $org->ou_type( $org_typelist_hash->{$org->ou_type()});
277                 }
278
279         next if (!defined($org->parent_ou) || $org->parent_ou eq "");
280
281                 my ($parent) = grep { $_->id == $org->parent_ou } @list;
282                 next unless $parent;
283                 $parent->children([]) unless defined($parent->children); 
284                 push( @{$parent->children}, $org );
285         }
286
287         return $list[0];
288 }
289
290 sub fetch_closed_date {
291         my( $self, $cd ) = @_;
292         my $evt;
293         
294         $logger->debug("Fetching closed_date $cd from cstore");
295
296         my $cd_obj = $self->simplereq(
297                 'open-ils.cstore',
298                 'open-ils.cstore.direct.actor.org_unit.closed_date.retrieve', $cd );
299
300         if(!$cd_obj) {
301                 $logger->info("closed_date $cd not found in the db");
302                 $evt = OpenILS::Event->new('ACTOR_USER_NOT_FOUND');
303         }
304
305         return ($cd_obj, $evt);
306 }
307
308 sub fetch_user {
309         my( $self, $userid ) = @_;
310         my( $user, $evt );
311         
312         $logger->debug("Fetching user $userid from cstore");
313
314         $user = $self->simplereq(
315                 'open-ils.cstore',
316                 'open-ils.cstore.direct.actor.user.retrieve', $userid );
317
318         if(!$user) {
319                 $logger->info("User $userid not found in the db");
320                 $evt = OpenILS::Event->new('ACTOR_USER_NOT_FOUND');
321         }
322
323         return ($user, $evt);
324 }
325
326 sub checkses {
327         my( $self, $session ) = @_;
328         my $user = $self->check_user_session($session) or 
329         return (undef, OpenILS::Event->new('NO_SESSION'));
330     return ($user);
331 }
332
333
334 # verifiese the session and checks the permissions agains the
335 # session user and the user's home_ou as the org id
336 sub checksesperm {
337         my( $self, $session, @perms ) = @_;
338         my $user; my $evt; my $e; 
339         $logger->debug("Checking user session $session and perms @perms");
340         ($user, $evt) = $self->checkses($session);
341         return (undef, $evt) if $evt;
342         $evt = $self->check_perms($user->id, $user->home_ou, @perms);
343         return ($user, $evt);
344 }
345
346
347 sub checkrequestor {
348         my( $self, $staffobj, $userid, @perms ) = @_;
349         my $user; my $evt;
350         $userid = $staffobj->id unless defined $userid;
351
352         $logger->debug("checkrequestor(): requestor => " . $staffobj->id . ", target => $userid");
353
354         if( $userid ne $staffobj->id ) {
355                 ($user, $evt) = $self->fetch_user($userid);
356                 return (undef, $evt) if $evt;
357                 $evt = $self->check_perms( $staffobj->id, $user->home_ou, @perms );
358
359         } else {
360                 $user = $staffobj;
361         }
362
363         return ($user, $evt);
364 }
365
366 sub checkses_requestor {
367         my( $self, $authtoken, $targetid, @perms ) = @_;
368         my( $requestor, $target, $evt );
369
370         ($requestor, $evt) = $self->checkses($authtoken);
371         return (undef, undef, $evt) if $evt;
372
373         ($target, $evt) = $self->checkrequestor( $requestor, $targetid, @perms );
374         return( $requestor, $target, $evt);
375 }
376
377 sub fetch_copy {
378         my( $self, $copyid ) = @_;
379         my( $copy, $evt );
380
381         $logger->debug("Fetching copy $copyid from cstore");
382
383         $copy = $self->simplereq(
384                 'open-ils.cstore',
385                 'open-ils.cstore.direct.asset.copy.retrieve', $copyid );
386
387         if(!$copy) { $evt = OpenILS::Event->new('ASSET_COPY_NOT_FOUND'); }
388
389         return( $copy, $evt );
390 }
391
392
393 # retrieves a circ object by id
394 sub fetch_circulation {
395         my( $self, $circid ) = @_;
396         my $circ; my $evt;
397         
398         $logger->debug("Fetching circ $circid from cstore");
399
400         $circ = $self->simplereq(
401                 'open-ils.cstore',
402                 "open-ils.cstore.direct.action.circulation.retrieve", $circid );
403
404         if(!$circ) {
405                 $evt = OpenILS::Event->new('ACTION_CIRCULATION_NOT_FOUND', circid => $circid );
406         }
407
408         return ( $circ, $evt );
409 }
410
411 sub fetch_record_by_copy {
412         my( $self, $copyid ) = @_;
413         my( $record, $evt );
414
415         $logger->debug("Fetching record by copy $copyid from cstore");
416
417         $record = $self->simplereq(
418                 'open-ils.cstore',
419                 'open-ils.cstore.direct.asset.copy.retrieve', $copyid,
420                 { flesh => 3,
421                   flesh_fields => {     bre => [ 'fixed_fields' ],
422                                         acn => [ 'record' ],
423                                         acp => [ 'call_number' ],
424                                   }
425                 }
426         );
427
428         if(!$record) {
429                 $evt = OpenILS::Event->new('BIBLIO_RECORD_ENTRY_NOT_FOUND');
430         } else {
431                 $record = $record->call_number->record;
432         }
433
434         return ($record, $evt);
435 }
436
437 # turns a record object into an mvr (mods) object
438 sub record_to_mvr {
439         my( $self, $record ) = @_;
440         return undef unless $record and $record->marc;
441         my $u = OpenILS::Utils::ModsParser->new();
442         $u->start_mods_batch( $record->marc );
443         my $mods = $u->finish_mods_batch();
444         $mods->doc_id($record->id);
445    $mods->tcn($record->tcn_value);
446         return $mods;
447 }
448
449 sub fetch_hold {
450         my( $self, $holdid ) = @_;
451         my( $hold, $evt );
452
453         $logger->debug("Fetching hold $holdid from cstore");
454
455         $hold = $self->simplereq(
456                 'open-ils.cstore',
457                 'open-ils.cstore.direct.action.hold_request.retrieve', $holdid);
458
459         $evt = OpenILS::Event->new('ACTION_HOLD_REQUEST_NOT_FOUND', holdid => $holdid) unless $hold;
460
461         return ($hold, $evt);
462 }
463
464
465 sub fetch_hold_transit_by_hold {
466         my( $self, $holdid ) = @_;
467         my( $transit, $evt );
468
469         $logger->debug("Fetching transit by hold $holdid from cstore");
470
471         $transit = $self->simplereq(
472                 'open-ils.cstore',
473                 'open-ils.cstore.direct.action.hold_transit_copy.search', { hold => $holdid } );
474
475         $evt = OpenILS::Event->new('ACTION_HOLD_TRANSIT_COPY_NOT_FOUND', holdid => $holdid) unless $transit;
476
477         return ($transit, $evt );
478 }
479
480 # fetches the captured, but not fulfilled hold attached to a given copy
481 sub fetch_open_hold_by_copy {
482         my( $self, $copyid ) = @_;
483         $logger->debug("Searching for active hold for copy $copyid");
484         my( $hold, $evt );
485
486         $hold = $self->cstorereq(
487                 'open-ils.cstore.direct.action.hold_request.search',
488                 { 
489                         current_copy            => $copyid , 
490                         capture_time            => { "!=" => undef }, 
491                         fulfillment_time        => undef,
492                         cancel_time                     => undef,
493                 } );
494
495         $evt = OpenILS::Event->new('ACTION_HOLD_REQUEST_NOT_FOUND', copyid => $copyid) unless $hold;
496         return ($hold, $evt);
497 }
498
499 sub fetch_hold_transit {
500         my( $self, $transid ) = @_;
501         my( $htransit, $evt );
502         $logger->debug("Fetching hold transit with hold id $transid");
503         $htransit = $self->cstorereq(
504                 'open-ils.cstore.direct.action.hold_transit_copy.retrieve', $transid );
505         $evt = OpenILS::Event->new('ACTION_HOLD_TRANSIT_COPY_NOT_FOUND', id => $transid) unless $htransit;
506         return ($htransit, $evt);
507 }
508
509 sub fetch_copy_by_barcode {
510         my( $self, $barcode ) = @_;
511         my( $copy, $evt );
512
513         $logger->debug("Fetching copy by barcode $barcode from cstore");
514
515         $copy = $self->simplereq( 'open-ils.cstore',
516                 'open-ils.cstore.direct.asset.copy.search', { barcode => $barcode, deleted => 'f'} );
517                 #'open-ils.storage.direct.asset.copy.search.barcode', $barcode );
518
519         $evt = OpenILS::Event->new('ASSET_COPY_NOT_FOUND', barcode => $barcode) unless $copy;
520
521         return ($copy, $evt);
522 }
523
524 sub fetch_open_billable_transaction {
525         my( $self, $transid ) = @_;
526         my( $transaction, $evt );
527
528         $logger->debug("Fetching open billable transaction $transid from cstore");
529
530         $transaction = $self->simplereq(
531                 'open-ils.cstore',
532                 'open-ils.cstore.direct.money.open_billable_transaction_summary.retrieve',  $transid);
533
534         $evt = OpenILS::Event->new(
535                 'MONEY_OPEN_BILLABLE_TRANSACTION_SUMMARY_NOT_FOUND', transid => $transid ) unless $transaction;
536
537         return ($transaction, $evt);
538 }
539
540
541
542 my %buckets;
543 $buckets{'biblio'} = 'biblio_record_entry_bucket';
544 $buckets{'callnumber'} = 'call_number_bucket';
545 $buckets{'copy'} = 'copy_bucket';
546 $buckets{'user'} = 'user_bucket';
547
548 sub fetch_container {
549         my( $self, $id, $type ) = @_;
550         my( $bucket, $evt );
551
552         $logger->debug("Fetching container $id with type $type");
553
554         my $e = 'CONTAINER_CALL_NUMBER_BUCKET_NOT_FOUND';
555         $e = 'CONTAINER_BIBLIO_RECORD_ENTRY_BUCKET_NOT_FOUND' if $type eq 'biblio';
556         $e = 'CONTAINER_USER_BUCKET_NOT_FOUND' if $type eq 'user';
557         $e = 'CONTAINER_COPY_BUCKET_NOT_FOUND' if $type eq 'copy';
558
559         my $meth = $buckets{$type};
560         $bucket = $self->simplereq(
561                 'open-ils.cstore',
562                 "open-ils.cstore.direct.container.$meth.retrieve", $id );
563
564         $evt = OpenILS::Event->new(
565                 $e, container => $id, container_type => $type ) unless $bucket;
566
567         return ($bucket, $evt);
568 }
569
570
571 sub fetch_container_e {
572         my( $self, $editor, $id, $type ) = @_;
573
574         my( $bucket, $evt );
575         $bucket = $editor->retrieve_container_copy_bucket($id) if $type eq 'copy';
576         $bucket = $editor->retrieve_container_call_number_bucket($id) if $type eq 'callnumber';
577         $bucket = $editor->retrieve_container_biblio_record_entry_bucket($id) if $type eq 'biblio';
578         $bucket = $editor->retrieve_container_user_bucket($id) if $type eq 'user';
579
580         $evt = $editor->event unless $bucket;
581         return ($bucket, $evt);
582 }
583
584 sub fetch_container_item_e {
585         my( $self, $editor, $id, $type ) = @_;
586
587         my( $bucket, $evt );
588         $bucket = $editor->retrieve_container_copy_bucket_item($id) if $type eq 'copy';
589         $bucket = $editor->retrieve_container_call_number_bucket_item($id) if $type eq 'callnumber';
590         $bucket = $editor->retrieve_container_biblio_record_entry_bucket_item($id) if $type eq 'biblio';
591         $bucket = $editor->retrieve_container_user_bucket_item($id) if $type eq 'user';
592
593         $evt = $editor->event unless $bucket;
594         return ($bucket, $evt);
595 }
596
597
598
599
600
601 sub fetch_container_item {
602         my( $self, $id, $type ) = @_;
603         my( $bucket, $evt );
604
605         $logger->debug("Fetching container item $id with type $type");
606
607         my $meth = $buckets{$type} . "_item";
608
609         $bucket = $self->simplereq(
610                 'open-ils.cstore',
611                 "open-ils.cstore.direct.container.$meth.retrieve", $id );
612
613
614         my $e = 'CONTAINER_CALL_NUMBER_BUCKET_ITEM_NOT_FOUND';
615         $e = 'CONTAINER_BIBLIO_RECORD_ENTRY_BUCKET_ITEM_NOT_FOUND' if $type eq 'biblio';
616         $e = 'CONTAINER_USER_BUCKET_ITEM_NOT_FOUND' if $type eq 'user';
617         $e = 'CONTAINER_COPY_BUCKET_ITEM_NOT_FOUND' if $type eq 'copy';
618
619         $evt = OpenILS::Event->new(
620                 $e, itemid => $id, container_type => $type ) unless $bucket;
621
622         return ($bucket, $evt);
623 }
624
625
626 sub fetch_patron_standings {
627         my $self = shift;
628         $logger->debug("Fetching patron standings");    
629         return $self->simplereq(
630                 'open-ils.cstore', 
631                 'open-ils.cstore.direct.config.standing.search.atomic', { id => { '!=' => undef } });
632 }
633
634
635 sub fetch_permission_group_tree {
636         my $self = shift;
637         $logger->debug("Fetching patron profiles");     
638         return $self->simplereq(
639                 'open-ils.actor', 
640                 'open-ils.actor.groups.tree.retrieve' );
641 }
642
643
644 sub fetch_patron_circ_summary {
645         my( $self, $userid ) = @_;
646         $logger->debug("Fetching patron summary for $userid");
647         my $summary = $self->simplereq(
648                 'open-ils.storage', 
649                 "open-ils.storage.action.circulation.patron_summary", $userid );
650
651         if( $summary ) {
652                 $summary->[0] ||= 0;
653                 $summary->[1] ||= 0.0;
654                 return $summary;
655         }
656         return undef;
657 }
658
659
660 sub fetch_copy_statuses {
661         my( $self ) = @_;
662         $logger->debug("Fetching copy statuses");
663         return $self->simplereq(
664                 'open-ils.cstore', 
665                 'open-ils.cstore.direct.config.copy_status.search.atomic', { id => { '!=' => undef } });
666 }
667
668 sub fetch_copy_location {
669         my( $self, $id ) = @_;
670         my $evt;
671         my $cl = $self->cstorereq(
672                 'open-ils.cstore.direct.asset.copy_location.retrieve', $id );
673         $evt = OpenILS::Event->new('ASSET_COPY_LOCATION_NOT_FOUND') unless $cl;
674         return ($cl, $evt);
675 }
676
677 sub fetch_copy_locations {
678         my $self = shift; 
679         return $self->simplereq(
680                 'open-ils.cstore', 
681                 'open-ils.cstore.direct.asset.copy_location.search.atomic', { id => { '!=' => undef } });
682 }
683
684 sub fetch_copy_location_by_name {
685         my( $self, $name, $org ) = @_;
686         my $evt;
687         my $cl = $self->cstorereq(
688                 'open-ils.cstore.direct.asset.copy_location.search',
689                         { name => $name, owning_lib => $org } );
690         $evt = OpenILS::Event->new('ASSET_COPY_LOCATION_NOT_FOUND') unless $cl;
691         return ($cl, $evt);
692 }
693
694 sub fetch_callnumber {
695         my( $self, $id ) = @_;
696         my $evt = undef;
697
698         my $e = OpenILS::Event->new( 'ASSET_CALL_NUMBER_NOT_FOUND', id => $id );
699         return( undef, $e ) unless $id;
700
701         $logger->debug("Fetching callnumber $id");
702
703         my $cn = $self->simplereq(
704                 'open-ils.cstore',
705                 'open-ils.cstore.direct.asset.call_number.retrieve', $id );
706         $evt = $e  unless $cn;
707
708         return ( $cn, $evt );
709 }
710
711 my %ORG_CACHE; # - these rarely change, so cache them..
712 sub fetch_org_unit {
713         my( $self, $id ) = @_;
714         return undef unless $id;
715         return $id if( ref($id) eq 'Fieldmapper::actor::org_unit' );
716         return $ORG_CACHE{$id} if $ORG_CACHE{$id};
717         $logger->debug("Fetching org unit $id");
718         my $evt = undef;
719
720         my $org = $self->simplereq(
721                 'open-ils.cstore', 
722                 'open-ils.cstore.direct.actor.org_unit.retrieve', $id );
723         $evt = OpenILS::Event->new( 'ACTOR_ORG_UNIT_NOT_FOUND', id => $id ) unless $org;
724         $ORG_CACHE{$id}  = $org;
725
726         return ($org, $evt);
727 }
728
729 sub fetch_stat_cat {
730         my( $self, $type, $id ) = @_;
731         my( $cat, $evt );
732         $logger->debug("Fetching $type stat cat: $id");
733         $cat = $self->simplereq(
734                 'open-ils.cstore', 
735                 "open-ils.cstore.direct.$type.stat_cat.retrieve", $id );
736
737         my $e = 'ASSET_STAT_CAT_NOT_FOUND';
738         $e = 'ACTOR_STAT_CAT_NOT_FOUND' if $type eq 'actor';
739
740         $evt = OpenILS::Event->new( $e, id => $id ) unless $cat;
741         return ( $cat, $evt );
742 }
743
744 sub fetch_stat_cat_entry {
745         my( $self, $type, $id ) = @_;
746         my( $entry, $evt );
747         $logger->debug("Fetching $type stat cat entry: $id");
748         $entry = $self->simplereq(
749                 'open-ils.cstore', 
750                 "open-ils.cstore.direct.$type.stat_cat_entry.retrieve", $id );
751
752         my $e = 'ASSET_STAT_CAT_ENTRY_NOT_FOUND';
753         $e = 'ACTOR_STAT_CAT_ENTRY_NOT_FOUND' if $type eq 'actor';
754
755         $evt = OpenILS::Event->new( $e, id => $id ) unless $entry;
756         return ( $entry, $evt );
757 }
758
759
760 sub find_org {
761         my( $self, $org_tree, $orgid )  = @_;
762     return undef unless $org_tree and defined $orgid;
763         return $org_tree if ( $org_tree->id eq $orgid );
764         return undef unless ref($org_tree->children);
765         for my $c (@{$org_tree->children}) {
766                 my $o = $self->find_org($c, $orgid);
767                 return $o if $o;
768         }
769         return undef;
770 }
771
772 sub fetch_non_cat_type_by_name_and_org {
773         my( $self, $name, $orgId ) = @_;
774         $logger->debug("Fetching non cat type $name at org $orgId");
775         my $types = $self->simplereq(
776                 'open-ils.cstore',
777                 'open-ils.cstore.direct.config.non_cataloged_type.search.atomic',
778                 { name => $name, owning_lib => $orgId } );
779         return ($types->[0], undef) if($types and @$types);
780         return (undef, OpenILS::Event->new('CONFIG_NON_CATALOGED_TYPE_NOT_FOUND') );
781 }
782
783 sub fetch_non_cat_type {
784         my( $self, $id ) = @_;
785         $logger->debug("Fetching non cat type $id");
786         my( $type, $evt );
787         $type = $self->simplereq(
788                 'open-ils.cstore', 
789                 'open-ils.cstore.direct.config.non_cataloged_type.retrieve', $id );
790         $evt = OpenILS::Event->new('CONFIG_NON_CATALOGED_TYPE_NOT_FOUND') unless $type;
791         return ($type, $evt);
792 }
793
794 sub DB_UPDATE_FAILED { 
795         my( $self, $payload ) = @_;
796         return OpenILS::Event->new('DATABASE_UPDATE_FAILED', 
797                 payload => ($payload) ? $payload : undef ); 
798 }
799
800 sub fetch_booking_reservation {
801         my( $self, $id ) = @_;
802         my( $res, $evt );
803
804         $res = $self->simplereq(
805                 'open-ils.cstore', 
806                 'open-ils.cstore.direct.booking.reservation.retrieve', $id
807         );
808
809         # simplereq doesn't know how to flesh so ...
810         if ($res) {
811                 $res->usr(
812                         $self->simplereq(
813                                 'open-ils.cstore', 
814                                 'open-ils.cstore.direct.actor.user.retrieve', $res->usr
815                         )
816                 );
817
818                 $res->target_resource_type(
819                         $self->simplereq(
820                                 'open-ils.cstore', 
821                                 'open-ils.cstore.direct.booking.resource_type.retrieve', $res->target_resource_type
822                         )
823                 );
824
825                 if ($res->current_resource) {
826                         $res->current_resource(
827                                 $self->simplereq(
828                                         'open-ils.cstore', 
829                                         'open-ils.cstore.direct.booking.resource.retrieve', $res->current_resource
830                                 )
831                         );
832
833                         if ($self->is_true( $res->target_resource_type->catalog_item )) {
834                                 $res->current_resource->catalog_item( $self->fetch_copy_by_barcode( $res->current_resource->barcode ) );
835                         }
836                 }
837
838                 if ($res->target_resource) {
839                         $res->target_resource(
840                                 $self->simplereq(
841                                         'open-ils.cstore', 
842                                         'open-ils.cstore.direct.booking.resource.retrieve', $res->target_resource
843                                 )
844                         );
845
846                         if ($self->is_true( $res->target_resource_type->catalog_item )) {
847                                 $res->target_resource->catalog_item( $self->fetch_copy_by_barcode( $res->target_resource->barcode ) );
848                         }
849                 }
850
851         } else {
852                 $evt = OpenILS::Event->new('RESERVATION_NOT_FOUND');
853         }
854
855         return ($res, $evt);
856 }
857
858 sub fetch_circ_duration_by_name {
859         my( $self, $name ) = @_;
860         my( $dur, $evt );
861         $dur = $self->simplereq(
862                 'open-ils.cstore', 
863                 'open-ils.cstore.direct.config.rules.circ_duration.search.atomic', { name => $name } );
864         $dur = $dur->[0];
865         $evt = OpenILS::Event->new('CONFIG_RULES_CIRC_DURATION_NOT_FOUND') unless $dur;
866         return ($dur, $evt);
867 }
868
869 sub fetch_recurring_fine_by_name {
870         my( $self, $name ) = @_;
871         my( $obj, $evt );
872         $obj = $self->simplereq(
873                 'open-ils.cstore', 
874                 'open-ils.cstore.direct.config.rules.recurring_fine.search.atomic', { name => $name } );
875         $obj = $obj->[0];
876         $evt = OpenILS::Event->new('CONFIG_RULES_RECURRING_FINE_NOT_FOUND') unless $obj;
877         return ($obj, $evt);
878 }
879
880 sub fetch_max_fine_by_name {
881         my( $self, $name ) = @_;
882         my( $obj, $evt );
883         $obj = $self->simplereq(
884                 'open-ils.cstore', 
885                 'open-ils.cstore.direct.config.rules.max_fine.search.atomic', { name => $name } );
886         $obj = $obj->[0];
887         $evt = OpenILS::Event->new('CONFIG_RULES_MAX_FINE_NOT_FOUND') unless $obj;
888         return ($obj, $evt);
889 }
890
891 sub storagereq {
892         my( $self, $method, @params ) = @_;
893         return $self->simplereq(
894                 'open-ils.storage', $method, @params );
895 }
896
897 sub storagereq_xact {
898         my($self, $method, @params) = @_;
899         my $ses = $self->start_db_session();
900         my $val = $ses->request($method, @params)->gather(1);
901         $self->rollback_db_session($ses);
902     return $val;
903 }
904
905 sub cstorereq {
906         my( $self, $method, @params ) = @_;
907         return $self->simplereq(
908                 'open-ils.cstore', $method, @params );
909 }
910
911 sub event_equals {
912         my( $self, $e, $name ) =  @_;
913         if( $e and ref($e) eq 'HASH' and 
914                 defined($e->{textcode}) and $e->{textcode} eq $name ) {
915                 return 1 ;
916         }
917         return 0;
918 }
919
920 sub logmark {
921         my( undef, $f, $l ) = caller(0);
922         my( undef, undef, undef, $s ) = caller(1);
923         $s =~ s/.*:://g;
924         $f =~ s/.*\///g;
925         $logger->debug("LOGMARK: $f:$l:$s");
926 }
927
928 # takes a copy id 
929 sub fetch_open_circulation {
930         my( $self, $cid ) = @_;
931         $self->logmark;
932
933         my $e = OpenILS::Utils::CStoreEditor->new;
934     my $circ = $e->search_action_circulation({
935         target_copy => $cid, 
936         stop_fines_time => undef, 
937         checkin_time => undef
938     })->[0];
939     
940     return ($circ, $e->event);
941 }
942
943 my $copy_statuses;
944 sub copy_status_from_name {
945         my( $self, $name ) = @_;
946         $copy_statuses = $self->fetch_copy_statuses unless $copy_statuses;
947         for my $status (@$copy_statuses) { 
948                 return $status if( $status->name =~ /$name/i );
949         }
950         return undef;
951 }
952
953 sub copy_status_to_name {
954         my( $self, $sid ) = @_;
955         $copy_statuses = $self->fetch_copy_statuses unless $copy_statuses;
956         for my $status (@$copy_statuses) { 
957                 return $status->name if( $status->id == $sid );
958         }
959         return undef;
960 }
961
962
963 sub copy_status {
964         my( $self, $arg ) = @_;
965         return $arg if ref $arg;
966         $copy_statuses = $self->fetch_copy_statuses unless $copy_statuses;
967         my ($stat) = grep { $_->id == $arg } @$copy_statuses;
968         return $stat;
969 }
970
971 sub fetch_open_transit_by_copy {
972         my( $self, $copyid ) = @_;
973         my($transit, $evt);
974         $transit = $self->cstorereq(
975                 'open-ils.cstore.direct.action.transit_copy.search',
976                 { target_copy => $copyid, dest_recv_time => undef });
977         $evt = OpenILS::Event->new('ACTION_TRANSIT_COPY_NOT_FOUND') unless $transit;
978         return ($transit, $evt);
979 }
980
981 sub unflesh_copy {
982         my( $self, $copy ) = @_;
983         return undef unless $copy;
984         $copy->status( $copy->status->id ) if ref($copy->status);
985         $copy->location( $copy->location->id ) if ref($copy->location);
986         $copy->circ_lib( $copy->circ_lib->id ) if ref($copy->circ_lib);
987         return $copy;
988 }
989
990 sub unflesh_reservation {
991         my( $self, $reservation ) = @_;
992         return undef unless $reservation;
993         $reservation->usr( $reservation->usr->id ) if ref($reservation->usr);
994         $reservation->target_resource_type( $reservation->target_resource_type->id ) if ref($reservation->target_resource_type);
995         $reservation->target_resource( $reservation->target_resource->id ) if ref($reservation->target_resource);
996         $reservation->current_resource( $reservation->current_resource->id ) if ref($reservation->current_resource);
997         return $reservation;
998 }
999
1000 # un-fleshes a copy and updates it in the DB
1001 # returns a DB_UPDATE_FAILED event on error
1002 # returns undef on success
1003 sub update_copy {
1004         my( $self, %params ) = @_;
1005
1006         my $copy                = $params{copy} || die "update_copy(): copy required";
1007         my $editor      = $params{editor} || die "update_copy(): copy editor required";
1008         my $session = $params{session};
1009
1010         $logger->debug("Updating copy in the database: " . $copy->id);
1011
1012         $self->unflesh_copy($copy);
1013         $copy->editor( $editor );
1014         $copy->edit_date( 'now' );
1015
1016         my $s;
1017         my $meth = 'open-ils.storage.direct.asset.copy.update';
1018
1019         $s = $session->request( $meth, $copy )->gather(1) if $session;
1020         $s = $self->storagereq( $meth, $copy ) unless $session;
1021
1022         $logger->debug("Update of copy ".$copy->id." returned: $s");
1023
1024         return $self->DB_UPDATE_FAILED($copy) unless $s;
1025         return undef;
1026 }
1027
1028 sub update_reservation {
1029         my( $self, %params ) = @_;
1030
1031         my $reservation = $params{reservation}  || die "update_reservation(): reservation required";
1032         my $editor              = $params{editor} || die "update_reservation(): copy editor required";
1033         my $session             = $params{session};
1034
1035         $logger->debug("Updating copy in the database: " . $reservation->id);
1036
1037         $self->unflesh_reservation($reservation);
1038
1039         my $s;
1040         my $meth = 'open-ils.cstore.direct.booking.reservation.update';
1041
1042         $s = $session->request( $meth, $reservation )->gather(1) if $session;
1043         $s = $self->cstorereq( $meth, $reservation ) unless $session;
1044
1045         $logger->debug("Update of copy ".$reservation->id." returned: $s");
1046
1047         return $self->DB_UPDATE_FAILED($reservation) unless $s;
1048         return undef;
1049 }
1050
1051 sub fetch_billable_xact {
1052         my( $self, $id ) = @_;
1053         my($xact, $evt);
1054         $logger->debug("Fetching billable transaction %id");
1055         $xact = $self->cstorereq(
1056                 'open-ils.cstore.direct.money.billable_transaction.retrieve', $id );
1057         $evt = OpenILS::Event->new('MONEY_BILLABLE_TRANSACTION_NOT_FOUND') unless $xact;
1058         return ($xact, $evt);
1059 }
1060
1061 sub fetch_billable_xact_summary {
1062         my( $self, $id ) = @_;
1063         my($xact, $evt);
1064         $logger->debug("Fetching billable transaction summary %id");
1065         $xact = $self->cstorereq(
1066                 'open-ils.cstore.direct.money.billable_transaction_summary.retrieve', $id );
1067         $evt = OpenILS::Event->new('MONEY_BILLABLE_TRANSACTION_NOT_FOUND') unless $xact;
1068         return ($xact, $evt);
1069 }
1070
1071 sub fetch_fleshed_copy {
1072         my( $self, $id ) = @_;
1073         my( $copy, $evt );
1074         $logger->info("Fetching fleshed copy $id");
1075         $copy = $self->cstorereq(
1076                 "open-ils.cstore.direct.asset.copy.retrieve", $id,
1077                 { flesh => 1,
1078                   flesh_fields => { acp => [ qw/ circ_lib location status stat_cat_entries / ] }
1079                 }
1080         );
1081         $evt = OpenILS::Event->new('ASSET_COPY_NOT_FOUND', id => $id) unless $copy;
1082         return ($copy, $evt);
1083 }
1084
1085
1086 # returns the org that owns the callnumber that the copy
1087 # is attached to
1088 sub fetch_copy_owner {
1089         my( $self, $copyid ) = @_;
1090         my( $copy, $cn, $evt );
1091         $logger->debug("Fetching copy owner $copyid");
1092         ($copy, $evt) = $self->fetch_copy($copyid);
1093         return (undef,$evt) if $evt;
1094         ($cn, $evt) = $self->fetch_callnumber($copy->call_number);
1095         return (undef,$evt) if $evt;
1096         return ($cn->owning_lib);
1097 }
1098
1099 sub fetch_copy_note {
1100         my( $self, $id ) = @_;
1101         my( $note, $evt );
1102         $logger->debug("Fetching copy note $id");
1103         $note = $self->cstorereq(
1104                 'open-ils.cstore.direct.asset.copy_note.retrieve', $id );
1105         $evt = OpenILS::Event->new('ASSET_COPY_NOTE_NOT_FOUND', id => $id ) unless $note;
1106         return ($note, $evt);
1107 }
1108
1109 sub fetch_call_numbers_by_title {
1110         my( $self, $titleid ) = @_;
1111         $logger->info("Fetching call numbers by title $titleid");
1112         return $self->cstorereq(
1113                 'open-ils.cstore.direct.asset.call_number.search.atomic', 
1114                 { record => $titleid, deleted => 'f' });
1115                 #'open-ils.storage.direct.asset.call_number.search.record.atomic', $titleid);
1116 }
1117
1118 sub fetch_copies_by_call_number {
1119         my( $self, $cnid ) = @_;
1120         $logger->info("Fetching copies by call number $cnid");
1121         return $self->cstorereq(
1122                 'open-ils.cstore.direct.asset.copy.search.atomic', { call_number => $cnid, deleted => 'f' } );
1123                 #'open-ils.storage.direct.asset.copy.search.call_number.atomic', $cnid );
1124 }
1125
1126 sub fetch_user_by_barcode {
1127         my( $self, $bc ) = @_;
1128         my $cardid = $self->cstorereq(
1129                 'open-ils.cstore.direct.actor.card.id_list', { barcode => $bc } );
1130         return (undef, OpenILS::Event->new('ACTOR_CARD_NOT_FOUND', barcode => $bc)) unless $cardid;
1131         my $user = $self->cstorereq(
1132                 'open-ils.cstore.direct.actor.user.search', { card => $cardid } );
1133         return (undef, OpenILS::Event->new('ACTOR_USER_NOT_FOUND', card => $cardid)) unless $user;
1134         return ($user);
1135         
1136 }
1137
1138 sub fetch_bill {
1139         my( $self, $billid ) = @_;
1140         $logger->debug("Fetching billing $billid");
1141         my $bill = $self->cstorereq(
1142                 'open-ils.cstore.direct.money.billing.retrieve', $billid );
1143         my $evt = OpenILS::Event->new('MONEY_BILLING_NOT_FOUND') unless $bill;
1144         return($bill, $evt);
1145 }
1146
1147 my $ORG_TREE;
1148 sub fetch_org_tree {
1149         my $self = shift;
1150         return $ORG_TREE if $ORG_TREE;
1151         return $ORG_TREE = OpenILS::Utils::CStoreEditor->new->search_actor_org_unit( 
1152                 [
1153                         {"parent_ou" => undef },
1154                         {
1155                                 flesh                           => -1,
1156                                 flesh_fields    => { aou =>  ['children'] },
1157                                 order_by       => { aou => 'name'}
1158                         }
1159                 ]
1160         )->[0];
1161 }
1162
1163 sub walk_org_tree {
1164         my( $self, $node, $callback ) = @_;
1165         return unless $node;
1166         $callback->($node);
1167         if( $node->children ) {
1168                 $self->walk_org_tree($_, $callback) for @{$node->children};
1169         }
1170 }
1171
1172 sub is_true {
1173         my( $self, $item ) = @_;
1174         return 1 if $item and $item !~ /^f$/i;
1175         return 0;
1176 }
1177
1178
1179 # This logic now lives in storage
1180 sub __patron_money_owed {
1181         my( $self, $patronid ) = @_;
1182         my $ses = OpenSRF::AppSession->create('open-ils.storage');
1183         my $req = $ses->request(
1184                 'open-ils.storage.money.billable_transaction.summary.search',
1185                 { usr => $patronid, xact_finish => undef } );
1186
1187         my $total = 0;
1188         my $data;
1189         while( $data = $req->recv ) {
1190                 $data = $data->content;
1191                 $total += $data->balance_owed;
1192         }
1193         return $total;
1194 }
1195
1196 sub patron_money_owed {
1197         my( $self, $userid ) = @_;
1198         my $ses = $self->start_db_session();
1199         my $val = $ses->request(
1200                 'open-ils.storage.actor.user.total_owed', $userid)->gather(1);
1201         $self->rollback_db_session($ses);
1202         return $val;
1203 }
1204
1205 sub patron_total_items_out {
1206         my( $self, $userid ) = @_;
1207         my $ses = $self->start_db_session();
1208         my $val = $ses->request(
1209                 'open-ils.storage.actor.user.total_out', $userid)->gather(1);
1210         $self->rollback_db_session($ses);
1211         return $val;
1212 }
1213
1214
1215
1216
1217 #---------------------------------------------------------------------
1218 # Returns  ($summary, $event) 
1219 #---------------------------------------------------------------------
1220 sub fetch_mbts {
1221         my $self = shift;
1222         my $id  = shift;
1223         my $e = shift || OpenILS::Utils::CStoreEditor->new;
1224         $id = $id->id if ref($id);
1225     
1226     my $xact = $e->retrieve_money_billable_transaction_summary($id)
1227             or return (undef, $e->event);
1228
1229     return ($xact);
1230 }
1231
1232
1233 #---------------------------------------------------------------------
1234 # Given a list of money.billable_transaction objects, this creates
1235 # transaction summary objects for each
1236 #--------------------------------------------------------------------
1237 sub make_mbts {
1238         my $self = shift;
1239     my $e = shift;
1240         my @xacts = @_;
1241         return () if (!@xacts);
1242     return @{$e->search_money_billable_transaction_summary({id => [ map { $_->id } @xacts ]})};
1243 }
1244                 
1245                 
1246 sub ou_ancestor_setting_value {
1247     my($self, $org_id, $name, $e) = @_;
1248     $e = $e || OpenILS::Utils::CStoreEditor->new;
1249     my $set = $self->ou_ancestor_setting($org_id, $name, $e);
1250     return $set->{value} if $set;
1251     return undef;
1252 }
1253
1254
1255 # If an authentication token is provided AND this org unit setting has a
1256 # view_perm, then make sure the user referenced by the auth token has
1257 # that permission.  This means that if you call this method without an
1258 # authtoken param, you can get whatever org unit setting values you want.
1259 # API users beware.
1260 #
1261 # NOTE: If you supply an editor ($e) arg AND an auth token arg, the editor's
1262 # authtoken is checked, but the $auth arg is NOT checked.  To say that another
1263 # way, be sure NOT to pass an editor argument if you want your token checked.
1264 # Otherwise the auth arg is just a flag saying "check the editor".  
1265
1266 sub ou_ancestor_setting {
1267     my( $self, $orgid, $name, $e, $auth ) = @_;
1268     $e = $e || OpenILS::Utils::CStoreEditor->new(
1269         (defined $auth) ? (authtoken => $auth) : ()
1270     );
1271     my $coust = $e->retrieve_config_org_unit_setting_type([
1272         $name, {flesh => 1, flesh_fields => {coust => ['view_perm']}}
1273     ]);
1274
1275     if ($auth && $coust && $coust->view_perm) {
1276         # And you can't have permission if you don't have a valid session.
1277         return undef if not $e->checkauth;
1278         # And now that we know you MIGHT have permission, we check it.
1279         return undef if not $e->allowed($coust->view_perm->code, $orgid);
1280     }
1281
1282     my $query = {from => ['actor.org_unit_ancestor_setting', $name, $orgid]};
1283     my $setting = $e->json_query($query)->[0];
1284     return undef unless $setting;
1285     return {org => $setting->{org_unit}, value => OpenSRF::Utils::JSON->JSON2perl($setting->{value})};
1286 }       
1287                 
1288
1289 # returns the ISO8601 string representation of the requested epoch in GMT
1290 sub epoch2ISO8601 {
1291     my( $self, $epoch ) = @_;
1292     my ($sec,$min,$hour,$mday,$mon,$year) = gmtime($epoch);
1293     $year += 1900; $mon += 1;
1294     my $date = sprintf(
1295         '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1296         $year, $mon, $mday, $hour, $min, $sec);
1297     return $date;
1298 }
1299                         
1300 sub find_highest_perm_org {
1301         my ( $self, $perm, $userid, $start_org, $org_tree ) = @_;
1302         my $org = $self->find_org($org_tree, $start_org );
1303
1304         my $lastid = -1;
1305         while( $org ) {
1306                 last if ($self->check_perms( $userid, $org->id, $perm )); # perm failed
1307                 $lastid = $org->id;
1308                 $org = $self->find_org( $org_tree, $org->parent_ou() );
1309         }
1310
1311         return $lastid;
1312 }
1313
1314
1315 # returns the org_unit ID's 
1316 sub user_has_work_perm_at {
1317     my($self, $e, $perm, $options, $user_id) = @_;
1318     $options ||= {};
1319     $user_id = (defined $user_id) ? $user_id : $e->requestor->id;
1320
1321     my $func = 'permission.usr_has_perm_at';
1322     $func = $func.'_all' if $$options{descendants};
1323
1324     my $orgs = $e->json_query({from => [$func, $user_id, $perm]});
1325     $orgs = [map { $_->{ (keys %$_)[0] } } @$orgs];
1326
1327     return $orgs unless $$options{objects};
1328
1329     return $e->search_actor_org_unit({id => $orgs});
1330 }
1331
1332 sub get_user_work_ou_ids {
1333     my($self, $e, $userid) = @_;
1334     my $work_orgs = $e->json_query({
1335         select => {puwoum => ['work_ou']},
1336         from => 'puwoum',
1337         where => {usr => $e->requestor->id}});
1338
1339     return [] unless @$work_orgs;
1340     my @work_orgs;
1341     push(@work_orgs, $_->{work_ou}) for @$work_orgs;
1342
1343     return \@work_orgs;
1344 }
1345
1346
1347 my $org_types;
1348 sub get_org_types {
1349         my($self, $client) = @_;
1350         return $org_types if $org_types;
1351         return $org_types = OpenILS::Utils::CStoreEditor->new->retrieve_all_actor_org_unit_type();
1352 }
1353
1354 sub get_org_tree {
1355         my $self = shift;
1356         my $locale = shift || '';
1357         my $cache = OpenSRF::Utils::Cache->new("global", 0);
1358         my $tree = $cache->get_cache("orgtree.$locale");
1359         return $tree if $tree;
1360
1361         my $ses = OpenILS::Utils::CStoreEditor->new;
1362         $ses->session->session_locale($locale);
1363         $tree = $ses->search_actor_org_unit( 
1364                 [
1365                         {"parent_ou" => undef },
1366                         {
1367                                 flesh                           => -1,
1368                                 flesh_fields    => { aou =>  ['children'] },
1369                                 order_by                        => { aou => 'name'}
1370                         }
1371                 ]
1372         )->[0];
1373
1374         $cache->put_cache("orgtree.$locale", $tree);
1375         return $tree;
1376 }
1377
1378 sub get_org_descendants {
1379         my($self, $org_id, $depth) = @_;
1380
1381         my $select = {
1382                 transform => 'actor.org_unit_descendants',
1383                 column => 'id',
1384                 result_field => 'id',
1385         };
1386         $select->{params} = [$depth] if defined $depth;
1387
1388         my $org_list = OpenILS::Utils::CStoreEditor->new->json_query({
1389                 select => {aou => [$select]},
1390         from => 'aou',
1391                 where => {id => $org_id}
1392         });
1393         my @orgs;
1394         push(@orgs, $_->{id}) for @$org_list;
1395         return \@orgs;
1396 }
1397
1398 sub get_org_ancestors {
1399         my($self, $org_id) = @_;
1400
1401         my $org_list = OpenILS::Utils::CStoreEditor->new->json_query({
1402                 select => {
1403                         aou => [{
1404                                 transform => 'actor.org_unit_ancestors',
1405                                 column => 'id',
1406                                 result_field => 'id',
1407                                 params => []
1408                         }],
1409                 },
1410                 from => 'aou',
1411                 where => {id => $org_id}
1412         });
1413
1414         my @orgs;
1415         push(@orgs, $_->{id}) for @$org_list;
1416         return \@orgs;
1417 }
1418
1419 sub get_org_full_path {
1420         my($self, $org_id, $depth) = @_;
1421
1422     my $query = {
1423         select => {
1424                         aou => [{
1425                                 transform => 'actor.org_unit_full_path',
1426                                 column => 'id',
1427                                 result_field => 'id',
1428                         }],
1429                 },
1430                 from => 'aou',
1431                 where => {id => $org_id}
1432         };
1433
1434     $query->{select}->{aou}->[0]->{params} = [$depth] if defined $depth;
1435         my $org_list = OpenILS::Utils::CStoreEditor->new->json_query($query);
1436     return [ map {$_->{id}} @$org_list ];
1437 }
1438
1439 # returns the ID of the org unit ancestor at the specified depth
1440 sub org_unit_ancestor_at_depth {
1441     my($class, $org_id, $depth) = @_;
1442     my $resp = OpenILS::Utils::CStoreEditor->new->json_query(
1443         {from => ['actor.org_unit_ancestor_at_depth', $org_id, $depth]})->[0];
1444     return ($resp) ? $resp->{id} : undef;
1445 }
1446
1447 # returns the user's configured locale as a string.  Defaults to en-US if none is configured.
1448 sub get_user_locale {
1449         my($self, $user_id, $e) = @_;
1450         $e ||= OpenILS::Utils::CStoreEditor->new;
1451
1452         # first, see if the user has an explicit locale set
1453         my $setting = $e->search_actor_user_setting(
1454                 {usr => $user_id, name => 'global.locale'})->[0];
1455         return OpenSRF::Utils::JSON->JSON2perl($setting->value) if $setting;
1456
1457         my $user = $e->retrieve_actor_user($user_id) or return $e->event;
1458         return $self->get_org_locale($user->home_ou, $e);
1459 }
1460
1461 # returns org locale setting
1462 sub get_org_locale {
1463         my($self, $org_id, $e) = @_;
1464         $e ||= OpenILS::Utils::CStoreEditor->new;
1465
1466         my $locale;
1467         if(defined $org_id) {
1468                 $locale = $self->ou_ancestor_setting_value($org_id, 'global.default_locale', $e);
1469                 return $locale if $locale;
1470         }
1471
1472         # system-wide default
1473         my $sclient = OpenSRF::Utils::SettingsClient->new;
1474         $locale = $sclient->config_value('default_locale');
1475     return $locale if $locale;
1476
1477         # if nothing else, fallback to locale=cowboy
1478         return 'en-US';
1479 }
1480
1481
1482 # xml-escape non-ascii characters
1483 sub entityize { 
1484     my($self, $string, $form) = @_;
1485         $form ||= "";
1486
1487         # If we're going to convert non-ASCII characters to XML entities,
1488         # we had better be dealing with a UTF8 string to begin with
1489         $string = decode_utf8($string);
1490
1491         if ($form eq 'D') {
1492                 $string = NFD($string);
1493         } else {
1494                 $string = NFC($string);
1495         }
1496
1497         # Convert raw ampersands to entities
1498         $string =~ s/&(?!\S+;)/&amp;/gso;
1499
1500         # Convert Unicode characters to entities
1501         $string =~ s/([\x{0080}-\x{fffd}])/sprintf('&#x%X;',ord($1))/sgoe;
1502
1503         return $string;
1504 }
1505
1506 # x0000-x0008 isn't legal in XML documents
1507 # XXX Perhaps this should just go into our standard entityize method
1508 sub strip_ctrl_chars {
1509         my ($self, $string) = @_;
1510
1511         $string =~ s/([\x{0000}-\x{0008}])//sgoe; 
1512         return $string;
1513 }
1514
1515 sub get_copy_price {
1516         my($self, $e, $copy, $volume) = @_;
1517
1518         $copy->price(0) if $copy->price and $copy->price < 0;
1519
1520         return $copy->price if $copy->price and $copy->price > 0;
1521
1522
1523         my $owner;
1524         if(ref $volume) {
1525                 if($volume->id == OILS_PRECAT_CALL_NUMBER) {
1526                         $owner = $copy->circ_lib;
1527                 } else {
1528                         $owner = $volume->owning_lib;
1529                 }
1530         } else {
1531                 if($copy->call_number == OILS_PRECAT_CALL_NUMBER) {
1532                         $owner = $copy->circ_lib;
1533                 } else {
1534                         $owner = $e->retrieve_asset_call_number($copy->call_number)->owning_lib;
1535                 }
1536         }
1537
1538         my $default_price = $self->ou_ancestor_setting_value(
1539                 $owner, OILS_SETTING_DEF_ITEM_PRICE, $e) || 0;
1540
1541         return $default_price unless defined $copy->price;
1542
1543         # price is 0.  Use the default?
1544     my $charge_on_0 = $self->ou_ancestor_setting_value(
1545         $owner, OILS_SETTING_CHARGE_LOST_ON_ZERO, $e) || 0;
1546
1547         return $default_price if $charge_on_0;
1548         return 0;
1549 }
1550
1551 # given a transaction ID, this returns the context org_unit for the transaction
1552 sub xact_org {
1553     my($self, $xact_id, $e) = @_;
1554     $e ||= OpenILS::Utils::CStoreEditor->new;
1555     
1556     my $loc = $e->json_query({
1557         "select" => {circ => ["circ_lib"]},
1558         from     => "circ",
1559         "where"  => {id => $xact_id},
1560     });
1561
1562     return $loc->[0]->{circ_lib} if @$loc;
1563
1564     $loc = $e->json_query({
1565         "select" => {mg => ["billing_location"]},
1566         from     => "mg",
1567         "where"  => {id => $xact_id},
1568     });
1569
1570     return $loc->[0]->{billing_location};
1571 }
1572
1573
1574 sub find_event_def_by_hook {
1575     my($self, $hook, $context_org, $e) = @_;
1576
1577     $e ||= OpenILS::Utils::CStoreEditor->new;
1578
1579     my $orgs = $self->get_org_ancestors($context_org);
1580
1581     # search from the context org up
1582     for my $org_id (reverse @$orgs) {
1583
1584         my $def = $e->search_action_trigger_event_definition(
1585             {hook => $hook, owner => $org_id})->[0];
1586
1587         return $def if $def;
1588     }
1589
1590     return undef;
1591 }
1592
1593
1594
1595 # If an event_def ID is not provided, use the hook and context org to find the 
1596 # most appropriate event.  create the event, fire it, then return the resulting
1597 # event with fleshed template_output and error_output
1598 sub fire_object_event {
1599     my($self, $event_def, $hook, $object, $context_org, $granularity, $user_data) = @_;
1600
1601     my $e = OpenILS::Utils::CStoreEditor->new;
1602     my $def;
1603
1604     my $auto_method = "open-ils.trigger.event.autocreate.by_definition";
1605
1606     if($event_def) {
1607         $def = $e->retrieve_action_trigger_event_definition($event_def)
1608             or return $e->event;
1609
1610         $auto_method .= '.include_inactive';
1611
1612     } else {
1613
1614         # find the most appropriate event def depending on context org
1615         $def = $self->find_event_def_by_hook($hook, $context_org, $e) 
1616             or return $e->event;
1617     }
1618
1619     if($def->group_field) {
1620         # we have a list of objects
1621         $object = [$object] unless ref $object eq 'ARRAY';
1622
1623         my @event_ids;
1624         $user_data ||= [];
1625         for my $i (0..$#$object) {
1626             my $obj = $$object[$i];
1627             my $udata = $$user_data[$i];
1628             my $event_id = $self->simplereq(
1629                 'open-ils.trigger', $auto_method, $def->id, $obj, $context_org, $udata);
1630             push(@event_ids, $event_id);
1631         }
1632
1633         $logger->info("EVENTS = " . OpenSRF::Utils::JSON->perl2JSON(\@event_ids));
1634
1635         my $resp = $self->simplereq(
1636             'open-ils.trigger', 
1637             'open-ils.trigger.event_group.fire',
1638             \@event_ids);
1639
1640         return undef unless $resp and $resp->{events} and @{$resp->{events}};
1641
1642         return $e->retrieve_action_trigger_event([
1643             $resp->{events}->[0]->id,
1644             {flesh => 1, flesh_fields => {atev => ['template_output', 'error_output']}}
1645         ]);
1646
1647     } else {
1648
1649         $object = $$object[0] if ref $object eq 'ARRAY';
1650
1651         my $event_id = $self->simplereq(
1652             'open-ils.trigger', $auto_method, $def->id, $object, $context_org, $user_data);
1653
1654         my $resp = $self->simplereq(
1655             'open-ils.trigger', 
1656             'open-ils.trigger.event.fire', 
1657             $event_id);
1658
1659         return undef unless $resp and $resp->{event};
1660
1661         return $e->retrieve_action_trigger_event([
1662             $resp->{event}->id,
1663             {flesh => 1, flesh_fields => {atev => ['template_output', 'error_output']}}
1664         ]);
1665     }
1666 }
1667
1668
1669 sub create_events_for_hook {
1670     my($self, $hook, $obj, $org_id, $wait) = @_;
1671     my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1672     my $req = $ses->request('open-ils.trigger.event.autocreate', $hook, $obj, $org_id);
1673     return undef unless $wait;
1674     my $resp = $req->recv;
1675     return $resp->content if $resp;
1676 }
1677
1678 sub create_uuid_string {
1679     return create_UUID_as_string();
1680 }
1681
1682 sub create_circ_chain_summary {
1683     my($class, $e, $circ_id) = @_;
1684     my $sum = $e->json_query({from => ['action.summarize_circ_chain', $circ_id]})->[0];
1685     return undef unless $sum;
1686     my $obj = Fieldmapper::action::circ_chain_summary->new;
1687     $obj->$_($sum->{$_}) for keys %$sum;
1688     return $obj;
1689 }
1690
1691 1;
1692