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