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