]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/Application/AppUtils.pm
Patron Stat Cat Enhancements: Add OpenSRF methods for retrieving actor stat cat defau...
[working/Evergreen.git] / Open-ILS / src / perlmods / lib / OpenILS / Application / AppUtils.pm
1 package OpenILS::Application::AppUtils;
2 # vim:noet:ts=4
3 use strict; use warnings;
4 use OpenILS::Application;
5 use base qw/OpenILS::Application/;
6 use OpenSRF::Utils::Cache;
7 use OpenSRF::Utils::Logger qw/$logger/;
8 use OpenILS::Utils::ModsParser;
9 use OpenSRF::EX qw(:try);
10 use OpenILS::Event;
11 use Data::Dumper;
12 use OpenILS::Utils::CStoreEditor;
13 use OpenILS::Const qw/:const/;
14 use Unicode::Normalize;
15 use OpenSRF::Utils::SettingsClient;
16 use UUID::Tiny;
17 use Encode;
18
19 # ---------------------------------------------------------------------------
20 # Pile of utilty methods used accross applications.
21 # ---------------------------------------------------------------------------
22 my $cache_client = "OpenSRF::Utils::Cache";
23
24
25 # ---------------------------------------------------------------------------
26 # on sucess, returns the created session, on failure throws ERROR exception
27 # ---------------------------------------------------------------------------
28 sub start_db_session {
29
30         my $self = shift;
31         my $session = OpenSRF::AppSession->connect( "open-ils.storage" );
32         my $trans_req = $session->request( "open-ils.storage.transaction.begin" );
33
34         my $trans_resp = $trans_req->recv();
35         if(ref($trans_resp) and UNIVERSAL::isa($trans_resp,"Error")) { throw $trans_resp; }
36         if( ! $trans_resp->content() ) {
37                 throw OpenSRF::ERROR 
38                         ("Unable to Begin Transaction with database" );
39         }
40         $trans_req->finish();
41
42         $logger->debug("Setting global storage session to ".
43                 "session: " . $session->session_id . " : " . $session->app );
44
45         return $session;
46 }
47
48 sub set_audit_info {
49         my $self = shift;
50         my $session = shift;
51         my $authtoken = shift;
52         my $user_id = shift;
53         my $ws_id = shift;
54         
55         my $audit_req = $session->request( "open-ils.storage.set_audit_info", $authtoken, $user_id, $ws_id );
56         my $audit_resp = $audit_req->recv();
57         $audit_req->finish();
58 }
59
60 my $PERM_QUERY = {
61     select => {
62         au => [ {
63             transform => 'permission.usr_has_perm',
64             alias => 'has_perm',
65             column => 'id',
66             params => []
67         } ]
68     },
69     from => 'au',
70     where => {},
71 };
72
73
74 # returns undef if user has all of the perms provided
75 # returns the first failed perm on failure
76 sub check_user_perms {
77         my($self, $user_id, $org_id, @perm_types ) = @_;
78         $logger->debug("Checking perms with user : $user_id , org: $org_id, @perm_types");
79
80         for my $type (@perm_types) {
81             $PERM_QUERY->{select}->{au}->[0]->{params} = [$type, $org_id];
82                 $PERM_QUERY->{where}->{id} = $user_id;
83                 return $type unless $self->is_true(OpenILS::Utils::CStoreEditor->new->json_query($PERM_QUERY)->[0]->{has_perm});
84         }
85         return undef;
86 }
87
88 # checks the list of user perms.  The first one that fails returns a new
89 sub check_perms {
90         my( $self, $user_id, $org_id, @perm_types ) = @_;
91         my $t = $self->check_user_perms( $user_id, $org_id, @perm_types );
92         return OpenILS::Event->new('PERM_FAILURE', ilsperm => $t, ilspermloc => $org_id ) if $t;
93         return undef;
94 }
95
96
97
98 # ---------------------------------------------------------------------------
99 # commits and destroys the session
100 # ---------------------------------------------------------------------------
101 sub commit_db_session {
102         my( $self, $session ) = @_;
103
104         my $req = $session->request( "open-ils.storage.transaction.commit" );
105         my $resp = $req->recv();
106
107         if(!$resp) {
108                 throw OpenSRF::EX::ERROR ("Unable to commit db session");
109         }
110
111         if(UNIVERSAL::isa($resp,"Error")) { 
112                 throw $resp ($resp->stringify); 
113         }
114
115         if(!$resp->content) {
116                 throw OpenSRF::EX::ERROR ("Unable to commit db session");
117         }
118
119         $session->finish();
120         $session->disconnect();
121         $session->kill_me();
122 }
123
124 sub rollback_db_session {
125         my( $self, $session ) = @_;
126
127         my $req = $session->request("open-ils.storage.transaction.rollback");
128         my $resp = $req->recv();
129         if(UNIVERSAL::isa($resp,"Error")) { throw $resp;  }
130
131         $session->finish();
132         $session->disconnect();
133         $session->kill_me();
134 }
135
136
137 # returns undef it the event is not an ILS event
138 # returns the event code otherwise
139 sub event_code {
140         my( $self, $evt ) = @_;
141         return $evt->{ilsevent} if( ref($evt) eq 'HASH' and defined($evt->{ilsevent})) ;
142         return undef;
143 }
144
145 # ---------------------------------------------------------------------------
146 # Checks to see if a user is logged in.  Returns the user record on success,
147 # throws an exception on error.
148 # ---------------------------------------------------------------------------
149 sub check_user_session {
150         my( $self, $user_session ) = @_;
151
152         my $content = $self->simplereq( 
153                 'open-ils.auth', 
154                 'open-ils.auth.session.retrieve', $user_session);
155
156     return undef if (!$content) or $self->event_code($content);
157         return $content;
158 }
159
160 # generic simple request returning a scalar value
161 sub simplereq {
162         my($self, $service, $method, @params) = @_;
163         return $self->simple_scalar_request($service, $method, @params);
164 }
165
166
167 sub simple_scalar_request {
168         my($self, $service, $method, @params) = @_;
169
170         my $session = OpenSRF::AppSession->create( $service );
171
172         my $request = $session->request( $method, @params );
173
174         my $val;
175         my $err;
176         try  {
177
178                 $val = $request->gather(1);     
179
180         } catch Error with {
181                 $err = shift;
182         };
183
184         if( $err ) {
185                 warn "received error : service=$service : method=$method : params=".Dumper(\@params) . "\n $err";
186                 throw $err ("Call to $service for method $method \n failed with exception: $err : " );
187         }
188
189         return $val;
190 }
191
192
193
194
195
196 my $tree                                                = undef;
197 my $orglist                                     = undef;
198 my $org_typelist                        = undef;
199 my $org_typelist_hash   = {};
200
201 sub __get_org_tree {
202         
203         # can we throw this version away??
204
205         my $self = shift;
206         if($tree) { return $tree; }
207
208         # see if it's in the cache
209         $tree = $cache_client->new()->get_cache('_orgtree');
210         if($tree) { return $tree; }
211
212         if(!$orglist) {
213                 warn "Retrieving Org Tree\n";
214                 $orglist = $self->simple_scalar_request( 
215                         "open-ils.cstore", 
216                         "open-ils.cstore.direct.actor.org_unit.search.atomic",
217                         { id => { '!=' => undef } }
218                 );
219         }
220
221         if( ! $org_typelist ) {
222                 warn "Retrieving org types\n";
223                 $org_typelist = $self->simple_scalar_request( 
224                         "open-ils.cstore", 
225                         "open-ils.cstore.direct.actor.org_unit_type.search.atomic",
226                         { id => { '!=' => undef } }
227                 );
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.cstore", 
251                         "open-ils.cstore.direct.actor.org_unit.search.atomic",
252                         { id => { '!=' => undef } }
253                 );
254         }
255
256         $slimtree = $self->build_org_tree($orglist);
257         $cache_client->new->put_cache('slimorgtree', $slimtree);
258         return $slimtree;
259
260 }
261
262
263 sub build_org_type { 
264         my($self, $org_typelist)  = @_;
265         for my $type (@$org_typelist) {
266                 $org_typelist_hash->{$type->id()} = $type;
267         }
268 }
269
270
271
272 sub build_org_tree {
273
274         my( $self, $orglist, $add_types ) = @_;
275
276         return $orglist unless ref $orglist; 
277     return $$orglist[0] if @$orglist == 1;
278
279         my @list = sort { 
280                 $a->ou_type <=> $b->ou_type ||
281                 $a->name cmp $b->name } @$orglist;
282
283         for my $org (@list) {
284
285                 next unless ($org);
286
287                 if(!ref($org->ou_type()) and $add_types) {
288                         $org->ou_type( $org_typelist_hash->{$org->ou_type()});
289                 }
290
291         next if (!defined($org->parent_ou) || $org->parent_ou eq "");
292
293                 my ($parent) = grep { $_->id == $org->parent_ou } @list;
294                 next unless $parent;
295                 $parent->children([]) unless defined($parent->children); 
296                 push( @{$parent->children}, $org );
297         }
298
299         return $list[0];
300 }
301
302 sub fetch_closed_date {
303         my( $self, $cd ) = @_;
304         my $evt;
305         
306         $logger->debug("Fetching closed_date $cd from cstore");
307
308         my $cd_obj = $self->simplereq(
309                 'open-ils.cstore',
310                 'open-ils.cstore.direct.actor.org_unit.closed_date.retrieve', $cd );
311
312         if(!$cd_obj) {
313                 $logger->info("closed_date $cd not found in the db");
314                 $evt = OpenILS::Event->new('ACTOR_USER_NOT_FOUND');
315         }
316
317         return ($cd_obj, $evt);
318 }
319
320 sub fetch_user {
321         my( $self, $userid ) = @_;
322         my( $user, $evt );
323         
324         $logger->debug("Fetching user $userid from cstore");
325
326         $user = $self->simplereq(
327                 'open-ils.cstore',
328                 'open-ils.cstore.direct.actor.user.retrieve', $userid );
329
330         if(!$user) {
331                 $logger->info("User $userid not found in the db");
332                 $evt = OpenILS::Event->new('ACTOR_USER_NOT_FOUND');
333         }
334
335         return ($user, $evt);
336 }
337
338 sub checkses {
339         my( $self, $session ) = @_;
340         my $user = $self->check_user_session($session) or 
341         return (undef, OpenILS::Event->new('NO_SESSION'));
342     return ($user);
343 }
344
345
346 # verifiese the session and checks the permissions agains the
347 # session user and the user's home_ou as the org id
348 sub checksesperm {
349         my( $self, $session, @perms ) = @_;
350         my $user; my $evt; my $e; 
351         $logger->debug("Checking user session $session and perms @perms");
352         ($user, $evt) = $self->checkses($session);
353         return (undef, $evt) if $evt;
354         $evt = $self->check_perms($user->id, $user->home_ou, @perms);
355         return ($user, $evt);
356 }
357
358
359 sub checkrequestor {
360         my( $self, $staffobj, $userid, @perms ) = @_;
361         my $user; my $evt;
362         $userid = $staffobj->id unless defined $userid;
363
364         $logger->debug("checkrequestor(): requestor => " . $staffobj->id . ", target => $userid");
365
366         if( $userid ne $staffobj->id ) {
367                 ($user, $evt) = $self->fetch_user($userid);
368                 return (undef, $evt) if $evt;
369                 $evt = $self->check_perms( $staffobj->id, $user->home_ou, @perms );
370
371         } else {
372                 $user = $staffobj;
373         }
374
375         return ($user, $evt);
376 }
377
378 sub checkses_requestor {
379         my( $self, $authtoken, $targetid, @perms ) = @_;
380         my( $requestor, $target, $evt );
381
382         ($requestor, $evt) = $self->checkses($authtoken);
383         return (undef, undef, $evt) if $evt;
384
385         ($target, $evt) = $self->checkrequestor( $requestor, $targetid, @perms );
386         return( $requestor, $target, $evt);
387 }
388
389 sub fetch_copy {
390         my( $self, $copyid ) = @_;
391         my( $copy, $evt );
392
393         $logger->debug("Fetching copy $copyid from cstore");
394
395         $copy = $self->simplereq(
396                 'open-ils.cstore',
397                 'open-ils.cstore.direct.asset.copy.retrieve', $copyid );
398
399         if(!$copy) { $evt = OpenILS::Event->new('ASSET_COPY_NOT_FOUND'); }
400
401         return( $copy, $evt );
402 }
403
404
405 # retrieves a circ object by id
406 sub fetch_circulation {
407         my( $self, $circid ) = @_;
408         my $circ; my $evt;
409         
410         $logger->debug("Fetching circ $circid from cstore");
411
412         $circ = $self->simplereq(
413                 'open-ils.cstore',
414                 "open-ils.cstore.direct.action.circulation.retrieve", $circid );
415
416         if(!$circ) {
417                 $evt = OpenILS::Event->new('ACTION_CIRCULATION_NOT_FOUND', circid => $circid );
418         }
419
420         return ( $circ, $evt );
421 }
422
423 sub fetch_record_by_copy {
424         my( $self, $copyid ) = @_;
425         my( $record, $evt );
426
427         $logger->debug("Fetching record by copy $copyid from cstore");
428
429         $record = $self->simplereq(
430                 'open-ils.cstore',
431                 'open-ils.cstore.direct.asset.copy.retrieve', $copyid,
432                 { flesh => 3,
433                   flesh_fields => {     bre => [ 'fixed_fields' ],
434                                         acn => [ 'record' ],
435                                         acp => [ 'call_number' ],
436                                   }
437                 }
438         );
439
440         if(!$record) {
441                 $evt = OpenILS::Event->new('BIBLIO_RECORD_ENTRY_NOT_FOUND');
442         } else {
443                 $record = $record->call_number->record;
444         }
445
446         return ($record, $evt);
447 }
448
449 # turns a record object into an mvr (mods) object
450 sub record_to_mvr {
451         my( $self, $record ) = @_;
452         return undef unless $record and $record->marc;
453         my $u = OpenILS::Utils::ModsParser->new();
454         $u->start_mods_batch( $record->marc );
455         my $mods = $u->finish_mods_batch();
456         $mods->doc_id($record->id);
457    $mods->tcn($record->tcn_value);
458         return $mods;
459 }
460
461 sub fetch_hold {
462         my( $self, $holdid ) = @_;
463         my( $hold, $evt );
464
465         $logger->debug("Fetching hold $holdid from cstore");
466
467         $hold = $self->simplereq(
468                 'open-ils.cstore',
469                 'open-ils.cstore.direct.action.hold_request.retrieve', $holdid);
470
471         $evt = OpenILS::Event->new('ACTION_HOLD_REQUEST_NOT_FOUND', holdid => $holdid) unless $hold;
472
473         return ($hold, $evt);
474 }
475
476
477 sub fetch_hold_transit_by_hold {
478         my( $self, $holdid ) = @_;
479         my( $transit, $evt );
480
481         $logger->debug("Fetching transit by hold $holdid from cstore");
482
483         $transit = $self->simplereq(
484                 'open-ils.cstore',
485                 'open-ils.cstore.direct.action.hold_transit_copy.search', { hold => $holdid } );
486
487         $evt = OpenILS::Event->new('ACTION_HOLD_TRANSIT_COPY_NOT_FOUND', holdid => $holdid) unless $transit;
488
489         return ($transit, $evt );
490 }
491
492 # fetches the captured, but not fulfilled hold attached to a given copy
493 sub fetch_open_hold_by_copy {
494         my( $self, $copyid ) = @_;
495         $logger->debug("Searching for active hold for copy $copyid");
496         my( $hold, $evt );
497
498         $hold = $self->cstorereq(
499                 'open-ils.cstore.direct.action.hold_request.search',
500                 { 
501                         current_copy            => $copyid , 
502                         capture_time            => { "!=" => undef }, 
503                         fulfillment_time        => undef,
504                         cancel_time                     => undef,
505                 } );
506
507         $evt = OpenILS::Event->new('ACTION_HOLD_REQUEST_NOT_FOUND', copyid => $copyid) unless $hold;
508         return ($hold, $evt);
509 }
510
511 sub fetch_hold_transit {
512         my( $self, $transid ) = @_;
513         my( $htransit, $evt );
514         $logger->debug("Fetching hold transit with hold id $transid");
515         $htransit = $self->cstorereq(
516                 'open-ils.cstore.direct.action.hold_transit_copy.retrieve', $transid );
517         $evt = OpenILS::Event->new('ACTION_HOLD_TRANSIT_COPY_NOT_FOUND', id => $transid) unless $htransit;
518         return ($htransit, $evt);
519 }
520
521 sub fetch_copy_by_barcode {
522         my( $self, $barcode ) = @_;
523         my( $copy, $evt );
524
525         $logger->debug("Fetching copy by barcode $barcode from cstore");
526
527         $copy = $self->simplereq( 'open-ils.cstore',
528                 'open-ils.cstore.direct.asset.copy.search', { barcode => $barcode, deleted => 'f'} );
529                 #'open-ils.storage.direct.asset.copy.search.barcode', $barcode );
530
531         $evt = OpenILS::Event->new('ASSET_COPY_NOT_FOUND', barcode => $barcode) unless $copy;
532
533         return ($copy, $evt);
534 }
535
536 sub fetch_open_billable_transaction {
537         my( $self, $transid ) = @_;
538         my( $transaction, $evt );
539
540         $logger->debug("Fetching open billable transaction $transid from cstore");
541
542         $transaction = $self->simplereq(
543                 'open-ils.cstore',
544                 'open-ils.cstore.direct.money.open_billable_transaction_summary.retrieve',  $transid);
545
546         $evt = OpenILS::Event->new(
547                 'MONEY_OPEN_BILLABLE_TRANSACTION_SUMMARY_NOT_FOUND', transid => $transid ) unless $transaction;
548
549         return ($transaction, $evt);
550 }
551
552
553
554 my %buckets;
555 $buckets{'biblio'} = 'biblio_record_entry_bucket';
556 $buckets{'callnumber'} = 'call_number_bucket';
557 $buckets{'copy'} = 'copy_bucket';
558 $buckets{'user'} = 'user_bucket';
559
560 sub fetch_container {
561         my( $self, $id, $type ) = @_;
562         my( $bucket, $evt );
563
564         $logger->debug("Fetching container $id with type $type");
565
566         my $e = 'CONTAINER_CALL_NUMBER_BUCKET_NOT_FOUND';
567         $e = 'CONTAINER_BIBLIO_RECORD_ENTRY_BUCKET_NOT_FOUND' if $type eq 'biblio';
568         $e = 'CONTAINER_USER_BUCKET_NOT_FOUND' if $type eq 'user';
569         $e = 'CONTAINER_COPY_BUCKET_NOT_FOUND' if $type eq 'copy';
570
571         my $meth = $buckets{$type};
572         $bucket = $self->simplereq(
573                 'open-ils.cstore',
574                 "open-ils.cstore.direct.container.$meth.retrieve", $id );
575
576         $evt = OpenILS::Event->new(
577                 $e, container => $id, container_type => $type ) unless $bucket;
578
579         return ($bucket, $evt);
580 }
581
582
583 sub fetch_container_e {
584         my( $self, $editor, $id, $type ) = @_;
585
586         my( $bucket, $evt );
587         $bucket = $editor->retrieve_container_copy_bucket($id) if $type eq 'copy';
588         $bucket = $editor->retrieve_container_call_number_bucket($id) if $type eq 'callnumber';
589         $bucket = $editor->retrieve_container_biblio_record_entry_bucket($id) if $type eq 'biblio';
590         $bucket = $editor->retrieve_container_user_bucket($id) if $type eq 'user';
591
592         $evt = $editor->event unless $bucket;
593         return ($bucket, $evt);
594 }
595
596 sub fetch_container_item_e {
597         my( $self, $editor, $id, $type ) = @_;
598
599         my( $bucket, $evt );
600         $bucket = $editor->retrieve_container_copy_bucket_item($id) if $type eq 'copy';
601         $bucket = $editor->retrieve_container_call_number_bucket_item($id) if $type eq 'callnumber';
602         $bucket = $editor->retrieve_container_biblio_record_entry_bucket_item($id) if $type eq 'biblio';
603         $bucket = $editor->retrieve_container_user_bucket_item($id) if $type eq 'user';
604
605         $evt = $editor->event unless $bucket;
606         return ($bucket, $evt);
607 }
608
609
610
611
612
613 sub fetch_container_item {
614         my( $self, $id, $type ) = @_;
615         my( $bucket, $evt );
616
617         $logger->debug("Fetching container item $id with type $type");
618
619         my $meth = $buckets{$type} . "_item";
620
621         $bucket = $self->simplereq(
622                 'open-ils.cstore',
623                 "open-ils.cstore.direct.container.$meth.retrieve", $id );
624
625
626         my $e = 'CONTAINER_CALL_NUMBER_BUCKET_ITEM_NOT_FOUND';
627         $e = 'CONTAINER_BIBLIO_RECORD_ENTRY_BUCKET_ITEM_NOT_FOUND' if $type eq 'biblio';
628         $e = 'CONTAINER_USER_BUCKET_ITEM_NOT_FOUND' if $type eq 'user';
629         $e = 'CONTAINER_COPY_BUCKET_ITEM_NOT_FOUND' if $type eq 'copy';
630
631         $evt = OpenILS::Event->new(
632                 $e, itemid => $id, container_type => $type ) unless $bucket;
633
634         return ($bucket, $evt);
635 }
636
637
638 sub fetch_patron_standings {
639         my $self = shift;
640         $logger->debug("Fetching patron standings");    
641         return $self->simplereq(
642                 'open-ils.cstore', 
643                 'open-ils.cstore.direct.config.standing.search.atomic', { id => { '!=' => undef } });
644 }
645
646
647 sub fetch_permission_group_tree {
648         my $self = shift;
649         $logger->debug("Fetching patron profiles");     
650         return $self->simplereq(
651                 'open-ils.actor', 
652                 'open-ils.actor.groups.tree.retrieve' );
653 }
654
655 sub fetch_permission_group_descendants {
656     my( $self, $profile ) = @_;
657     my $group_tree = $self->fetch_permission_group_tree();
658     my $start_here;
659     my @groups;
660
661     # FIXME: okay, so it's not an org tree, but it is compatible
662     $self->walk_org_tree($group_tree, sub {
663         my $g = shift;
664         if ($g->id == $profile) {
665             $start_here = $g;
666         }
667     });
668
669     $self->walk_org_tree($start_here, sub {
670         my $g = shift;
671         push(@groups,$g->id);
672     });
673
674     return \@groups;
675 }
676
677 sub fetch_patron_circ_summary {
678         my( $self, $userid ) = @_;
679         $logger->debug("Fetching patron summary for $userid");
680         my $summary = $self->simplereq(
681                 'open-ils.storage', 
682                 "open-ils.storage.action.circulation.patron_summary", $userid );
683
684         if( $summary ) {
685                 $summary->[0] ||= 0;
686                 $summary->[1] ||= 0.0;
687                 return $summary;
688         }
689         return undef;
690 }
691
692
693 sub fetch_copy_statuses {
694         my( $self ) = @_;
695         $logger->debug("Fetching copy statuses");
696         return $self->simplereq(
697                 'open-ils.cstore', 
698                 'open-ils.cstore.direct.config.copy_status.search.atomic', { id => { '!=' => undef } });
699 }
700
701 sub fetch_copy_location {
702         my( $self, $id ) = @_;
703         my $evt;
704         my $cl = $self->cstorereq(
705                 'open-ils.cstore.direct.asset.copy_location.retrieve', $id );
706         $evt = OpenILS::Event->new('ASSET_COPY_LOCATION_NOT_FOUND') unless $cl;
707         return ($cl, $evt);
708 }
709
710 sub fetch_copy_locations {
711         my $self = shift; 
712         return $self->simplereq(
713                 'open-ils.cstore', 
714                 'open-ils.cstore.direct.asset.copy_location.search.atomic', { id => { '!=' => undef } });
715 }
716
717 sub fetch_copy_location_by_name {
718         my( $self, $name, $org ) = @_;
719         my $evt;
720         my $cl = $self->cstorereq(
721                 'open-ils.cstore.direct.asset.copy_location.search',
722                         { name => $name, owning_lib => $org } );
723         $evt = OpenILS::Event->new('ASSET_COPY_LOCATION_NOT_FOUND') unless $cl;
724         return ($cl, $evt);
725 }
726
727 sub fetch_callnumber {
728         my( $self, $id, $flesh, $e ) = @_;
729
730         $e ||= OpenILS::Utils::CStoreEditor->new;
731
732         my $evt = OpenILS::Event->new( 'ASSET_CALL_NUMBER_NOT_FOUND', id => $id );
733         return( undef, $evt ) unless $id;
734
735         $logger->debug("Fetching callnumber $id");
736
737     my $cn = $e->retrieve_asset_call_number([
738         $id,
739         { flesh => $flesh, flesh_fields => { acn => [ 'prefix', 'suffix', 'label_class' ] } },
740     ]);
741
742         return ( $cn, $e->event );
743 }
744
745 my %ORG_CACHE; # - these rarely change, so cache them..
746 sub fetch_org_unit {
747         my( $self, $id ) = @_;
748         return undef unless $id;
749         return $id if( ref($id) eq 'Fieldmapper::actor::org_unit' );
750         return $ORG_CACHE{$id} if $ORG_CACHE{$id};
751         $logger->debug("Fetching org unit $id");
752         my $evt = undef;
753
754         my $org = $self->simplereq(
755                 'open-ils.cstore', 
756                 'open-ils.cstore.direct.actor.org_unit.retrieve', $id );
757         $evt = OpenILS::Event->new( 'ACTOR_ORG_UNIT_NOT_FOUND', id => $id ) unless $org;
758         $ORG_CACHE{$id}  = $org;
759
760         return ($org, $evt);
761 }
762
763 sub fetch_stat_cat {
764         my( $self, $type, $id ) = @_;
765         my( $cat, $evt );
766         $logger->debug("Fetching $type stat cat: $id");
767         $cat = $self->simplereq(
768                 'open-ils.cstore', 
769                 "open-ils.cstore.direct.$type.stat_cat.retrieve", $id );
770
771         my $e = 'ASSET_STAT_CAT_NOT_FOUND';
772         $e = 'ACTOR_STAT_CAT_NOT_FOUND' if $type eq 'actor';
773
774         $evt = OpenILS::Event->new( $e, id => $id ) unless $cat;
775         return ( $cat, $evt );
776 }
777
778 sub fetch_stat_cat_entry {
779         my( $self, $type, $id ) = @_;
780         my( $entry, $evt );
781         $logger->debug("Fetching $type stat cat entry: $id");
782         $entry = $self->simplereq(
783                 'open-ils.cstore', 
784                 "open-ils.cstore.direct.$type.stat_cat_entry.retrieve", $id );
785
786         my $e = 'ASSET_STAT_CAT_ENTRY_NOT_FOUND';
787         $e = 'ACTOR_STAT_CAT_ENTRY_NOT_FOUND' if $type eq 'actor';
788
789         $evt = OpenILS::Event->new( $e, id => $id ) unless $entry;
790         return ( $entry, $evt );
791 }
792
793 sub fetch_stat_cat_entry_default {
794     my( $self, $type, $id ) = @_;
795     my( $entry_default, $evt );
796     $logger->debug("Fetching $type stat cat entry default: $id");
797     $entry_default = $self->simplereq(
798         'open-ils.cstore', 
799         "open-ils.cstore.direct.$type.stat_cat_entry_default.retrieve", $id );
800
801     my $e = 'ASSET_STAT_CAT_ENTRY_DEFAULT_NOT_FOUND';
802     $e = 'ACTOR_STAT_CAT_ENTRY_DEFAULT_NOT_FOUND' if $type eq 'actor';
803
804     $evt = OpenILS::Event->new( $e, id => $id ) unless $entry_default;
805     return ( $entry_default, $evt );
806 }
807
808 sub fetch_stat_cat_entry_default_by_stat_cat_and_org {
809     my( $self, $type, $stat_cat, $orgId ) = @_;
810     my $entry_default;
811     $logger->info("### Fetching $type stat cat entry default with stat_cat $stat_cat owned by org_unit $orgId");
812     $entry_default = $self->simplereq(
813         'open-ils.cstore', 
814         "open-ils.cstore.direct.$type.stat_cat_entry_default.search.atomic", 
815         { stat_cat => $stat_cat, owner => $orgId } );
816
817     $entry_default = $entry_default->[0];
818     return ($entry_default, undef) if $entry_default;
819
820     my $e = 'ASSET_STAT_CAT_ENTRY_DEFAULT_NOT_FOUND';
821     $e = 'ACTOR_STAT_CAT_ENTRY_DEFAULT_NOT_FOUND' if $type eq 'actor';
822     return (undef, OpenILS::Event->new($e) );
823 }
824
825 sub find_org {
826         my( $self, $org_tree, $orgid )  = @_;
827     return undef unless $org_tree and defined $orgid;
828         return $org_tree if ( $org_tree->id eq $orgid );
829         return undef unless ref($org_tree->children);
830         for my $c (@{$org_tree->children}) {
831                 my $o = $self->find_org($c, $orgid);
832                 return $o if $o;
833         }
834         return undef;
835 }
836
837 sub fetch_non_cat_type_by_name_and_org {
838         my( $self, $name, $orgId ) = @_;
839         $logger->debug("Fetching non cat type $name at org $orgId");
840         my $types = $self->simplereq(
841                 'open-ils.cstore',
842                 'open-ils.cstore.direct.config.non_cataloged_type.search.atomic',
843                 { name => $name, owning_lib => $orgId } );
844         return ($types->[0], undef) if($types and @$types);
845         return (undef, OpenILS::Event->new('CONFIG_NON_CATALOGED_TYPE_NOT_FOUND') );
846 }
847
848 sub fetch_non_cat_type {
849         my( $self, $id ) = @_;
850         $logger->debug("Fetching non cat type $id");
851         my( $type, $evt );
852         $type = $self->simplereq(
853                 'open-ils.cstore', 
854                 'open-ils.cstore.direct.config.non_cataloged_type.retrieve', $id );
855         $evt = OpenILS::Event->new('CONFIG_NON_CATALOGED_TYPE_NOT_FOUND') unless $type;
856         return ($type, $evt);
857 }
858
859 sub DB_UPDATE_FAILED { 
860         my( $self, $payload ) = @_;
861         return OpenILS::Event->new('DATABASE_UPDATE_FAILED', 
862                 payload => ($payload) ? $payload : undef ); 
863 }
864
865 sub fetch_booking_reservation {
866         my( $self, $id ) = @_;
867         my( $res, $evt );
868
869         $res = $self->simplereq(
870                 'open-ils.cstore', 
871                 'open-ils.cstore.direct.booking.reservation.retrieve', $id
872         );
873
874         # simplereq doesn't know how to flesh so ...
875         if ($res) {
876                 $res->usr(
877                         $self->simplereq(
878                                 'open-ils.cstore', 
879                                 'open-ils.cstore.direct.actor.user.retrieve', $res->usr
880                         )
881                 );
882
883                 $res->target_resource_type(
884                         $self->simplereq(
885                                 'open-ils.cstore', 
886                                 'open-ils.cstore.direct.booking.resource_type.retrieve', $res->target_resource_type
887                         )
888                 );
889
890                 if ($res->current_resource) {
891                         $res->current_resource(
892                                 $self->simplereq(
893                                         'open-ils.cstore', 
894                                         'open-ils.cstore.direct.booking.resource.retrieve', $res->current_resource
895                                 )
896                         );
897
898                         if ($self->is_true( $res->target_resource_type->catalog_item )) {
899                                 $res->current_resource->catalog_item( $self->fetch_copy_by_barcode( $res->current_resource->barcode ) );
900                         }
901                 }
902
903                 if ($res->target_resource) {
904                         $res->target_resource(
905                                 $self->simplereq(
906                                         'open-ils.cstore', 
907                                         'open-ils.cstore.direct.booking.resource.retrieve', $res->target_resource
908                                 )
909                         );
910
911                         if ($self->is_true( $res->target_resource_type->catalog_item )) {
912                                 $res->target_resource->catalog_item( $self->fetch_copy_by_barcode( $res->target_resource->barcode ) );
913                         }
914                 }
915
916         } else {
917                 $evt = OpenILS::Event->new('RESERVATION_NOT_FOUND');
918         }
919
920         return ($res, $evt);
921 }
922
923 sub fetch_circ_duration_by_name {
924         my( $self, $name ) = @_;
925         my( $dur, $evt );
926         $dur = $self->simplereq(
927                 'open-ils.cstore', 
928                 'open-ils.cstore.direct.config.rules.circ_duration.search.atomic', { name => $name } );
929         $dur = $dur->[0];
930         $evt = OpenILS::Event->new('CONFIG_RULES_CIRC_DURATION_NOT_FOUND') unless $dur;
931         return ($dur, $evt);
932 }
933
934 sub fetch_recurring_fine_by_name {
935         my( $self, $name ) = @_;
936         my( $obj, $evt );
937         $obj = $self->simplereq(
938                 'open-ils.cstore', 
939                 'open-ils.cstore.direct.config.rules.recurring_fine.search.atomic', { name => $name } );
940         $obj = $obj->[0];
941         $evt = OpenILS::Event->new('CONFIG_RULES_RECURRING_FINE_NOT_FOUND') unless $obj;
942         return ($obj, $evt);
943 }
944
945 sub fetch_max_fine_by_name {
946         my( $self, $name ) = @_;
947         my( $obj, $evt );
948         $obj = $self->simplereq(
949                 'open-ils.cstore', 
950                 'open-ils.cstore.direct.config.rules.max_fine.search.atomic', { name => $name } );
951         $obj = $obj->[0];
952         $evt = OpenILS::Event->new('CONFIG_RULES_MAX_FINE_NOT_FOUND') unless $obj;
953         return ($obj, $evt);
954 }
955
956 sub fetch_hard_due_date_by_name {
957         my( $self, $name ) = @_;
958         my( $obj, $evt );
959         $obj = $self->simplereq(
960                 'open-ils.cstore', 
961                 'open-ils.cstore.direct.config.hard_due_date.search.atomic', { name => $name } );
962         $obj = $obj->[0];
963         $evt = OpenILS::Event->new('CONFIG_RULES_HARD_DUE_DATE_NOT_FOUND') unless $obj;
964         return ($obj, $evt);
965 }
966
967 sub storagereq {
968         my( $self, $method, @params ) = @_;
969         return $self->simplereq(
970                 'open-ils.storage', $method, @params );
971 }
972
973 sub storagereq_xact {
974         my($self, $method, @params) = @_;
975         my $ses = $self->start_db_session();
976         my $val = $ses->request($method, @params)->gather(1);
977         $self->rollback_db_session($ses);
978     return $val;
979 }
980
981 sub cstorereq {
982         my( $self, $method, @params ) = @_;
983         return $self->simplereq(
984                 'open-ils.cstore', $method, @params );
985 }
986
987 sub event_equals {
988         my( $self, $e, $name ) =  @_;
989         if( $e and ref($e) eq 'HASH' and 
990                 defined($e->{textcode}) and $e->{textcode} eq $name ) {
991                 return 1 ;
992         }
993         return 0;
994 }
995
996 sub logmark {
997         my( undef, $f, $l ) = caller(0);
998         my( undef, undef, undef, $s ) = caller(1);
999         $s =~ s/.*:://g;
1000         $f =~ s/.*\///g;
1001         $logger->debug("LOGMARK: $f:$l:$s");
1002 }
1003
1004 # takes a copy id 
1005 sub fetch_open_circulation {
1006         my( $self, $cid ) = @_;
1007         $self->logmark;
1008
1009         my $e = OpenILS::Utils::CStoreEditor->new;
1010     my $circ = $e->search_action_circulation({
1011         target_copy => $cid, 
1012         stop_fines_time => undef, 
1013         checkin_time => undef
1014     })->[0];
1015     
1016     return ($circ, $e->event);
1017 }
1018
1019 my $copy_statuses;
1020 sub copy_status_from_name {
1021         my( $self, $name ) = @_;
1022         $copy_statuses = $self->fetch_copy_statuses unless $copy_statuses;
1023         for my $status (@$copy_statuses) { 
1024                 return $status if( $status->name =~ /$name/i );
1025         }
1026         return undef;
1027 }
1028
1029 sub copy_status_to_name {
1030         my( $self, $sid ) = @_;
1031         $copy_statuses = $self->fetch_copy_statuses unless $copy_statuses;
1032         for my $status (@$copy_statuses) { 
1033                 return $status->name if( $status->id == $sid );
1034         }
1035         return undef;
1036 }
1037
1038
1039 sub copy_status {
1040         my( $self, $arg ) = @_;
1041         return $arg if ref $arg;
1042         $copy_statuses = $self->fetch_copy_statuses unless $copy_statuses;
1043         my ($stat) = grep { $_->id == $arg } @$copy_statuses;
1044         return $stat;
1045 }
1046
1047 sub fetch_open_transit_by_copy {
1048         my( $self, $copyid ) = @_;
1049         my($transit, $evt);
1050         $transit = $self->cstorereq(
1051                 'open-ils.cstore.direct.action.transit_copy.search',
1052                 { target_copy => $copyid, dest_recv_time => undef });
1053         $evt = OpenILS::Event->new('ACTION_TRANSIT_COPY_NOT_FOUND') unless $transit;
1054         return ($transit, $evt);
1055 }
1056
1057 sub unflesh_copy {
1058         my( $self, $copy ) = @_;
1059         return undef unless $copy;
1060         $copy->status( $copy->status->id ) if ref($copy->status);
1061         $copy->location( $copy->location->id ) if ref($copy->location);
1062         $copy->circ_lib( $copy->circ_lib->id ) if ref($copy->circ_lib);
1063         return $copy;
1064 }
1065
1066 sub unflesh_reservation {
1067         my( $self, $reservation ) = @_;
1068         return undef unless $reservation;
1069         $reservation->usr( $reservation->usr->id ) if ref($reservation->usr);
1070         $reservation->target_resource_type( $reservation->target_resource_type->id ) if ref($reservation->target_resource_type);
1071         $reservation->target_resource( $reservation->target_resource->id ) if ref($reservation->target_resource);
1072         $reservation->current_resource( $reservation->current_resource->id ) if ref($reservation->current_resource);
1073         return $reservation;
1074 }
1075
1076 # un-fleshes a copy and updates it in the DB
1077 # returns a DB_UPDATE_FAILED event on error
1078 # returns undef on success
1079 sub update_copy {
1080         my( $self, %params ) = @_;
1081
1082         my $copy                = $params{copy} || die "update_copy(): copy required";
1083         my $editor      = $params{editor} || die "update_copy(): copy editor required";
1084         my $session = $params{session};
1085
1086         $logger->debug("Updating copy in the database: " . $copy->id);
1087
1088         $self->unflesh_copy($copy);
1089         $copy->editor( $editor );
1090         $copy->edit_date( 'now' );
1091
1092         my $s;
1093         my $meth = 'open-ils.storage.direct.asset.copy.update';
1094
1095         $s = $session->request( $meth, $copy )->gather(1) if $session;
1096         $s = $self->storagereq( $meth, $copy ) unless $session;
1097
1098         $logger->debug("Update of copy ".$copy->id." returned: $s");
1099
1100         return $self->DB_UPDATE_FAILED($copy) unless $s;
1101         return undef;
1102 }
1103
1104 sub update_reservation {
1105         my( $self, %params ) = @_;
1106
1107         my $reservation = $params{reservation}  || die "update_reservation(): reservation required";
1108         my $editor              = $params{editor} || die "update_reservation(): copy editor required";
1109         my $session             = $params{session};
1110
1111         $logger->debug("Updating copy in the database: " . $reservation->id);
1112
1113         $self->unflesh_reservation($reservation);
1114
1115         my $s;
1116         my $meth = 'open-ils.cstore.direct.booking.reservation.update';
1117
1118         $s = $session->request( $meth, $reservation )->gather(1) if $session;
1119         $s = $self->cstorereq( $meth, $reservation ) unless $session;
1120
1121         $logger->debug("Update of copy ".$reservation->id." returned: $s");
1122
1123         return $self->DB_UPDATE_FAILED($reservation) unless $s;
1124         return undef;
1125 }
1126
1127 sub fetch_billable_xact {
1128         my( $self, $id ) = @_;
1129         my($xact, $evt);
1130         $logger->debug("Fetching billable transaction %id");
1131         $xact = $self->cstorereq(
1132                 'open-ils.cstore.direct.money.billable_transaction.retrieve', $id );
1133         $evt = OpenILS::Event->new('MONEY_BILLABLE_TRANSACTION_NOT_FOUND') unless $xact;
1134         return ($xact, $evt);
1135 }
1136
1137 sub fetch_billable_xact_summary {
1138         my( $self, $id ) = @_;
1139         my($xact, $evt);
1140         $logger->debug("Fetching billable transaction summary %id");
1141         $xact = $self->cstorereq(
1142                 'open-ils.cstore.direct.money.billable_transaction_summary.retrieve', $id );
1143         $evt = OpenILS::Event->new('MONEY_BILLABLE_TRANSACTION_NOT_FOUND') unless $xact;
1144         return ($xact, $evt);
1145 }
1146
1147 sub fetch_fleshed_copy {
1148         my( $self, $id ) = @_;
1149         my( $copy, $evt );
1150         $logger->info("Fetching fleshed copy $id");
1151         $copy = $self->cstorereq(
1152                 "open-ils.cstore.direct.asset.copy.retrieve", $id,
1153                 { flesh => 1,
1154                   flesh_fields => { acp => [ qw/ circ_lib location status stat_cat_entries / ] }
1155                 }
1156         );
1157         $evt = OpenILS::Event->new('ASSET_COPY_NOT_FOUND', id => $id) unless $copy;
1158         return ($copy, $evt);
1159 }
1160
1161
1162 # returns the org that owns the callnumber that the copy
1163 # is attached to
1164 sub fetch_copy_owner {
1165         my( $self, $copyid ) = @_;
1166         my( $copy, $cn, $evt );
1167         $logger->debug("Fetching copy owner $copyid");
1168         ($copy, $evt) = $self->fetch_copy($copyid);
1169         return (undef,$evt) if $evt;
1170         ($cn, $evt) = $self->fetch_callnumber($copy->call_number);
1171         return (undef,$evt) if $evt;
1172         return ($cn->owning_lib);
1173 }
1174
1175 sub fetch_copy_note {
1176         my( $self, $id ) = @_;
1177         my( $note, $evt );
1178         $logger->debug("Fetching copy note $id");
1179         $note = $self->cstorereq(
1180                 'open-ils.cstore.direct.asset.copy_note.retrieve', $id );
1181         $evt = OpenILS::Event->new('ASSET_COPY_NOTE_NOT_FOUND', id => $id ) unless $note;
1182         return ($note, $evt);
1183 }
1184
1185 sub fetch_call_numbers_by_title {
1186         my( $self, $titleid ) = @_;
1187         $logger->info("Fetching call numbers by title $titleid");
1188         return $self->cstorereq(
1189                 'open-ils.cstore.direct.asset.call_number.search.atomic', 
1190                 { record => $titleid, deleted => 'f' });
1191                 #'open-ils.storage.direct.asset.call_number.search.record.atomic', $titleid);
1192 }
1193
1194 sub fetch_copies_by_call_number {
1195         my( $self, $cnid ) = @_;
1196         $logger->info("Fetching copies by call number $cnid");
1197         return $self->cstorereq(
1198                 'open-ils.cstore.direct.asset.copy.search.atomic', { call_number => $cnid, deleted => 'f' } );
1199                 #'open-ils.storage.direct.asset.copy.search.call_number.atomic', $cnid );
1200 }
1201
1202 sub fetch_user_by_barcode {
1203         my( $self, $bc ) = @_;
1204         my $cardid = $self->cstorereq(
1205                 'open-ils.cstore.direct.actor.card.id_list', { barcode => $bc } );
1206         return (undef, OpenILS::Event->new('ACTOR_CARD_NOT_FOUND', barcode => $bc)) unless $cardid;
1207         my $user = $self->cstorereq(
1208                 'open-ils.cstore.direct.actor.user.search', { card => $cardid } );
1209         return (undef, OpenILS::Event->new('ACTOR_USER_NOT_FOUND', card => $cardid)) unless $user;
1210         return ($user);
1211         
1212 }
1213
1214 sub fetch_bill {
1215         my( $self, $billid ) = @_;
1216         $logger->debug("Fetching billing $billid");
1217         my $bill = $self->cstorereq(
1218                 'open-ils.cstore.direct.money.billing.retrieve', $billid );
1219         my $evt = OpenILS::Event->new('MONEY_BILLING_NOT_FOUND') unless $bill;
1220         return($bill, $evt);
1221 }
1222
1223 my $ORG_TREE;
1224 sub fetch_org_tree {
1225         my $self = shift;
1226         return $ORG_TREE if $ORG_TREE;
1227         return $ORG_TREE = OpenILS::Utils::CStoreEditor->new->search_actor_org_unit( 
1228                 [
1229                         {"parent_ou" => undef },
1230                         {
1231                                 flesh                           => -1,
1232                                 flesh_fields    => { aou =>  ['children'] },
1233                                 order_by       => { aou => 'name'}
1234                         }
1235                 ]
1236         )->[0];
1237 }
1238
1239 sub walk_org_tree {
1240         my( $self, $node, $callback ) = @_;
1241         return unless $node;
1242         $callback->($node);
1243         if( $node->children ) {
1244                 $self->walk_org_tree($_, $callback) for @{$node->children};
1245         }
1246 }
1247
1248 sub is_true {
1249         my( $self, $item ) = @_;
1250         return 1 if $item and $item !~ /^f$/i;
1251         return 0;
1252 }
1253
1254
1255 sub patientreq {
1256     my ($self, $client, $service, $method, @params) = @_;
1257     my ($response, $err);
1258
1259     my $session = create OpenSRF::AppSession($service);
1260     my $request = $session->request($method, @params);
1261
1262     my $spurt = 10;
1263     my $give_up = time + 1000;
1264
1265     try {
1266         while (time < $give_up) {
1267             $response = $request->recv("timeout" => $spurt);
1268             last if $request->complete;
1269
1270             $client->status(new OpenSRF::DomainObject::oilsContinueStatus);
1271         }
1272     } catch Error with {
1273         $err = shift;
1274     };
1275
1276     if ($err) {
1277         warn "received error : service=$service : method=$method : params=".Dumper(\@params) . "\n $err";
1278         throw $err ("Call to $service for method $method \n failed with exception: $err : " );
1279     }
1280
1281     return $response->content;
1282 }
1283
1284 # This logic now lives in storage
1285 sub __patron_money_owed {
1286         my( $self, $patronid ) = @_;
1287         my $ses = OpenSRF::AppSession->create('open-ils.storage');
1288         my $req = $ses->request(
1289                 'open-ils.storage.money.billable_transaction.summary.search',
1290                 { usr => $patronid, xact_finish => undef } );
1291
1292         my $total = 0;
1293         my $data;
1294         while( $data = $req->recv ) {
1295                 $data = $data->content;
1296                 $total += $data->balance_owed;
1297         }
1298         return $total;
1299 }
1300
1301 sub patron_money_owed {
1302         my( $self, $userid ) = @_;
1303         my $ses = $self->start_db_session();
1304         my $val = $ses->request(
1305                 'open-ils.storage.actor.user.total_owed', $userid)->gather(1);
1306         $self->rollback_db_session($ses);
1307         return $val;
1308 }
1309
1310 sub patron_total_items_out {
1311         my( $self, $userid ) = @_;
1312         my $ses = $self->start_db_session();
1313         my $val = $ses->request(
1314                 'open-ils.storage.actor.user.total_out', $userid)->gather(1);
1315         $self->rollback_db_session($ses);
1316         return $val;
1317 }
1318
1319
1320
1321
1322 #---------------------------------------------------------------------
1323 # Returns  ($summary, $event) 
1324 #---------------------------------------------------------------------
1325 sub fetch_mbts {
1326         my $self = shift;
1327         my $id  = shift;
1328         my $e = shift || OpenILS::Utils::CStoreEditor->new;
1329         $id = $id->id if ref($id);
1330     
1331     my $xact = $e->retrieve_money_billable_transaction_summary($id)
1332             or return (undef, $e->event);
1333
1334     return ($xact);
1335 }
1336
1337
1338 #---------------------------------------------------------------------
1339 # Given a list of money.billable_transaction objects, this creates
1340 # transaction summary objects for each
1341 #--------------------------------------------------------------------
1342 sub make_mbts {
1343         my $self = shift;
1344     my $e = shift;
1345         my @xacts = @_;
1346         return () if (!@xacts);
1347     return @{$e->search_money_billable_transaction_summary({id => [ map { $_->id } @xacts ]})};
1348 }
1349                 
1350                 
1351 sub ou_ancestor_setting_value {
1352     my($self, $org_id, $name, $e) = @_;
1353     $e = $e || OpenILS::Utils::CStoreEditor->new;
1354     my $set = $self->ou_ancestor_setting($org_id, $name, $e);
1355     return $set->{value} if $set;
1356     return undef;
1357 }
1358
1359
1360 # If an authentication token is provided AND this org unit setting has a
1361 # view_perm, then make sure the user referenced by the auth token has
1362 # that permission.  This means that if you call this method without an
1363 # authtoken param, you can get whatever org unit setting values you want.
1364 # API users beware.
1365 #
1366 # NOTE: If you supply an editor ($e) arg AND an auth token arg, the editor's
1367 # authtoken is checked, but the $auth arg is NOT checked.  To say that another
1368 # way, be sure NOT to pass an editor argument if you want your token checked.
1369 # Otherwise the auth arg is just a flag saying "check the editor".  
1370
1371 sub ou_ancestor_setting {
1372     my( $self, $orgid, $name, $e, $auth ) = @_;
1373     $e = $e || OpenILS::Utils::CStoreEditor->new(
1374         (defined $auth) ? (authtoken => $auth) : ()
1375     );
1376     my $coust = $e->retrieve_config_org_unit_setting_type([
1377         $name, {flesh => 1, flesh_fields => {coust => ['view_perm']}}
1378     ]);
1379
1380     if ($auth && $coust && $coust->view_perm) {
1381         # And you can't have permission if you don't have a valid session.
1382         return undef if not $e->checkauth;
1383         # And now that we know you MIGHT have permission, we check it.
1384         return undef if not $e->allowed($coust->view_perm->code, $orgid);
1385     }
1386
1387     my $query = {from => ['actor.org_unit_ancestor_setting', $name, $orgid]};
1388     my $setting = $e->json_query($query)->[0];
1389     return undef unless $setting;
1390     return {org => $setting->{org_unit}, value => OpenSRF::Utils::JSON->JSON2perl($setting->{value})};
1391 }       
1392                 
1393
1394 # returns the ISO8601 string representation of the requested epoch in GMT
1395 sub epoch2ISO8601 {
1396     my( $self, $epoch ) = @_;
1397     my ($sec,$min,$hour,$mday,$mon,$year) = gmtime($epoch);
1398     $year += 1900; $mon += 1;
1399     my $date = sprintf(
1400         '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1401         $year, $mon, $mday, $hour, $min, $sec);
1402     return $date;
1403 }
1404                         
1405 sub find_highest_perm_org {
1406         my ( $self, $perm, $userid, $start_org, $org_tree ) = @_;
1407         my $org = $self->find_org($org_tree, $start_org );
1408
1409         my $lastid = -1;
1410         while( $org ) {
1411                 last if ($self->check_perms( $userid, $org->id, $perm )); # perm failed
1412                 $lastid = $org->id;
1413                 $org = $self->find_org( $org_tree, $org->parent_ou() );
1414         }
1415
1416         return $lastid;
1417 }
1418
1419
1420 # returns the org_unit ID's 
1421 sub user_has_work_perm_at {
1422     my($self, $e, $perm, $options, $user_id) = @_;
1423     $options ||= {};
1424     $user_id = (defined $user_id) ? $user_id : $e->requestor->id;
1425
1426     my $func = 'permission.usr_has_perm_at';
1427     $func = $func.'_all' if $$options{descendants};
1428
1429     my $orgs = $e->json_query({from => [$func, $user_id, $perm]});
1430     $orgs = [map { $_->{ (keys %$_)[0] } } @$orgs];
1431
1432     return $orgs unless $$options{objects};
1433
1434     return $e->search_actor_org_unit({id => $orgs});
1435 }
1436
1437 sub get_user_work_ou_ids {
1438     my($self, $e, $userid) = @_;
1439     my $work_orgs = $e->json_query({
1440         select => {puwoum => ['work_ou']},
1441         from => 'puwoum',
1442         where => {usr => $e->requestor->id}});
1443
1444     return [] unless @$work_orgs;
1445     my @work_orgs;
1446     push(@work_orgs, $_->{work_ou}) for @$work_orgs;
1447
1448     return \@work_orgs;
1449 }
1450
1451
1452 my $org_types;
1453 sub get_org_types {
1454         my($self, $client) = @_;
1455         return $org_types if $org_types;
1456         return $org_types = OpenILS::Utils::CStoreEditor->new->retrieve_all_actor_org_unit_type();
1457 }
1458
1459 sub get_org_tree {
1460         my $self = shift;
1461         my $locale = shift || '';
1462         my $cache = OpenSRF::Utils::Cache->new("global", 0);
1463         my $tree = $cache->get_cache("orgtree.$locale");
1464         return $tree if $tree;
1465
1466         my $ses = OpenILS::Utils::CStoreEditor->new;
1467         $ses->session->session_locale($locale);
1468         $tree = $ses->search_actor_org_unit( 
1469                 [
1470                         {"parent_ou" => undef },
1471                         {
1472                                 flesh                           => -1,
1473                                 flesh_fields    => { aou =>  ['children'] },
1474                                 order_by                        => { aou => 'name'}
1475                         }
1476                 ]
1477         )->[0];
1478
1479         $cache->put_cache("orgtree.$locale", $tree);
1480         return $tree;
1481 }
1482
1483 sub get_org_descendants {
1484         my($self, $org_id, $depth) = @_;
1485
1486         my $select = {
1487                 transform => 'actor.org_unit_descendants',
1488                 column => 'id',
1489                 result_field => 'id',
1490         };
1491         $select->{params} = [$depth] if defined $depth;
1492
1493         my $org_list = OpenILS::Utils::CStoreEditor->new->json_query({
1494                 select => {aou => [$select]},
1495         from => 'aou',
1496                 where => {id => $org_id}
1497         });
1498         my @orgs;
1499         push(@orgs, $_->{id}) for @$org_list;
1500         return \@orgs;
1501 }
1502
1503 sub get_org_ancestors {
1504         my($self, $org_id, $use_cache) = @_;
1505
1506     my ($cache, $orgs);
1507
1508     if ($use_cache) {
1509         $cache = OpenSRF::Utils::Cache->new("global", 0);
1510         $orgs = $cache->get_cache("org.ancestors.$org_id");
1511         return $orgs if $orgs;
1512     }
1513
1514         my $org_list = OpenILS::Utils::CStoreEditor->new->json_query({
1515                 select => {
1516                         aou => [{
1517                                 transform => 'actor.org_unit_ancestors',
1518                                 column => 'id',
1519                                 result_field => 'id',
1520                                 params => []
1521                         }],
1522                 },
1523                 from => 'aou',
1524                 where => {id => $org_id}
1525         });
1526
1527         $orgs = [ map { $_->{id} } @$org_list ];
1528
1529     $cache->put_cache("org.ancestors.$org_id", $orgs) if $use_cache;
1530         return $orgs;
1531 }
1532
1533 sub get_org_full_path {
1534         my($self, $org_id, $depth) = @_;
1535
1536     my $query = {
1537         select => {
1538                         aou => [{
1539                                 transform => 'actor.org_unit_full_path',
1540                                 column => 'id',
1541                                 result_field => 'id',
1542                         }],
1543                 },
1544                 from => 'aou',
1545                 where => {id => $org_id}
1546         };
1547
1548     $query->{select}->{aou}->[0]->{params} = [$depth] if defined $depth;
1549         my $org_list = OpenILS::Utils::CStoreEditor->new->json_query($query);
1550     return [ map {$_->{id}} @$org_list ];
1551 }
1552
1553 # returns the ID of the org unit ancestor at the specified depth
1554 sub org_unit_ancestor_at_depth {
1555     my($class, $org_id, $depth) = @_;
1556     my $resp = OpenILS::Utils::CStoreEditor->new->json_query(
1557         {from => ['actor.org_unit_ancestor_at_depth', $org_id, $depth]})->[0];
1558     return ($resp) ? $resp->{id} : undef;
1559 }
1560
1561 # returns the user's configured locale as a string.  Defaults to en-US if none is configured.
1562 sub get_user_locale {
1563         my($self, $user_id, $e) = @_;
1564         $e ||= OpenILS::Utils::CStoreEditor->new;
1565
1566         # first, see if the user has an explicit locale set
1567         my $setting = $e->search_actor_user_setting(
1568                 {usr => $user_id, name => 'global.locale'})->[0];
1569         return OpenSRF::Utils::JSON->JSON2perl($setting->value) if $setting;
1570
1571         my $user = $e->retrieve_actor_user($user_id) or return $e->event;
1572         return $self->get_org_locale($user->home_ou, $e);
1573 }
1574
1575 # returns org locale setting
1576 sub get_org_locale {
1577         my($self, $org_id, $e) = @_;
1578         $e ||= OpenILS::Utils::CStoreEditor->new;
1579
1580         my $locale;
1581         if(defined $org_id) {
1582                 $locale = $self->ou_ancestor_setting_value($org_id, 'global.default_locale', $e);
1583                 return $locale if $locale;
1584         }
1585
1586         # system-wide default
1587         my $sclient = OpenSRF::Utils::SettingsClient->new;
1588         $locale = $sclient->config_value('default_locale');
1589     return $locale if $locale;
1590
1591         # if nothing else, fallback to locale=cowboy
1592         return 'en-US';
1593 }
1594
1595
1596 # xml-escape non-ascii characters
1597 sub entityize { 
1598     my($self, $string, $form) = @_;
1599         $form ||= "";
1600
1601         # If we're going to convert non-ASCII characters to XML entities,
1602         # we had better be dealing with a UTF8 string to begin with
1603         $string = decode_utf8($string);
1604
1605         if ($form eq 'D') {
1606                 $string = NFD($string);
1607         } else {
1608                 $string = NFC($string);
1609         }
1610
1611         # Convert raw ampersands to entities
1612         $string =~ s/&(?!\S+;)/&amp;/gso;
1613
1614         # Convert Unicode characters to entities
1615         $string =~ s/([\x{0080}-\x{fffd}])/sprintf('&#x%X;',ord($1))/sgoe;
1616
1617         return $string;
1618 }
1619
1620 # x0000-x0008 isn't legal in XML documents
1621 # XXX Perhaps this should just go into our standard entityize method
1622 sub strip_ctrl_chars {
1623         my ($self, $string) = @_;
1624
1625         $string =~ s/([\x{0000}-\x{0008}])//sgoe; 
1626         return $string;
1627 }
1628
1629 sub get_copy_price {
1630         my($self, $e, $copy, $volume) = @_;
1631
1632         $copy->price(0) if $copy->price and $copy->price < 0;
1633
1634         return $copy->price if $copy->price and $copy->price > 0;
1635
1636
1637         my $owner;
1638         if(ref $volume) {
1639                 if($volume->id == OILS_PRECAT_CALL_NUMBER) {
1640                         $owner = $copy->circ_lib;
1641                 } else {
1642                         $owner = $volume->owning_lib;
1643                 }
1644         } else {
1645                 if($copy->call_number == OILS_PRECAT_CALL_NUMBER) {
1646                         $owner = $copy->circ_lib;
1647                 } else {
1648                         $owner = $e->retrieve_asset_call_number($copy->call_number)->owning_lib;
1649                 }
1650         }
1651
1652         my $default_price = $self->ou_ancestor_setting_value(
1653                 $owner, OILS_SETTING_DEF_ITEM_PRICE, $e) || 0;
1654
1655         return $default_price unless defined $copy->price;
1656
1657         # price is 0.  Use the default?
1658     my $charge_on_0 = $self->ou_ancestor_setting_value(
1659         $owner, OILS_SETTING_CHARGE_LOST_ON_ZERO, $e) || 0;
1660
1661         return $default_price if $charge_on_0;
1662         return 0;
1663 }
1664
1665 # given a transaction ID, this returns the context org_unit for the transaction
1666 sub xact_org {
1667     my($self, $xact_id, $e) = @_;
1668     $e ||= OpenILS::Utils::CStoreEditor->new;
1669     
1670     my $loc = $e->json_query({
1671         "select" => {circ => ["circ_lib"]},
1672         from     => "circ",
1673         "where"  => {id => $xact_id},
1674     });
1675
1676     return $loc->[0]->{circ_lib} if @$loc;
1677
1678     $loc = $e->json_query({
1679         "select" => {bresv => ["request_lib"]},
1680         from     => "bresv",
1681         "where"  => {id => $xact_id},
1682     });
1683
1684     return $loc->[0]->{request_lib} if @$loc;
1685
1686     $loc = $e->json_query({
1687         "select" => {mg => ["billing_location"]},
1688         from     => "mg",
1689         "where"  => {id => $xact_id},
1690     });
1691
1692     return $loc->[0]->{billing_location};
1693 }
1694
1695
1696 sub find_event_def_by_hook {
1697     my($self, $hook, $context_org, $e) = @_;
1698
1699     $e ||= OpenILS::Utils::CStoreEditor->new;
1700
1701     my $orgs = $self->get_org_ancestors($context_org);
1702
1703     # search from the context org up
1704     for my $org_id (reverse @$orgs) {
1705
1706         my $def = $e->search_action_trigger_event_definition(
1707             {hook => $hook, owner => $org_id})->[0];
1708
1709         return $def if $def;
1710     }
1711
1712     return undef;
1713 }
1714
1715
1716
1717 # If an event_def ID is not provided, use the hook and context org to find the 
1718 # most appropriate event.  create the event, fire it, then return the resulting
1719 # event with fleshed template_output and error_output
1720 sub fire_object_event {
1721     my($self, $event_def, $hook, $object, $context_org, $granularity, $user_data, $client) = @_;
1722
1723     my $e = OpenILS::Utils::CStoreEditor->new;
1724     my $def;
1725
1726     my $auto_method = "open-ils.trigger.event.autocreate.by_definition";
1727
1728     if($event_def) {
1729         $def = $e->retrieve_action_trigger_event_definition($event_def)
1730             or return $e->event;
1731
1732         $auto_method .= '.include_inactive';
1733
1734     } else {
1735
1736         # find the most appropriate event def depending on context org
1737         $def = $self->find_event_def_by_hook($hook, $context_org, $e) 
1738             or return $e->event;
1739     }
1740
1741     my $final_resp;
1742
1743     if($def->group_field) {
1744         # we have a list of objects
1745         $object = [$object] unless ref $object eq 'ARRAY';
1746
1747         my @event_ids;
1748         $user_data ||= [];
1749         for my $i (0..$#$object) {
1750             my $obj = $$object[$i];
1751             my $udata = $$user_data[$i];
1752             my $event_id = $self->simplereq(
1753                 'open-ils.trigger', $auto_method, $def->id, $obj, $context_org, $udata);
1754             push(@event_ids, $event_id);
1755         }
1756
1757         $logger->info("EVENTS = " . OpenSRF::Utils::JSON->perl2JSON(\@event_ids));
1758
1759         my $resp;
1760         if (not defined $client) {
1761             $resp = $self->simplereq(
1762                 'open-ils.trigger',
1763                 'open-ils.trigger.event_group.fire',
1764                 \@event_ids);
1765         } else {
1766             $resp = $self->patientreq(
1767                 $client,
1768                 "open-ils.trigger", "open-ils.trigger.event_group.fire",
1769                 \@event_ids
1770             );
1771         }
1772
1773         if($resp and $resp->{events} and @{$resp->{events}}) {
1774
1775             $e->xact_begin;
1776             $final_resp = $e->retrieve_action_trigger_event([
1777                 $resp->{events}->[0]->id,
1778                 {flesh => 1, flesh_fields => {atev => ['template_output', 'error_output']}}
1779             ]);
1780             $e->rollback;
1781         }
1782
1783     } else {
1784
1785         $object = $$object[0] if ref $object eq 'ARRAY';
1786
1787         my $event_id;
1788         my $resp;
1789
1790         if (not defined $client) {
1791             $event_id = $self->simplereq(
1792                 'open-ils.trigger',
1793                 $auto_method, $def->id, $object, $context_org, $user_data
1794             );
1795
1796             $resp = $self->simplereq(
1797                 'open-ils.trigger',
1798                 'open-ils.trigger.event.fire',
1799                 $event_id
1800             );
1801         } else {
1802             $event_id = $self->patientreq(
1803                 $client,
1804                 'open-ils.trigger',
1805                 $auto_method, $def->id, $object, $context_org, $user_data
1806             );
1807
1808             $resp = $self->patientreq(
1809                 $client,
1810                 'open-ils.trigger',
1811                 'open-ils.trigger.event.fire',
1812                 $event_id
1813             );
1814         }
1815         
1816         if($resp and $resp->{event}) {
1817             $e->xact_begin;
1818             $final_resp = $e->retrieve_action_trigger_event([
1819                 $resp->{event}->id,
1820                 {flesh => 1, flesh_fields => {atev => ['template_output', 'error_output']}}
1821             ]);
1822             $e->rollback;
1823         }
1824     }
1825
1826     return $final_resp;
1827 }
1828
1829
1830 sub create_events_for_hook {
1831     my($self, $hook, $obj, $org_id, $granularity, $user_data, $wait) = @_;
1832     my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1833     my $req = $ses->request('open-ils.trigger.event.autocreate', 
1834         $hook, $obj, $org_id, $granularity, $user_data);
1835     return undef unless $wait;
1836     my $resp = $req->recv;
1837     return $resp->content if $resp;
1838 }
1839
1840 sub create_uuid_string {
1841     return create_UUID_as_string();
1842 }
1843
1844 sub create_circ_chain_summary {
1845     my($class, $e, $circ_id) = @_;
1846     my $sum = $e->json_query({from => ['action.summarize_circ_chain', $circ_id]})->[0];
1847     return undef unless $sum;
1848     my $obj = Fieldmapper::action::circ_chain_summary->new;
1849     $obj->$_($sum->{$_}) for keys %$sum;
1850     return $obj;
1851 }
1852
1853
1854 # Returns "mra" attribute key/value pairs for a set of bre's
1855 # Takes a list of bre IDs, returns a hash of hashes,
1856 # {bre_id1 => {key1 => {code => value1, label => label1}, ...}...}
1857 my $ccvm_cache;
1858 sub get_bre_attrs {
1859     my ($class, $bre_ids, $e) = @_;
1860     $e = $e || OpenILS::Utils::CStoreEditor->new;
1861
1862     my $attrs = {};
1863     return $attrs unless defined $bre_ids;
1864     $bre_ids = [$bre_ids] unless ref $bre_ids;
1865
1866     my $mra = $e->json_query({
1867         select => {
1868             mra => [
1869                 {
1870                     column => 'id',
1871                     alias => 'bre'
1872                 }, {
1873                     column => 'attrs',
1874                     transform => 'each',
1875                     result_field => 'key',
1876                     alias => 'key'
1877                 },{
1878                     column => 'attrs',
1879                     transform => 'each',
1880                     result_field => 'value',
1881                     alias => 'value'
1882                 }
1883             ]
1884         },
1885         from => 'mra',
1886         where => {id => $bre_ids}
1887     });
1888
1889     return $attrs unless $mra;
1890
1891     $ccvm_cache = $ccvm_cache || $e->search_config_coded_value_map({id => {'!=' => undef}});
1892
1893     for my $id (@$bre_ids) {
1894         $attrs->{$id} = {};
1895         for my $mra (grep { $_->{bre} eq $id } @$mra) {
1896             my $ctype = $mra->{key};
1897             my $code = $mra->{value};
1898             $attrs->{$id}->{$ctype} = {code => $code};
1899             if($code) {
1900                 my ($ccvm) = grep { $_->ctype eq $ctype and $_->code eq $code } @$ccvm_cache;
1901                 $attrs->{$id}->{$ctype}->{label} = $ccvm->value if $ccvm;
1902             }
1903         }
1904     }
1905
1906     return $attrs;
1907 }
1908
1909 # Shorter version of bib_container_items_via_search() below, only using
1910 # the queryparser record_list filter instead of the container filter.
1911 sub bib_record_list_via_search {
1912     my ($class, $search_query, $search_args) = @_;
1913
1914     # First, Use search API to get container items sorted in any way that crad
1915     # sorters support.
1916     my $search_result = $class->simplereq(
1917         "open-ils.search", "open-ils.search.biblio.multiclass.query",
1918         $search_args, $search_query
1919     );
1920
1921     unless ($search_result) {
1922         # empty result sets won't cause this, but actual errors should.
1923         $logger->warn("bib_record_list_via_search() got nothing from search");
1924         return;
1925     }
1926
1927     # Throw away other junk from search, keeping only bib IDs.
1928     return [ map { pop @$_ } @{$search_result->{ids}} ];
1929 }
1930
1931 # 'no_flesh' avoids fleshing the target_biblio_record_entry
1932 sub bib_container_items_via_search {
1933     my ($class, $container_id, $search_query, $search_args, $no_flesh) = @_;
1934
1935     # First, Use search API to get container items sorted in any way that crad
1936     # sorters support.
1937     my $search_result = $class->simplereq(
1938         "open-ils.search", "open-ils.search.biblio.multiclass.query",
1939         $search_args, $search_query
1940     );
1941     unless ($search_result) {
1942         # empty result sets won't cause this, but actual errors should.
1943         $logger->warn("bib_container_items_via_search() got nothing from search");
1944         return;
1945     }
1946
1947     # Throw away other junk from search, keeping only bib IDs.
1948     my $id_list = [ map { pop @$_ } @{$search_result->{ids}} ];
1949
1950     return [] unless @$id_list;
1951
1952     # Now get the bib container items themselves...
1953     my $e = new OpenILS::Utils::CStoreEditor;
1954     unless ($e) {
1955         $logger->warn("bib_container_items_via_search() couldn't get cstoreeditor");
1956         return;
1957     }
1958
1959     my @flesh_fields = qw/notes/;
1960     push(@flesh_fields, 'target_biblio_record_entry') unless $no_flesh;
1961
1962     my $items = $e->search_container_biblio_record_entry_bucket_item([
1963         {
1964             "target_biblio_record_entry" => $id_list,
1965             "bucket" => $container_id
1966         }, {
1967             flesh => 1,
1968             flesh_fields => {"cbrebi" => \@flesh_fields}
1969         }
1970     ]);
1971     unless ($items) {
1972         $logger->warn(
1973             "bib_container_items_via_search() couldn't get bucket items: " .
1974             $e->die_event->{textcode}
1975         );
1976         return;
1977     }
1978
1979     # ... and put them in the same order that the search API said they
1980     # should be in.
1981     my %ordering_hash = map { 
1982         ($no_flesh) ? $_->target_biblio_record_entry : $_->target_biblio_record_entry->id, 
1983         $_ 
1984     } @$items;
1985
1986     return [map { $ordering_hash{$_} } @$id_list];
1987 }
1988
1989 # returns undef on success, Event on error
1990 sub log_user_activity {
1991     my ($class, $user_id, $who, $what, $e, $async) = @_;
1992
1993     my $commit = 0;
1994     if (!$e) {
1995         $e = OpenILS::Utils::CStoreEditor->new(xact => 1);
1996         $commit = 1;
1997     }
1998
1999     my $res = $e->json_query({
2000         from => [
2001             'actor.insert_usr_activity', 
2002             $user_id, $who, $what, OpenSRF::AppSession->ingress
2003         ]
2004     });
2005
2006     if ($res) { # call returned OK
2007
2008         $e->commit   if $commit and @$res;
2009         $e->rollback if $commit and !@$res;
2010
2011     } else {
2012         return $e->die_event;
2013     }
2014
2015     return undef;
2016 }
2017
2018 # I hate to put this here exactly, but this code needs to be shared between
2019 # the TPAC's mod_perl module and open-ils.serial.
2020 #
2021 # There is a reason every part of the query *except* those parts dealing
2022 # with scope are moved here from the code's origin in TPAC.  The serials
2023 # use case does *not* want the same scoping logic.
2024 #
2025 # Also, note that for the serials uses case, we may filter in OPAC visible
2026 # status and copy/call_number deletedness, but we don't filter on any
2027 # particular values for serial.item.status or serial.item.date_received.
2028 # Since we're only using this *after* winnowing down the set of issuances
2029 # that copies should be related to, I'm not sure we need any such serial.item
2030 # filters.
2031
2032 sub basic_opac_copy_query {
2033     ######################################################################
2034     # Pass a defined value for either $rec_id OR ($iss_id AND $dist_id), #
2035     # not both.                                                          #
2036     ######################################################################
2037     my ($self,$rec_id,$iss_id,$dist_id,$copy_limit,$copy_offset,$staff) = @_;
2038
2039     return {
2040         select => {
2041             acp => ['id', 'barcode', 'circ_lib', 'create_date',
2042                     'age_protect', 'holdable'],
2043             acpl => [
2044                 {column => 'name', alias => 'copy_location'},
2045                 {column => 'holdable', alias => 'location_holdable'}
2046             ],
2047             ccs => [
2048                 {column => 'name', alias => 'copy_status'},
2049                 {column => 'holdable', alias => 'status_holdable'}
2050             ],
2051             acn => [
2052                 {column => 'label', alias => 'call_number_label'},
2053                 {column => 'id', alias => 'call_number'}
2054             ],
2055             circ => ['due_date'],
2056             acnp => [
2057                 {column => 'label', alias => 'call_number_prefix_label'},
2058                 {column => 'id', alias => 'call_number_prefix'}
2059             ],
2060             acns => [
2061                 {column => 'label', alias => 'call_number_suffix_label'},
2062                 {column => 'id', alias => 'call_number_suffix'}
2063             ],
2064             bmp => [
2065                 {column => 'label', alias => 'part_label'},
2066             ],
2067             ($iss_id ? (sitem => ["issuance"]) : ())
2068         },
2069
2070         from => {
2071             acp => {
2072                 ($iss_id ? (
2073                     sitem => {
2074                         fkey => 'id',
2075                         field => 'unit',
2076                         filter => {issuance => $iss_id},
2077                         join => {
2078                             sstr => { }
2079                         }
2080                     }
2081                 ) : ()),
2082                 acn => {
2083                     join => {
2084                         acnp => { fkey => 'prefix' },
2085                         acns => { fkey => 'suffix' }
2086                     },
2087                     filter => [
2088                         {deleted => 'f'},
2089                         ($rec_id ? {record => $rec_id} : ())
2090                     ],
2091                 },
2092                 circ => { # If the copy is circulating, retrieve the open circ
2093                     type => 'left',
2094                     filter => {checkin_time => undef}
2095                 },
2096                 acpl => {
2097                     ($staff ? () : (filter => { opac_visible => 't' }))
2098                 },
2099                 ccs => {
2100                     ($staff ? () : (filter => { opac_visible => 't' }))
2101                 },
2102                 aou => {},
2103                 acpm => {
2104                     type => 'left',
2105                     join => {
2106                         bmp => { type => 'left' }
2107                     }
2108                 }
2109             }
2110         },
2111
2112         where => {
2113             '+acp' => {
2114                 deleted => 'f',
2115                 ($staff ? () : (opac_visible => 't'))
2116             },
2117             ($dist_id ? ( '+sstr' => { distribution => $dist_id } ) : ()),
2118             ($staff ? () : ( '+aou' => { opac_visible => 't' } ))
2119         },
2120
2121         order_by => [
2122             {class => 'aou', field => 'name'},
2123             {class => 'acn', field => 'label'}
2124         ],
2125
2126         limit => $copy_limit,
2127         offset => $copy_offset
2128     };
2129 }
2130
2131 1;
2132