]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/OpenILS/Application/AppUtils.pm
slimmed down the generic requestor
[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
173         if( $service eq 'open-ils.storage' ) {
174                 if( $session = get_storage_session() ) {
175                         $logger->debug("simple request using existing storage session ".$session->session_id);
176                 } else { $session = undef; }
177         }
178
179         $session = OpenSRF::AppSession->create( $service ) unless $session;
180
181         my $request = $session->request( $method, @params );
182
183         my $val;
184         my $err;
185         try  {
186
187                 $val = $request->gather(1);     
188
189         } catch Error with {
190                 $err = shift;
191         };
192
193         if( $err ) {
194                 warn "received error : service=$service : method=$method : params=".Dumper(\@params) . "\n $err";
195                 throw $err ("Call to $service for method $method \n failed with exception: $err : " );
196         }
197
198         return $val;
199 }
200
201
202
203
204
205 my $tree                                                = undef;
206 my $orglist                                     = undef;
207 my $org_typelist                        = undef;
208 my $org_typelist_hash   = {};
209
210 sub get_org_tree {
211
212         my $self = shift;
213         if($tree) { return $tree; }
214
215         # see if it's in the cache
216         $tree = $cache_client->new()->get_cache('_orgtree');
217         if($tree) { return $tree; }
218
219         if(!$orglist) {
220                 warn "Retrieving Org Tree\n";
221                 $orglist = $self->simple_scalar_request( 
222                         "open-ils.storage", 
223                         "open-ils.storage.direct.actor.org_unit.retrieve.all.atomic" );
224         }
225
226         if( ! $org_typelist ) {
227                 warn "Retrieving org types\n";
228                 $org_typelist = $self->simple_scalar_request( 
229                         "open-ils.storage", 
230                         "open-ils.storage.direct.actor.org_unit_type.retrieve.all.atomic" );
231                 $self->build_org_type($org_typelist);
232         }
233
234         $tree = $self->build_org_tree($orglist,1);
235         $cache_client->new()->put_cache('_orgtree', $tree);
236         return $tree;
237
238 }
239
240 my $slimtree = undef;
241 sub get_slim_org_tree {
242
243         my $self = shift;
244         if($slimtree) { return $slimtree; }
245
246         # see if it's in the cache
247         $slimtree = $cache_client->new()->get_cache('slimorgtree');
248         if($slimtree) { return $slimtree; }
249
250         if(!$orglist) {
251                 warn "Retrieving Org Tree\n";
252                 $orglist = $self->simple_scalar_request( 
253                         "open-ils.storage", 
254                         "open-ils.storage.direct.actor.org_unit.retrieve.all.atomic" );
255         }
256
257         $slimtree = $self->build_org_tree($orglist);
258         $cache_client->new->put_cache('slimorgtree', $slimtree);
259         return $slimtree;
260
261 }
262
263
264 sub build_org_type { 
265         my($self, $org_typelist)  = @_;
266         for my $type (@$org_typelist) {
267                 $org_typelist_hash->{$type->id()} = $type;
268         }
269 }
270
271
272
273 sub build_org_tree {
274
275         my( $self, $orglist, $add_types ) = @_;
276
277         return $orglist unless ( 
278                         ref($orglist) and @$orglist > 1 );
279
280         my @list = sort { 
281                 $a->ou_type <=> $b->ou_type ||
282                 $a->name cmp $b->name } @$orglist;
283
284         for my $org (@list) {
285
286                 next unless ($org);
287
288                 if(!ref($org->ou_type()) and $add_types) {
289                         $org->ou_type( $org_typelist_hash->{$org->ou_type()});
290                 }
291
292                 next unless (defined($org->parent_ou));
293
294                 my ($parent) = grep { $_->id == $org->parent_ou } @list;
295                 next unless $parent;
296                 $parent->children([]) unless defined($parent->children); 
297                 push( @{$parent->children}, $org );
298         }
299
300         return $list[0];
301
302 }
303
304 sub fetch_closed_date {
305         my( $self, $cd ) = @_;
306         my $evt;
307         
308         $logger->debug("Fetching closed_date $cd from storage");
309
310         my $cd_obj = $self->simplereq(
311                 'open-ils.storage',
312                 'open-ils.storage.direct.actor.org_unit.closed_date.retrieve', $cd );
313
314         if(!$cd_obj) {
315                 $logger->info("closed_date $cd not found in the db");
316                 $evt = OpenILS::Event->new('ACTOR_USER_NOT_FOUND');
317         }
318
319         return ($cd_obj, $evt);
320 }
321
322 sub fetch_user {
323         my( $self, $userid ) = @_;
324         my( $user, $evt );
325         
326         $logger->debug("Fetching user $userid from storage");
327
328         $user = $self->simplereq(
329                 'open-ils.storage',
330                 'open-ils.storage.direct.actor.user.retrieve', $userid );
331
332         if(!$user) {
333                 $logger->info("User $userid not found in the db");
334                 $evt = OpenILS::Event->new('ACTOR_USER_NOT_FOUND');
335         }
336
337         return ($user, $evt);
338 }
339
340 sub checkses {
341         my( $self, $session ) = @_;
342         my $user; my $evt; my $e; 
343
344         $logger->debug("Checking user session $session");
345
346         try {
347                 $user = $self->check_user_session($session);
348         } catch Error with { $e = 1; };
349
350         if( $e or !$user ) { $evt = OpenILS::Event->new('NO_SESSION'); }
351         return ( $user, $evt );
352 }
353
354
355 # verifiese the session and checks the permissions agains the
356 # session user and the user's home_ou as the org id
357 sub checksesperm {
358         my( $self, $session, @perms ) = @_;
359         my $user; my $evt; my $e; 
360         $logger->debug("Checking user session $session and perms @perms");
361         ($user, $evt) = $self->checkses($session);
362         return (undef, $evt) if $evt;
363         $evt = $self->check_perms($user->id, $user->home_ou, @perms);
364         return ($user, $evt);
365 }
366
367
368 sub checkrequestor {
369         my( $self, $staffobj, $userid, @perms ) = @_;
370         my $user; my $evt;
371         $userid = $staffobj->id unless defined $userid;
372
373         $logger->debug("checkrequestor(): requestor => " . $staffobj->id . ", target => $userid");
374
375         if( $userid ne $staffobj->id ) {
376                 ($user, $evt) = $self->fetch_user($userid);
377                 return (undef, $evt) if $evt;
378                 $evt = $self->check_perms( $staffobj->id, $user->home_ou, @perms );
379
380         } else {
381                 $user = $staffobj;
382         }
383
384         return ($user, $evt);
385 }
386
387 sub checkses_requestor {
388         my( $self, $authtoken, $targetid, @perms ) = @_;
389         my( $requestor, $target, $evt );
390
391         ($requestor, $evt) = $self->checkses($authtoken);
392         return (undef, undef, $evt) if $evt;
393
394         ($target, $evt) = $self->checkrequestor( $requestor, $targetid, @perms );
395         return( $requestor, $target, $evt);
396 }
397
398 sub fetch_copy {
399         my( $self, $copyid ) = @_;
400         my( $copy, $evt );
401
402         $logger->debug("Fetching copy $copyid from storage");
403
404         $copy = $self->simplereq(
405                 'open-ils.storage',
406                 'open-ils.storage.direct.asset.copy.retrieve', $copyid );
407
408         if(!$copy) { $evt = OpenILS::Event->new('ASSET_COPY_NOT_FOUND'); }
409
410         return( $copy, $evt );
411 }
412
413
414 # retrieves a circ object by id
415 sub fetch_circulation {
416         my( $self, $circid ) = @_;
417         my $circ; my $evt;
418         
419         $logger->debug("Fetching circ $circid from storage");
420
421         $circ = $self->simplereq(
422                 'open-ils.storage',
423                 "open-ils.storage.direct.action.circulation.retrieve", $circid );
424
425         if(!$circ) {
426                 $evt = OpenILS::Event->new('ACTION_CIRCULATION_NOT_FOUND', circid => $circid );
427         }
428
429         return ( $circ, $evt );
430 }
431
432 sub fetch_record_by_copy {
433         my( $self, $copyid ) = @_;
434         my( $record, $evt );
435
436         $logger->debug("Fetching record by copy $copyid from storage");
437
438         $record = $self->simplereq(
439                 'open-ils.storage',
440                 'open-ils.storage.fleshed.biblio.record_entry.retrieve_by_copy', $copyid );
441
442         if(!$record) {
443                 $evt = OpenILS::Event->new('BIBLIO_RECORD_ENTRY_NOT_FOUND');
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         my $u = OpenILS::Utils::ModsParser->new();
453         $u->start_mods_batch( $record->marc );
454         my $mods = $u->finish_mods_batch();
455         $mods->doc_id($record->id);
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 storage");
464
465         $hold = $self->simplereq(
466                 'open-ils.storage',
467                 'open-ils.storage.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 storage");
480
481         $transit = $self->simplereq(
482                 'open-ils.storage',
483                 'open-ils.storage.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->storagereq(
497                 'open-ils.storage.direct.action.hold_request.search_where',
498                 { 
499                         current_copy            => $copyid , 
500                         capture_time            => { "!=" => undef }, 
501                         fulfillment_time        => undef 
502                 } );
503
504         $evt = OpenILS::Event->new('ACTION_HOLD_REQUEST_NOT_FOUND', copyid => $copyid) unless $hold;
505         return ($hold, $evt);
506 }
507
508 sub fetch_hold_transit {
509         my( $self, $transid ) = @_;
510         my( $htransit, $evt );
511         $logger->debug("Fetching hold transit with hold id $transid");
512         $htransit = $self->storagereq(
513                 'open-ils.storage.direct.action.hold_transit_copy.retrieve', $transid );
514         $evt = OpenILS::Event->new('ACTION_HOLD_TRANSIT_COPY_NOT_FOUND', id => $transid) unless $htransit;
515         return ($htransit, $evt);
516 }
517
518 sub fetch_copy_by_barcode {
519         my( $self, $barcode ) = @_;
520         my( $copy, $evt );
521
522         $logger->debug("Fetching copy by barcode $barcode from storage");
523
524         $copy = $self->simplereq( 'open-ils.storage',
525                 'open-ils.storage.direct.asset.copy.search_where', { barcode => $barcode, deleted => 'f'} );
526                 #'open-ils.storage.direct.asset.copy.search.barcode', $barcode );
527
528         $evt = OpenILS::Event->new('ASSET_COPY_NOT_FOUND', barcode => $barcode) unless $copy;
529
530         return ($copy, $evt);
531 }
532
533 sub fetch_open_billable_transaction {
534         my( $self, $transid ) = @_;
535         my( $transaction, $evt );
536
537         $logger->debug("Fetching open billable transaction $transid from storage");
538
539         $transaction = $self->simplereq(
540                 'open-ils.storage',
541                 'open-ils.storage.direct.money.open_billable_transaction_summary.retrieve',  $transid);
542
543         $evt = OpenILS::Event->new(
544                 'MONEY_OPEN_BILLABLE_TRANSACTION_SUMMARY_NOT_FOUND', transid => $transid ) unless $transaction;
545
546         return ($transaction, $evt);
547 }
548
549
550
551 my %buckets;
552 $buckets{'biblio'} = 'biblio_record_entry_bucket';
553 $buckets{'callnumber'} = 'call_number_bucket';
554 $buckets{'copy'} = 'copy_bucket';
555 $buckets{'user'} = 'user_bucket';
556
557 sub fetch_container {
558         my( $self, $id, $type ) = @_;
559         my( $bucket, $evt );
560
561         $logger->debug("Fetching container $id with type $type");
562
563         my $e = 'CONTAINER_CALL_NUMBER_BUCKET_NOT_FOUND';
564         $e = 'CONTAINER_BIBLIO_RECORD_ENTRY_BUCKET_NOT_FOUND' if $type eq 'biblio';
565         $e = 'CONTAINER_USER_BUCKET_NOT_FOUND' if $type eq 'user';
566         $e = 'CONTAINER_COPY_BUCKET_NOT_FOUND' if $type eq 'copy';
567
568         my $meth = $buckets{$type};
569         $bucket = $self->simplereq(
570                 'open-ils.storage',
571                 "open-ils.storage.direct.container.$meth.retrieve", $id );
572
573         $evt = OpenILS::Event->new(
574                 $e, container => $id, container_type => $type ) unless $bucket;
575
576         return ($bucket, $evt);
577 }
578
579
580 sub fetch_container_item {
581         my( $self, $id, $type ) = @_;
582         my( $bucket, $evt );
583
584         $logger->debug("Fetching container item $id with type $type");
585
586         my $meth = $buckets{$type} . "_item";
587
588         $bucket = $self->simplereq(
589                 'open-ils.storage',
590                 "open-ils.storage.direct.container.$meth.retrieve", $id );
591
592
593         my $e = 'CONTAINER_CALL_NUMBER_BUCKET_ITEM_NOT_FOUND';
594         $e = 'CONTAINER_BIBLIO_RECORD_ENTRY_BUCKET_ITEM_NOT_FOUND' if $type eq 'biblio';
595         $e = 'CONTAINER_USER_BUCKET_ITEM_NOT_FOUND' if $type eq 'user';
596         $e = 'CONTAINER_COPY_BUCKET_ITEM_NOT_FOUND' if $type eq 'copy';
597
598
599         $evt = OpenILS::Event->new(
600                 $e, itemid => $id, container_type => $type ) unless $bucket;
601
602         return ($bucket, $evt);
603 }
604
605
606 sub fetch_patron_standings {
607         my $self = shift;
608         $logger->debug("Fetching patron standings");    
609         return $self->simplereq(
610                 'open-ils.storage', 
611                 'open-ils.storage.direct.config.standing.retrieve.all.atomic');
612 }
613
614
615 sub fetch_permission_group_tree {
616         my $self = shift;
617         $logger->debug("Fetching patron profiles");     
618         return $self->simplereq(
619                 'open-ils.actor', 
620                 'open-ils.actor.groups.tree.retrieve' );
621 }
622
623
624 sub fetch_patron_circ_summary {
625         my( $self, $userid ) = @_;
626         $logger->debug("Fetching patron summary for $userid");
627         my $summary = $self->simplereq(
628                 'open-ils.storage', 
629                 "open-ils.storage.action.circulation.patron_summary", $userid );
630
631         if( $summary ) {
632                 $summary->[0] ||= 0;
633                 $summary->[1] ||= 0.0;
634                 return $summary;
635         }
636         return undef;
637 }
638
639
640 sub fetch_copy_statuses {
641         my( $self ) = @_;
642         $logger->debug("Fetching copy statuses");
643         return $self->simplereq(
644                 'open-ils.storage', 
645                 'open-ils.storage.direct.config.copy_status.retrieve.all.atomic' );
646 }
647
648 sub fetch_copy_location {
649         my( $self, $id ) = @_;
650         my $evt;
651         my $cl = $self->storagereq(
652                 'open-ils.storage.direct.asset.copy_location.retrieve', $id );
653         $evt = OpenILS::Event->new('ASSET_COPY_LOCATION_NOT_FOUND') unless $cl;
654         return ($cl, $evt);
655 }
656
657 sub fetch_copy_locations {
658         my $self = shift; 
659         return $self->simplereq(
660                 'open-ils.storage', 
661                 'open-ils.storage.direct.asset.copy_location.retrieve.all.atomic');
662 }
663
664 sub fetch_copy_location_by_name {
665         my( $self, $name, $org ) = @_;
666         my $evt;
667         my $cl = $self->storagereq(
668                 'open-ils.storage.direct.asset.copy_location.search_where',
669                         { name => $name, owning_lib => $org } );
670         $evt = OpenILS::Event->new('ASSET_COPY_LOCATION_NOT_FOUND') unless $cl;
671         return ($cl, $evt);
672 }
673
674 sub fetch_callnumber {
675         my( $self, $id ) = @_;
676         my $evt = undef;
677         $logger->debug("Fetching callnumber $id");
678
679         my $cn = $self->simplereq(
680                 'open-ils.storage',
681                 'open-ils.storage.direct.asset.call_number.retrieve', $id );
682         $evt = OpenILS::Event->new( 'ASSET_CALL_NUMBER_NOT_FOUND', id => $id ) unless $cn;
683
684         return ( $cn, $evt );
685 }
686
687 my %ORG_CACHE; # - these rarely change, so cache them..
688 sub fetch_org_unit {
689         my( $self, $id ) = @_;
690         return $id if( ref($id) eq 'Fieldmapper::actor::org_unit' );
691         return $ORG_CACHE{$id} if $ORG_CACHE{$id};
692         $logger->debug("Fetching org unit $id");
693         my $evt = undef;
694
695         my $org = $self->simplereq(
696                 'open-ils.storage', 
697                 'open-ils.storage.direct.actor.org_unit.retrieve', $id );
698         $evt = OpenILS::Event->new( 'ACTOR_ORG_UNIT_NOT_FOUND', id => $id ) unless $org;
699         $ORG_CACHE{$id}  = $org;
700
701         return ($org, $evt);
702 }
703
704 sub fetch_stat_cat {
705         my( $self, $type, $id ) = @_;
706         my( $cat, $evt );
707         $logger->debug("Fetching $type stat cat: $id");
708         $cat = $self->simplereq(
709                 'open-ils.storage', 
710                 "open-ils.storage.direct.$type.stat_cat.retrieve", $id );
711
712         my $e = 'ASSET_STAT_CAT_NOT_FOUND';
713         $e = 'ACTOR_STAT_CAT_NOT_FOUND' if $type eq 'actor';
714
715         $evt = OpenILS::Event->new( $e, id => $id ) unless $cat;
716         return ( $cat, $evt );
717 }
718
719 sub fetch_stat_cat_entry {
720         my( $self, $type, $id ) = @_;
721         my( $entry, $evt );
722         $logger->debug("Fetching $type stat cat entry: $id");
723         $entry = $self->simplereq(
724                 'open-ils.storage', 
725                 "open-ils.storage.direct.$type.stat_cat_entry.retrieve", $id );
726
727         my $e = 'ASSET_STAT_CAT_ENTRY_NOT_FOUND';
728         $e = 'ACTOR_STAT_CAT_ENTRY_NOT_FOUND' if $type eq 'actor';
729
730         $evt = OpenILS::Event->new( $e, id => $id ) unless $entry;
731         return ( $entry, $evt );
732 }
733
734
735 sub find_org {
736         my( $self, $org_tree, $orgid )  = @_;
737         return $org_tree if ( $org_tree->id eq $orgid );
738         return undef unless ref($org_tree->children);
739         for my $c (@{$org_tree->children}) {
740                 my $o = $self->find_org($c, $orgid);
741                 return $o if $o;
742         }
743         return undef;
744 }
745
746 sub fetch_non_cat_type_by_name_and_org {
747         my( $self, $name, $orgId ) = @_;
748         $logger->debug("Fetching non cat type $name at org $orgId");
749         my $types = $self->simplereq(
750                 'open-ils.storage',
751                 'open-ils.storage.direct.config.non_cataloged_type.search_where.atomic',
752                 { name => $name, owning_lib => $orgId } );
753         return ($types->[0], undef) if($types and @$types);
754         return (undef, OpenILS::Event->new('CONFIG_NON_CATALOGED_TYPE_NOT_FOUND') );
755 }
756
757 sub fetch_non_cat_type {
758         my( $self, $id ) = @_;
759         $logger->debug("Fetching non cat type $id");
760         my( $type, $evt );
761         $type = $self->simplereq(
762                 'open-ils.storage', 
763                 'open-ils.storage.direct.config.non_cataloged_type.retrieve', $id );
764         $evt = OpenILS::Event->new('CONFIG_NON_CATALOGED_TYPE_NOT_FOUND') unless $type;
765         return ($type, $evt);
766 }
767
768 sub DB_UPDATE_FAILED { 
769         my( $self, $payload ) = @_;
770         return OpenILS::Event->new('DATABASE_UPDATE_FAILED', 
771                 payload => ($payload) ? $payload : undef ); 
772 }
773
774 sub fetch_circ_duration_by_name {
775         my( $self, $name ) = @_;
776         my( $dur, $evt );
777         $dur = $self->simplereq(
778                 'open-ils.storage', 
779                 'open-ils.storage.direct.config.rules.circ_duration.search.name.atomic', $name );
780         $dur = $dur->[0];
781         $evt = OpenILS::Event->new('CONFIG_RULES_CIRC_DURATION_NOT_FOUND') unless $dur;
782         return ($dur, $evt);
783 }
784
785 sub fetch_recurring_fine_by_name {
786         my( $self, $name ) = @_;
787         my( $obj, $evt );
788         $obj = $self->simplereq(
789                 'open-ils.storage', 
790                 'open-ils.storage.direct.config.rules.recuring_fine.search.name.atomic', $name );
791         $obj = $obj->[0];
792         $evt = OpenILS::Event->new('CONFIG_RULES_RECURING_FINE_NOT_FOUND') unless $obj;
793         return ($obj, $evt);
794 }
795
796 sub fetch_max_fine_by_name {
797         my( $self, $name ) = @_;
798         my( $obj, $evt );
799         $obj = $self->simplereq(
800                 'open-ils.storage', 
801                 'open-ils.storage.direct.config.rules.max_fine.search.name.atomic', $name );
802         $obj = $obj->[0];
803         $evt = OpenILS::Event->new('CONFIG_RULES_MAX_FINE_NOT_FOUND') unless $obj;
804         return ($obj, $evt);
805 }
806
807 sub storagereq {
808         my( $self, $method, @params ) = @_;
809         return $self->simplereq(
810                 'open-ils.storage', $method, @params );
811 }
812
813 sub event_equals {
814         my( $self, $e, $name ) =  @_;
815         if( $e and ref($e) eq 'HASH' and 
816                 defined($e->{textcode}) and $e->{textcode} eq $name ) {
817                 return 1 ;
818         }
819         return 0;
820 }
821
822 sub logmark {
823         my( undef, $f, $l ) = caller(0);
824         my( undef, undef, undef, $s ) = caller(1);
825         $s =~ s/.*:://g;
826         $f =~ s/.*\///g;
827         $logger->debug("LOGMARK: $f:$l:$s");
828 }
829
830 # takes a copy id 
831 sub fetch_open_circulation {
832         my( $self, $cid ) = @_;
833         my $evt;
834         $self->logmark;
835         my $circ = $self->storagereq(
836                 'open-ils.storage.direct.action.open_circulation.search_where',
837                 { target_copy => $cid, stop_fines_time => undef } );
838         $evt = OpenILS::Event->new('ACTION_CIRCULATION_NOT_FOUND') unless $circ;        
839         return ($circ, $evt);
840 }
841
842 sub fetch_all_open_circulation {
843         my( $self, $cid ) = @_;
844         my $evt;
845         $self->logmark;
846         my $circ = $self->storagereq(
847                 'open-ils.storage.direct.action.open_circulation.search_where',
848                 { target_copy => $cid, xact_finish => undef } );
849         $evt = OpenILS::Event->new('ACTION_CIRCULATION_NOT_FOUND') unless $circ;        
850         return ($circ, $evt);
851 }
852
853 my $copy_statuses;
854 sub copy_status_from_name {
855         my( $self, $name ) = @_;
856         $copy_statuses = $self->fetch_copy_statuses unless $copy_statuses;
857         for my $status (@$copy_statuses) { 
858                 return $status if( $status->name =~ /$name/i );
859         }
860         return undef;
861 }
862
863 sub copy_status_to_name {
864         my( $self, $sid ) = @_;
865         $copy_statuses = $self->fetch_copy_statuses unless $copy_statuses;
866         for my $status (@$copy_statuses) { 
867                 return $status->name if( $status->id == $sid );
868         }
869         return undef;
870 }
871
872 sub fetch_open_transit_by_copy {
873         my( $self, $copyid ) = @_;
874         my($transit, $evt);
875         $transit = $self->storagereq(
876                 'open-ils.storage.direct.action.transit_copy.search_where',
877                 { target_copy => $copyid, dest_recv_time => undef });
878         $evt = OpenILS::Event->new('ACTION_TRANSIT_COPY_NOT_FOUND') unless $transit;
879         return ($transit, $evt);
880 }
881
882 sub unflesh_copy {
883         my( $self, $copy ) = @_;
884         return undef unless $copy;
885         $copy->status( $copy->status->id ) if ref($copy->status);
886         $copy->location( $copy->location->id ) if ref($copy->location);
887         $copy->circ_lib( $copy->circ_lib->id ) if ref($copy->circ_lib);
888         return $copy;
889 }
890
891 # un-fleshes a copy and updates it in the DB
892 # returns a DB_UPDATE_FAILED event on error
893 # returns undef on success
894 sub update_copy {
895         my( $self, %params ) = @_;
896
897         my $copy                = $params{copy} || die "update_copy(): copy required";
898         my $editor      = $params{editor} || die "update_copy(): copy editor required";
899         my $session = $params{session};
900
901         $logger->debug("Updating copy in the database: " . $copy->id);
902
903         $self->unflesh_copy($copy);
904         $copy->editor( $editor );
905         $copy->edit_date( 'now' );
906
907         my $s;
908         my $meth = 'open-ils.storage.direct.asset.copy.update';
909
910         $s = $session->request( $meth, $copy )->gather(1) if $session;
911         $s = $self->storagereq( $meth, $copy ) unless $session;
912
913         $logger->debug("Update of copy ".$copy->id." returned: $s");
914
915         return $self->DB_UPDATE_FAILED($copy) unless $s;
916         return undef;
917 }
918
919 sub fetch_billable_xact {
920         my( $self, $id ) = @_;
921         my($xact, $evt);
922         $logger->debug("Fetching billable transaction %id");
923         $xact = $self->storagereq(
924                 'open-ils.storage.direct.money.billable_transaction.retrieve', $id );
925         $evt = OpenILS::Event->new('MONEY_BILLABLE_TRANSACTION_NOT_FOUND') unless $xact;
926         return ($xact, $evt);
927 }
928
929
930 sub fetch_fleshed_copy {
931         my( $self, $id ) = @_;
932         my( $copy, $evt );
933         $logger->info("Fetching fleshed copy $id");
934         $copy = $self->storagereq(
935                 "open-ils.storage.fleshed.asset.copy.retrieve", $id );
936         $evt = OpenILS::Event->new('ASSET_COPY_NOT_FOUND', id => $id) unless $copy;
937         return ($copy, $evt);
938 }
939
940
941 # returns the org that owns the callnumber that the copy
942 # is attached to
943 sub fetch_copy_owner {
944         my( $self, $copyid ) = @_;
945         my( $copy, $cn, $evt );
946         $logger->debug("Fetching copy owner $copyid");
947         ($copy, $evt) = $self->fetch_copy($copyid);
948         return (undef,$evt) if $evt;
949         ($cn, $evt) = $self->fetch_callnumber($copy->call_number);
950         return (undef,$evt) if $evt;
951         return ($cn->owning_lib);
952 }
953
954 sub fetch_copy_note {
955         my( $self, $id ) = @_;
956         my( $note, $evt );
957         $logger->debug("Fetching copy note $id");
958         $note = $self->storagereq(
959                 'open-ils.storage.direct.asset.copy_note.retrieve', $id );
960         $evt = OpenILS::Event->new('ASSET_COPY_NOTE_NOT_FOUND', id => $id ) unless $note;
961         return ($note, $evt);
962 }
963
964 sub fetch_call_numbers_by_title {
965         my( $self, $titleid ) = @_;
966         $logger->info("Fetching call numbers by title $titleid");
967         return $self->storagereq(
968                 'open-ils.storage.direct.asset.call_number.search_where.atomic', 
969                 { record => $titleid, deleted => 'f' });
970                 #'open-ils.storage.direct.asset.call_number.search.record.atomic', $titleid);
971 }
972
973 sub fetch_copies_by_call_number {
974         my( $self, $cnid ) = @_;
975         $logger->info("Fetching copies by call number $cnid");
976         return $self->storagereq(
977                 'open-ils.storage.direct.asset.copy.search_where.atomic', { call_number => $cnid, deleted => 'f' } );
978                 #'open-ils.storage.direct.asset.copy.search.call_number.atomic', $cnid );
979 }
980
981 sub fetch_user_by_barcode {
982         my( $self, $bc ) = @_;
983         my $cardid = $self->storagereq(
984                 'open-ils.storage.id_list.actor.card.search.barcode', $bc );
985         return (undef, OpenILS::Event->new('ACTOR_CARD_NOT_FOUND', barcode => $bc)) unless $cardid;
986         my $user = $self->storagereq(
987                 'open-ils.storage.direct.actor.user.search.card', $cardid );
988         return (undef, OpenILS::Event->new('ACTOR_USER_NOT_FOUND', card => $cardid)) unless $user;
989         return ($user);
990         
991 }
992
993
994 # ---------------------------------------------------------------------
995 # Updates and returns the patron penalties
996 # ---------------------------------------------------------------------
997 sub update_patron_penalties {
998         my( $self, %args ) = @_;
999         return $self->simplereq(
1000                 'open-ils.penalty',
1001                 'open-ils.penalty.patron_penalty.calculate', 
1002                 { update => 1, %args }
1003         );
1004 }
1005
1006 sub fetch_bill {
1007         my( $self, $billid ) = @_;
1008         $logger->debug("Fetching billing $billid");
1009         my $bill = $self->storagereq(
1010                 'open-ils.storage.direct.money.billing.retrieve', $billid );
1011         my $evt = OpenILS::Event->new('MONEY_BILLING_NOT_FOUND') unless $bill;
1012         return($bill, $evt);
1013 }
1014
1015
1016
1017
1018 1;
1019