]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/OpenILS/Application/AppUtils.pm
sanity check
[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.cstore", 
220                         "open-ils.cstore.direct.actor.org_unit.search.atomic",
221                         { id => { '!=' => undef } }
222                 );
223         }
224
225         if( ! $org_typelist ) {
226                 warn "Retrieving org types\n";
227                 $org_typelist = $self->simple_scalar_request( 
228                         "open-ils.cstore", 
229                         "open-ils.cstore.direct.actor.org_unit_type.search.atomic",
230                         { id => { '!=' => undef } }
231                 );
232                 $self->build_org_type($org_typelist);
233         }
234
235         $tree = $self->build_org_tree($orglist,1);
236         $cache_client->new()->put_cache('_orgtree', $tree);
237         return $tree;
238
239 }
240
241 my $slimtree = undef;
242 sub get_slim_org_tree {
243
244         my $self = shift;
245         if($slimtree) { return $slimtree; }
246
247         # see if it's in the cache
248         $slimtree = $cache_client->new()->get_cache('slimorgtree');
249         if($slimtree) { return $slimtree; }
250
251         if(!$orglist) {
252                 warn "Retrieving Org Tree\n";
253                 $orglist = $self->simple_scalar_request( 
254                         "open-ils.cstore", 
255                         "open-ils.cstore.direct.actor.org_unit.search.atomic",
256                         { id => { '!=' => undef } }
257                 );
258         }
259
260         $slimtree = $self->build_org_tree($orglist);
261         $cache_client->new->put_cache('slimorgtree', $slimtree);
262         return $slimtree;
263
264 }
265
266
267 sub build_org_type { 
268         my($self, $org_typelist)  = @_;
269         for my $type (@$org_typelist) {
270                 $org_typelist_hash->{$type->id()} = $type;
271         }
272 }
273
274
275
276 sub build_org_tree {
277
278         my( $self, $orglist, $add_types ) = @_;
279
280         return $orglist unless ( 
281                         ref($orglist) and @$orglist > 1 );
282
283         my @list = sort { 
284                 $a->ou_type <=> $b->ou_type ||
285                 $a->name cmp $b->name } @$orglist;
286
287         for my $org (@list) {
288
289                 next unless ($org);
290
291                 if(!ref($org->ou_type()) and $add_types) {
292                         $org->ou_type( $org_typelist_hash->{$org->ou_type()});
293                 }
294
295                 next unless (defined($org->parent_ou));
296
297                 my ($parent) = grep { $_->id == $org->parent_ou } @list;
298                 next unless $parent;
299                 $parent->children([]) unless defined($parent->children); 
300                 push( @{$parent->children}, $org );
301         }
302
303         return $list[0];
304
305 }
306
307 sub fetch_closed_date {
308         my( $self, $cd ) = @_;
309         my $evt;
310         
311         $logger->debug("Fetching closed_date $cd from cstore");
312
313         my $cd_obj = $self->simplereq(
314                 'open-ils.cstore',
315                 'open-ils.cstore.direct.actor.org_unit.closed_date.retrieve', $cd );
316
317         if(!$cd_obj) {
318                 $logger->info("closed_date $cd not found in the db");
319                 $evt = OpenILS::Event->new('ACTOR_USER_NOT_FOUND');
320         }
321
322         return ($cd_obj, $evt);
323 }
324
325 sub fetch_user {
326         my( $self, $userid ) = @_;
327         my( $user, $evt );
328         
329         $logger->debug("Fetching user $userid from cstore");
330
331         $user = $self->simplereq(
332                 'open-ils.cstore',
333                 'open-ils.cstore.direct.actor.user.retrieve', $userid );
334
335         if(!$user) {
336                 $logger->info("User $userid not found in the db");
337                 $evt = OpenILS::Event->new('ACTOR_USER_NOT_FOUND');
338         }
339
340         return ($user, $evt);
341 }
342
343 sub checkses {
344         my( $self, $session ) = @_;
345         my $user; my $evt; my $e; 
346
347         $logger->debug("Checking user session $session");
348
349         try {
350                 $user = $self->check_user_session($session);
351         } catch Error with { $e = 1; };
352
353         $logger->debug("Done checking user session $session " . (($e) ? "error = $e" : "") );
354
355         if( $e or !$user ) { $evt = OpenILS::Event->new('NO_SESSION'); }
356         return ( $user, $evt );
357 }
358
359
360 # verifiese the session and checks the permissions agains the
361 # session user and the user's home_ou as the org id
362 sub checksesperm {
363         my( $self, $session, @perms ) = @_;
364         my $user; my $evt; my $e; 
365         $logger->debug("Checking user session $session and perms @perms");
366         ($user, $evt) = $self->checkses($session);
367         return (undef, $evt) if $evt;
368         $evt = $self->check_perms($user->id, $user->home_ou, @perms);
369         return ($user, $evt);
370 }
371
372
373 sub checkrequestor {
374         my( $self, $staffobj, $userid, @perms ) = @_;
375         my $user; my $evt;
376         $userid = $staffobj->id unless defined $userid;
377
378         $logger->debug("checkrequestor(): requestor => " . $staffobj->id . ", target => $userid");
379
380         if( $userid ne $staffobj->id ) {
381                 ($user, $evt) = $self->fetch_user($userid);
382                 return (undef, $evt) if $evt;
383                 $evt = $self->check_perms( $staffobj->id, $user->home_ou, @perms );
384
385         } else {
386                 $user = $staffobj;
387         }
388
389         return ($user, $evt);
390 }
391
392 sub checkses_requestor {
393         my( $self, $authtoken, $targetid, @perms ) = @_;
394         my( $requestor, $target, $evt );
395
396         ($requestor, $evt) = $self->checkses($authtoken);
397         return (undef, undef, $evt) if $evt;
398
399         ($target, $evt) = $self->checkrequestor( $requestor, $targetid, @perms );
400         return( $requestor, $target, $evt);
401 }
402
403 sub fetch_copy {
404         my( $self, $copyid ) = @_;
405         my( $copy, $evt );
406
407         $logger->debug("Fetching copy $copyid from cstore");
408
409         $copy = $self->simplereq(
410                 'open-ils.cstore',
411                 'open-ils.cstore.direct.asset.copy.retrieve', $copyid );
412
413         if(!$copy) { $evt = OpenILS::Event->new('ASSET_COPY_NOT_FOUND'); }
414
415         return( $copy, $evt );
416 }
417
418
419 # retrieves a circ object by id
420 sub fetch_circulation {
421         my( $self, $circid ) = @_;
422         my $circ; my $evt;
423         
424         $logger->debug("Fetching circ $circid from cstore");
425
426         $circ = $self->simplereq(
427                 'open-ils.cstore',
428                 "open-ils.cstore.direct.action.circulation.retrieve", $circid );
429
430         if(!$circ) {
431                 $evt = OpenILS::Event->new('ACTION_CIRCULATION_NOT_FOUND', circid => $circid );
432         }
433
434         return ( $circ, $evt );
435 }
436
437 sub fetch_record_by_copy {
438         my( $self, $copyid ) = @_;
439         my( $record, $evt );
440
441         $logger->debug("Fetching record by copy $copyid from cstore");
442
443         $record = $self->simplereq(
444                 'open-ils.cstore',
445                 'open-ils.cstore.direct.asset.copy.retrieve', $copyid,
446                 { flesh => 3,
447                   flesh_fields => {     bre => [ 'fixed_fields' ],
448                                         acn => [ 'record' ],
449                                         acp => [ 'call_number' ],
450                                   }
451                 }
452         );
453
454         if(!$record) {
455                 $evt = OpenILS::Event->new('BIBLIO_RECORD_ENTRY_NOT_FOUND');
456         } else {
457                 $record = $record->call_number->record;
458         }
459
460         return ($record, $evt);
461 }
462
463 # turns a record object into an mvr (mods) object
464 sub record_to_mvr {
465         my( $self, $record ) = @_;
466         return undef unless $record and $record->marc;
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 cstore");
479
480         $hold = $self->simplereq(
481                 'open-ils.cstore',
482                 'open-ils.cstore.direct.action.hold_request.retrieve', $holdid);
483
484         $evt = OpenILS::Event->new('ACTION_HOLD_REQUEST_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 cstore");
495
496         $transit = $self->simplereq(
497                 'open-ils.cstore',
498                 'open-ils.cstore.direct.action.hold_transit_copy.search', { hold => $holdid } );
499
500         $evt = OpenILS::Event->new('ACTION_HOLD_TRANSIT_COPY_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->cstorereq(
512                 'open-ils.cstore.direct.action.hold_request.search',
513                 { 
514                         current_copy            => $copyid , 
515                         capture_time            => { "!=" => undef }, 
516                         fulfillment_time        => undef 
517                 } );
518
519         $evt = OpenILS::Event->new('ACTION_HOLD_REQUEST_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->cstorereq(
528                 'open-ils.cstore.direct.action.hold_transit_copy.retrieve', $transid );
529         $evt = OpenILS::Event->new('ACTION_HOLD_TRANSIT_COPY_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 cstore");
538
539         $copy = $self->simplereq( 'open-ils.cstore',
540                 'open-ils.cstore.direct.asset.copy.search', { barcode => $barcode, deleted => 'f'} );
541                 #'open-ils.storage.direct.asset.copy.search.barcode', $barcode );
542
543         $evt = OpenILS::Event->new('ASSET_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 cstore");
553
554         $transaction = $self->simplereq(
555                 'open-ils.cstore',
556                 'open-ils.cstore.direct.money.open_billable_transaction_summary.retrieve',  $transid);
557
558         $evt = OpenILS::Event->new(
559                 'MONEY_OPEN_BILLABLE_TRANSACTION_SUMMARY_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 $e = 'CONTAINER_CALL_NUMBER_BUCKET_NOT_FOUND';
579         $e = 'CONTAINER_BIBLIO_RECORD_ENTRY_BUCKET_NOT_FOUND' if $type eq 'biblio';
580         $e = 'CONTAINER_USER_BUCKET_NOT_FOUND' if $type eq 'user';
581         $e = 'CONTAINER_COPY_BUCKET_NOT_FOUND' if $type eq 'copy';
582
583         my $meth = $buckets{$type};
584         $bucket = $self->simplereq(
585                 'open-ils.cstore',
586                 "open-ils.cstore.direct.container.$meth.retrieve", $id );
587
588         $evt = OpenILS::Event->new(
589                 $e, container => $id, container_type => $type ) unless $bucket;
590
591         return ($bucket, $evt);
592 }
593
594
595 sub fetch_container_e {
596         my( $self, $editor, $id, $type ) = @_;
597
598         my( $bucket, $evt );
599         $bucket = $editor->retrieve_container_copy_bucket($id) if $type eq 'copy';
600         $bucket = $editor->retrieve_container_call_number_bucket($id) if $type eq 'callnumber';
601         $bucket = $editor->retrieve_container_biblio_record_entry_bucket($id) if $type eq 'biblio';
602         $bucket = $editor->retrieve_container_user_bucket($id) if $type eq 'user';
603
604         $evt = $editor->event unless $bucket;
605         return ($bucket, $evt);
606 }
607
608 sub fetch_container_item_e {
609         my( $self, $editor, $id, $type ) = @_;
610
611         my( $bucket, $evt );
612         $bucket = $editor->retrieve_container_copy_bucket_item($id) if $type eq 'copy';
613         $bucket = $editor->retrieve_container_call_number_bucket_item($id) if $type eq 'callnumber';
614         $bucket = $editor->retrieve_container_biblio_record_entry_bucket_item($id) if $type eq 'biblio';
615         $bucket = $editor->retrieve_container_user_bucket_item($id) if $type eq 'user';
616
617         $evt = $editor->event unless $bucket;
618         return ($bucket, $evt);
619 }
620
621
622
623
624
625 sub fetch_container_item {
626         my( $self, $id, $type ) = @_;
627         my( $bucket, $evt );
628
629         $logger->debug("Fetching container item $id with type $type");
630
631         my $meth = $buckets{$type} . "_item";
632
633         $bucket = $self->simplereq(
634                 'open-ils.cstore',
635                 "open-ils.cstore.direct.container.$meth.retrieve", $id );
636
637
638         my $e = 'CONTAINER_CALL_NUMBER_BUCKET_ITEM_NOT_FOUND';
639         $e = 'CONTAINER_BIBLIO_RECORD_ENTRY_BUCKET_ITEM_NOT_FOUND' if $type eq 'biblio';
640         $e = 'CONTAINER_USER_BUCKET_ITEM_NOT_FOUND' if $type eq 'user';
641         $e = 'CONTAINER_COPY_BUCKET_ITEM_NOT_FOUND' if $type eq 'copy';
642
643         $evt = OpenILS::Event->new(
644                 $e, itemid => $id, container_type => $type ) unless $bucket;
645
646         return ($bucket, $evt);
647 }
648
649
650 sub fetch_patron_standings {
651         my $self = shift;
652         $logger->debug("Fetching patron standings");    
653         return $self->simplereq(
654                 'open-ils.cstore', 
655                 'open-ils.cstore.direct.config.standing.search.atomic', { id => { '!=' => undef } });
656 }
657
658
659 sub fetch_permission_group_tree {
660         my $self = shift;
661         $logger->debug("Fetching patron profiles");     
662         return $self->simplereq(
663                 'open-ils.actor', 
664                 'open-ils.actor.groups.tree.retrieve' );
665 }
666
667
668 sub fetch_patron_circ_summary {
669         my( $self, $userid ) = @_;
670         $logger->debug("Fetching patron summary for $userid");
671         my $summary = $self->simplereq(
672                 'open-ils.storage', 
673                 "open-ils.storage.action.circulation.patron_summary", $userid );
674
675         if( $summary ) {
676                 $summary->[0] ||= 0;
677                 $summary->[1] ||= 0.0;
678                 return $summary;
679         }
680         return undef;
681 }
682
683
684 sub fetch_copy_statuses {
685         my( $self ) = @_;
686         $logger->debug("Fetching copy statuses");
687         return $self->simplereq(
688                 'open-ils.cstore', 
689                 'open-ils.cstore.direct.config.copy_status.search.atomic', { id => { '!=' => undef } });
690 }
691
692 sub fetch_copy_location {
693         my( $self, $id ) = @_;
694         my $evt;
695         my $cl = $self->cstorereq(
696                 'open-ils.cstore.direct.asset.copy_location.retrieve', $id );
697         $evt = OpenILS::Event->new('ASSET_COPY_LOCATION_NOT_FOUND') unless $cl;
698         return ($cl, $evt);
699 }
700
701 sub fetch_copy_locations {
702         my $self = shift; 
703         return $self->simplereq(
704                 'open-ils.cstore', 
705                 'open-ils.cstore.direct.asset.copy_location.search.atomic', { id => { '!=' => undef } });
706 }
707
708 sub fetch_copy_location_by_name {
709         my( $self, $name, $org ) = @_;
710         my $evt;
711         my $cl = $self->cstorereq(
712                 'open-ils.cstore.direct.asset.copy_location.search',
713                         { name => $name, owning_lib => $org } );
714         $evt = OpenILS::Event->new('ASSET_COPY_LOCATION_NOT_FOUND') unless $cl;
715         return ($cl, $evt);
716 }
717
718 sub fetch_callnumber {
719         my( $self, $id ) = @_;
720         my $evt = undef;
721
722         my $e = OpenILS::Event->new( 'ASSET_CALL_NUMBER_NOT_FOUND', id => $id );
723         return( undef, $e ) unless $id;
724
725         $logger->debug("Fetching callnumber $id");
726
727         my $cn = $self->simplereq(
728                 'open-ils.cstore',
729                 'open-ils.cstore.direct.asset.call_number.retrieve', $id );
730         $evt = $e  unless $cn;
731
732         return ( $cn, $evt );
733 }
734
735 my %ORG_CACHE; # - these rarely change, so cache them..
736 sub fetch_org_unit {
737         my( $self, $id ) = @_;
738         return $id if( ref($id) eq 'Fieldmapper::actor::org_unit' );
739         return $ORG_CACHE{$id} if $ORG_CACHE{$id};
740         $logger->debug("Fetching org unit $id");
741         my $evt = undef;
742
743         my $org = $self->simplereq(
744                 'open-ils.cstore', 
745                 'open-ils.cstore.direct.actor.org_unit.retrieve', $id );
746         $evt = OpenILS::Event->new( 'ACTOR_ORG_UNIT_NOT_FOUND', id => $id ) unless $org;
747         $ORG_CACHE{$id}  = $org;
748
749         return ($org, $evt);
750 }
751
752 sub fetch_stat_cat {
753         my( $self, $type, $id ) = @_;
754         my( $cat, $evt );
755         $logger->debug("Fetching $type stat cat: $id");
756         $cat = $self->simplereq(
757                 'open-ils.cstore', 
758                 "open-ils.cstore.direct.$type.stat_cat.retrieve", $id );
759
760         my $e = 'ASSET_STAT_CAT_NOT_FOUND';
761         $e = 'ACTOR_STAT_CAT_NOT_FOUND' if $type eq 'actor';
762
763         $evt = OpenILS::Event->new( $e, id => $id ) unless $cat;
764         return ( $cat, $evt );
765 }
766
767 sub fetch_stat_cat_entry {
768         my( $self, $type, $id ) = @_;
769         my( $entry, $evt );
770         $logger->debug("Fetching $type stat cat entry: $id");
771         $entry = $self->simplereq(
772                 'open-ils.cstore', 
773                 "open-ils.cstore.direct.$type.stat_cat_entry.retrieve", $id );
774
775         my $e = 'ASSET_STAT_CAT_ENTRY_NOT_FOUND';
776         $e = 'ACTOR_STAT_CAT_ENTRY_NOT_FOUND' if $type eq 'actor';
777
778         $evt = OpenILS::Event->new( $e, id => $id ) unless $entry;
779         return ( $entry, $evt );
780 }
781
782
783 sub find_org {
784         my( $self, $org_tree, $orgid )  = @_;
785         return $org_tree if ( $org_tree->id eq $orgid );
786         return undef unless ref($org_tree->children);
787         for my $c (@{$org_tree->children}) {
788                 my $o = $self->find_org($c, $orgid);
789                 return $o if $o;
790         }
791         return undef;
792 }
793
794 sub fetch_non_cat_type_by_name_and_org {
795         my( $self, $name, $orgId ) = @_;
796         $logger->debug("Fetching non cat type $name at org $orgId");
797         my $types = $self->simplereq(
798                 'open-ils.cstore',
799                 'open-ils.cstore.direct.config.non_cataloged_type.search.atomic',
800                 { name => $name, owning_lib => $orgId } );
801         return ($types->[0], undef) if($types and @$types);
802         return (undef, OpenILS::Event->new('CONFIG_NON_CATALOGED_TYPE_NOT_FOUND') );
803 }
804
805 sub fetch_non_cat_type {
806         my( $self, $id ) = @_;
807         $logger->debug("Fetching non cat type $id");
808         my( $type, $evt );
809         $type = $self->simplereq(
810                 'open-ils.cstore', 
811                 'open-ils.cstore.direct.config.non_cataloged_type.retrieve', $id );
812         $evt = OpenILS::Event->new('CONFIG_NON_CATALOGED_TYPE_NOT_FOUND') unless $type;
813         return ($type, $evt);
814 }
815
816 sub DB_UPDATE_FAILED { 
817         my( $self, $payload ) = @_;
818         return OpenILS::Event->new('DATABASE_UPDATE_FAILED', 
819                 payload => ($payload) ? $payload : undef ); 
820 }
821
822 sub fetch_circ_duration_by_name {
823         my( $self, $name ) = @_;
824         my( $dur, $evt );
825         $dur = $self->simplereq(
826                 'open-ils.cstore', 
827                 'open-ils.cstore.direct.config.rules.circ_duration.search.atomic', { name => $name } );
828         $dur = $dur->[0];
829         $evt = OpenILS::Event->new('CONFIG_RULES_CIRC_DURATION_NOT_FOUND') unless $dur;
830         return ($dur, $evt);
831 }
832
833 sub fetch_recurring_fine_by_name {
834         my( $self, $name ) = @_;
835         my( $obj, $evt );
836         $obj = $self->simplereq(
837                 'open-ils.cstore', 
838                 'open-ils.cstore.direct.config.rules.recuring_fine.search.atomic', { name => $name } );
839         $obj = $obj->[0];
840         $evt = OpenILS::Event->new('CONFIG_RULES_RECURING_FINE_NOT_FOUND') unless $obj;
841         return ($obj, $evt);
842 }
843
844 sub fetch_max_fine_by_name {
845         my( $self, $name ) = @_;
846         my( $obj, $evt );
847         $obj = $self->simplereq(
848                 'open-ils.cstore', 
849                 'open-ils.cstore.direct.config.rules.max_fine.search.atomic', { name => $name } );
850         $obj = $obj->[0];
851         $evt = OpenILS::Event->new('CONFIG_RULES_MAX_FINE_NOT_FOUND') unless $obj;
852         return ($obj, $evt);
853 }
854
855 sub storagereq {
856         my( $self, $method, @params ) = @_;
857         return $self->simplereq(
858                 'open-ils.storage', $method, @params );
859 }
860
861 sub cstorereq {
862         my( $self, $method, @params ) = @_;
863         return $self->simplereq(
864                 'open-ils.cstore', $method, @params );
865 }
866
867 sub event_equals {
868         my( $self, $e, $name ) =  @_;
869         if( $e and ref($e) eq 'HASH' and 
870                 defined($e->{textcode}) and $e->{textcode} eq $name ) {
871                 return 1 ;
872         }
873         return 0;
874 }
875
876 sub logmark {
877         my( undef, $f, $l ) = caller(0);
878         my( undef, undef, undef, $s ) = caller(1);
879         $s =~ s/.*:://g;
880         $f =~ s/.*\///g;
881         $logger->debug("LOGMARK: $f:$l:$s");
882 }
883
884 # takes a copy id 
885 sub fetch_open_circulation {
886         my( $self, $cid ) = @_;
887         my $evt;
888         $self->logmark;
889         my $circ = $self->cstorereq(
890                 'open-ils.cstore.direct.action.open_circulation.search',
891                 { target_copy => $cid, stop_fines_time => undef } );
892         $evt = OpenILS::Event->new('ACTION_CIRCULATION_NOT_FOUND') unless $circ;        
893         return ($circ, $evt);
894 }
895
896 sub fetch_all_open_circulation {
897         my( $self, $cid ) = @_;
898         my $evt;
899         $self->logmark;
900         my $circ = $self->cstorereq(
901                 'open-ils.cstore.direct.action.open_circulation.search',
902                 { target_copy => $cid, xact_finish => undef } );
903         $evt = OpenILS::Event->new('ACTION_CIRCULATION_NOT_FOUND') unless $circ;        
904         return ($circ, $evt);
905 }
906
907 my $copy_statuses;
908 sub copy_status_from_name {
909         my( $self, $name ) = @_;
910         $copy_statuses = $self->fetch_copy_statuses unless $copy_statuses;
911         for my $status (@$copy_statuses) { 
912                 return $status if( $status->name =~ /$name/i );
913         }
914         return undef;
915 }
916
917 sub copy_status_to_name {
918         my( $self, $sid ) = @_;
919         $copy_statuses = $self->fetch_copy_statuses unless $copy_statuses;
920         for my $status (@$copy_statuses) { 
921                 return $status->name if( $status->id == $sid );
922         }
923         return undef;
924 }
925
926 sub fetch_open_transit_by_copy {
927         my( $self, $copyid ) = @_;
928         my($transit, $evt);
929         $transit = $self->cstorereq(
930                 'open-ils.cstore.direct.action.transit_copy.search',
931                 { target_copy => $copyid, dest_recv_time => undef });
932         $evt = OpenILS::Event->new('ACTION_TRANSIT_COPY_NOT_FOUND') unless $transit;
933         return ($transit, $evt);
934 }
935
936 sub unflesh_copy {
937         my( $self, $copy ) = @_;
938         return undef unless $copy;
939         $copy->status( $copy->status->id ) if ref($copy->status);
940         $copy->location( $copy->location->id ) if ref($copy->location);
941         $copy->circ_lib( $copy->circ_lib->id ) if ref($copy->circ_lib);
942         return $copy;
943 }
944
945 # un-fleshes a copy and updates it in the DB
946 # returns a DB_UPDATE_FAILED event on error
947 # returns undef on success
948 sub update_copy {
949         my( $self, %params ) = @_;
950
951         my $copy                = $params{copy} || die "update_copy(): copy required";
952         my $editor      = $params{editor} || die "update_copy(): copy editor required";
953         my $session = $params{session};
954
955         $logger->debug("Updating copy in the database: " . $copy->id);
956
957         $self->unflesh_copy($copy);
958         $copy->editor( $editor );
959         $copy->edit_date( 'now' );
960
961         my $s;
962         my $meth = 'open-ils.storage.direct.asset.copy.update';
963
964         $s = $session->request( $meth, $copy )->gather(1) if $session;
965         $s = $self->storagereq( $meth, $copy ) unless $session;
966
967         $logger->debug("Update of copy ".$copy->id." returned: $s");
968
969         return $self->DB_UPDATE_FAILED($copy) unless $s;
970         return undef;
971 }
972
973 sub fetch_billable_xact {
974         my( $self, $id ) = @_;
975         my($xact, $evt);
976         $logger->debug("Fetching billable transaction %id");
977         $xact = $self->cstorereq(
978                 'open-ils.cstore.direct.money.billable_transaction.retrieve', $id );
979         $evt = OpenILS::Event->new('MONEY_BILLABLE_TRANSACTION_NOT_FOUND') unless $xact;
980         return ($xact, $evt);
981 }
982
983
984 sub fetch_fleshed_copy {
985         my( $self, $id ) = @_;
986         my( $copy, $evt );
987         $logger->info("Fetching fleshed copy $id");
988         $copy = $self->cstorereq(
989                 "open-ils.cstore.direct.asset.copy.retrieve", $id,
990                 { flesh => 1,
991                   flesh_fields => { acp => [ qw/ circ_lib location status stat_cat_entries / ] }
992                 }
993         );
994         $evt = OpenILS::Event->new('ASSET_COPY_NOT_FOUND', id => $id) unless $copy;
995         return ($copy, $evt);
996 }
997
998
999 # returns the org that owns the callnumber that the copy
1000 # is attached to
1001 sub fetch_copy_owner {
1002         my( $self, $copyid ) = @_;
1003         my( $copy, $cn, $evt );
1004         $logger->debug("Fetching copy owner $copyid");
1005         ($copy, $evt) = $self->fetch_copy($copyid);
1006         return (undef,$evt) if $evt;
1007         ($cn, $evt) = $self->fetch_callnumber($copy->call_number);
1008         return (undef,$evt) if $evt;
1009         return ($cn->owning_lib);
1010 }
1011
1012 sub fetch_copy_note {
1013         my( $self, $id ) = @_;
1014         my( $note, $evt );
1015         $logger->debug("Fetching copy note $id");
1016         $note = $self->cstorereq(
1017                 'open-ils.cstore.direct.asset.copy_note.retrieve', $id );
1018         $evt = OpenILS::Event->new('ASSET_COPY_NOTE_NOT_FOUND', id => $id ) unless $note;
1019         return ($note, $evt);
1020 }
1021
1022 sub fetch_call_numbers_by_title {
1023         my( $self, $titleid ) = @_;
1024         $logger->info("Fetching call numbers by title $titleid");
1025         return $self->cstorereq(
1026                 'open-ils.cstore.direct.asset.call_number.search.atomic', 
1027                 { record => $titleid, deleted => 'f' });
1028                 #'open-ils.storage.direct.asset.call_number.search.record.atomic', $titleid);
1029 }
1030
1031 sub fetch_copies_by_call_number {
1032         my( $self, $cnid ) = @_;
1033         $logger->info("Fetching copies by call number $cnid");
1034         return $self->cstorereq(
1035                 'open-ils.cstore.direct.asset.copy.search.atomic', { call_number => $cnid, deleted => 'f' } );
1036                 #'open-ils.storage.direct.asset.copy.search.call_number.atomic', $cnid );
1037 }
1038
1039 sub fetch_user_by_barcode {
1040         my( $self, $bc ) = @_;
1041         my $cardid = $self->cstorereq(
1042                 'open-ils.cstore.direct.actor.card.id_list', { barcode => $bc } );
1043         return (undef, OpenILS::Event->new('ACTOR_CARD_NOT_FOUND', barcode => $bc)) unless $cardid;
1044         my $user = $self->cstorereq(
1045                 'open-ils.cstore.direct.actor.user.search', { card => $cardid } );
1046         return (undef, OpenILS::Event->new('ACTOR_USER_NOT_FOUND', card => $cardid)) unless $user;
1047         return ($user);
1048         
1049 }
1050
1051
1052 # ---------------------------------------------------------------------
1053 # Updates and returns the patron penalties
1054 # ---------------------------------------------------------------------
1055 sub update_patron_penalties {
1056         my( $self, %args ) = @_;
1057         return $self->simplereq(
1058                 'open-ils.penalty',
1059                 'open-ils.penalty.patron_penalty.calculate', 
1060                 { update => 1, %args }
1061         );
1062 }
1063
1064 sub fetch_bill {
1065         my( $self, $billid ) = @_;
1066         $logger->debug("Fetching billing $billid");
1067         my $bill = $self->cstorereq(
1068                 'open-ils.cstore.direct.money.billing.retrieve', $billid );
1069         my $evt = OpenILS::Event->new('MONEY_BILLING_NOT_FOUND') unless $bill;
1070         return($bill, $evt);
1071 }
1072
1073
1074
1075 my $ORG_TREE;
1076 sub fetch_org_tree {
1077         my $self = shift;
1078         return $ORG_TREE if $ORG_TREE;
1079         return $ORG_TREE = OpenILS::Utils::CStoreEditor->new->search_actor_org_unit( 
1080                 [
1081                         {"parent_ou" => undef },
1082                         {
1083                                 flesh                           => 2,
1084                                 flesh_fields    => { aou =>  ['children'] },
1085                                 order_by       => { aou => 'name'}
1086                         }
1087                 ]
1088         )->[0];
1089 }
1090
1091 sub walk_org_tree {
1092         my( $self, $node, $callback ) = @_;
1093         return unless $node;
1094         $callback->($node);
1095         if( $node->children ) {
1096                 $self->walk_org_tree($_, $callback) for @{$node->children};
1097         }
1098 }
1099
1100 sub is_true {
1101         my( $self, $item ) = @_;
1102         return 1 if $item and $item !~ /^f$/i;
1103         return 0;
1104 }
1105
1106
1107 1;
1108