]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/OpenILS/Application/AppUtils.pm
added some logging
[Evergreen.git] / Open-ILS / src / perlmods / OpenILS / Application / AppUtils.pm
1 package OpenILS::Application::AppUtils;
2 use strict; use warnings;
3 use base qw/OpenSRF::Application/;
4 use OpenSRF::Utils::Cache;
5 use OpenSRF::EX qw(:try);
6 use OpenILS::Perm;
7 use OpenSRF::Utils::Logger;
8 use OpenILS::Utils::ModsParser;
9 use OpenILS::Event;
10 use Data::Dumper;
11 my $logger = "OpenSRF::Utils::Logger";
12
13
14 my $cache_client = "OpenSRF::Utils::Cache";
15
16 my $storage_session = undef;
17
18 # ---------------------------------------------------------------------------
19 # Pile of utilty methods used accross applications.
20 # ---------------------------------------------------------------------------
21
22
23 # ---------------------------------------------------------------------------
24 # on sucess, returns the created session, on failure throws ERROR exception
25 # ---------------------------------------------------------------------------
26 sub start_db_session {
27
28         my $self = shift;
29         my $session = OpenSRF::AppSession->connect( "open-ils.storage" );
30         my $trans_req = $session->request( "open-ils.storage.transaction.begin" );
31
32         my $trans_resp = $trans_req->recv();
33         if(ref($trans_resp) and UNIVERSAL::isa($trans_resp,"Error")) { throw $trans_resp; }
34         if( ! $trans_resp->content() ) {
35                 throw OpenSRF::ERROR 
36                         ("Unable to Begin Transaction with database" );
37         }
38         $trans_req->finish();
39
40         $logger->debug("Setting global storage session to ".
41                 "session: " . $session->session_id . " : " . $session->app );
42
43         $storage_session = $session;
44         return $session;
45 }
46
47
48 # returns undef if user has all of the perms provided
49 # returns the first failed perm on failure
50 sub check_user_perms {
51         my($self, $user_id, $org_id, @perm_types ) = @_;
52         $logger->debug("Checking perms with user : $user_id , org: $org_id, @perm_types");
53         for my $type (@perm_types) {
54                 return $type unless ($self->storagereq(
55                         "open-ils.storage.permission.user_has_perm", 
56                         $user_id, $type, $org_id ));
57         }
58         return undef;
59 }
60
61 # checks the list of user perms.  The first one that fails returns a new
62 # OpenILS::Perm object of that type.  Returns undef if all perms are allowed
63 sub check_perms {
64         my( $self, $user_id, $org_id, @perm_types ) = @_;
65         my $t = $self->check_user_perms( $user_id, $org_id, @perm_types );
66         return OpenILS::Event->new('PERM_FAILURE', ilsperm => $t, ilspermloc => $org_id ) if $t;
67         return undef;
68 }
69
70
71
72 # ---------------------------------------------------------------------------
73 # commits and destroys the session
74 # ---------------------------------------------------------------------------
75 sub commit_db_session {
76         my( $self, $session ) = @_;
77
78         my $req = $session->request( "open-ils.storage.transaction.commit" );
79         my $resp = $req->recv();
80
81         if(!$resp) {
82                 throw OpenSRF::EX::ERROR ("Unable to commit db session");
83         }
84
85         if(UNIVERSAL::isa($resp,"Error")) { 
86                 throw $resp ($resp->stringify); 
87         }
88
89         if(!$resp->content) {
90                 throw OpenSRF::EX::ERROR ("Unable to commit db session");
91         }
92
93         $session->finish();
94         $session->disconnect();
95         $session->kill_me();
96         $storage_session = undef;
97 }
98
99 sub rollback_db_session {
100         my( $self, $session ) = @_;
101
102         my $req = $session->request("open-ils.storage.transaction.rollback");
103         my $resp = $req->recv();
104         if(UNIVERSAL::isa($resp,"Error")) { throw $resp;  }
105
106         $session->finish();
107         $session->disconnect();
108         $session->kill_me();
109         $storage_session = undef;
110 }
111
112
113 # returns undef it the event is not an ILS event
114 # returns the event code otherwise
115 sub event_code {
116         my( $self, $evt ) = @_;
117         return $evt->{ilsevent} if( ref($evt) eq 'HASH' and defined($evt->{ilsevent})) ;
118         return undef;
119 }
120
121 # ---------------------------------------------------------------------------
122 # Checks to see if a user is logged in.  Returns the user record on success,
123 # throws an exception on error.
124 # ---------------------------------------------------------------------------
125 sub check_user_session {
126
127         my( $self, $user_session ) = @_;
128
129         my $content = $self->simplereq( 
130                 'open-ils.auth', 
131                 'open-ils.auth.session.retrieve', $user_session );
132
133
134         if(! $content or $self->event_code($content)) {
135                 throw OpenSRF::EX::ERROR 
136                         ("Session [$user_session] cannot be authenticated" );
137         }
138
139         $logger->debug("Fetch user session $user_session found user " . $content->id );
140
141         return $content;
142 }
143
144 # generic simple request returning a scalar value
145 sub simplereq {
146         my($self, $service, $method, @params) = @_;
147         return $self->simple_scalar_request($service, $method, @params);
148 }
149
150 sub get_storage_session {
151
152         return undef; # XXX testing
153
154         if(     $storage_session and 
155                         $storage_session->connected and
156                         $storage_session->transport_connected and
157                         $storage_session->app eq 'open-ils.storage' ) {
158
159                 $logger->debug("get_storage_session(): returning existing session");
160                 return $storage_session;
161         }
162         $logger->debug("get_storage_session(): returning undef");
163         $storage_session = undef;
164         return undef;
165 }
166
167
168 sub simple_scalar_request {
169         my($self, $service, $method, @params) = @_;
170
171         my $session = undef;
172         if( $service eq 'open-ils.storage' ) {
173                 if( $session = get_storage_session() ) {
174                         $logger->debug("simple request using existing storage session ".$session->session_id);
175                 } else { $session = undef; }
176         }
177
178         $session = OpenSRF::AppSession->create( $service ) unless $session;
179
180         $logger->debug("simple request for service $service using session " .$session->app);
181
182         my $request = $session->request( $method, @params );
183         my $response = $request->recv(60);
184
185         $request->wait_complete;
186
187         if(!$request->complete) {
188                 warn "request did not complete : service=$service : method=$method\n";
189                 throw OpenSRF::EX::ERROR 
190                         ("Call to $service for method $method with params @params" . 
191                                 "\n did not complete successfully");
192         }
193
194         if(!$response) {
195                 warn "No response from $service for method $method with params @params";
196         }
197
198         if(UNIVERSAL::isa($response,"Error")) {
199                 warn "received error : service=$service : method=$method : params=".Dumper(\@params) . "\n $response";
200                 throw $response ("Call to $service for method $method with params @params" . 
201                                 "\n failed with exception: $response : " . Dumper(\@params) );
202         }
203
204
205         $request->finish();
206
207         if($service ne 'open-ils.storage' or !get_storage_session() ) {
208                 $session->finish();
209                 $session->disconnect();
210         }
211
212         my $value;
213
214         if($response) { $value = $response->content; }
215         else { $value = undef; }
216
217         return $value;
218 }
219
220
221
222
223
224 my $tree                                                = undef;
225 my $orglist                                     = undef;
226 my $org_typelist                        = undef;
227 my $org_typelist_hash   = {};
228
229 sub get_org_tree {
230
231         my $self = shift;
232         if($tree) { return $tree; }
233
234         # see if it's in the cache
235         $tree = $cache_client->new()->get_cache('_orgtree');
236         if($tree) { return $tree; }
237
238         if(!$orglist) {
239                 warn "Retrieving Org Tree\n";
240                 $orglist = $self->simple_scalar_request( 
241                         "open-ils.storage", 
242                         "open-ils.storage.direct.actor.org_unit.retrieve.all.atomic" );
243         }
244
245         if( ! $org_typelist ) {
246                 warn "Retrieving org types\n";
247                 $org_typelist = $self->simple_scalar_request( 
248                         "open-ils.storage", 
249                         "open-ils.storage.direct.actor.org_unit_type.retrieve.all.atomic" );
250                 $self->build_org_type($org_typelist);
251         }
252
253         $tree = $self->build_org_tree($orglist,1);
254         $cache_client->new()->put_cache('_orgtree', $tree);
255         return $tree;
256
257 }
258
259 my $slimtree = undef;
260 sub get_slim_org_tree {
261
262         my $self = shift;
263         if($slimtree) { return $slimtree; }
264
265         # see if it's in the cache
266         $slimtree = $cache_client->new()->get_cache('slimorgtree');
267         if($slimtree) { return $slimtree; }
268
269         if(!$orglist) {
270                 warn "Retrieving Org Tree\n";
271                 $orglist = $self->simple_scalar_request( 
272                         "open-ils.storage", 
273                         "open-ils.storage.direct.actor.org_unit.retrieve.all.atomic" );
274         }
275
276         $slimtree = $self->build_org_tree($orglist);
277         $cache_client->new->put_cache('slimorgtree', $slimtree);
278         return $slimtree;
279
280 }
281
282
283 sub build_org_type { 
284         my($self, $org_typelist)  = @_;
285         for my $type (@$org_typelist) {
286                 $org_typelist_hash->{$type->id()} = $type;
287         }
288 }
289
290
291
292 sub build_org_tree {
293
294         my( $self, $orglist, $add_types ) = @_;
295
296         return $orglist unless ( 
297                         ref($orglist) and @$orglist > 1 );
298
299         my @list = sort { 
300                 $a->ou_type <=> $b->ou_type ||
301                 $a->name cmp $b->name } @$orglist;
302
303         for my $org (@list) {
304
305                 next unless ($org);
306
307                 if(!ref($org->ou_type()) and $add_types) {
308                         $org->ou_type( $org_typelist_hash->{$org->ou_type()});
309                 }
310
311                 next unless (defined($org->parent_ou));
312
313                 my ($parent) = grep { $_->id == $org->parent_ou } @list;
314                 next unless $parent;
315                 $parent->children([]) unless defined($parent->children); 
316                 push( @{$parent->children}, $org );
317         }
318
319         return $list[0];
320
321 }
322
323 sub fetch_closed_date {
324         my( $self, $cd ) = @_;
325         my $evt;
326         
327         $logger->debug("Fetching closed_date $cd from storage");
328
329         my $cd_obj = $self->simplereq(
330                 'open-ils.storage',
331                 'open-ils.storage.direct.actor.org_unit.closed_date.retrieve', $cd );
332
333         if(!$cd_obj) {
334                 $logger->info("closed_date $cd not found in the db");
335                 $evt = OpenILS::Event->new('ACTOR_USER_NOT_FOUND');
336         }
337
338         return ($cd_obj, $evt);
339 }
340
341 sub fetch_user {
342         my( $self, $userid ) = @_;
343         my( $user, $evt );
344         
345         $logger->debug("Fetching user $userid from storage");
346
347         $user = $self->simplereq(
348                 'open-ils.storage',
349                 'open-ils.storage.direct.actor.user.retrieve', $userid );
350
351         if(!$user) {
352                 $logger->info("User $userid not found in the db");
353                 $evt = OpenILS::Event->new('ACTOR_USER_NOT_FOUND');
354         }
355
356         return ($user, $evt);
357 }
358
359 sub checkses {
360         my( $self, $session ) = @_;
361         my $user; my $evt; my $e; 
362
363         $logger->debug("Checking user session $session");
364
365         try {
366                 $user = $self->check_user_session($session);
367         } catch Error with { $e = 1; };
368
369         if( $e or !$user ) { $evt = OpenILS::Event->new('NO_SESSION'); }
370         return ( $user, $evt );
371 }
372
373
374 # verifiese the session and checks the permissions agains the
375 # session user and the user's home_ou as the org id
376 sub checksesperm {
377         my( $self, $session, @perms ) = @_;
378         my $user; my $evt; my $e; 
379         $logger->debug("Checking user session $session and perms @perms");
380         ($user, $evt) = $self->checkses($session);
381         return (undef, $evt) if $evt;
382         $evt = $self->check_perms($user->id, $user->home_ou, @perms);
383         return ($user, $evt);
384 }
385
386
387 sub checkrequestor {
388         my( $self, $staffobj, $userid, @perms ) = @_;
389         my $user; my $evt;
390         $userid = $staffobj->id unless defined $userid;
391
392         $logger->debug("checkrequestor(): requestor => " . $staffobj->id . ", target => $userid");
393
394         if( $userid ne $staffobj->id ) {
395                 ($user, $evt) = $self->fetch_user($userid);
396                 return (undef, $evt) if $evt;
397                 $evt = $self->check_perms( $staffobj->id, $user->home_ou, @perms );
398
399         } else {
400                 $user = $staffobj;
401         }
402
403         return ($user, $evt);
404 }
405
406 sub checkses_requestor {
407         my( $self, $authtoken, $targetid, @perms ) = @_;
408         my( $requestor, $target, $evt );
409
410         ($requestor, $evt) = $self->checkses($authtoken);
411         return (undef, undef, $evt) if $evt;
412
413         ($target, $evt) = $self->checkrequestor( $requestor, $targetid, @perms );
414         return( $requestor, $target, $evt);
415 }
416
417 sub fetch_copy {
418         my( $self, $copyid ) = @_;
419         my( $copy, $evt );
420
421         $logger->debug("Fetching copy $copyid from storage");
422
423         $copy = $self->simplereq(
424                 'open-ils.storage',
425                 'open-ils.storage.direct.asset.copy.retrieve', $copyid );
426
427         if(!$copy) { $evt = OpenILS::Event->new('ASSET_COPY_NOT_FOUND'); }
428
429         return( $copy, $evt );
430 }
431
432
433 # retrieves a circ object by id
434 sub fetch_circulation {
435         my( $self, $circid ) = @_;
436         my $circ; my $evt;
437         
438         $logger->debug("Fetching circ $circid from storage");
439
440         $circ = $self->simplereq(
441                 'open-ils.storage',
442                 "open-ils.storage.direct.action.circulation.retrieve", $circid );
443
444         if(!$circ) {
445                 $evt = OpenILS::Event->new('ACTION_CIRCULATION_NOT_FOUND', circid => $circid );
446         }
447
448         return ( $circ, $evt );
449 }
450
451 sub fetch_record_by_copy {
452         my( $self, $copyid ) = @_;
453         my( $record, $evt );
454
455         $logger->debug("Fetching record by copy $copyid from storage");
456
457         $record = $self->simplereq(
458                 'open-ils.storage',
459                 'open-ils.storage.fleshed.biblio.record_entry.retrieve_by_copy', $copyid );
460
461         if(!$record) {
462                 $evt = OpenILS::Event->new('BIBLIO_RECORD_ENTRY_NOT_FOUND');
463         }
464
465         return ($record, $evt);
466 }
467
468 # turns a record object into an mvr (mods) object
469 sub record_to_mvr {
470         my( $self, $record ) = @_;
471         my $u = OpenILS::Utils::ModsParser->new();
472         $u->start_mods_batch( $record->marc );
473         my $mods = $u->finish_mods_batch();
474         $mods->doc_id($record->id);
475         return $mods;
476 }
477
478 sub fetch_hold {
479         my( $self, $holdid ) = @_;
480         my( $hold, $evt );
481
482         $logger->debug("Fetching hold $holdid from storage");
483
484         $hold = $self->simplereq(
485                 'open-ils.storage',
486                 'open-ils.storage.direct.action.hold_request.retrieve', $holdid);
487
488         $evt = OpenILS::Event->new('ACTION_HOLD_REQUEST_NOT_FOUND', holdid => $holdid) unless $hold;
489
490         return ($hold, $evt);
491 }
492
493
494 sub fetch_hold_transit_by_hold {
495         my( $self, $holdid ) = @_;
496         my( $transit, $evt );
497
498         $logger->debug("Fetching transit by hold $holdid from storage");
499
500         $transit = $self->simplereq(
501                 'open-ils.storage',
502                 'open-ils.storage.direct.action.hold_transit_copy.search.hold', $holdid );
503
504         $evt = OpenILS::Event->new('ACTION_HOLD_TRANSIT_COPY_NOT_FOUND', holdid => $holdid) unless $transit;
505
506         return ($transit, $evt );
507 }
508
509 # fetches the captured, but not fulfilled hold attached to a given copy
510 sub fetch_open_hold_by_copy {
511         my( $self, $copyid ) = @_;
512         $logger->debug("Searching for active hold for copy $copyid");
513         my( $hold, $evt );
514
515         $hold = $self->storagereq(
516                 'open-ils.storage.direct.action.hold_request.search_where',
517                 { 
518                         current_copy            => $copyid , 
519                         capture_time            => { "!=" => undef }, 
520                         fulfillment_time        => undef 
521                 } );
522
523         $evt = OpenILS::Event->new('ACTION_HOLD_REQUEST_NOT_FOUND', copyid => $copyid) unless $hold;
524         return ($hold, $evt);
525 }
526
527 sub fetch_hold_transit {
528         my( $self, $transid ) = @_;
529         my( $htransit, $evt );
530         $logger->debug("Fetching hold transit with hold id $transid");
531         $htransit = $self->storagereq(
532                 'open-ils.storage.direct.action.hold_transit_copy.retrieve', $transid );
533         $evt = OpenILS::Event->new('ACTION_HOLD_TRANSIT_COPY_NOT_FOUND', id => $transid) unless $htransit;
534         return ($htransit, $evt);
535 }
536
537 sub fetch_copy_by_barcode {
538         my( $self, $barcode ) = @_;
539         my( $copy, $evt );
540
541         $logger->debug("Fetching copy by barcode $barcode from storage");
542
543         $copy = $self->simplereq( 'open-ils.storage',
544                 'open-ils.storage.direct.asset.copy.search_where', { barcode => $barcode, deleted => 'f'} );
545                 #'open-ils.storage.direct.asset.copy.search.barcode', $barcode );
546
547         $evt = OpenILS::Event->new('ASSET_COPY_NOT_FOUND', barcode => $barcode) unless $copy;
548
549         return ($copy, $evt);
550 }
551
552 sub fetch_open_billable_transaction {
553         my( $self, $transid ) = @_;
554         my( $transaction, $evt );
555
556         $logger->debug("Fetching open billable transaction $transid from storage");
557
558         $transaction = $self->simplereq(
559                 'open-ils.storage',
560                 'open-ils.storage.direct.money.open_billable_transaction_summary.retrieve',  $transid);
561
562         $evt = OpenILS::Event->new(
563                 'MONEY_OPEN_BILLABLE_TRANSACTION_SUMMARY_NOT_FOUND', transid => $transid ) unless $transaction;
564
565         return ($transaction, $evt);
566 }
567
568
569
570 my %buckets;
571 $buckets{'biblio'} = 'biblio_record_entry_bucket';
572 $buckets{'callnumber'} = 'call_number_bucket';
573 $buckets{'copy'} = 'copy_bucket';
574 $buckets{'user'} = 'user_bucket';
575
576 sub fetch_container {
577         my( $self, $id, $type ) = @_;
578         my( $bucket, $evt );
579
580         $logger->debug("Fetching container $id with type $type");
581
582         my $e = 'CONTAINER_CALL_NUMBER_BUCKET_NOT_FOUND';
583         $e = 'CONTAINER_BIBLIO_RECORD_ENTRY_BUCKET_NOT_FOUND' if $type eq 'biblio';
584         $e = 'CONTAINER_USER_BUCKET_NOT_FOUND' if $type eq 'user';
585         $e = 'CONTAINER_COPY_BUCKET_NOT_FOUND' if $type eq 'copy';
586
587         my $meth = $buckets{$type};
588         $bucket = $self->simplereq(
589                 'open-ils.storage',
590                 "open-ils.storage.direct.container.$meth.retrieve", $id );
591
592         $evt = OpenILS::Event->new(
593                 $e, container => $id, container_type => $type ) unless $bucket;
594
595         return ($bucket, $evt);
596 }
597
598
599 sub fetch_container_item {
600         my( $self, $id, $type ) = @_;
601         my( $bucket, $evt );
602
603         $logger->debug("Fetching container item $id with type $type");
604
605         my $meth = $buckets{$type} . "_item";
606
607         $bucket = $self->simplereq(
608                 'open-ils.storage',
609                 "open-ils.storage.direct.container.$meth.retrieve", $id );
610
611
612         my $e = 'CONTAINER_CALL_NUMBER_BUCKET_ITEM_NOT_FOUND';
613         $e = 'CONTAINER_BIBLIO_RECORD_ENTRY_BUCKET_ITEM_NOT_FOUND' if $type eq 'biblio';
614         $e = 'CONTAINER_USER_BUCKET_ITEM_NOT_FOUND' if $type eq 'user';
615         $e = 'CONTAINER_COPY_BUCKET_ITEM_NOT_FOUND' if $type eq 'copy';
616
617
618         $evt = OpenILS::Event->new(
619                 $e, itemid => $id, container_type => $type ) unless $bucket;
620
621         return ($bucket, $evt);
622 }
623
624
625 sub fetch_patron_standings {
626         my $self = shift;
627         $logger->debug("Fetching patron standings");    
628         return $self->simplereq(
629                 'open-ils.storage', 
630                 'open-ils.storage.direct.config.standing.retrieve.all.atomic');
631 }
632
633
634 sub fetch_permission_group_tree {
635         my $self = shift;
636         $logger->debug("Fetching patron profiles");     
637         return $self->simplereq(
638                 'open-ils.actor', 
639                 'open-ils.actor.groups.tree.retrieve' );
640 }
641
642
643 sub fetch_patron_circ_summary {
644         my( $self, $userid ) = @_;
645         $logger->debug("Fetching patron summary for $userid");
646         my $summary = $self->simplereq(
647                 'open-ils.storage', 
648                 "open-ils.storage.action.circulation.patron_summary", $userid );
649
650         if( $summary ) {
651                 $summary->[0] ||= 0;
652                 $summary->[1] ||= 0.0;
653                 return $summary;
654         }
655         return undef;
656 }
657
658
659 sub fetch_copy_statuses {
660         my( $self ) = @_;
661         $logger->debug("Fetching copy statuses");
662         return $self->simplereq(
663                 'open-ils.storage', 
664                 'open-ils.storage.direct.config.copy_status.retrieve.all.atomic' );
665 }
666
667 sub fetch_copy_location {
668         my( $self, $id ) = @_;
669         my $evt;
670         my $cl = $self->storagereq(
671                 'open-ils.storage.direct.asset.copy_location.retrieve', $id );
672         $evt = OpenILS::Event->new('ASSET_COPY_LOCATION_NOT_FOUND') unless $cl;
673         return ($cl, $evt);
674 }
675
676 sub fetch_copy_locations {
677         my $self = shift; 
678         return $self->simplereq(
679                 'open-ils.storage', 
680                 'open-ils.storage.direct.asset.copy_location.retrieve.all.atomic');
681 }
682
683 sub fetch_copy_location_by_name {
684         my( $self, $name, $org ) = @_;
685         my $evt;
686         my $cl = $self->storagereq(
687                 'open-ils.storage.direct.asset.copy_location.search_where',
688                         { name => $name, owning_lib => $org } );
689         $evt = OpenILS::Event->new('ASSET_COPY_LOCATION_NOT_FOUND') unless $cl;
690         return ($cl, $evt);
691 }
692
693 sub fetch_callnumber {
694         my( $self, $id ) = @_;
695         my $evt = undef;
696         $logger->debug("Fetching callnumber $id");
697
698         my $cn = $self->simplereq(
699                 'open-ils.storage',
700                 'open-ils.storage.direct.asset.call_number.retrieve', $id );
701         $evt = OpenILS::Event->new( 'ASSET_CALL_NUMBER_NOT_FOUND', id => $id ) unless $cn;
702
703         return ( $cn, $evt );
704 }
705
706 my %ORG_CACHE; # - these rarely change, so cache them..
707 sub fetch_org_unit {
708         my( $self, $id ) = @_;
709         return $id if( ref($id) eq 'Fieldmapper::actor::org_unit' );
710         return $ORG_CACHE{$id} if $ORG_CACHE{$id};
711         $logger->debug("Fetching org unit $id");
712         my $evt = undef;
713
714         my $org = $self->simplereq(
715                 'open-ils.storage', 
716                 'open-ils.storage.direct.actor.org_unit.retrieve', $id );
717         $evt = OpenILS::Event->new( 'ACTOR_ORG_UNIT_NOT_FOUND', id => $id ) unless $org;
718         $ORG_CACHE{$id}  = $org;
719
720         return ($org, $evt);
721 }
722
723 sub fetch_stat_cat {
724         my( $self, $type, $id ) = @_;
725         my( $cat, $evt );
726         $logger->debug("Fetching $type stat cat: $id");
727         $cat = $self->simplereq(
728                 'open-ils.storage', 
729                 "open-ils.storage.direct.$type.stat_cat.retrieve", $id );
730
731         my $e = 'ASSET_STAT_CAT_NOT_FOUND';
732         $e = 'ACTOR_STAT_CAT_NOT_FOUND' if $type eq 'actor';
733
734         $evt = OpenILS::Event->new( $e, id => $id ) unless $cat;
735         return ( $cat, $evt );
736 }
737
738 sub fetch_stat_cat_entry {
739         my( $self, $type, $id ) = @_;
740         my( $entry, $evt );
741         $logger->debug("Fetching $type stat cat entry: $id");
742         $entry = $self->simplereq(
743                 'open-ils.storage', 
744                 "open-ils.storage.direct.$type.stat_cat_entry.retrieve", $id );
745
746         my $e = 'ASSET_STAT_CAT_ENTRY_NOT_FOUND';
747         $e = 'ACTOR_STAT_CAT_ENTRY_NOT_FOUND' if $type eq 'actor';
748
749         $evt = OpenILS::Event->new( $e, id => $id ) unless $entry;
750         return ( $entry, $evt );
751 }
752
753
754 sub find_org {
755         my( $self, $org_tree, $orgid )  = @_;
756         return $org_tree if ( $org_tree->id eq $orgid );
757         return undef unless ref($org_tree->children);
758         for my $c (@{$org_tree->children}) {
759                 my $o = $self->find_org($c, $orgid);
760                 return $o if $o;
761         }
762         return undef;
763 }
764
765 sub fetch_non_cat_type_by_name_and_org {
766         my( $self, $name, $orgId ) = @_;
767         $logger->debug("Fetching non cat type $name at org $orgId");
768         my $types = $self->simplereq(
769                 'open-ils.storage',
770                 'open-ils.storage.direct.config.non_cataloged_type.search_where.atomic',
771                 { name => $name, owning_lib => $orgId } );
772         return ($types->[0], undef) if($types and @$types);
773         return (undef, OpenILS::Event->new('CONFIG_NON_CATALOGED_TYPE_NOT_FOUND') );
774 }
775
776 sub fetch_non_cat_type {
777         my( $self, $id ) = @_;
778         $logger->debug("Fetching non cat type $id");
779         my( $type, $evt );
780         $type = $self->simplereq(
781                 'open-ils.storage', 
782                 'open-ils.storage.direct.config.non_cataloged_type.retrieve', $id );
783         $evt = OpenILS::Event->new('CONFIG_NON_CATALOGED_TYPE_NOT_FOUND') unless $type;
784         return ($type, $evt);
785 }
786
787 sub DB_UPDATE_FAILED { 
788         my( $self, $payload ) = @_;
789         return OpenILS::Event->new('DATABASE_UPDATE_FAILED', 
790                 payload => ($payload) ? $payload : undef ); 
791 }
792
793 sub fetch_circ_duration_by_name {
794         my( $self, $name ) = @_;
795         my( $dur, $evt );
796         $dur = $self->simplereq(
797                 'open-ils.storage', 
798                 'open-ils.storage.direct.config.rules.circ_duration.search.name.atomic', $name );
799         $dur = $dur->[0];
800         $evt = OpenILS::Event->new('CONFIG_RULES_CIRC_DURATION_NOT_FOUND') unless $dur;
801         return ($dur, $evt);
802 }
803
804 sub fetch_recurring_fine_by_name {
805         my( $self, $name ) = @_;
806         my( $obj, $evt );
807         $obj = $self->simplereq(
808                 'open-ils.storage', 
809                 'open-ils.storage.direct.config.rules.recuring_fine.search.name.atomic', $name );
810         $obj = $obj->[0];
811         $evt = OpenILS::Event->new('CONFIG_RULES_RECURING_FINE_NOT_FOUND') unless $obj;
812         return ($obj, $evt);
813 }
814
815 sub fetch_max_fine_by_name {
816         my( $self, $name ) = @_;
817         my( $obj, $evt );
818         $obj = $self->simplereq(
819                 'open-ils.storage', 
820                 'open-ils.storage.direct.config.rules.max_fine.search.name.atomic', $name );
821         $obj = $obj->[0];
822         $evt = OpenILS::Event->new('CONFIG_RULES_MAX_FINE_NOT_FOUND') unless $obj;
823         return ($obj, $evt);
824 }
825
826 sub storagereq {
827         my( $self, $method, @params ) = @_;
828         return $self->simplereq(
829                 'open-ils.storage', $method, @params );
830 }
831
832 sub event_equals {
833         my( $self, $e, $name ) =  @_;
834         if( $e and ref($e) eq 'HASH' and 
835                 defined($e->{textcode}) and $e->{textcode} eq $name ) {
836                 return 1 ;
837         }
838         return 0;
839 }
840
841 sub logmark {
842         my( undef, $f, $l ) = caller(0);
843         my( undef, undef, undef, $s ) = caller(1);
844         $s =~ s/.*:://g;
845         $f =~ s/.*\///g;
846         $logger->debug("LOGMARK: $f:$l:$s");
847 }
848
849 # takes a copy id 
850 sub fetch_open_circulation {
851         my( $self, $cid ) = @_;
852         my $evt;
853         $self->logmark;
854         my $circ = $self->storagereq(
855                 'open-ils.storage.direct.action.open_circulation.search_where',
856                 { target_copy => $cid, stop_fines_time => undef } );
857         $evt = OpenILS::Event->new('ACTION_CIRCULATION_NOT_FOUND') unless $circ;        
858         return ($circ, $evt);
859 }
860
861 my $copy_statuses;
862 sub copy_status_from_name {
863         my( $self, $name ) = @_;
864         $copy_statuses = $self->fetch_copy_statuses unless $copy_statuses;
865         for my $status (@$copy_statuses) { 
866                 return $status if( $status->name =~ /$name/i );
867         }
868         return undef;
869 }
870
871 sub copy_status_to_name {
872         my( $self, $sid ) = @_;
873         $copy_statuses = $self->fetch_copy_statuses unless $copy_statuses;
874         for my $status (@$copy_statuses) { 
875                 return $status->name if( $status->id == $sid );
876         }
877         return undef;
878 }
879
880 sub fetch_open_transit_by_copy {
881         my( $self, $copyid ) = @_;
882         my($transit, $evt);
883         $transit = $self->storagereq(
884                 'open-ils.storage.direct.action.transit_copy.search_where',
885                 { target_copy => $copyid, dest_recv_time => undef });
886         $evt = OpenILS::Event->new('ACTION_TRANSIT_COPY_NOT_FOUND') unless $transit;
887         return ($transit, $evt);
888 }
889
890 sub unflesh_copy {
891         my( $self, $copy ) = @_;
892         return undef unless $copy;
893         $copy->status( $copy->status->id ) if ref($copy->status);
894         $copy->location( $copy->location->id ) if ref($copy->location);
895         $copy->circ_lib( $copy->circ_lib->id ) if ref($copy->circ_lib);
896         return $copy;
897 }
898
899 # un-fleshes a copy and updates it in the DB
900 # returns a DB_UPDATE_FAILED event on error
901 # returns undef on success
902 sub update_copy {
903         my( $self, %params ) = @_;
904
905         my $copy                = $params{copy} || die "update_copy(): copy required";
906         my $editor      = $params{editor} || die "update_copy(): copy editor required";
907         my $session = $params{session};
908
909         $logger->debug("Updating copy in the database: " . $copy->id);
910
911         $self->unflesh_copy($copy);
912         $copy->editor( $editor );
913         $copy->edit_date( 'now' );
914
915         my $s;
916         my $meth = 'open-ils.storage.direct.asset.copy.update';
917
918         $s = $session->request( $meth, $copy )->gather(1) if $session;
919         $s = $self->storagereq( $meth, $copy ) unless $session;
920
921         $logger->debug("Update of copy ".$copy->id." returned: $s");
922
923         return $self->DB_UPDATE_FAILED($copy) unless $s;
924         return undef;
925 }
926
927 sub fetch_billable_xact {
928         my( $self, $id ) = @_;
929         my($xact, $evt);
930         $logger->debug("Fetching billable transaction %id");
931         $xact = $self->storagereq(
932                 'open-ils.storage.direct.money.billable_transaction.retrieve', $id );
933         $evt = OpenILS::Event->new('MONEY_BILLABLE_TRANSACTION_NOT_FOUND') unless $xact;
934         return ($xact, $evt);
935 }
936
937
938 sub fetch_fleshed_copy {
939         my( $self, $id ) = @_;
940         my( $copy, $evt );
941         $logger->info("Fetching fleshed copy $id");
942         $copy = $self->storagereq(
943                 "open-ils.storage.fleshed.asset.copy.retrieve", $id );
944         $evt = OpenILS::Event->new('ASSET_COPY_NOT_FOUND', id => $id) unless $copy;
945         return ($copy, $evt);
946 }
947
948
949 # returns the org that owns the callnumber that the copy
950 # is attached to
951 sub fetch_copy_owner {
952         my( $self, $copyid ) = @_;
953         my( $copy, $cn, $evt );
954         $logger->debug("Fetching copy owner $copyid");
955         ($copy, $evt) = $self->fetch_copy($copyid);
956         return (undef,$evt) if $evt;
957         ($cn, $evt) = $self->fetch_callnumber($copy->call_number);
958         return (undef,$evt) if $evt;
959         return ($cn->owning_lib);
960 }
961
962 sub fetch_copy_note {
963         my( $self, $id ) = @_;
964         my( $note, $evt );
965         $logger->debug("Fetching copy note $id");
966         $note = $self->storagereq(
967                 'open-ils.storage.direct.asset.copy_note.retrieve', $id );
968         $evt = OpenILS::Event->new('ASSET_COPY_NOTE_NOT_FOUND', id => $id ) unless $note;
969         return ($note, $evt);
970 }
971
972 sub fetch_call_numbers_by_title {
973         my( $self, $titleid ) = @_;
974         $logger->info("Fetching call numbers by title $titleid");
975         return $self->storagereq(
976                 'open-ils.storage.direct.asset.call_number.search_where.atomic', 
977                 { record => $titleid, deleted => 'f' });
978                 #'open-ils.storage.direct.asset.call_number.search.record.atomic', $titleid);
979 }
980
981 sub fetch_copies_by_call_number {
982         my( $self, $cnid ) = @_;
983         $logger->info("Fetching copies by call number $cnid");
984         return $self->storagereq(
985                 'open-ils.storage.direct.asset.copy.search_where.atomic', { call_number => $cnid, deleted => 'f' } );
986                 #'open-ils.storage.direct.asset.copy.search.call_number.atomic', $cnid );
987 }
988
989 sub fetch_user_by_barcode {
990         my( $self, $bc ) = @_;
991         my $cardid = $self->storagereq(
992                 'open-ils.storage.id_list.actor.card.search.barcode', $bc );
993         return (undef, OpenILS::Event->new('ACTOR_CARD_NOT_FOUND', barcode => $bc)) unless $cardid;
994         my $user = $self->storagereq(
995                 'open-ils.storage.direct.actor.user.search.card', $cardid );
996         return (undef, OpenILS::Event->new('ACTOR_USER_NOT_FOUND', card => $cardid)) unless $user;
997         return ($user);
998         
999 }
1000
1001
1002 # ---------------------------------------------------------------------
1003 # Updates and returns the patron penalties
1004 # ---------------------------------------------------------------------
1005 sub update_patron_penalties {
1006         my( $self, %args ) = @_;
1007         return $self->simplereq(
1008                 'open-ils.penalty',
1009                 'open-ils.penalty.patron_penalty.calculate', 
1010                 { update => 1, %args }
1011         );
1012 }
1013
1014 sub fetch_bill {
1015         my( $self, $billid ) = @_;
1016         $logger->debug("Fetching billing $billid");
1017         my $bill = $self->storagereq(
1018                 'open-ils.storage.direct.money.billing.retrieve', $billid );
1019         my $evt = OpenILS::Event->new('MONEY_BILLING_NOT_FOUND') unless $bill;
1020         return($bill, $evt);
1021 }
1022
1023
1024
1025
1026 1;
1027