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