]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/OpenILS/Application/AppUtils.pm
moved old-fashioned perm check to json_query for speed
[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 qw/:funcs/;
13 use OpenILS::Const qw/:const/;
14
15 # ---------------------------------------------------------------------------
16 # Pile of utilty methods used accross applications.
17 # ---------------------------------------------------------------------------
18 my $cache_client = "OpenSRF::Utils::Cache";
19
20
21 # ---------------------------------------------------------------------------
22 # on sucess, returns the created session, on failure throws ERROR exception
23 # ---------------------------------------------------------------------------
24 sub start_db_session {
25
26         my $self = shift;
27         my $session = OpenSRF::AppSession->connect( "open-ils.storage" );
28         my $trans_req = $session->request( "open-ils.storage.transaction.begin" );
29
30         my $trans_resp = $trans_req->recv();
31         if(ref($trans_resp) and UNIVERSAL::isa($trans_resp,"Error")) { throw $trans_resp; }
32         if( ! $trans_resp->content() ) {
33                 throw OpenSRF::ERROR 
34                         ("Unable to Begin Transaction with database" );
35         }
36         $trans_req->finish();
37
38         $logger->debug("Setting global storage session to ".
39                 "session: " . $session->session_id . " : " . $session->app );
40
41         return $session;
42 }
43
44 my $PERM_QUERY = {
45     select => {
46         au => [ {
47             transform => 'permission.usr_has_perm',
48             alias => 'has_perm',
49             column => 'id',
50             params => []
51         } ]
52     },
53     from => 'au',
54     where => {},
55 };
56
57
58 # returns undef if user has all of the perms provided
59 # returns the first failed perm on failure
60 sub check_user_perms {
61         my($self, $user_id, $org_id, @perm_types ) = @_;
62         $logger->debug("Checking perms with user : $user_id , org: $org_id, @perm_types");
63
64         for my $type (@perm_types) {
65             $PERM_QUERY->{select}->{au}->[0]->{params} = [$type, $org_id];
66                 $PERM_QUERY->{where}->{id} = $user_id;
67                 return $type unless $self->is_true(new_editor()->json_query($PERM_QUERY)->[0]->{has_perm});
68         }
69         return undef;
70 }
71
72 # checks the list of user perms.  The first one that fails returns a new
73 sub check_perms {
74         my( $self, $user_id, $org_id, @perm_types ) = @_;
75         my $t = $self->check_user_perms( $user_id, $org_id, @perm_types );
76         return OpenILS::Event->new('PERM_FAILURE', ilsperm => $t, ilspermloc => $org_id ) if $t;
77         return undef;
78 }
79
80
81
82 # ---------------------------------------------------------------------------
83 # commits and destroys the session
84 # ---------------------------------------------------------------------------
85 sub commit_db_session {
86         my( $self, $session ) = @_;
87
88         my $req = $session->request( "open-ils.storage.transaction.commit" );
89         my $resp = $req->recv();
90
91         if(!$resp) {
92                 throw OpenSRF::EX::ERROR ("Unable to commit db session");
93         }
94
95         if(UNIVERSAL::isa($resp,"Error")) { 
96                 throw $resp ($resp->stringify); 
97         }
98
99         if(!$resp->content) {
100                 throw OpenSRF::EX::ERROR ("Unable to commit db session");
101         }
102
103         $session->finish();
104         $session->disconnect();
105         $session->kill_me();
106 }
107
108 sub rollback_db_session {
109         my( $self, $session ) = @_;
110
111         my $req = $session->request("open-ils.storage.transaction.rollback");
112         my $resp = $req->recv();
113         if(UNIVERSAL::isa($resp,"Error")) { throw $resp;  }
114
115         $session->finish();
116         $session->disconnect();
117         $session->kill_me();
118 }
119
120
121 # returns undef it the event is not an ILS event
122 # returns the event code otherwise
123 sub event_code {
124         my( $self, $evt ) = @_;
125         return $evt->{ilsevent} if( ref($evt) eq 'HASH' and defined($evt->{ilsevent})) ;
126         return undef;
127 }
128
129 # ---------------------------------------------------------------------------
130 # Checks to see if a user is logged in.  Returns the user record on success,
131 # throws an exception on error.
132 # ---------------------------------------------------------------------------
133 sub check_user_session {
134
135         my( $self, $user_session ) = @_;
136
137         my $content = $self->simplereq( 
138                 'open-ils.auth', 
139                 'open-ils.auth.session.retrieve', $user_session );
140
141         if(! $content or $self->event_code($content)) {
142                 throw OpenSRF::EX::ERROR 
143                         ("Session [$user_session] cannot be authenticated" );
144         }
145
146         $logger->debug("Fetch user session $user_session found user " . $content->id );
147
148         return $content;
149 }
150
151 # generic simple request returning a scalar value
152 sub simplereq {
153         my($self, $service, $method, @params) = @_;
154         return $self->simple_scalar_request($service, $method, @params);
155 }
156
157
158 sub simple_scalar_request {
159         my($self, $service, $method, @params) = @_;
160
161         my $session = OpenSRF::AppSession->create( $service );
162
163         my $request = $session->request( $method, @params );
164
165         my $val;
166         my $err;
167         try  {
168
169                 $val = $request->gather(1);     
170
171         } catch Error with {
172                 $err = shift;
173         };
174
175         if( $err ) {
176                 warn "received error : service=$service : method=$method : params=".Dumper(\@params) . "\n $err";
177                 throw $err ("Call to $service for method $method \n failed with exception: $err : " );
178         }
179
180         return $val;
181 }
182
183
184
185
186
187 my $tree                                                = undef;
188 my $orglist                                     = undef;
189 my $org_typelist                        = undef;
190 my $org_typelist_hash   = {};
191
192 sub get_org_tree {
193
194         my $self = shift;
195         if($tree) { return $tree; }
196
197         # see if it's in the cache
198         $tree = $cache_client->new()->get_cache('_orgtree');
199         if($tree) { return $tree; }
200
201         if(!$orglist) {
202                 warn "Retrieving Org Tree\n";
203                 $orglist = $self->simple_scalar_request( 
204                         "open-ils.cstore", 
205                         "open-ils.cstore.direct.actor.org_unit.search.atomic",
206                         { id => { '!=' => undef } }
207                 );
208         }
209
210         if( ! $org_typelist ) {
211                 warn "Retrieving org types\n";
212                 $org_typelist = $self->simple_scalar_request( 
213                         "open-ils.cstore", 
214                         "open-ils.cstore.direct.actor.org_unit_type.search.atomic",
215                         { id => { '!=' => undef } }
216                 );
217                 $self->build_org_type($org_typelist);
218         }
219
220         $tree = $self->build_org_tree($orglist,1);
221         $cache_client->new()->put_cache('_orgtree', $tree);
222         return $tree;
223
224 }
225
226 my $slimtree = undef;
227 sub get_slim_org_tree {
228
229         my $self = shift;
230         if($slimtree) { return $slimtree; }
231
232         # see if it's in the cache
233         $slimtree = $cache_client->new()->get_cache('slimorgtree');
234         if($slimtree) { return $slimtree; }
235
236         if(!$orglist) {
237                 warn "Retrieving Org Tree\n";
238                 $orglist = $self->simple_scalar_request( 
239                         "open-ils.cstore", 
240                         "open-ils.cstore.direct.actor.org_unit.search.atomic",
241                         { id => { '!=' => undef } }
242                 );
243         }
244
245         $slimtree = $self->build_org_tree($orglist);
246         $cache_client->new->put_cache('slimorgtree', $slimtree);
247         return $slimtree;
248
249 }
250
251
252 sub build_org_type { 
253         my($self, $org_typelist)  = @_;
254         for my $type (@$org_typelist) {
255                 $org_typelist_hash->{$type->id()} = $type;
256         }
257 }
258
259
260
261 sub build_org_tree {
262
263         my( $self, $orglist, $add_types ) = @_;
264
265         return $orglist unless ref $orglist; 
266     return $$orglist[0] if @$orglist == 1;
267
268         my @list = sort { 
269                 $a->ou_type <=> $b->ou_type ||
270                 $a->name cmp $b->name } @$orglist;
271
272         for my $org (@list) {
273
274                 next unless ($org);
275
276                 if(!ref($org->ou_type()) and $add_types) {
277                         $org->ou_type( $org_typelist_hash->{$org->ou_type()});
278                 }
279
280                 next unless (defined($org->parent_ou));
281
282                 my ($parent) = grep { $_->id == $org->parent_ou } @list;
283                 next unless $parent;
284                 $parent->children([]) unless defined($parent->children); 
285                 push( @{$parent->children}, $org );
286         }
287
288         return $list[0];
289 }
290
291 sub fetch_closed_date {
292         my( $self, $cd ) = @_;
293         my $evt;
294         
295         $logger->debug("Fetching closed_date $cd from cstore");
296
297         my $cd_obj = $self->simplereq(
298                 'open-ils.cstore',
299                 'open-ils.cstore.direct.actor.org_unit.closed_date.retrieve', $cd );
300
301         if(!$cd_obj) {
302                 $logger->info("closed_date $cd not found in the db");
303                 $evt = OpenILS::Event->new('ACTOR_USER_NOT_FOUND');
304         }
305
306         return ($cd_obj, $evt);
307 }
308
309 sub fetch_user {
310         my( $self, $userid ) = @_;
311         my( $user, $evt );
312         
313         $logger->debug("Fetching user $userid from cstore");
314
315         $user = $self->simplereq(
316                 'open-ils.cstore',
317                 'open-ils.cstore.direct.actor.user.retrieve', $userid );
318
319         if(!$user) {
320                 $logger->info("User $userid not found in the db");
321                 $evt = OpenILS::Event->new('ACTOR_USER_NOT_FOUND');
322         }
323
324         return ($user, $evt);
325 }
326
327 sub checkses {
328         my( $self, $session ) = @_;
329         my $user; my $evt; my $e; 
330
331         $logger->debug("Checking user session $session");
332
333         try {
334                 $user = $self->check_user_session($session);
335         } catch Error with { $e = 1; };
336
337         $logger->debug("Done checking user session $session " . (($e) ? "error = $e" : "") );
338
339         if( $e or !$user ) { $evt = OpenILS::Event->new('NO_SESSION'); }
340         return ( $user, $evt );
341 }
342
343
344 # verifiese the session and checks the permissions agains the
345 # session user and the user's home_ou as the org id
346 sub checksesperm {
347         my( $self, $session, @perms ) = @_;
348         my $user; my $evt; my $e; 
349         $logger->debug("Checking user session $session and perms @perms");
350         ($user, $evt) = $self->checkses($session);
351         return (undef, $evt) if $evt;
352         $evt = $self->check_perms($user->id, $user->home_ou, @perms);
353         return ($user, $evt);
354 }
355
356
357 sub checkrequestor {
358         my( $self, $staffobj, $userid, @perms ) = @_;
359         my $user; my $evt;
360         $userid = $staffobj->id unless defined $userid;
361
362         $logger->debug("checkrequestor(): requestor => " . $staffobj->id . ", target => $userid");
363
364         if( $userid ne $staffobj->id ) {
365                 ($user, $evt) = $self->fetch_user($userid);
366                 return (undef, $evt) if $evt;
367                 $evt = $self->check_perms( $staffobj->id, $user->home_ou, @perms );
368
369         } else {
370                 $user = $staffobj;
371         }
372
373         return ($user, $evt);
374 }
375
376 sub checkses_requestor {
377         my( $self, $authtoken, $targetid, @perms ) = @_;
378         my( $requestor, $target, $evt );
379
380         ($requestor, $evt) = $self->checkses($authtoken);
381         return (undef, undef, $evt) if $evt;
382
383         ($target, $evt) = $self->checkrequestor( $requestor, $targetid, @perms );
384         return( $requestor, $target, $evt);
385 }
386
387 sub fetch_copy {
388         my( $self, $copyid ) = @_;
389         my( $copy, $evt );
390
391         $logger->debug("Fetching copy $copyid from cstore");
392
393         $copy = $self->simplereq(
394                 'open-ils.cstore',
395                 'open-ils.cstore.direct.asset.copy.retrieve', $copyid );
396
397         if(!$copy) { $evt = OpenILS::Event->new('ASSET_COPY_NOT_FOUND'); }
398
399         return( $copy, $evt );
400 }
401
402
403 # retrieves a circ object by id
404 sub fetch_circulation {
405         my( $self, $circid ) = @_;
406         my $circ; my $evt;
407         
408         $logger->debug("Fetching circ $circid from cstore");
409
410         $circ = $self->simplereq(
411                 'open-ils.cstore',
412                 "open-ils.cstore.direct.action.circulation.retrieve", $circid );
413
414         if(!$circ) {
415                 $evt = OpenILS::Event->new('ACTION_CIRCULATION_NOT_FOUND', circid => $circid );
416         }
417
418         return ( $circ, $evt );
419 }
420
421 sub fetch_record_by_copy {
422         my( $self, $copyid ) = @_;
423         my( $record, $evt );
424
425         $logger->debug("Fetching record by copy $copyid from cstore");
426
427         $record = $self->simplereq(
428                 'open-ils.cstore',
429                 'open-ils.cstore.direct.asset.copy.retrieve', $copyid,
430                 { flesh => 3,
431                   flesh_fields => {     bre => [ 'fixed_fields' ],
432                                         acn => [ 'record' ],
433                                         acp => [ 'call_number' ],
434                                   }
435                 }
436         );
437
438         if(!$record) {
439                 $evt = OpenILS::Event->new('BIBLIO_RECORD_ENTRY_NOT_FOUND');
440         } else {
441                 $record = $record->call_number->record;
442         }
443
444         return ($record, $evt);
445 }
446
447 # turns a record object into an mvr (mods) object
448 sub record_to_mvr {
449         my( $self, $record ) = @_;
450         return undef unless $record and $record->marc;
451         my $u = OpenILS::Utils::ModsParser->new();
452         $u->start_mods_batch( $record->marc );
453         my $mods = $u->finish_mods_batch();
454         $mods->doc_id($record->id);
455    $mods->tcn($record->tcn_value);
456         return $mods;
457 }
458
459 sub fetch_hold {
460         my( $self, $holdid ) = @_;
461         my( $hold, $evt );
462
463         $logger->debug("Fetching hold $holdid from cstore");
464
465         $hold = $self->simplereq(
466                 'open-ils.cstore',
467                 'open-ils.cstore.direct.action.hold_request.retrieve', $holdid);
468
469         $evt = OpenILS::Event->new('ACTION_HOLD_REQUEST_NOT_FOUND', holdid => $holdid) unless $hold;
470
471         return ($hold, $evt);
472 }
473
474
475 sub fetch_hold_transit_by_hold {
476         my( $self, $holdid ) = @_;
477         my( $transit, $evt );
478
479         $logger->debug("Fetching transit by hold $holdid from cstore");
480
481         $transit = $self->simplereq(
482                 'open-ils.cstore',
483                 'open-ils.cstore.direct.action.hold_transit_copy.search', { hold => $holdid } );
484
485         $evt = OpenILS::Event->new('ACTION_HOLD_TRANSIT_COPY_NOT_FOUND', holdid => $holdid) unless $transit;
486
487         return ($transit, $evt );
488 }
489
490 # fetches the captured, but not fulfilled hold attached to a given copy
491 sub fetch_open_hold_by_copy {
492         my( $self, $copyid ) = @_;
493         $logger->debug("Searching for active hold for copy $copyid");
494         my( $hold, $evt );
495
496         $hold = $self->cstorereq(
497                 'open-ils.cstore.direct.action.hold_request.search',
498                 { 
499                         current_copy            => $copyid , 
500                         capture_time            => { "!=" => undef }, 
501                         fulfillment_time        => undef,
502                         cancel_time                     => undef,
503                 } );
504
505         $evt = OpenILS::Event->new('ACTION_HOLD_REQUEST_NOT_FOUND', copyid => $copyid) unless $hold;
506         return ($hold, $evt);
507 }
508
509 sub fetch_hold_transit {
510         my( $self, $transid ) = @_;
511         my( $htransit, $evt );
512         $logger->debug("Fetching hold transit with hold id $transid");
513         $htransit = $self->cstorereq(
514                 'open-ils.cstore.direct.action.hold_transit_copy.retrieve', $transid );
515         $evt = OpenILS::Event->new('ACTION_HOLD_TRANSIT_COPY_NOT_FOUND', id => $transid) unless $htransit;
516         return ($htransit, $evt);
517 }
518
519 sub fetch_copy_by_barcode {
520         my( $self, $barcode ) = @_;
521         my( $copy, $evt );
522
523         $logger->debug("Fetching copy by barcode $barcode from cstore");
524
525         $copy = $self->simplereq( 'open-ils.cstore',
526                 'open-ils.cstore.direct.asset.copy.search', { barcode => $barcode, deleted => 'f'} );
527                 #'open-ils.storage.direct.asset.copy.search.barcode', $barcode );
528
529         $evt = OpenILS::Event->new('ASSET_COPY_NOT_FOUND', barcode => $barcode) unless $copy;
530
531         return ($copy, $evt);
532 }
533
534 sub fetch_open_billable_transaction {
535         my( $self, $transid ) = @_;
536         my( $transaction, $evt );
537
538         $logger->debug("Fetching open billable transaction $transid from cstore");
539
540         $transaction = $self->simplereq(
541                 'open-ils.cstore',
542                 'open-ils.cstore.direct.money.open_billable_transaction_summary.retrieve',  $transid);
543
544         $evt = OpenILS::Event->new(
545                 'MONEY_OPEN_BILLABLE_TRANSACTION_SUMMARY_NOT_FOUND', transid => $transid ) unless $transaction;
546
547         return ($transaction, $evt);
548 }
549
550
551
552 my %buckets;
553 $buckets{'biblio'} = 'biblio_record_entry_bucket';
554 $buckets{'callnumber'} = 'call_number_bucket';
555 $buckets{'copy'} = 'copy_bucket';
556 $buckets{'user'} = 'user_bucket';
557
558 sub fetch_container {
559         my( $self, $id, $type ) = @_;
560         my( $bucket, $evt );
561
562         $logger->debug("Fetching container $id with type $type");
563
564         my $e = 'CONTAINER_CALL_NUMBER_BUCKET_NOT_FOUND';
565         $e = 'CONTAINER_BIBLIO_RECORD_ENTRY_BUCKET_NOT_FOUND' if $type eq 'biblio';
566         $e = 'CONTAINER_USER_BUCKET_NOT_FOUND' if $type eq 'user';
567         $e = 'CONTAINER_COPY_BUCKET_NOT_FOUND' if $type eq 'copy';
568
569         my $meth = $buckets{$type};
570         $bucket = $self->simplereq(
571                 'open-ils.cstore',
572                 "open-ils.cstore.direct.container.$meth.retrieve", $id );
573
574         $evt = OpenILS::Event->new(
575                 $e, container => $id, container_type => $type ) unless $bucket;
576
577         return ($bucket, $evt);
578 }
579
580
581 sub fetch_container_e {
582         my( $self, $editor, $id, $type ) = @_;
583
584         my( $bucket, $evt );
585         $bucket = $editor->retrieve_container_copy_bucket($id) if $type eq 'copy';
586         $bucket = $editor->retrieve_container_call_number_bucket($id) if $type eq 'callnumber';
587         $bucket = $editor->retrieve_container_biblio_record_entry_bucket($id) if $type eq 'biblio';
588         $bucket = $editor->retrieve_container_user_bucket($id) if $type eq 'user';
589
590         $evt = $editor->event unless $bucket;
591         return ($bucket, $evt);
592 }
593
594 sub fetch_container_item_e {
595         my( $self, $editor, $id, $type ) = @_;
596
597         my( $bucket, $evt );
598         $bucket = $editor->retrieve_container_copy_bucket_item($id) if $type eq 'copy';
599         $bucket = $editor->retrieve_container_call_number_bucket_item($id) if $type eq 'callnumber';
600         $bucket = $editor->retrieve_container_biblio_record_entry_bucket_item($id) if $type eq 'biblio';
601         $bucket = $editor->retrieve_container_user_bucket_item($id) if $type eq 'user';
602
603         $evt = $editor->event unless $bucket;
604         return ($bucket, $evt);
605 }
606
607
608
609
610
611 sub fetch_container_item {
612         my( $self, $id, $type ) = @_;
613         my( $bucket, $evt );
614
615         $logger->debug("Fetching container item $id with type $type");
616
617         my $meth = $buckets{$type} . "_item";
618
619         $bucket = $self->simplereq(
620                 'open-ils.cstore',
621                 "open-ils.cstore.direct.container.$meth.retrieve", $id );
622
623
624         my $e = 'CONTAINER_CALL_NUMBER_BUCKET_ITEM_NOT_FOUND';
625         $e = 'CONTAINER_BIBLIO_RECORD_ENTRY_BUCKET_ITEM_NOT_FOUND' if $type eq 'biblio';
626         $e = 'CONTAINER_USER_BUCKET_ITEM_NOT_FOUND' if $type eq 'user';
627         $e = 'CONTAINER_COPY_BUCKET_ITEM_NOT_FOUND' if $type eq 'copy';
628
629         $evt = OpenILS::Event->new(
630                 $e, itemid => $id, container_type => $type ) unless $bucket;
631
632         return ($bucket, $evt);
633 }
634
635
636 sub fetch_patron_standings {
637         my $self = shift;
638         $logger->debug("Fetching patron standings");    
639         return $self->simplereq(
640                 'open-ils.cstore', 
641                 'open-ils.cstore.direct.config.standing.search.atomic', { id => { '!=' => undef } });
642 }
643
644
645 sub fetch_permission_group_tree {
646         my $self = shift;
647         $logger->debug("Fetching patron profiles");     
648         return $self->simplereq(
649                 'open-ils.actor', 
650                 'open-ils.actor.groups.tree.retrieve' );
651 }
652
653
654 sub fetch_patron_circ_summary {
655         my( $self, $userid ) = @_;
656         $logger->debug("Fetching patron summary for $userid");
657         my $summary = $self->simplereq(
658                 'open-ils.storage', 
659                 "open-ils.storage.action.circulation.patron_summary", $userid );
660
661         if( $summary ) {
662                 $summary->[0] ||= 0;
663                 $summary->[1] ||= 0.0;
664                 return $summary;
665         }
666         return undef;
667 }
668
669
670 sub fetch_copy_statuses {
671         my( $self ) = @_;
672         $logger->debug("Fetching copy statuses");
673         return $self->simplereq(
674                 'open-ils.cstore', 
675                 'open-ils.cstore.direct.config.copy_status.search.atomic', { id => { '!=' => undef } });
676 }
677
678 sub fetch_copy_location {
679         my( $self, $id ) = @_;
680         my $evt;
681         my $cl = $self->cstorereq(
682                 'open-ils.cstore.direct.asset.copy_location.retrieve', $id );
683         $evt = OpenILS::Event->new('ASSET_COPY_LOCATION_NOT_FOUND') unless $cl;
684         return ($cl, $evt);
685 }
686
687 sub fetch_copy_locations {
688         my $self = shift; 
689         return $self->simplereq(
690                 'open-ils.cstore', 
691                 'open-ils.cstore.direct.asset.copy_location.search.atomic', { id => { '!=' => undef } });
692 }
693
694 sub fetch_copy_location_by_name {
695         my( $self, $name, $org ) = @_;
696         my $evt;
697         my $cl = $self->cstorereq(
698                 'open-ils.cstore.direct.asset.copy_location.search',
699                         { name => $name, owning_lib => $org } );
700         $evt = OpenILS::Event->new('ASSET_COPY_LOCATION_NOT_FOUND') unless $cl;
701         return ($cl, $evt);
702 }
703
704 sub fetch_callnumber {
705         my( $self, $id ) = @_;
706         my $evt = undef;
707
708         my $e = OpenILS::Event->new( 'ASSET_CALL_NUMBER_NOT_FOUND', id => $id );
709         return( undef, $e ) unless $id;
710
711         $logger->debug("Fetching callnumber $id");
712
713         my $cn = $self->simplereq(
714                 'open-ils.cstore',
715                 'open-ils.cstore.direct.asset.call_number.retrieve', $id );
716         $evt = $e  unless $cn;
717
718         return ( $cn, $evt );
719 }
720
721 my %ORG_CACHE; # - these rarely change, so cache them..
722 sub fetch_org_unit {
723         my( $self, $id ) = @_;
724         return undef unless $id;
725         return $id if( ref($id) eq 'Fieldmapper::actor::org_unit' );
726         return $ORG_CACHE{$id} if $ORG_CACHE{$id};
727         $logger->debug("Fetching org unit $id");
728         my $evt = undef;
729
730         my $org = $self->simplereq(
731                 'open-ils.cstore', 
732                 'open-ils.cstore.direct.actor.org_unit.retrieve', $id );
733         $evt = OpenILS::Event->new( 'ACTOR_ORG_UNIT_NOT_FOUND', id => $id ) unless $org;
734         $ORG_CACHE{$id}  = $org;
735
736         return ($org, $evt);
737 }
738
739 sub fetch_stat_cat {
740         my( $self, $type, $id ) = @_;
741         my( $cat, $evt );
742         $logger->debug("Fetching $type stat cat: $id");
743         $cat = $self->simplereq(
744                 'open-ils.cstore', 
745                 "open-ils.cstore.direct.$type.stat_cat.retrieve", $id );
746
747         my $e = 'ASSET_STAT_CAT_NOT_FOUND';
748         $e = 'ACTOR_STAT_CAT_NOT_FOUND' if $type eq 'actor';
749
750         $evt = OpenILS::Event->new( $e, id => $id ) unless $cat;
751         return ( $cat, $evt );
752 }
753
754 sub fetch_stat_cat_entry {
755         my( $self, $type, $id ) = @_;
756         my( $entry, $evt );
757         $logger->debug("Fetching $type stat cat entry: $id");
758         $entry = $self->simplereq(
759                 'open-ils.cstore', 
760                 "open-ils.cstore.direct.$type.stat_cat_entry.retrieve", $id );
761
762         my $e = 'ASSET_STAT_CAT_ENTRY_NOT_FOUND';
763         $e = 'ACTOR_STAT_CAT_ENTRY_NOT_FOUND' if $type eq 'actor';
764
765         $evt = OpenILS::Event->new( $e, id => $id ) unless $entry;
766         return ( $entry, $evt );
767 }
768
769
770 sub find_org {
771         my( $self, $org_tree, $orgid )  = @_;
772         if (!$org_tree) {
773                 $logger->warn("find_org() did not receive a value for \$org_tree");
774                 return undef;
775         } elsif (!$orgid) {
776                 $logger->warn("find_org() did not receive a value for \$orgid");
777                 return undef;
778     }
779         return $org_tree if ( $org_tree->id eq $orgid );
780         return undef unless ref($org_tree->children);
781         for my $c (@{$org_tree->children}) {
782                 my $o = $self->find_org($c, $orgid);
783                 return $o if $o;
784         }
785         return undef;
786 }
787
788 sub fetch_non_cat_type_by_name_and_org {
789         my( $self, $name, $orgId ) = @_;
790         $logger->debug("Fetching non cat type $name at org $orgId");
791         my $types = $self->simplereq(
792                 'open-ils.cstore',
793                 'open-ils.cstore.direct.config.non_cataloged_type.search.atomic',
794                 { name => $name, owning_lib => $orgId } );
795         return ($types->[0], undef) if($types and @$types);
796         return (undef, OpenILS::Event->new('CONFIG_NON_CATALOGED_TYPE_NOT_FOUND') );
797 }
798
799 sub fetch_non_cat_type {
800         my( $self, $id ) = @_;
801         $logger->debug("Fetching non cat type $id");
802         my( $type, $evt );
803         $type = $self->simplereq(
804                 'open-ils.cstore', 
805                 'open-ils.cstore.direct.config.non_cataloged_type.retrieve', $id );
806         $evt = OpenILS::Event->new('CONFIG_NON_CATALOGED_TYPE_NOT_FOUND') unless $type;
807         return ($type, $evt);
808 }
809
810 sub DB_UPDATE_FAILED { 
811         my( $self, $payload ) = @_;
812         return OpenILS::Event->new('DATABASE_UPDATE_FAILED', 
813                 payload => ($payload) ? $payload : undef ); 
814 }
815
816 sub fetch_circ_duration_by_name {
817         my( $self, $name ) = @_;
818         my( $dur, $evt );
819         $dur = $self->simplereq(
820                 'open-ils.cstore', 
821                 'open-ils.cstore.direct.config.rules.circ_duration.search.atomic', { name => $name } );
822         $dur = $dur->[0];
823         $evt = OpenILS::Event->new('CONFIG_RULES_CIRC_DURATION_NOT_FOUND') unless $dur;
824         return ($dur, $evt);
825 }
826
827 sub fetch_recurring_fine_by_name {
828         my( $self, $name ) = @_;
829         my( $obj, $evt );
830         $obj = $self->simplereq(
831                 'open-ils.cstore', 
832                 'open-ils.cstore.direct.config.rules.recuring_fine.search.atomic', { name => $name } );
833         $obj = $obj->[0];
834         $evt = OpenILS::Event->new('CONFIG_RULES_RECURING_FINE_NOT_FOUND') unless $obj;
835         return ($obj, $evt);
836 }
837
838 sub fetch_max_fine_by_name {
839         my( $self, $name ) = @_;
840         my( $obj, $evt );
841         $obj = $self->simplereq(
842                 'open-ils.cstore', 
843                 'open-ils.cstore.direct.config.rules.max_fine.search.atomic', { name => $name } );
844         $obj = $obj->[0];
845         $evt = OpenILS::Event->new('CONFIG_RULES_MAX_FINE_NOT_FOUND') unless $obj;
846         return ($obj, $evt);
847 }
848
849 sub storagereq {
850         my( $self, $method, @params ) = @_;
851         return $self->simplereq(
852                 'open-ils.storage', $method, @params );
853 }
854
855 sub cstorereq {
856         my( $self, $method, @params ) = @_;
857         return $self->simplereq(
858                 'open-ils.cstore', $method, @params );
859 }
860
861 sub event_equals {
862         my( $self, $e, $name ) =  @_;
863         if( $e and ref($e) eq 'HASH' and 
864                 defined($e->{textcode}) and $e->{textcode} eq $name ) {
865                 return 1 ;
866         }
867         return 0;
868 }
869
870 sub logmark {
871         my( undef, $f, $l ) = caller(0);
872         my( undef, undef, undef, $s ) = caller(1);
873         $s =~ s/.*:://g;
874         $f =~ s/.*\///g;
875         $logger->debug("LOGMARK: $f:$l:$s");
876 }
877
878 # takes a copy id 
879 sub fetch_open_circulation {
880         my( $self, $cid ) = @_;
881         my $evt;
882         $self->logmark;
883         my $circ = $self->cstorereq(
884                 'open-ils.cstore.direct.action.open_circulation.search',
885                 { target_copy => $cid, stop_fines_time => undef } );
886         $evt = OpenILS::Event->new('ACTION_CIRCULATION_NOT_FOUND') unless $circ;        
887         return ($circ, $evt);
888 }
889
890 sub fetch_all_open_circulation {
891         my( $self, $cid ) = @_;
892         my $evt;
893         $self->logmark;
894         my $circ = $self->cstorereq(
895                 'open-ils.cstore.direct.action.open_circulation.search',
896                 { target_copy => $cid, xact_finish => undef } );
897         $evt = OpenILS::Event->new('ACTION_CIRCULATION_NOT_FOUND') unless $circ;        
898         return ($circ, $evt);
899 }
900
901 my $copy_statuses;
902 sub copy_status_from_name {
903         my( $self, $name ) = @_;
904         $copy_statuses = $self->fetch_copy_statuses unless $copy_statuses;
905         for my $status (@$copy_statuses) { 
906                 return $status if( $status->name =~ /$name/i );
907         }
908         return undef;
909 }
910
911 sub copy_status_to_name {
912         my( $self, $sid ) = @_;
913         $copy_statuses = $self->fetch_copy_statuses unless $copy_statuses;
914         for my $status (@$copy_statuses) { 
915                 return $status->name if( $status->id == $sid );
916         }
917         return undef;
918 }
919
920
921 sub copy_status {
922         my( $self, $arg ) = @_;
923         return $arg if ref $arg;
924         $copy_statuses = $self->fetch_copy_statuses unless $copy_statuses;
925         my ($stat) = grep { $_->id == $arg } @$copy_statuses;
926         return $stat;
927 }
928
929 sub fetch_open_transit_by_copy {
930         my( $self, $copyid ) = @_;
931         my($transit, $evt);
932         $transit = $self->cstorereq(
933                 'open-ils.cstore.direct.action.transit_copy.search',
934                 { target_copy => $copyid, dest_recv_time => undef });
935         $evt = OpenILS::Event->new('ACTION_TRANSIT_COPY_NOT_FOUND') unless $transit;
936         return ($transit, $evt);
937 }
938
939 sub unflesh_copy {
940         my( $self, $copy ) = @_;
941         return undef unless $copy;
942         $copy->status( $copy->status->id ) if ref($copy->status);
943         $copy->location( $copy->location->id ) if ref($copy->location);
944         $copy->circ_lib( $copy->circ_lib->id ) if ref($copy->circ_lib);
945         return $copy;
946 }
947
948 # un-fleshes a copy and updates it in the DB
949 # returns a DB_UPDATE_FAILED event on error
950 # returns undef on success
951 sub update_copy {
952         my( $self, %params ) = @_;
953
954         my $copy                = $params{copy} || die "update_copy(): copy required";
955         my $editor      = $params{editor} || die "update_copy(): copy editor required";
956         my $session = $params{session};
957
958         $logger->debug("Updating copy in the database: " . $copy->id);
959
960         $self->unflesh_copy($copy);
961         $copy->editor( $editor );
962         $copy->edit_date( 'now' );
963
964         my $s;
965         my $meth = 'open-ils.storage.direct.asset.copy.update';
966
967         $s = $session->request( $meth, $copy )->gather(1) if $session;
968         $s = $self->storagereq( $meth, $copy ) unless $session;
969
970         $logger->debug("Update of copy ".$copy->id." returned: $s");
971
972         return $self->DB_UPDATE_FAILED($copy) unless $s;
973         return undef;
974 }
975
976 sub fetch_billable_xact {
977         my( $self, $id ) = @_;
978         my($xact, $evt);
979         $logger->debug("Fetching billable transaction %id");
980         $xact = $self->cstorereq(
981                 'open-ils.cstore.direct.money.billable_transaction.retrieve', $id );
982         $evt = OpenILS::Event->new('MONEY_BILLABLE_TRANSACTION_NOT_FOUND') unless $xact;
983         return ($xact, $evt);
984 }
985
986 sub fetch_billable_xact_summary {
987         my( $self, $id ) = @_;
988         my($xact, $evt);
989         $logger->debug("Fetching billable transaction summary %id");
990         $xact = $self->cstorereq(
991                 'open-ils.cstore.direct.money.billable_transaction_summary.retrieve', $id );
992         $evt = OpenILS::Event->new('MONEY_BILLABLE_TRANSACTION_NOT_FOUND') unless $xact;
993         return ($xact, $evt);
994 }
995
996 sub fetch_fleshed_copy {
997         my( $self, $id ) = @_;
998         my( $copy, $evt );
999         $logger->info("Fetching fleshed copy $id");
1000         $copy = $self->cstorereq(
1001                 "open-ils.cstore.direct.asset.copy.retrieve", $id,
1002                 { flesh => 1,
1003                   flesh_fields => { acp => [ qw/ circ_lib location status stat_cat_entries / ] }
1004                 }
1005         );
1006         $evt = OpenILS::Event->new('ASSET_COPY_NOT_FOUND', id => $id) unless $copy;
1007         return ($copy, $evt);
1008 }
1009
1010
1011 # returns the org that owns the callnumber that the copy
1012 # is attached to
1013 sub fetch_copy_owner {
1014         my( $self, $copyid ) = @_;
1015         my( $copy, $cn, $evt );
1016         $logger->debug("Fetching copy owner $copyid");
1017         ($copy, $evt) = $self->fetch_copy($copyid);
1018         return (undef,$evt) if $evt;
1019         ($cn, $evt) = $self->fetch_callnumber($copy->call_number);
1020         return (undef,$evt) if $evt;
1021         return ($cn->owning_lib);
1022 }
1023
1024 sub fetch_copy_note {
1025         my( $self, $id ) = @_;
1026         my( $note, $evt );
1027         $logger->debug("Fetching copy note $id");
1028         $note = $self->cstorereq(
1029                 'open-ils.cstore.direct.asset.copy_note.retrieve', $id );
1030         $evt = OpenILS::Event->new('ASSET_COPY_NOTE_NOT_FOUND', id => $id ) unless $note;
1031         return ($note, $evt);
1032 }
1033
1034 sub fetch_call_numbers_by_title {
1035         my( $self, $titleid ) = @_;
1036         $logger->info("Fetching call numbers by title $titleid");
1037         return $self->cstorereq(
1038                 'open-ils.cstore.direct.asset.call_number.search.atomic', 
1039                 { record => $titleid, deleted => 'f' });
1040                 #'open-ils.storage.direct.asset.call_number.search.record.atomic', $titleid);
1041 }
1042
1043 sub fetch_copies_by_call_number {
1044         my( $self, $cnid ) = @_;
1045         $logger->info("Fetching copies by call number $cnid");
1046         return $self->cstorereq(
1047                 'open-ils.cstore.direct.asset.copy.search.atomic', { call_number => $cnid, deleted => 'f' } );
1048                 #'open-ils.storage.direct.asset.copy.search.call_number.atomic', $cnid );
1049 }
1050
1051 sub fetch_user_by_barcode {
1052         my( $self, $bc ) = @_;
1053         my $cardid = $self->cstorereq(
1054                 'open-ils.cstore.direct.actor.card.id_list', { barcode => $bc } );
1055         return (undef, OpenILS::Event->new('ACTOR_CARD_NOT_FOUND', barcode => $bc)) unless $cardid;
1056         my $user = $self->cstorereq(
1057                 'open-ils.cstore.direct.actor.user.search', { card => $cardid } );
1058         return (undef, OpenILS::Event->new('ACTOR_USER_NOT_FOUND', card => $cardid)) unless $user;
1059         return ($user);
1060         
1061 }
1062
1063
1064 # ---------------------------------------------------------------------
1065 # Updates and returns the patron penalties
1066 # ---------------------------------------------------------------------
1067 sub update_patron_penalties {
1068         my( $self, %args ) = @_;
1069         return $self->simplereq(
1070                 'open-ils.penalty',
1071                 'open-ils.penalty.patron_penalty.calculate', 
1072                 { update => 1, %args }
1073         );
1074 }
1075
1076 sub fetch_bill {
1077         my( $self, $billid ) = @_;
1078         $logger->debug("Fetching billing $billid");
1079         my $bill = $self->cstorereq(
1080                 'open-ils.cstore.direct.money.billing.retrieve', $billid );
1081         my $evt = OpenILS::Event->new('MONEY_BILLING_NOT_FOUND') unless $bill;
1082         return($bill, $evt);
1083 }
1084
1085
1086
1087 my $ORG_TREE;
1088 sub fetch_org_tree {
1089         my $self = shift;
1090         return $ORG_TREE if $ORG_TREE;
1091         return $ORG_TREE = OpenILS::Utils::CStoreEditor->new->search_actor_org_unit( 
1092                 [
1093                         {"parent_ou" => undef },
1094                         {
1095                                 flesh                           => 2,
1096                                 flesh_fields    => { aou =>  ['children'] },
1097                                 order_by       => { aou => 'name'}
1098                         }
1099                 ]
1100         )->[0];
1101 }
1102
1103 sub walk_org_tree {
1104         my( $self, $node, $callback ) = @_;
1105         return unless $node;
1106         $callback->($node);
1107         if( $node->children ) {
1108                 $self->walk_org_tree($_, $callback) for @{$node->children};
1109         }
1110 }
1111
1112 sub is_true {
1113         my( $self, $item ) = @_;
1114         return 1 if $item and $item !~ /^f$/i;
1115         return 0;
1116 }
1117
1118
1119 # This logic now lives in storage
1120 sub __patron_money_owed {
1121         my( $self, $patronid ) = @_;
1122         my $ses = OpenSRF::AppSession->create('open-ils.storage');
1123         my $req = $ses->request(
1124                 'open-ils.storage.money.billable_transaction.summary.search',
1125                 { usr => $patronid, xact_finish => undef } );
1126
1127         my $total = 0;
1128         my $data;
1129         while( $data = $req->recv ) {
1130                 $data = $data->content;
1131                 $total += $data->balance_owed;
1132         }
1133         return $total;
1134 }
1135
1136 sub patron_money_owed {
1137         my( $self, $userid ) = @_;
1138         return $self->storagereq(
1139                 'open-ils.storage.actor.user.total_owed', $userid);
1140 }
1141
1142 sub patron_total_items_out {
1143         my( $self, $userid ) = @_;
1144         return $self->storagereq(
1145                 'open-ils.storage.actor.user.total_out', $userid);
1146 }
1147
1148
1149
1150
1151 #---------------------------------------------------------------------
1152 # Returns  ($summary, $event) 
1153 #---------------------------------------------------------------------
1154 sub fetch_mbts {
1155         my $self = shift;
1156         my $id  = shift;
1157         my $editor = shift || OpenILS::Utils::CStoreEditor->new;
1158
1159         $id = $id->id if (ref($id));
1160
1161         my $xact = $editor->retrieve_money_billable_transaction(
1162                 [
1163                         $id, {  
1164                                 flesh => 1, 
1165                                 flesh_fields => { mbt => [ qw/billings payments grocery circulation/ ] } 
1166                         }
1167                 ]
1168         ) or return (undef, $editor->event);
1169
1170         return $self->make_mbts($xact);
1171 }
1172
1173
1174 #---------------------------------------------------------------------
1175 # Given a list of money.billable_transaction objects, this creates
1176 # transaction summary objects for each
1177 #--------------------------------------------------------------------
1178 sub make_mbts {
1179         my $self = shift;
1180         my @xacts = @_;
1181
1182         my @mbts;
1183         for my $x (@xacts) {
1184
1185                 my $s = new Fieldmapper::money::billable_transaction_summary;
1186
1187                 $s->id( $x->id );
1188                 $s->usr( $x->usr );
1189                 $s->xact_start( $x->xact_start );
1190                 $s->xact_finish( $x->xact_finish );
1191                 
1192                 my $to = 0;
1193                 my $lb = undef;
1194                 for my $b (@{ $x->billings }) {
1195                         next if ($self->is_true($b->voided));
1196                         $to += ($b->amount * 100);
1197                         $lb ||= $b->billing_ts;
1198                         if ($b->billing_ts ge $lb) {
1199                                 $lb = $b->billing_ts;
1200                                 $s->last_billing_note($b->note);
1201                                 $s->last_billing_ts($b->billing_ts);
1202                                 $s->last_billing_type($b->billing_type);
1203                         }
1204                 }
1205
1206                 $s->total_owed( sprintf('%0.2f', $to / 100 ) );
1207                 
1208                 my $tp = 0;
1209                 my $lp = undef;
1210                 for my $p (@{ $x->payments }) {
1211                         next if ($self->is_true($p->voided));
1212                         $tp += ($p->amount * 100);
1213                         $lp ||= $p->payment_ts;
1214                         if ($p->payment_ts ge $lp) {
1215                                 $lp = $p->payment_ts;
1216                                 $s->last_payment_note($p->note);
1217                                 $s->last_payment_ts($p->payment_ts);
1218                                 $s->last_payment_type($p->payment_type);
1219                         }
1220                 }
1221
1222                 $s->total_paid( sprintf('%0.2f', $tp / 100 ) );
1223                 $s->balance_owed( sprintf('%0.2f', ($to - $tp) / 100) );
1224                 $s->xact_type('grocery') if ($x->grocery);
1225                 $s->xact_type('circulation') if ($x->circulation);
1226
1227                 $logger->debug("Created mbts with balance_owed = ". $s->balance_owed);
1228                 
1229                 push @mbts, $s;
1230         }
1231                 
1232         return @mbts;
1233 }
1234                 
1235                 
1236 sub ou_ancestor_setting_value {
1237     my $obj = ou_ancestor_setting(@_);
1238     return ($obj) ? $obj->{value} : undef;
1239 }
1240
1241 sub ou_ancestor_setting {
1242     my( $self, $orgid, $name, $e ) = @_;
1243     $e = $e || OpenILS::Utils::CStoreEditor->new;
1244
1245     do {
1246         my $setting = $e->search_actor_org_unit_setting({org_unit=>$orgid, name=>$name})->[0];
1247
1248         if( $setting ) {
1249             $logger->info("found org_setting $name at org $orgid : " . $setting->value);
1250             return { org => $orgid, value => OpenSRF::Utils::JSON->JSON2perl($setting->value) };
1251         }
1252
1253         my $org = $e->retrieve_actor_org_unit($orgid) or return $e->event;
1254         $orgid = $org->parent_ou or return undef;
1255
1256     } while(1);
1257
1258     return undef;
1259 }       
1260                 
1261
1262 # returns the ISO8601 string representation of the requested epoch in GMT
1263 sub epoch2ISO8601 {
1264     my( $self, $epoch ) = @_;
1265     my ($sec,$min,$hour,$mday,$mon,$year) = gmtime($epoch);
1266     $year += 1900; $mon += 1;
1267     my $date = sprintf(
1268         '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1269         $year, $mon, $mday, $hour, $min, $sec);
1270     return $date;
1271 }
1272                         
1273         
1274 1;
1275