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