]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/Application/AppUtils.pm
LP2045292 Color contrast for AngularJS patron bills
[Evergreen.git] / Open-ILS / src / perlmods / lib / OpenILS / Application / AppUtils.pm
1 package OpenILS::Application::AppUtils;
2 use strict; use warnings;
3 use MARC::Record;
4 use MARC::File::XML (BinaryEncoding => 'utf8', RecordFormat => 'USMARC');
5 use OpenILS::Application;
6 use base qw/OpenILS::Application/;
7 use OpenSRF::Utils::Cache;
8 use OpenSRF::Utils::Logger qw/$logger/;
9 use OpenILS::Utils::ModsParser;
10 use OpenSRF::EX qw(:try);
11 use OpenILS::Event;
12 use Data::Dumper;
13 use OpenILS::Utils::CStoreEditor;
14 use OpenILS::Const qw/:const/;
15 use Unicode::Normalize;
16 use OpenSRF::Utils::SettingsClient;
17 use UUID::Tiny;
18 use Encode;
19 use DateTime;
20 use DateTime::Format::ISO8601;
21 use List::MoreUtils qw/uniq/;
22 use Digest::MD5 qw(md5_hex);
23
24 # ---------------------------------------------------------------------------
25 # Pile of utilty methods used accross applications.
26 # ---------------------------------------------------------------------------
27 my $cache_client = "OpenSRF::Utils::Cache";
28
29 # ---------------------------------------------------------------------------
30 # on sucess, returns the created session, on failure throws ERROR exception
31 # ---------------------------------------------------------------------------
32 sub start_db_session {
33
34     my $self = shift;
35     my $session = OpenSRF::AppSession->connect( "open-ils.storage" );
36     my $trans_req = $session->request( "open-ils.storage.transaction.begin" );
37
38     my $trans_resp = $trans_req->recv();
39     if(ref($trans_resp) and UNIVERSAL::isa($trans_resp,"Error")) { throw $trans_resp; }
40     if( ! $trans_resp->content() ) {
41         throw OpenSRF::ERROR 
42             ("Unable to Begin Transaction with database" );
43     }
44     $trans_req->finish();
45
46     $logger->debug("Setting global storage session to ".
47         "session: " . $session->session_id . " : " . $session->app );
48
49     return $session;
50 }
51
52 sub set_audit_info {
53     my $self = shift;
54     my $session = shift;
55     my $authtoken = shift;
56     my $user_id = shift;
57     my $ws_id = shift;
58     
59     my $audit_req = $session->request( "open-ils.storage.set_audit_info", $authtoken, $user_id, $ws_id );
60     my $audit_resp = $audit_req->recv();
61     $audit_req->finish();
62 }
63
64 my $PERM_QUERY = {
65     select => {
66         au => [ {
67             transform => 'permission.usr_has_perm',
68             alias => 'has_perm',
69             column => 'id',
70             params => []
71         } ]
72     },
73     from => 'au',
74     where => {},
75 };
76
77
78 # returns undef if user has all of the perms provided
79 # returns the first failed perm on failure
80 sub check_user_perms {
81     my($self, $user_id, $org_id, @perm_types ) = @_;
82     $logger->debug("Checking perms with user : $user_id , org: $org_id, @perm_types");
83
84     for my $type (@perm_types) {
85         $PERM_QUERY->{select}->{au}->[0]->{params} = [$type, $org_id];
86         $PERM_QUERY->{where}->{id} = $user_id;
87         return $type unless $self->is_true(OpenILS::Utils::CStoreEditor->new->json_query($PERM_QUERY)->[0]->{has_perm});
88     }
89     return undef;
90 }
91
92 # checks the list of user perms.  The first one that fails returns a new
93 sub check_perms {
94     my( $self, $user_id, $org_id, @perm_types ) = @_;
95     my $t = $self->check_user_perms( $user_id, $org_id, @perm_types );
96     return OpenILS::Event->new('PERM_FAILURE', ilsperm => $t, ilspermloc => $org_id ) if $t;
97     return undef;
98 }
99
100
101
102 # ---------------------------------------------------------------------------
103 # commits and destroys the session
104 # ---------------------------------------------------------------------------
105 sub commit_db_session {
106     my( $self, $session ) = @_;
107
108     my $req = $session->request( "open-ils.storage.transaction.commit" );
109     my $resp = $req->recv();
110
111     if(!$resp) {
112         throw OpenSRF::EX::ERROR ("Unable to commit db session");
113     }
114
115     if(UNIVERSAL::isa($resp,"Error")) { 
116         throw $resp ($resp->stringify); 
117     }
118
119     if(!$resp->content) {
120         throw OpenSRF::EX::ERROR ("Unable to commit db session");
121     }
122
123     $session->finish();
124     $session->disconnect();
125     $session->kill_me();
126 }
127
128 sub rollback_db_session {
129     my( $self, $session ) = @_;
130
131     my $req = $session->request("open-ils.storage.transaction.rollback");
132     my $resp = $req->recv();
133     if(UNIVERSAL::isa($resp,"Error")) { throw $resp;  }
134
135     $session->finish();
136     $session->disconnect();
137     $session->kill_me();
138 }
139
140
141 # returns undef it the event is not an ILS event
142 # returns the event code otherwise
143 sub event_code {
144     my( $self, $evt ) = @_;
145     return $evt->{ilsevent} if $self->is_event($evt);
146     return undef;
147 }
148
149 # some events, in particular auto-generated events, don't have an 
150 # ilsevent key.  treat hashes with a 'textcode' key as events.
151 sub is_event {
152     my ($self, $evt) = @_;
153     return (
154         ref($evt) eq 'HASH' and (
155             defined $evt->{ilsevent} or
156             defined $evt->{textcode}
157         )
158     );
159 }
160
161 # ---------------------------------------------------------------------------
162 # Checks to see if a user is logged in.  Returns the user record on success,
163 # throws an exception on error.
164 # ---------------------------------------------------------------------------
165 sub check_user_session {
166     my( $self, $user_session ) = @_;
167
168     my $content = $self->simplereq( 
169         'open-ils.auth', 
170         'open-ils.auth.session.retrieve', $user_session);
171
172     return undef if (!$content) or $self->event_code($content);
173     return $content;
174 }
175
176 # generic simple request returning a scalar value
177 sub simplereq {
178     my($self, $service, $method, @params) = @_;
179     return $self->simple_scalar_request($service, $method, @params);
180 }
181
182
183 sub simple_scalar_request {
184     my($self, $service, $method, @params) = @_;
185
186     my $session = OpenSRF::AppSession->create( $service );
187
188     my $request = $session->request( $method, @params );
189
190     my $val;
191     my $err;
192     try  {
193
194         $val = $request->gather(1); 
195
196     } catch Error with {
197         $err = shift;
198     };
199
200     if( $err ) {
201         warn "received error : service=$service : method=$method : params=".Dumper(\@params) . "\n $err";
202         throw $err ("Call to $service for method $method \n failed with exception: $err : " );
203     }
204
205     return $val;
206 }
207
208 sub build_org_tree {
209     my( $self, $orglist ) = @_;
210
211     return $orglist unless ref $orglist; 
212     return $$orglist[0] if @$orglist == 1;
213
214     my @list = sort { 
215         $a->ou_type <=> $b->ou_type ||
216         $a->name cmp $b->name } @$orglist;
217
218     for my $org (@list) {
219
220         next unless ($org);
221         next if (!defined($org->parent_ou) || $org->parent_ou eq "");
222
223         my ($parent) = grep { $_->id == $org->parent_ou } @list;
224         next unless $parent;
225         $parent->children([]) unless defined($parent->children); 
226         push( @{$parent->children}, $org );
227     }
228
229     return $list[0];
230 }
231
232 sub fetch_closed_date {
233     my( $self, $cd ) = @_;
234     my $evt;
235     
236     $logger->debug("Fetching closed_date $cd from cstore");
237
238     my $cd_obj = $self->simplereq(
239         'open-ils.cstore',
240         'open-ils.cstore.direct.actor.org_unit.closed_date.retrieve', $cd );
241
242     if(!$cd_obj) {
243         $logger->info("closed_date $cd not found in the db");
244         $evt = OpenILS::Event->new('ACTOR_USER_NOT_FOUND');
245     }
246
247     return ($cd_obj, $evt);
248 }
249
250 sub fetch_user {
251     my( $self, $userid ) = @_;
252     my( $user, $evt );
253     
254     $logger->debug("Fetching user $userid from cstore");
255
256     $user = $self->simplereq(
257         'open-ils.cstore',
258         'open-ils.cstore.direct.actor.user.retrieve', $userid );
259
260     if(!$user) {
261         $logger->info("User $userid not found in the db");
262         $evt = OpenILS::Event->new('ACTOR_USER_NOT_FOUND');
263     }
264
265     return ($user, $evt);
266 }
267
268 sub checkses {
269     my( $self, $session ) = @_;
270     my $user = $self->check_user_session($session) or 
271         return (undef, OpenILS::Event->new('NO_SESSION'));
272     return ($user);
273 }
274
275
276 # verifiese the session and checks the permissions agains the
277 # session user and the user's home_ou as the org id
278 sub checksesperm {
279     my( $self, $session, @perms ) = @_;
280     my $user; my $evt; my $e; 
281     $logger->debug("Checking user session $session and perms @perms");
282     ($user, $evt) = $self->checkses($session);
283     return (undef, $evt) if $evt;
284     $evt = $self->check_perms($user->id, $user->home_ou, @perms);
285     return ($user, $evt);
286 }
287
288
289 sub checkrequestor {
290     my( $self, $staffobj, $userid, @perms ) = @_;
291     my $user; my $evt;
292     $userid = $staffobj->id unless defined $userid;
293
294     $logger->debug("checkrequestor(): requestor => " . $staffobj->id . ", target => $userid");
295
296     if( $userid ne $staffobj->id ) {
297         ($user, $evt) = $self->fetch_user($userid);
298         return (undef, $evt) if $evt;
299         $evt = $self->check_perms( $staffobj->id, $user->home_ou, @perms );
300
301     } else {
302         $user = $staffobj;
303     }
304
305     return ($user, $evt);
306 }
307
308 sub checkses_requestor {
309     my( $self, $authtoken, $targetid, @perms ) = @_;
310     my( $requestor, $target, $evt );
311
312     ($requestor, $evt) = $self->checkses($authtoken);
313     return (undef, undef, $evt) if $evt;
314
315     ($target, $evt) = $self->checkrequestor( $requestor, $targetid, @perms );
316     return( $requestor, $target, $evt);
317 }
318
319 sub fetch_copy {
320     my( $self, $copyid ) = @_;
321     my( $copy, $evt );
322
323     $logger->debug("Fetching copy $copyid from cstore");
324
325     $copy = $self->simplereq(
326         'open-ils.cstore',
327         'open-ils.cstore.direct.asset.copy.retrieve', $copyid );
328
329     if(!$copy) { $evt = OpenILS::Event->new('ASSET_COPY_NOT_FOUND'); }
330
331     return( $copy, $evt );
332 }
333
334
335 # retrieves a circ object by id
336 sub fetch_circulation {
337     my( $self, $circid ) = @_;
338     my $circ; my $evt;
339     
340     $logger->debug("Fetching circ $circid from cstore");
341
342     $circ = $self->simplereq(
343         'open-ils.cstore',
344         "open-ils.cstore.direct.action.circulation.retrieve", $circid );
345
346     if(!$circ) {
347         $evt = OpenILS::Event->new('ACTION_CIRCULATION_NOT_FOUND', circid => $circid );
348     }
349
350     return ( $circ, $evt );
351 }
352
353 sub fetch_record_by_copy {
354     my( $self, $copyid ) = @_;
355     my( $record, $evt );
356
357     $logger->debug("Fetching record by copy $copyid from cstore");
358
359     $record = $self->simplereq(
360         'open-ils.cstore',
361         'open-ils.cstore.direct.asset.copy.retrieve', $copyid,
362         { flesh => 3,
363           flesh_fields => { bre => [ 'fixed_fields' ],
364                     acn => [ 'record' ],
365                     acp => [ 'call_number' ],
366                   }
367         }
368     );
369
370     if(!$record) {
371         $evt = OpenILS::Event->new('BIBLIO_RECORD_ENTRY_NOT_FOUND');
372     } else {
373         $record = $record->call_number->record;
374     }
375
376     return ($record, $evt);
377 }
378
379 # turns a record object into an mvr (mods) object
380 sub record_to_mvr {
381     my( $self, $record ) = @_;
382     return undef unless $record and $record->marc;
383     my $u = OpenILS::Utils::ModsParser->new();
384     $u->start_mods_batch( $record->marc );
385     my $mods = $u->finish_mods_batch();
386     $mods->doc_id($record->id);
387    $mods->tcn($record->tcn_value);
388     return $mods;
389 }
390
391 sub fetch_hold {
392     my( $self, $holdid ) = @_;
393     my( $hold, $evt );
394
395     $logger->debug("Fetching hold $holdid from cstore");
396
397     $hold = $self->simplereq(
398         'open-ils.cstore',
399         'open-ils.cstore.direct.action.hold_request.retrieve', $holdid);
400
401     $evt = OpenILS::Event->new('ACTION_HOLD_REQUEST_NOT_FOUND', holdid => $holdid) unless $hold;
402
403     return ($hold, $evt);
404 }
405
406
407 sub fetch_hold_transit_by_hold {
408     my( $self, $holdid ) = @_;
409     my( $transit, $evt );
410
411     $logger->debug("Fetching transit by hold $holdid from cstore");
412
413     $transit = $self->simplereq(
414         'open-ils.cstore',
415         'open-ils.cstore.direct.action.hold_transit_copy.search', { hold => $holdid, cancel_time => undef } );
416
417     $evt = OpenILS::Event->new('ACTION_HOLD_TRANSIT_COPY_NOT_FOUND', holdid => $holdid) unless $transit;
418
419     return ($transit, $evt );
420 }
421
422 # fetches the captured, but not fulfilled hold attached to a given copy
423 sub fetch_open_hold_by_copy {
424     my( $self, $copyid ) = @_;
425     $logger->debug("Searching for active hold for copy $copyid");
426     my( $hold, $evt );
427
428     $hold = $self->cstorereq(
429         'open-ils.cstore.direct.action.hold_request.search',
430         { 
431             current_copy        => $copyid , 
432             capture_time        => { "!=" => undef }, 
433             fulfillment_time    => undef,
434             cancel_time         => undef,
435         } );
436
437     $evt = OpenILS::Event->new('ACTION_HOLD_REQUEST_NOT_FOUND', copyid => $copyid) unless $hold;
438     return ($hold, $evt);
439 }
440
441 sub fetch_hold_transit {
442     my( $self, $transid ) = @_;
443     my( $htransit, $evt );
444     $logger->debug("Fetching hold transit with hold id $transid");
445     $htransit = $self->cstorereq(
446         'open-ils.cstore.direct.action.hold_transit_copy.retrieve', $transid );
447     $evt = OpenILS::Event->new('ACTION_HOLD_TRANSIT_COPY_NOT_FOUND', id => $transid) unless $htransit;
448     return ($htransit, $evt);
449 }
450
451 sub fetch_copy_by_barcode {
452     my( $self, $barcode ) = @_;
453     my( $copy, $evt );
454
455     $logger->debug("Fetching copy by barcode $barcode from cstore");
456
457     $copy = $self->simplereq( 'open-ils.cstore',
458         'open-ils.cstore.direct.asset.copy.search', { barcode => $barcode, deleted => 'f'} );
459         #'open-ils.storage.direct.asset.copy.search.barcode', $barcode );
460
461     $evt = OpenILS::Event->new('ASSET_COPY_NOT_FOUND', barcode => $barcode) unless $copy;
462
463     return ($copy, $evt);
464 }
465
466 sub fetch_open_billable_transaction {
467     my( $self, $transid ) = @_;
468     my( $transaction, $evt );
469
470     $logger->debug("Fetching open billable transaction $transid from cstore");
471
472     $transaction = $self->simplereq(
473         'open-ils.cstore',
474         'open-ils.cstore.direct.money.open_billable_transaction_summary.retrieve',  $transid);
475
476     $evt = OpenILS::Event->new(
477         'MONEY_OPEN_BILLABLE_TRANSACTION_SUMMARY_NOT_FOUND', transid => $transid ) unless $transaction;
478
479     return ($transaction, $evt);
480 }
481
482
483
484 my %buckets;
485 $buckets{'biblio'} = 'biblio_record_entry_bucket';
486 $buckets{'callnumber'} = 'call_number_bucket';
487 $buckets{'copy'} = 'copy_bucket';
488 $buckets{'user'} = 'user_bucket';
489
490 sub fetch_container {
491     my( $self, $id, $type ) = @_;
492     my( $bucket, $evt );
493
494     $logger->debug("Fetching container $id with type $type");
495
496     my $e = 'CONTAINER_CALL_NUMBER_BUCKET_NOT_FOUND';
497     $e = 'CONTAINER_BIBLIO_RECORD_ENTRY_BUCKET_NOT_FOUND' if $type eq 'biblio';
498     $e = 'CONTAINER_USER_BUCKET_NOT_FOUND' if $type eq 'user';
499     $e = 'CONTAINER_COPY_BUCKET_NOT_FOUND' if $type eq 'copy';
500
501     my $meth = $buckets{$type};
502     $bucket = $self->simplereq(
503         'open-ils.cstore',
504         "open-ils.cstore.direct.container.$meth.retrieve", $id );
505
506     $evt = OpenILS::Event->new(
507         $e, container => $id, container_type => $type ) unless $bucket;
508
509     return ($bucket, $evt);
510 }
511
512
513 sub fetch_container_e {
514     my( $self, $editor, $id, $type ) = @_;
515
516     my( $bucket, $evt );
517     $bucket = $editor->retrieve_container_copy_bucket($id) if $type eq 'copy';
518     $bucket = $editor->retrieve_container_call_number_bucket($id) if $type eq 'callnumber';
519     $bucket = $editor->retrieve_container_biblio_record_entry_bucket($id) if $type eq 'biblio';
520     $bucket = $editor->retrieve_container_user_bucket($id) if $type eq 'user';
521
522     $evt = $editor->event unless $bucket;
523     return ($bucket, $evt);
524 }
525
526 sub fetch_container_item_e {
527     my( $self, $editor, $id, $type ) = @_;
528
529     my( $bucket, $evt );
530     $bucket = $editor->retrieve_container_copy_bucket_item($id) if $type eq 'copy';
531     $bucket = $editor->retrieve_container_call_number_bucket_item($id) if $type eq 'callnumber';
532     $bucket = $editor->retrieve_container_biblio_record_entry_bucket_item($id) if $type eq 'biblio';
533     $bucket = $editor->retrieve_container_user_bucket_item($id) if $type eq 'user';
534
535     $evt = $editor->event unless $bucket;
536     return ($bucket, $evt);
537 }
538
539
540
541
542
543 sub fetch_container_item {
544     my( $self, $id, $type ) = @_;
545     my( $bucket, $evt );
546
547     $logger->debug("Fetching container item $id with type $type");
548
549     my $meth = $buckets{$type} . "_item";
550
551     $bucket = $self->simplereq(
552         'open-ils.cstore',
553         "open-ils.cstore.direct.container.$meth.retrieve", $id );
554
555
556     my $e = 'CONTAINER_CALL_NUMBER_BUCKET_ITEM_NOT_FOUND';
557     $e = 'CONTAINER_BIBLIO_RECORD_ENTRY_BUCKET_ITEM_NOT_FOUND' if $type eq 'biblio';
558     $e = 'CONTAINER_USER_BUCKET_ITEM_NOT_FOUND' if $type eq 'user';
559     $e = 'CONTAINER_COPY_BUCKET_ITEM_NOT_FOUND' if $type eq 'copy';
560
561     $evt = OpenILS::Event->new(
562         $e, itemid => $id, container_type => $type ) unless $bucket;
563
564     return ($bucket, $evt);
565 }
566
567
568 sub fetch_patron_standings {
569     my $self = shift;
570     $logger->debug("Fetching patron standings");    
571     return $self->simplereq(
572         'open-ils.cstore', 
573         'open-ils.cstore.direct.config.standing.search.atomic', { id => { '!=' => undef } });
574 }
575
576
577 sub fetch_permission_group_tree {
578     my $self = shift;
579     $logger->debug("Fetching patron profiles"); 
580     return $self->simplereq(
581         'open-ils.actor', 
582         'open-ils.actor.groups.tree.retrieve' );
583 }
584
585 sub fetch_permission_group_descendants {
586     my( $self, $profile ) = @_;
587     my $group_tree = $self->fetch_permission_group_tree();
588     my $start_here;
589     my @groups;
590
591     # FIXME: okay, so it's not an org tree, but it is compatible
592     $self->walk_org_tree($group_tree, sub {
593         my $g = shift;
594         if ($g->id == $profile) {
595             $start_here = $g;
596         }
597     });
598
599     $self->walk_org_tree($start_here, sub {
600         my $g = shift;
601         push(@groups,$g->id);
602     });
603
604     return \@groups;
605 }
606
607 sub fetch_patron_circ_summary {
608     my( $self, $userid ) = @_;
609     $logger->debug("Fetching patron summary for $userid");
610     my $summary = $self->simplereq(
611         'open-ils.storage', 
612         "open-ils.storage.action.circulation.patron_summary", $userid );
613
614     if( $summary ) {
615         $summary->[0] ||= 0;
616         $summary->[1] ||= 0.0;
617         return $summary;
618     }
619     return undef;
620 }
621
622
623 sub fetch_copy_statuses {
624     my( $self ) = @_;
625     $logger->debug("Fetching copy statuses");
626     return $self->simplereq(
627         'open-ils.cstore', 
628         'open-ils.cstore.direct.config.copy_status.search.atomic', { id => { '!=' => undef } });
629 }
630
631 sub fetch_copy_location {
632     my( $self, $id ) = @_;
633     my $evt;
634     my $cl = $self->cstorereq(
635         'open-ils.cstore.direct.asset.copy_location.retrieve', $id );
636     $evt = OpenILS::Event->new('ASSET_COPY_LOCATION_NOT_FOUND') unless $cl;
637     return ($cl, $evt);
638 }
639
640 sub fetch_copy_locations {
641     my $self = shift; 
642     return $self->simplereq(
643         'open-ils.cstore', 
644         'open-ils.cstore.direct.asset.copy_location.search.atomic', { id => { '!=' => undef }, deleted => 'f' });
645 }
646
647 sub fetch_copy_location_by_name {
648     my( $self, $name, $org ) = @_;
649     my $evt;
650     my $cl = $self->cstorereq(
651         'open-ils.cstore.direct.asset.copy_location.search',
652             { name => $name, owning_lib => $org, deleted => 'f' } );
653     $evt = OpenILS::Event->new('ASSET_COPY_LOCATION_NOT_FOUND') unless $cl;
654     return ($cl, $evt);
655 }
656
657 sub fetch_callnumber {
658     my( $self, $id, $flesh, $e ) = @_;
659
660     $e ||= OpenILS::Utils::CStoreEditor->new;
661
662     my $evt = OpenILS::Event->new( 'ASSET_CALL_NUMBER_NOT_FOUND', id => $id );
663     return( undef, $evt ) unless $id;
664
665     $logger->debug("Fetching callnumber $id");
666
667     my $cn = $e->retrieve_asset_call_number([
668         $id,
669         { flesh => $flesh, flesh_fields => { acn => [ 'prefix', 'suffix', 'label_class' ] } },
670     ]);
671
672     return ( $cn, $e->event );
673 }
674
675 my %ORG_CACHE; # - these rarely change, so cache them..
676 sub fetch_org_unit {
677     my( $self, $id ) = @_;
678     return undef unless $id;
679     return $id if( ref($id) eq 'Fieldmapper::actor::org_unit' );
680     return $ORG_CACHE{$id} if $ORG_CACHE{$id};
681     $logger->debug("Fetching org unit $id");
682     my $evt = undef;
683
684     my $org = $self->simplereq(
685         'open-ils.cstore', 
686         'open-ils.cstore.direct.actor.org_unit.retrieve', $id );
687     $evt = OpenILS::Event->new( 'ACTOR_ORG_UNIT_NOT_FOUND', id => $id ) unless $org;
688     $ORG_CACHE{$id}  = $org;
689
690     return ($org, $evt);
691 }
692
693 sub fetch_stat_cat {
694     my( $self, $type, $id ) = @_;
695     my( $cat, $evt );
696     $logger->debug("Fetching $type stat cat: $id");
697     $cat = $self->simplereq(
698         'open-ils.cstore', 
699         "open-ils.cstore.direct.$type.stat_cat.retrieve", $id );
700
701     my $e = 'ASSET_STAT_CAT_NOT_FOUND';
702     $e = 'ACTOR_STAT_CAT_NOT_FOUND' if $type eq 'actor';
703
704     $evt = OpenILS::Event->new( $e, id => $id ) unless $cat;
705     return ( $cat, $evt );
706 }
707
708 sub fetch_stat_cat_entry {
709     my( $self, $type, $id ) = @_;
710     my( $entry, $evt );
711     $logger->debug("Fetching $type stat cat entry: $id");
712     $entry = $self->simplereq(
713         'open-ils.cstore', 
714         "open-ils.cstore.direct.$type.stat_cat_entry.retrieve", $id );
715
716     my $e = 'ASSET_STAT_CAT_ENTRY_NOT_FOUND';
717     $e = 'ACTOR_STAT_CAT_ENTRY_NOT_FOUND' if $type eq 'actor';
718
719     $evt = OpenILS::Event->new( $e, id => $id ) unless $entry;
720     return ( $entry, $evt );
721 }
722
723 sub fetch_stat_cat_entry_default {
724     my( $self, $type, $id ) = @_;
725     my( $entry_default, $evt );
726     $logger->debug("Fetching $type stat cat entry default: $id");
727     $entry_default = $self->simplereq(
728         'open-ils.cstore', 
729         "open-ils.cstore.direct.$type.stat_cat_entry_default.retrieve", $id );
730
731     my $e = 'ASSET_STAT_CAT_ENTRY_DEFAULT_NOT_FOUND';
732     $e = 'ACTOR_STAT_CAT_ENTRY_DEFAULT_NOT_FOUND' if $type eq 'actor';
733
734     $evt = OpenILS::Event->new( $e, id => $id ) unless $entry_default;
735     return ( $entry_default, $evt );
736 }
737
738 sub fetch_stat_cat_entry_default_by_stat_cat_and_org {
739     my( $self, $type, $stat_cat, $orgId ) = @_;
740     my $entry_default;
741     $logger->info("### Fetching $type stat cat entry default with stat_cat $stat_cat owned by org_unit $orgId");
742     $entry_default = $self->simplereq(
743         'open-ils.cstore', 
744         "open-ils.cstore.direct.$type.stat_cat_entry_default.search.atomic", 
745         { stat_cat => $stat_cat, owner => $orgId } );
746
747     $entry_default = $entry_default->[0];
748     return ($entry_default, undef) if $entry_default;
749
750     my $e = 'ASSET_STAT_CAT_ENTRY_DEFAULT_NOT_FOUND';
751     $e = 'ACTOR_STAT_CAT_ENTRY_DEFAULT_NOT_FOUND' if $type eq 'actor';
752     return (undef, OpenILS::Event->new($e) );
753 }
754
755 sub find_org {
756     my( $self, $org_tree, $orgid )  = @_;
757     return undef unless $org_tree and defined $orgid;
758     return $org_tree if ( $org_tree->id eq $orgid );
759     return undef unless ref($org_tree->children);
760     for my $c (@{$org_tree->children}) {
761         my $o = $self->find_org($c, $orgid);
762         return $o if $o;
763     }
764     return undef;
765 }
766
767 sub find_org_by_shortname {
768     my( $self, $org_tree, $shortname )  = @_;
769     return undef unless $org_tree and defined $shortname;
770     return $org_tree if ( $org_tree->shortname eq $shortname );
771     return undef unless ref($org_tree->children);
772     for my $c (@{$org_tree->children}) {
773         my $o = $self->find_org_by_shortname($c, $shortname);
774         return $o if $o;
775     }
776     return undef;
777 }
778
779 sub find_lasso_by_name {
780     my( $self, $name )  = @_;
781     return $self->simplereq(
782         'open-ils.cstore', 
783         'open-ils.cstore.direct.actor.org_lasso.search.atomic', { name => $name } )->[0];
784 }
785
786 sub fetch_lasso_org_maps {
787     my( $self, $lasso )  = @_;
788     return $self->simplereq(
789         'open-ils.cstore', 
790         'open-ils.cstore.direct.actor.org_lasso_map.search.atomic', { lasso => $lasso } );
791 }
792
793 sub fetch_non_cat_type_by_name_and_org {
794     my( $self, $name, $orgId ) = @_;
795     $logger->debug("Fetching non cat type $name at org $orgId");
796     my $types = $self->simplereq(
797         'open-ils.cstore',
798         'open-ils.cstore.direct.config.non_cataloged_type.search.atomic',
799         { name => $name, owning_lib => $orgId } );
800     return ($types->[0], undef) if($types and @$types);
801     return (undef, OpenILS::Event->new('CONFIG_NON_CATALOGED_TYPE_NOT_FOUND') );
802 }
803
804 sub fetch_non_cat_type {
805     my( $self, $id ) = @_;
806     $logger->debug("Fetching non cat type $id");
807     my( $type, $evt );
808     $type = $self->simplereq(
809         'open-ils.cstore', 
810         'open-ils.cstore.direct.config.non_cataloged_type.retrieve', $id );
811     $evt = OpenILS::Event->new('CONFIG_NON_CATALOGED_TYPE_NOT_FOUND') unless $type;
812     return ($type, $evt);
813 }
814
815 sub DB_UPDATE_FAILED { 
816     my( $self, $payload ) = @_;
817     return OpenILS::Event->new('DATABASE_UPDATE_FAILED', 
818         payload => ($payload) ? $payload : undef ); 
819 }
820
821 sub fetch_booking_reservation {
822     my( $self, $id ) = @_;
823     my( $res, $evt );
824
825     $res = $self->simplereq(
826         'open-ils.cstore', 
827         'open-ils.cstore.direct.booking.reservation.retrieve', $id
828     );
829
830     # simplereq doesn't know how to flesh so ...
831     if ($res) {
832         $res->usr(
833             $self->simplereq(
834                 'open-ils.cstore', 
835                 'open-ils.cstore.direct.actor.user.retrieve', $res->usr
836             )
837         );
838
839         $res->target_resource_type(
840             $self->simplereq(
841                 'open-ils.cstore', 
842                 'open-ils.cstore.direct.booking.resource_type.retrieve', $res->target_resource_type
843             )
844         );
845
846         if ($res->current_resource) {
847             $res->current_resource(
848                 $self->simplereq(
849                     'open-ils.cstore', 
850                     'open-ils.cstore.direct.booking.resource.retrieve', $res->current_resource
851                 )
852             );
853
854             if ($self->is_true( $res->target_resource_type->catalog_item )) {
855                 $res->current_resource->catalog_item( $self->fetch_copy_by_barcode( $res->current_resource->barcode ) );
856             }
857         }
858
859         if ($res->target_resource) {
860             $res->target_resource(
861                 $self->simplereq(
862                     'open-ils.cstore', 
863                     'open-ils.cstore.direct.booking.resource.retrieve', $res->target_resource
864                 )
865             );
866
867             if ($self->is_true( $res->target_resource_type->catalog_item )) {
868                 $res->target_resource->catalog_item( $self->fetch_copy_by_barcode( $res->target_resource->barcode ) );
869             }
870         }
871
872     } else {
873         $evt = OpenILS::Event->new('RESERVATION_NOT_FOUND');
874     }
875
876     return ($res, $evt);
877 }
878
879 sub fetch_circ_duration_by_name {
880     my( $self, $name ) = @_;
881     my( $dur, $evt );
882     $dur = $self->simplereq(
883         'open-ils.cstore', 
884         'open-ils.cstore.direct.config.rules.circ_duration.search.atomic', { name => $name } );
885     $dur = $dur->[0];
886     $evt = OpenILS::Event->new('CONFIG_RULES_CIRC_DURATION_NOT_FOUND') unless $dur;
887     return ($dur, $evt);
888 }
889
890 sub fetch_recurring_fine_by_name {
891     my( $self, $name ) = @_;
892     my( $obj, $evt );
893     $obj = $self->simplereq(
894         'open-ils.cstore', 
895         'open-ils.cstore.direct.config.rules.recurring_fine.search.atomic', { name => $name } );
896     $obj = $obj->[0];
897     $evt = OpenILS::Event->new('CONFIG_RULES_RECURRING_FINE_NOT_FOUND') unless $obj;
898     return ($obj, $evt);
899 }
900
901 sub fetch_max_fine_by_name {
902     my( $self, $name ) = @_;
903     my( $obj, $evt );
904     $obj = $self->simplereq(
905         'open-ils.cstore', 
906         'open-ils.cstore.direct.config.rules.max_fine.search.atomic', { name => $name } );
907     $obj = $obj->[0];
908     $evt = OpenILS::Event->new('CONFIG_RULES_MAX_FINE_NOT_FOUND') unless $obj;
909     return ($obj, $evt);
910 }
911
912 sub fetch_hard_due_date_by_name {
913     my( $self, $name ) = @_;
914     my( $obj, $evt );
915     $obj = $self->simplereq(
916         'open-ils.cstore', 
917         'open-ils.cstore.direct.config.hard_due_date.search.atomic', { name => $name } );
918     $obj = $obj->[0];
919     $evt = OpenILS::Event->new('CONFIG_RULES_HARD_DUE_DATE_NOT_FOUND') unless $obj;
920     return ($obj, $evt);
921 }
922
923 sub storagereq {
924     my( $self, $method, @params ) = @_;
925     return $self->simplereq(
926         'open-ils.storage', $method, @params );
927 }
928
929 sub storagereq_xact {
930     my($self, $method, @params) = @_;
931     my $ses = $self->start_db_session();
932     my $val = $ses->request($method, @params)->gather(1);
933     $self->rollback_db_session($ses);
934     return $val;
935 }
936
937 sub cstorereq {
938     my( $self, $method, @params ) = @_;
939     return $self->simplereq(
940         'open-ils.cstore', $method, @params );
941 }
942
943 sub event_equals {
944     my( $self, $e, $name ) =  @_;
945     if( $e and ref($e) eq 'HASH' and 
946         defined($e->{textcode}) and $e->{textcode} eq $name ) {
947         return 1 ;
948     }
949     return 0;
950 }
951
952 sub logmark {
953     my( undef, $f, $l ) = caller(0);
954     my( undef, undef, undef, $s ) = caller(1);
955     $s =~ s/.*:://g;
956     $f =~ s/.*\///g;
957     $logger->debug("LOGMARK: $f:$l:$s");
958 }
959
960 # takes a copy id 
961 sub fetch_open_circulation {
962     my( $self, $cid ) = @_;
963     $self->logmark;
964
965     my $e = OpenILS::Utils::CStoreEditor->new;
966     my $circ = $e->search_action_circulation({
967         target_copy => $cid, 
968         stop_fines_time => undef, 
969         checkin_time => undef
970     })->[0];
971     
972     return ($circ, $e->event);
973 }
974
975 my $copy_statuses;
976 sub copy_status_from_name {
977     my( $self, $name ) = @_;
978     $copy_statuses = $self->fetch_copy_statuses unless $copy_statuses;
979     for my $status (@$copy_statuses) { 
980         return $status if( $status->name =~ /$name/i );
981     }
982     return undef;
983 }
984
985 sub copy_status_to_name {
986     my( $self, $sid ) = @_;
987     $copy_statuses = $self->fetch_copy_statuses unless $copy_statuses;
988     for my $status (@$copy_statuses) { 
989         return $status->name if( $status->id == $sid );
990     }
991     return undef;
992 }
993
994
995 sub copy_status {
996     my( $self, $arg ) = @_;
997     return $arg if ref $arg;
998     $copy_statuses = $self->fetch_copy_statuses unless $copy_statuses;
999     my ($stat) = grep { $_->id == $arg } @$copy_statuses;
1000     return $stat;
1001 }
1002
1003 sub fetch_open_transit_by_copy {
1004     my( $self, $copyid ) = @_;
1005     my($transit, $evt);
1006     $transit = $self->cstorereq(
1007         'open-ils.cstore.direct.action.transit_copy.search',
1008         { target_copy => $copyid, dest_recv_time => undef, cancel_time => undef });
1009     $evt = OpenILS::Event->new('ACTION_TRANSIT_COPY_NOT_FOUND') unless $transit;
1010     return ($transit, $evt);
1011 }
1012
1013 sub unflesh_copy {
1014     my( $self, $copy ) = @_;
1015     return undef unless $copy;
1016     $copy->status( $copy->status->id ) if ref($copy->status);
1017     $copy->location( $copy->location->id ) if ref($copy->location);
1018     $copy->circ_lib( $copy->circ_lib->id ) if ref($copy->circ_lib);
1019     return $copy;
1020 }
1021
1022 sub unflesh_reservation {
1023     my( $self, $reservation ) = @_;
1024     return undef unless $reservation;
1025     $reservation->usr( $reservation->usr->id ) if ref($reservation->usr);
1026     $reservation->target_resource_type( $reservation->target_resource_type->id ) if ref($reservation->target_resource_type);
1027     $reservation->target_resource( $reservation->target_resource->id ) if ref($reservation->target_resource);
1028     $reservation->current_resource( $reservation->current_resource->id ) if ref($reservation->current_resource);
1029     return $reservation;
1030 }
1031
1032 # un-fleshes a copy and updates it in the DB
1033 # returns a DB_UPDATE_FAILED event on error
1034 # returns undef on success
1035 sub update_copy {
1036     my( $self, %params ) = @_;
1037
1038     my $copy        = $params{copy} || die "update_copy(): copy required";
1039     my $editor  = $params{editor} || die "update_copy(): copy editor required";
1040     my $session = $params{session};
1041
1042     $logger->debug("Updating copy in the database: " . $copy->id);
1043
1044     $self->unflesh_copy($copy);
1045     $copy->editor( $editor );
1046     $copy->edit_date( 'now' );
1047
1048     my $s;
1049     my $meth = 'open-ils.storage.direct.asset.copy.update';
1050
1051     $s = $session->request( $meth, $copy )->gather(1) if $session;
1052     $s = $self->storagereq( $meth, $copy ) unless $session;
1053
1054     $logger->debug("Update of copy ".$copy->id." returned: $s");
1055
1056     return $self->DB_UPDATE_FAILED($copy) unless $s;
1057     return undef;
1058 }
1059
1060 sub update_reservation {
1061     my( $self, %params ) = @_;
1062
1063     my $reservation = $params{reservation}  || die "update_reservation(): reservation required";
1064     my $editor      = $params{editor} || die "update_reservation(): copy editor required";
1065     my $session     = $params{session};
1066
1067     $logger->debug("Updating copy in the database: " . $reservation->id);
1068
1069     $self->unflesh_reservation($reservation);
1070
1071     my $s;
1072     my $meth = 'open-ils.cstore.direct.booking.reservation.update';
1073
1074     $s = $session->request( $meth, $reservation )->gather(1) if $session;
1075     $s = $self->cstorereq( $meth, $reservation ) unless $session;
1076
1077     $logger->debug("Update of copy ".$reservation->id." returned: $s");
1078
1079     return $self->DB_UPDATE_FAILED($reservation) unless $s;
1080     return undef;
1081 }
1082
1083 sub fetch_billable_xact {
1084     my( $self, $id ) = @_;
1085     my($xact, $evt);
1086     $logger->debug("Fetching billable transaction %id");
1087     $xact = $self->cstorereq(
1088         'open-ils.cstore.direct.money.billable_transaction.retrieve', $id );
1089     $evt = OpenILS::Event->new('MONEY_BILLABLE_TRANSACTION_NOT_FOUND') unless $xact;
1090     return ($xact, $evt);
1091 }
1092
1093 sub fetch_billable_xact_summary {
1094     my( $self, $id ) = @_;
1095     my($xact, $evt);
1096     $logger->debug("Fetching billable transaction summary %id");
1097     $xact = $self->cstorereq(
1098         'open-ils.cstore.direct.money.billable_transaction_summary.retrieve', $id );
1099     $evt = OpenILS::Event->new('MONEY_BILLABLE_TRANSACTION_NOT_FOUND') unless $xact;
1100     return ($xact, $evt);
1101 }
1102
1103 sub fetch_fleshed_copy {
1104     my( $self, $id ) = @_;
1105     my( $copy, $evt );
1106     $logger->info("Fetching fleshed copy $id");
1107     $copy = $self->cstorereq(
1108         "open-ils.cstore.direct.asset.copy.retrieve", $id,
1109         { flesh => 1,
1110           flesh_fields => { acp => [ qw/ circ_lib location status stat_cat_entries / ] }
1111         }
1112     );
1113     $evt = OpenILS::Event->new('ASSET_COPY_NOT_FOUND', id => $id) unless $copy;
1114     return ($copy, $evt);
1115 }
1116
1117
1118 # returns the org that owns the callnumber that the copy
1119 # is attached to
1120 sub fetch_copy_owner {
1121     my( $self, $copyid ) = @_;
1122     my( $copy, $cn, $evt );
1123     $logger->debug("Fetching copy owner $copyid");
1124     ($copy, $evt) = $self->fetch_copy($copyid);
1125     return (undef,$evt) if $evt;
1126     ($cn, $evt) = $self->fetch_callnumber($copy->call_number);
1127     return (undef,$evt) if $evt;
1128     return ($cn->owning_lib);
1129 }
1130
1131 sub fetch_copy_note {
1132     my( $self, $id ) = @_;
1133     my( $note, $evt );
1134     $logger->debug("Fetching copy note $id");
1135     $note = $self->cstorereq(
1136         'open-ils.cstore.direct.asset.copy_note.retrieve', $id );
1137     $evt = OpenILS::Event->new('ASSET_COPY_NOTE_NOT_FOUND', id => $id ) unless $note;
1138     return ($note, $evt);
1139 }
1140
1141 sub fetch_call_numbers_by_title {
1142     my( $self, $titleid ) = @_;
1143     $logger->info("Fetching call numbers by title $titleid");
1144     return $self->cstorereq(
1145         'open-ils.cstore.direct.asset.call_number.search.atomic', 
1146         { record => $titleid, deleted => 'f' });
1147         #'open-ils.storage.direct.asset.call_number.search.record.atomic', $titleid);
1148 }
1149
1150 sub fetch_copies_by_call_number {
1151     my( $self, $cnid ) = @_;
1152     $logger->info("Fetching copies by call number $cnid");
1153     return $self->cstorereq(
1154         'open-ils.cstore.direct.asset.copy.search.atomic', { call_number => $cnid, deleted => 'f' } );
1155         #'open-ils.storage.direct.asset.copy.search.call_number.atomic', $cnid );
1156 }
1157
1158 sub fetch_user_by_barcode {
1159     my( $self, $bc ) = @_;
1160     my $cardid = $self->cstorereq(
1161         'open-ils.cstore.direct.actor.card.id_list', { barcode => $bc } );
1162     return (undef, OpenILS::Event->new('ACTOR_CARD_NOT_FOUND', barcode => $bc)) unless $cardid;
1163     my $user = $self->cstorereq(
1164         'open-ils.cstore.direct.actor.user.search', { card => $cardid } );
1165     return (undef, OpenILS::Event->new('ACTOR_USER_NOT_FOUND', card => $cardid)) unless $user;
1166     return ($user);
1167     
1168 }
1169
1170 sub fetch_bill {
1171     my( $self, $billid ) = @_;
1172     $logger->debug("Fetching billing $billid");
1173     my $bill = $self->cstorereq(
1174         'open-ils.cstore.direct.money.billing.retrieve', $billid );
1175     my $evt = OpenILS::Event->new('MONEY_BILLING_NOT_FOUND') unless $bill;
1176     return($bill, $evt);
1177 }
1178
1179 sub walk_org_tree {
1180     my( $self, $node, $callback ) = @_;
1181     return unless $node;
1182     $callback->($node);
1183     if( $node->children ) {
1184         $self->walk_org_tree($_, $callback) for @{$node->children};
1185     }
1186 }
1187
1188 sub is_true {
1189     my( $self, $item ) = @_;
1190     return 1 if $item and $item !~ /^f$/i;
1191     return 0;
1192 }
1193
1194
1195 sub patientreq {
1196     my ($self, $client, $service, $method, @params) = @_;
1197     my ($response, $err);
1198
1199     my $session = create OpenSRF::AppSession($service);
1200     my $request = $session->request($method, @params);
1201
1202     my $spurt = 10;
1203     my $give_up = time + 1000;
1204
1205     try {
1206         while (time < $give_up) {
1207             $response = $request->recv("timeout" => $spurt);
1208             last if $request->complete;
1209
1210             $client->status(new OpenSRF::DomainObject::oilsContinueStatus);
1211         }
1212     } catch Error with {
1213         $err = shift;
1214     };
1215
1216     if ($err) {
1217         warn "received error : service=$service : method=$method : params=".Dumper(\@params) . "\n $err";
1218         throw $err ("Call to $service for method $method \n failed with exception: $err : " );
1219     }
1220
1221     return $response->content;
1222 }
1223
1224 # This logic now lives in storage
1225 sub __patron_money_owed {
1226     my( $self, $patronid ) = @_;
1227     my $ses = OpenSRF::AppSession->create('open-ils.storage');
1228     my $req = $ses->request(
1229         'open-ils.storage.money.billable_transaction.summary.search',
1230         { usr => $patronid, xact_finish => undef } );
1231
1232     my $total = 0;
1233     my $data;
1234     while( $data = $req->recv ) {
1235         $data = $data->content;
1236         $total += $data->balance_owed;
1237     }
1238     return $total;
1239 }
1240
1241 sub patron_money_owed {
1242     my( $self, $userid ) = @_;
1243     my $ses = $self->start_db_session();
1244     my $val = $ses->request(
1245         'open-ils.storage.actor.user.total_owed', $userid)->gather(1);
1246     $self->rollback_db_session($ses);
1247     return $val;
1248 }
1249
1250 sub patron_total_items_out {
1251     my( $self, $userid ) = @_;
1252     my $ses = $self->start_db_session();
1253     my $val = $ses->request(
1254         'open-ils.storage.actor.user.total_out', $userid)->gather(1);
1255     $self->rollback_db_session($ses);
1256     return $val;
1257 }
1258
1259
1260
1261
1262 #---------------------------------------------------------------------
1263 # Returns  ($summary, $event) 
1264 #---------------------------------------------------------------------
1265 sub fetch_mbts {
1266     my $self = shift;
1267     my $id  = shift;
1268     my $e = shift || OpenILS::Utils::CStoreEditor->new;
1269     $id = $id->id if ref($id);
1270     
1271     my $xact = $e->retrieve_money_billable_transaction_summary($id)
1272         or return (undef, $e->event);
1273
1274     return ($xact);
1275 }
1276
1277
1278 #---------------------------------------------------------------------
1279 # Given a list of money.billable_transaction objects, this creates
1280 # transaction summary objects for each
1281 #--------------------------------------------------------------------
1282 sub make_mbts {
1283     my $self = shift;
1284     my $e = shift;
1285     my @xacts = @_;
1286     return () if (!@xacts);
1287     return @{$e->search_money_billable_transaction_summary({id => [ map { $_->id } @xacts ]})};
1288 }
1289         
1290         
1291 sub ou_ancestor_setting_value {
1292     my($self, $org_id, $name, $e) = @_;
1293     $e = $e || OpenILS::Utils::CStoreEditor->new;
1294     my $set = $self->ou_ancestor_setting($org_id, $name, $e);
1295     return $set->{value} if $set;
1296     return undef;
1297 }
1298
1299
1300 # If an authentication token is provided AND this org unit setting has a
1301 # view_perm, then make sure the user referenced by the auth token has
1302 # that permission.  This means that if you call this method without an
1303 # authtoken param, you can get whatever org unit setting values you want.
1304 # API users beware.
1305 #
1306 # NOTE: If you supply an editor ($e) arg AND an auth token arg, the editor's
1307 # authtoken is checked, but the $auth arg is NOT checked.  To say that another
1308 # way, be sure NOT to pass an editor argument if you want your token checked.
1309 # Otherwise the auth arg is just a flag saying "check the editor".  
1310
1311 sub ou_ancestor_setting {
1312     my( $self, $orgid, $name, $e, $auth ) = @_;
1313     $e = $e || OpenILS::Utils::CStoreEditor->new(
1314         (defined $auth) ? (authtoken => $auth) : ()
1315     );
1316
1317     if ($auth) {
1318         my $coust = $e->retrieve_config_org_unit_setting_type([
1319             $name, {flesh => 1, flesh_fields => {coust => ['view_perm']}}
1320         ]);
1321         return undef unless defined $coust;
1322         if ($coust->view_perm) {
1323             return undef unless $self->ou_ancestor_setting_perm_check($orgid, $coust->view_perm->code, $e, $auth);
1324         }
1325     }
1326
1327     my $query = {from => ['actor.org_unit_ancestor_setting', $name, $orgid]};
1328     my $setting = $e->json_query($query)->[0];
1329     return undef unless $setting;
1330     return {org => $setting->{org_unit}, value => OpenSRF::Utils::JSON->JSON2perl($setting->{value})};
1331 }
1332
1333 # Returns the org id if the requestor has the permissions required
1334 # to view the ou setting.
1335 sub ou_ancestor_setting_perm_check {
1336     my( $self, $orgid, $view_perm, $e, $auth ) = @_;
1337     $e = $e || OpenILS::Utils::CStoreEditor->new(
1338         (defined $auth) ? (authtoken => $auth) : ()
1339     );
1340
1341     # And you can't have permission if you don't have a valid session.
1342     return undef if not $e->checkauth;
1343     # And now that we know you MIGHT have permission, we check it.
1344     if ($view_perm) {
1345         return undef unless $e->allowed($view_perm, $orgid);
1346     }
1347
1348     return $orgid;
1349 }
1350
1351 sub ou_ancestor_setting_log {
1352     my ( $self, $orgid, $name, $e, $auth ) = @_;
1353     $e = $e || OpenILS::Utils::CStoreEditor->new(
1354         (defined $auth) ? (authtoken => $auth, xact => 1) : ()
1355     );
1356     my $coust;
1357
1358     if ($auth) {
1359         $coust = $e->retrieve_config_org_unit_setting_type([
1360             $name, {flesh => 1, flesh_fields => {coust => ['view_perm']}}
1361         ]);
1362
1363         my $perm_code = $coust->view_perm ? $coust->view_perm->code : undef;
1364         my $qorg = $self->ou_ancestor_setting_perm_check(
1365             $orgid,
1366             $perm_code,
1367             $e,
1368             $auth
1369         );
1370         my $sort = { order_by => { coustl => 'date_applied DESC' } };
1371         return $e->json_query({
1372             from => 'coustl',
1373             where => {
1374                 field_name => $name,
1375                 org => $qorg
1376             },
1377             $sort
1378         });
1379     };
1380 }
1381
1382 # This fetches a set of OU settings in one fell swoop,
1383 # which can be significantly faster than invoking
1384 # $U->ou_ancestor_setting() one setting at a time.
1385 # As the "_insecure" implies, however, callers are
1386 # responsible for ensuring that the settings to be
1387 # fetch do not need view permission checks.
1388 sub ou_ancestor_setting_batch_insecure {
1389     my( $self, $orgid, $names ) = @_;
1390
1391     my %result = map { $_ => undef } @$names;
1392     my $query = {
1393         from => [
1394             'actor.org_unit_ancestor_setting_batch',
1395             $orgid,
1396             '{' . join(',', @$names) . '}'
1397         ]
1398     };
1399     my $e = OpenILS::Utils::CStoreEditor->new();
1400     my $settings = $e->json_query($query);
1401     foreach my $setting (@$settings) {
1402         $result{$setting->{name}} = {
1403             org => $setting->{org_unit},
1404             value => OpenSRF::Utils::JSON->JSON2perl($setting->{value})
1405         };
1406     }
1407     return %result;
1408 }
1409
1410 # Returns a hash of hashes like so:
1411 # { 
1412 #   $lookup_org_id => {org => $context_org, value => $setting_value},
1413 #   $lookup_org_id2 => {org => $context_org2, value => $setting_value2},
1414 #   $lookup_org_id3 => {} # example of no setting value exists
1415 #   ...
1416 # }
1417 sub ou_ancestor_setting_batch_by_org_insecure {
1418     my ($self, $org_ids, $name, $e) = @_;
1419
1420     $e ||= OpenILS::Utils::CStoreEditor->new();
1421     my %result = map { $_ => {value => undef} } @$org_ids;
1422
1423     my $query = {
1424         from => [
1425             'actor.org_unit_ancestor_setting_batch_by_org',
1426             $name, '{' . join(',', @$org_ids) . '}'
1427         ]
1428     };
1429
1430     # DB func returns an array of settings matching the order of the
1431     # list of org unit IDs.  If the setting does not contain a valid
1432     # ->id value, then no setting value exists for that org unit.
1433     my $settings = $e->json_query($query);
1434     for my $idx (0 .. $#$org_ids) {
1435         my $setting = $settings->[$idx];
1436         my $org_id = $org_ids->[$idx];
1437
1438         next unless $setting->{id}; # null ID means no value is present.
1439
1440         $result{$org_id}->{org} = $setting->{org_unit};
1441         $result{$org_id}->{value} = 
1442             OpenSRF::Utils::JSON->JSON2perl($setting->{value});
1443     }
1444
1445     return %result;
1446 }
1447
1448 # returns the ISO8601 string representation of the requested epoch in GMT
1449 sub epoch2ISO8601 {
1450     my( $self, $epoch ) = @_;
1451     my ($sec,$min,$hour,$mday,$mon,$year) = gmtime($epoch);
1452     $year += 1900; $mon += 1;
1453     my $date = sprintf(
1454         '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1455         $year, $mon, $mday, $hour, $min, $sec);
1456     return $date;
1457 }
1458             
1459 sub find_highest_perm_org {
1460     my ( $self, $perm, $userid, $start_org, $org_tree ) = @_;
1461     my $org = $self->find_org($org_tree, $start_org );
1462
1463     my $lastid = -1;
1464     while( $org ) {
1465         last if ($self->check_perms( $userid, $org->id, $perm )); # perm failed
1466         $lastid = $org->id;
1467         $org = $self->find_org( $org_tree, $org->parent_ou() );
1468     }
1469
1470     return $lastid;
1471 }
1472
1473
1474 # returns the org_unit ID's 
1475 sub user_has_work_perm_at {
1476     my($self, $e, $perm, $options, $user_id) = @_;
1477     $options ||= {};
1478     $user_id = (defined $user_id) ? $user_id : $e->requestor->id;
1479
1480     my $func = 'permission.usr_has_perm_at';
1481     $func = $func.'_all' if $$options{descendants};
1482
1483     my $orgs = $e->json_query({from => [$func, $user_id, $perm]});
1484     $orgs = [map { $_->{ (keys %$_)[0] } } @$orgs];
1485
1486     return $orgs unless $$options{objects};
1487
1488     return $e->search_actor_org_unit({id => $orgs});
1489 }
1490
1491 sub get_user_work_ou_ids {
1492     my($self, $e, $userid) = @_;
1493     my $work_orgs = $e->json_query({
1494         select => {puwoum => ['work_ou']},
1495         from => 'puwoum',
1496         where => {usr => $e->requestor->id}});
1497
1498     return [] unless @$work_orgs;
1499     my @work_orgs;
1500     push(@work_orgs, $_->{work_ou}) for @$work_orgs;
1501
1502     return \@work_orgs;
1503 }
1504
1505
1506 my $org_types;
1507 sub get_org_types {
1508     my($self, $client) = @_;
1509     return $org_types if $org_types;
1510     return $org_types = OpenILS::Utils::CStoreEditor->new->retrieve_all_actor_org_unit_type();
1511 }
1512
1513 my %ORG_TREE;
1514 sub get_org_tree {
1515     my $self = shift;
1516     my $locale = shift || '';
1517     my $cache = OpenSRF::Utils::Cache->new("global", 0);
1518     my $tree = $ORG_TREE{$locale} || $cache->get_cache("orgtree.$locale");
1519     $ORG_TREE{$locale} = $tree; # make sure to populate the process-local cache
1520     return $tree if $tree;
1521
1522     my $ses = OpenILS::Utils::CStoreEditor->new;
1523     $ses->session->session_locale($locale);
1524     $tree = $ses->search_actor_org_unit( 
1525         [
1526             {"parent_ou" => undef },
1527             {
1528                 flesh               => -1,
1529                 flesh_fields    => { aou =>  ['children'] },
1530                 order_by            => { aou => 'name'}
1531             }
1532         ]
1533     )->[0];
1534
1535     $ORG_TREE{$locale} = $tree;
1536     $cache->put_cache("orgtree.$locale", $tree);
1537     return $tree;
1538 }
1539
1540 sub get_global_flag {
1541     my($self, $flag) = @_;
1542     return undef unless ($flag);
1543     return OpenILS::Utils::CStoreEditor->new->retrieve_config_global_flag($flag);
1544 }
1545
1546 sub get_org_descendants {
1547     my($self, $org_id, $depth) = @_;
1548
1549     my $select = {
1550         transform => 'actor.org_unit_descendants',
1551         column => 'id',
1552         result_field => 'id',
1553     };
1554     $select->{params} = [$depth] if defined $depth;
1555
1556     my $org_list = OpenILS::Utils::CStoreEditor->new->json_query({
1557         select => {aou => [$select]},
1558         from => 'aou',
1559         where => {id => $org_id}
1560     });
1561     my @orgs;
1562     push(@orgs, $_->{id}) for @$org_list;
1563     return \@orgs;
1564 }
1565
1566 sub get_org_ancestors {
1567     my($self, $org_id, $use_cache) = @_;
1568
1569     my ($cache, $orgs);
1570
1571     if ($use_cache) {
1572         $cache = OpenSRF::Utils::Cache->new("global", 0);
1573         $orgs = $cache->get_cache("org.ancestors.$org_id");
1574         return $orgs if $orgs;
1575     }
1576
1577     my $org_list = OpenILS::Utils::CStoreEditor->new->json_query({
1578         select => {
1579             aou => [{
1580                 transform => 'actor.org_unit_ancestors',
1581                 column => 'id',
1582                 result_field => 'id',
1583                 params => []
1584             }],
1585         },
1586         from => 'aou',
1587         where => {id => $org_id}
1588     });
1589
1590     $orgs = [ map { $_->{id} } @$org_list ];
1591
1592     $cache->put_cache("org.ancestors.$org_id", $orgs) if $use_cache;
1593     return $orgs;
1594 }
1595
1596 sub get_org_full_path {
1597     my($self, $org_id, $depth) = @_;
1598
1599     my $query = {
1600         select => {
1601             aou => [{
1602                 transform => 'actor.org_unit_full_path',
1603                 column => 'id',
1604                 result_field => 'id',
1605             }],
1606         },
1607         from => 'aou',
1608         where => {id => $org_id}
1609     };
1610
1611     $query->{select}->{aou}->[0]->{params} = [$depth] if defined $depth;
1612     my $org_list = OpenILS::Utils::CStoreEditor->new->json_query($query);
1613     return [ map {$_->{id}} @$org_list ];
1614 }
1615
1616 # returns the ID of the org unit ancestor at the specified depth
1617 sub org_unit_ancestor_at_depth {
1618     my($class, $org_id, $depth) = @_;
1619     my $resp = OpenILS::Utils::CStoreEditor->new->json_query(
1620         {from => ['actor.org_unit_ancestor_at_depth', $org_id, $depth]})->[0];
1621     return ($resp) ? $resp->{id} : undef;
1622 }
1623
1624 # returns the ID of the org unit ancestor at the specified distance
1625 sub get_org_unit_ancestor_at_distance {
1626     my ($class, $org_id, $distance) = @_;
1627     my $ancestors = OpenILS::Utils::CStoreEditor->new->json_query(
1628         { from => ['actor.org_unit_ancestors_distance', $org_id] });
1629     my @match = grep { $_->{distance} == $distance } @{$ancestors};
1630     return (@match) ? $match[0]->{id} : undef;
1631 }
1632
1633 # returns the ID of the org unit parent
1634 sub get_org_unit_parent {
1635     my ($class, $org_id) = @_;
1636     return $class->get_org_unit_ancestor_at_distance($org_id, 1);
1637 }
1638
1639 # Returns the proximity value between two org units.
1640 sub get_org_unit_proximity {
1641     my ($class, $e, $from_org, $to_org) = @_;
1642     $e = OpenILS::Utils::CStoreEditor->new unless ($e);
1643     my $r = $e->json_query(
1644         {
1645             select => {aoup => ['prox']},
1646             from => 'aoup',
1647             where => {from_org => $from_org, to_org => $to_org}
1648         }
1649     );
1650     if (ref($r) eq 'ARRAY' && @$r) {
1651         return $r->[0]->{prox};
1652     }
1653     return undef;
1654 }
1655
1656 # returns the user's configured locale as a string.  Defaults to en-US if none is configured.
1657 sub get_user_locale {
1658     my($self, $user_id, $e) = @_;
1659     $e ||= OpenILS::Utils::CStoreEditor->new;
1660
1661     # first, see if the user has an explicit locale set
1662     my $setting = $e->search_actor_user_setting(
1663         {usr => $user_id, name => 'global.locale'})->[0];
1664     return OpenSRF::Utils::JSON->JSON2perl($setting->value) if $setting;
1665
1666     my $user = $e->retrieve_actor_user($user_id) or return $e->event;
1667     return $self->get_org_locale($user->home_ou, $e);
1668 }
1669
1670 # returns org locale setting
1671 sub get_org_locale {
1672     my($self, $org_id, $e) = @_;
1673     $e ||= OpenILS::Utils::CStoreEditor->new;
1674
1675     my $locale;
1676     if(defined $org_id) {
1677         $locale = $self->ou_ancestor_setting_value($org_id, 'global.default_locale', $e);
1678         return $locale if $locale;
1679     }
1680
1681     # system-wide default
1682     my $sclient = OpenSRF::Utils::SettingsClient->new;
1683     $locale = $sclient->config_value('default_locale');
1684     return $locale if $locale;
1685
1686     # if nothing else, fallback to locale=cowboy
1687     return 'en-US';
1688 }
1689
1690
1691 # xml-escape non-ascii characters
1692 sub entityize { 
1693     my($self, $string, $form) = @_;
1694     $form ||= "";
1695
1696     if ($form eq 'D') {
1697         $string = NFD($string);
1698     } else {
1699         $string = NFC($string);
1700     }
1701
1702     # Convert raw ampersands to entities
1703     $string =~ s/&(?!\S+;)/&amp;/gso;
1704
1705     # Convert Unicode characters to entities
1706     $string =~ s/([\x{0080}-\x{fffd}])/sprintf('&#x%X;',ord($1))/sgoe;
1707
1708     return $string;
1709 }
1710
1711 # x0000-x0008 isn't legal in XML documents
1712 # XXX Perhaps this should just go into our standard entityize method
1713 sub strip_ctrl_chars {
1714     my ($self, $string) = @_;
1715
1716     $string =~ s/([\x{0000}-\x{0008}])//sgoe; 
1717     return $string;
1718 }
1719
1720 sub get_copy_price {
1721     my($self, $e, $copy, $volume) = @_;
1722
1723     $copy->price(0) if $copy->price and $copy->price < 0;
1724
1725
1726     my $owner;
1727     if(ref $volume) {
1728         if($volume->id == OILS_PRECAT_CALL_NUMBER) {
1729             $owner = $copy->circ_lib;
1730         } else {
1731             $owner = $volume->owning_lib;
1732         }
1733     } else {
1734         if($copy->call_number == OILS_PRECAT_CALL_NUMBER) {
1735             $owner = $copy->circ_lib;
1736         } else {
1737             $owner = $e->retrieve_asset_call_number($copy->call_number)->owning_lib;
1738         }
1739     }
1740
1741     my $min_price = $self->ou_ancestor_setting_value($owner, OILS_SETTING_MIN_ITEM_PRICE);
1742     my $max_price = $self->ou_ancestor_setting_value($owner, OILS_SETTING_MAX_ITEM_PRICE);
1743     my $charge_on_0 = $self->ou_ancestor_setting_value($owner, OILS_SETTING_CHARGE_LOST_ON_ZERO, $e);
1744     my $primary_field = $self->ou_ancestor_setting_value($owner, OILS_SETTING_PRIMARY_ITEM_VALUE_FIELD, $e);
1745     my $backup_field = $self->ou_ancestor_setting_value($owner, OILS_SETTING_SECONDARY_ITEM_VALUE_FIELD, $e);
1746
1747     my $price = defined $primary_field && $primary_field eq 'cost'
1748         ? $copy->cost
1749         : $copy->price;
1750
1751     # set the default price if needed
1752     if (!defined $price or ($price == 0 and $charge_on_0)) {
1753         if (defined $backup_field && $backup_field eq 'cost') {
1754             $price = $copy->cost;
1755         } elsif (defined $backup_field && $backup_field eq 'price') {
1756             $price = $copy->price;
1757         }
1758     }
1759     # possible fallthrough to original default item price behavior
1760     if (!defined $price or ($price == 0 and $charge_on_0)) {
1761         # set to default price
1762         $price = $self->ou_ancestor_setting_value(
1763             $owner, OILS_SETTING_DEF_ITEM_PRICE, $e) || 0;
1764     }
1765
1766     # adjust to min/max range if needed
1767     if (defined $max_price and $price > $max_price) {
1768         $price = $max_price;
1769     } elsif (defined $min_price and $price < $min_price
1770         and ($price != 0 or $charge_on_0 or !defined $charge_on_0)) {
1771         # default to raising the price to the minimum,
1772         # but let 0 fall through if $charge_on_0 is set and is false
1773         $price = $min_price;
1774     }
1775
1776     return $price;
1777 }
1778
1779 # given a transaction ID, this returns the context org_unit for the transaction
1780 sub xact_org {
1781     my($self, $xact_id, $e) = @_;
1782     $e ||= OpenILS::Utils::CStoreEditor->new;
1783     
1784     my $loc = $e->json_query({
1785         "select" => {circ => ["circ_lib"]},
1786         from     => "circ",
1787         "where"  => {id => $xact_id},
1788     });
1789
1790     return $loc->[0]->{circ_lib} if @$loc;
1791
1792     $loc = $e->json_query({
1793         "select" => {bresv => ["request_lib"]},
1794         from     => "bresv",
1795         "where"  => {id => $xact_id},
1796     });
1797
1798     return $loc->[0]->{request_lib} if @$loc;
1799
1800     $loc = $e->json_query({
1801         "select" => {mg => ["billing_location"]},
1802         from     => "mg",
1803         "where"  => {id => $xact_id},
1804     });
1805
1806     return $loc->[0]->{billing_location};
1807 }
1808
1809
1810 sub find_event_def_by_hook {
1811     my($self, $hook, $context_org, $e) = @_;
1812
1813     $e ||= OpenILS::Utils::CStoreEditor->new;
1814
1815     my $orgs = $self->get_org_ancestors($context_org);
1816
1817     # search from the context org up
1818     for my $org_id (reverse @$orgs) {
1819
1820         my $def = $e->search_action_trigger_event_definition(
1821             {hook => $hook, owner => $org_id, active => 't'})->[0];
1822
1823         return $def if $def;
1824     }
1825
1826     return undef;
1827 }
1828
1829
1830
1831 # If an event_def ID is not provided, use the hook and context org to find the 
1832 # most appropriate event.  create the event, fire it, then return the resulting
1833 # event with fleshed template_output and error_output
1834 sub fire_object_event {
1835     my($self, $event_def, $hook, $object, $context_org, $granularity, $user_data, $client) = @_;
1836
1837     my $e = OpenILS::Utils::CStoreEditor->new;
1838     my $def;
1839
1840     my $auto_method = "open-ils.trigger.event.autocreate.by_definition";
1841
1842     if($event_def) {
1843         $def = $e->retrieve_action_trigger_event_definition($event_def)
1844             or return $e->event;
1845
1846         $auto_method .= '.include_inactive';
1847
1848     } else {
1849
1850         # find the most appropriate event def depending on context org
1851         $def = $self->find_event_def_by_hook($hook, $context_org, $e) 
1852             or return $e->event;
1853     }
1854
1855     my $final_resp;
1856
1857     if($def->group_field) {
1858         # we have a list of objects
1859         $object = [$object] unless ref $object eq 'ARRAY';
1860
1861         my @event_ids;
1862         $user_data ||= [];
1863         for my $i (0..$#$object) {
1864             my $obj = $$object[$i];
1865             my $udata = $$user_data[$i];
1866             my $event_id = $self->simplereq(
1867                 'open-ils.trigger', $auto_method, $def->id, $obj, $context_org, $udata);
1868             push(@event_ids, $event_id);
1869         }
1870
1871         $logger->info("EVENTS = " . OpenSRF::Utils::JSON->perl2JSON(\@event_ids));
1872
1873         my $resp;
1874         if (not defined $client) {
1875             $resp = $self->simplereq(
1876                 'open-ils.trigger',
1877                 'open-ils.trigger.event_group.fire',
1878                 \@event_ids);
1879         } else {
1880             $resp = $self->patientreq(
1881                 $client,
1882                 "open-ils.trigger", "open-ils.trigger.event_group.fire",
1883                 \@event_ids
1884             );
1885         }
1886
1887         if($resp and $resp->{events} and @{$resp->{events}}) {
1888
1889             $e->xact_begin;
1890             $final_resp = $e->retrieve_action_trigger_event([
1891                 $resp->{events}->[0]->id,
1892                 {flesh => 1, flesh_fields => {atev => ['template_output', 'error_output']}}
1893             ]);
1894             $e->rollback;
1895         }
1896
1897     } else {
1898
1899         $object = $$object[0] if ref $object eq 'ARRAY';
1900
1901         my $event_id;
1902         my $resp;
1903
1904         if (not defined $client) {
1905             $event_id = $self->simplereq(
1906                 'open-ils.trigger',
1907                 $auto_method, $def->id, $object, $context_org, $user_data
1908             );
1909
1910             $resp = $self->simplereq(
1911                 'open-ils.trigger',
1912                 'open-ils.trigger.event.fire',
1913                 $event_id
1914             );
1915         } else {
1916             $event_id = $self->patientreq(
1917                 $client,
1918                 'open-ils.trigger',
1919                 $auto_method, $def->id, $object, $context_org, $user_data
1920             );
1921
1922             $resp = $self->patientreq(
1923                 $client,
1924                 'open-ils.trigger',
1925                 'open-ils.trigger.event.fire',
1926                 $event_id
1927             );
1928         }
1929         
1930         if($resp and $resp->{event}) {
1931             $e->xact_begin;
1932             $final_resp = $e->retrieve_action_trigger_event([
1933                 $resp->{event}->id,
1934                 {flesh => 1, flesh_fields => {atev => ['template_output', 'error_output']}}
1935             ]);
1936             $e->rollback;
1937         }
1938     }
1939
1940     return $final_resp;
1941 }
1942
1943
1944 sub create_events_for_hook {
1945     my($self, $hook, $obj, $org_id, $granularity, $user_data, $wait) = @_;
1946     my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1947     my $req = $ses->request('open-ils.trigger.event.autocreate', 
1948         $hook, $obj, $org_id, $granularity, $user_data);
1949     return undef unless $wait;
1950     my $resp = $req->recv;
1951     return $resp->content if $resp;
1952 }
1953
1954 sub create_uuid_string {
1955     return create_UUID_as_string();
1956 }
1957
1958 sub create_circ_chain_summary {
1959     my($class, $e, $circ_id) = @_;
1960     my $sum = $e->json_query({from => ['action.summarize_all_circ_chain', $circ_id]})->[0];
1961     return undef unless $sum;
1962     my $obj = Fieldmapper::action::circ_chain_summary->new;
1963     $obj->$_($sum->{$_}) for keys %$sum;
1964     return $obj;
1965 }
1966
1967
1968 # Returns "mra" attribute key/value pairs for a set of bre's
1969 # Takes a list of bre IDs, returns a hash of hashes,
1970 # {bre_id1 => {key1 => {code => value1, label => label1}, ...}...}
1971 my $ccvm_cache;
1972 sub get_bre_attrs {
1973     my ($class, $bre_ids, $e) = @_;
1974     $e = $e || OpenILS::Utils::CStoreEditor->new;
1975
1976     my $attrs = {};
1977     return $attrs unless defined $bre_ids;
1978     $bre_ids = [$bre_ids] unless ref $bre_ids;
1979
1980     my $mra = $e->json_query({
1981         select => {
1982             mra => [
1983                 {
1984                     column => 'id',
1985                     alias => 'bre'
1986                 }, {
1987                     column => 'attrs',
1988                     transform => 'each',
1989                     result_field => 'key',
1990                     alias => 'key'
1991                 },{
1992                     column => 'attrs',
1993                     transform => 'each',
1994                     result_field => 'value',
1995                     alias => 'value'
1996                 }
1997             ]
1998         },
1999         from => 'mra',
2000         where => {id => $bre_ids}
2001     });
2002
2003     return $attrs unless $mra;
2004
2005     $ccvm_cache = $ccvm_cache || $e->search_config_coded_value_map({id => {'!=' => undef}});
2006
2007     for my $id (@$bre_ids) {
2008         $attrs->{$id} = {};
2009         for my $mra (grep { $_->{bre} eq $id } @$mra) {
2010             my $ctype = $mra->{key};
2011             my $code = $mra->{value};
2012             $attrs->{$id}->{$ctype} = {code => $code};
2013             if($code) {
2014                 my ($ccvm) = grep { $_->ctype eq $ctype and $_->code eq $code } @$ccvm_cache;
2015                 $attrs->{$id}->{$ctype}->{label} = $ccvm->value if $ccvm;
2016             }
2017         }
2018     }
2019
2020     return $attrs;
2021 }
2022
2023 # Shorter version of bib_container_items_via_search() below, only using
2024 # the queryparser record_list filter instead of the container filter.
2025 sub bib_record_list_via_search {
2026     my ($class, $search_query, $search_args) = @_;
2027
2028     # First, Use search API to get container items sorted in any way that crad
2029     # sorters support.
2030     my $search_result = $class->simplereq(
2031         "open-ils.search", "open-ils.search.biblio.multiclass.query",
2032         $search_args, $search_query
2033     );
2034
2035     unless ($search_result) {
2036         # empty result sets won't cause this, but actual errors should.
2037         $logger->warn("bib_record_list_via_search() got nothing from search");
2038         return;
2039     }
2040
2041     # Throw away other junk from search, keeping only bib IDs.
2042     return [ map { shift @$_ } @{$search_result->{ids}} ];
2043 }
2044
2045 # 'no_flesh' avoids fleshing the target_biblio_record_entry
2046 sub bib_container_items_via_search {
2047     my ($class, $container_id, $search_query, $search_args, $no_flesh) = @_;
2048
2049     # First, Use search API to get container items sorted in any way that crad
2050     # sorters support.
2051     my $search_result = $class->simplereq(
2052         "open-ils.search", "open-ils.search.biblio.multiclass.query",
2053         $search_args, $search_query
2054     );
2055     unless ($search_result) {
2056         # empty result sets won't cause this, but actual errors should.
2057         $logger->warn("bib_container_items_via_search() got nothing from search");
2058         return;
2059     }
2060
2061     # Throw away other junk from search, keeping only bib IDs.
2062     my $id_list = [ map { shift @$_ } @{$search_result->{ids}} ];
2063
2064     return [] unless @$id_list;
2065
2066     # Now get the bib container items themselves...
2067     my $e = new OpenILS::Utils::CStoreEditor;
2068     unless ($e) {
2069         $logger->warn("bib_container_items_via_search() couldn't get cstoreeditor");
2070         return;
2071     }
2072
2073     my @flesh_fields = qw/notes/;
2074     push(@flesh_fields, 'target_biblio_record_entry') unless $no_flesh;
2075
2076     my $items = $e->search_container_biblio_record_entry_bucket_item([
2077         {
2078             "target_biblio_record_entry" => $id_list,
2079             "bucket" => $container_id
2080         }, {
2081             flesh => 1,
2082             flesh_fields => {"cbrebi" => \@flesh_fields}
2083         }
2084     ], {substream => 1});
2085
2086     unless ($items) {
2087         $logger->warn(
2088             "bib_container_items_via_search() couldn't get bucket items: " .
2089             $e->die_event->{textcode}
2090         );
2091         return;
2092     }
2093
2094     # ... and put them in the same order that the search API said they
2095     # should be in.
2096     my %ordering_hash = map { 
2097         ($no_flesh) ? $_->target_biblio_record_entry : $_->target_biblio_record_entry->id, 
2098         $_ 
2099     } @$items;
2100
2101     return [map { $ordering_hash{$_} } @$id_list];
2102 }
2103
2104 # returns undef on success, Event on error
2105 sub log_user_activity {
2106     my ($class, $user_id, $who, $what, $e, $async) = @_;
2107
2108     my $commit = 0;
2109     if (!$e) {
2110         $e = OpenILS::Utils::CStoreEditor->new(xact => 1);
2111         $commit = 1;
2112     }
2113
2114     my $res = $e->json_query({
2115         from => [
2116             'actor.insert_usr_activity', 
2117             $user_id, $who, $what, OpenSRF::AppSession->ingress
2118         ]
2119     });
2120
2121     if ($res) { # call returned OK
2122
2123         $e->commit   if $commit and @$res;
2124         $e->rollback if $commit and !@$res;
2125
2126     } else {
2127         return $e->die_event;
2128     }
2129
2130     return undef;
2131 }
2132
2133 # I hate to put this here exactly, but this code needs to be shared between
2134 # the TPAC's mod_perl module and open-ils.serial.
2135 #
2136 # There is a reason every part of the query *except* those parts dealing
2137 # with scope are moved here from the code's origin in TPAC.  The serials
2138 # use case does *not* want the same scoping logic.
2139 #
2140 # Also, note that for the serials uses case, we may filter in OPAC visible
2141 # status and copy/call_number deletedness, but we don't filter on any
2142 # particular values for serial.item.status or serial.item.date_received.
2143 # Since we're only using this *after* winnowing down the set of issuances
2144 # that copies should be related to, I'm not sure we need any such serial.item
2145 # filters.
2146
2147 sub basic_opac_copy_query {
2148     ######################################################################
2149     # Pass a defined value for either $rec_id OR ($iss_id AND $dist_id), #
2150     # not both.                                                          #
2151     ######################################################################
2152     my ($self,$rec_id,$iss_id,$dist_id,$copy_limit,$copy_offset,$staff) = @_;
2153
2154     return {
2155         select => {
2156             acp => ['id', 'barcode', 'circ_lib', 'create_date', 'active_date',
2157                     'age_protect', 'holdable', 'copy_number', 'circ_modifier'],
2158             acpl => [
2159                 {column => 'name', alias => 'copy_location'},
2160                 {column => 'holdable', alias => 'location_holdable'},
2161                 {column => 'url', alias => 'location_url'}
2162             ],
2163             ccs => [
2164                 {column => 'id', alias => 'status_code'},
2165                 {column => 'name', alias => 'copy_status'},
2166                 {column => 'holdable', alias => 'status_holdable'},
2167                 {column => 'is_available', alias => 'is_available'}
2168             ],
2169             acn => [
2170                 {column => 'label', alias => 'call_number_label'},
2171                 {column => 'id', alias => 'call_number'},
2172                 {column => 'owning_lib', alias => 'call_number_owning_lib'}
2173             ],
2174             circ => ['due_date',{column => 'circ_lib', alias => 'circ_circ_lib'}],
2175             acnp => [
2176                 {column => 'label', alias => 'call_number_prefix_label'},
2177                 {column => 'id', alias => 'call_number_prefix'}
2178             ],
2179             acns => [
2180                 {column => 'label', alias => 'call_number_suffix_label'},
2181                 {column => 'id', alias => 'call_number_suffix'}
2182             ],
2183             bmp => [
2184                 {column => 'label', alias => 'part_label'},
2185             ],
2186             ($staff ? (erfcc => ['circ_count']) : ()),
2187             crahp => [
2188                 {column => 'name', alias => 'age_protect_label'}
2189             ],
2190             ($iss_id ? (sitem => ["issuance"]) : ())
2191         },
2192
2193         from => {
2194             acp => [
2195                 {acn => { # 0
2196                     join => {
2197                         acnp => { fkey => 'prefix' },
2198                         acns => { fkey => 'suffix' }
2199                     },
2200                     filter => [
2201                         {deleted => 'f'},
2202                         ($rec_id ? {record => $rec_id} : ())
2203                     ],
2204                 }},
2205                 'aou', # 1
2206                 {circ => { # 2 If the copy is circulating, retrieve the open circ
2207                     type => 'left',
2208                     filter => {checkin_time => undef}
2209                 }},
2210                 {acpl => { # 3
2211                     filter => {
2212                         deleted => 'f',
2213                         ($staff ? () : ( opac_visible => 't' )),
2214                     },
2215                 }},
2216                 {ccs => { # 4
2217                     ($staff ? () : (filter => { opac_visible => 't' }))
2218                 }},
2219                 {acpm => { # 5
2220                     type => 'left',
2221                     join => {
2222                         bmp => { type => 'left', filter => { deleted => 'f' } }
2223                     }
2224                 }},
2225                 {'crahp' => { # 6
2226                     type => 'left'
2227                 }},
2228                 ($iss_id ? { # 7
2229                     sitem => {
2230                         fkey => 'id',
2231                         field => 'unit',
2232                         filter => {issuance => $iss_id},
2233                         join => {
2234                             sstr => { }
2235                         }
2236                     }
2237                 } : ()),
2238                 ($staff ? {
2239                     erfcc => {
2240                         fkey => 'id',
2241                         field => 'id'
2242                     }
2243                 }: ()),
2244             ]
2245         },
2246
2247         where => {
2248             '+acp' => {
2249                 deleted => 'f',
2250                 ($staff ? () : (opac_visible => 't'))
2251             },
2252             ($dist_id ? ( '+sstr' => { distribution => $dist_id } ) : ()),
2253             ($staff ? () : ( '+aou' => { opac_visible => 't' } ))
2254         },
2255
2256         order_by => [
2257             {class => 'aou', field => 'name'},
2258             {class => 'acn', field => 'label_sortkey'},
2259             {class => 'acns', field => 'label_sortkey'},
2260             {class => 'bmp', field => 'label_sortkey'},
2261             {class => 'acp', field => 'copy_number'},
2262             {class => 'acp', field => 'barcode'}
2263         ],
2264
2265         limit => $copy_limit,
2266         offset => $copy_offset
2267     };
2268 }
2269
2270 # Compare two dates, date1 and date2. If date2 is not defined, then
2271 # DateTime->now will be used. Assumes dates are in ISO8601 format as
2272 # supported by DateTime::Format::ISO8601. (A future enhancement might
2273 # be to support other formats.)
2274 #
2275 # Returns -1 if $date1 < $date2
2276 # Returns 0 if $date1 == $date2
2277 # Returns 1 if $date1 > $date2
2278 sub datecmp {
2279     my $self = shift;
2280     my $date1 = shift;
2281     my $date2 = shift;
2282
2283     # Check for timezone offsets and limit them to 2 digits:
2284     if ($date1 && $date1 =~ /(?:-|\+)\d\d\d\d$/) {
2285         $date1 = substr($date1, 0, length($date1) - 2);
2286     }
2287     if ($date2 && $date2 =~ /(?:-|\+)\d\d\d\d$/) {
2288         $date2 = substr($date2, 0, length($date2) - 2);
2289     }
2290
2291     # check date1:
2292     unless (UNIVERSAL::isa($date1, "DateTime")) {
2293         $date1 = DateTime::Format::ISO8601->parse_datetime($date1);
2294     }
2295
2296     # Check for date2:
2297     unless ($date2) {
2298         $date2 = DateTime->now;
2299     } else {
2300         unless (UNIVERSAL::isa($date2, "DateTime")) {
2301             $date2 = DateTime::Format::ISO8601->parse_datetime($date2);
2302         }
2303     }
2304
2305     return DateTime->compare($date1, $date2);
2306 }
2307
2308
2309 # marcdoc is an XML::LibXML document
2310 # updates the doc and returns the entityized MARC string
2311 sub strip_marc_fields {
2312     my ($class, $e, $marcdoc, $grps) = @_;
2313     
2314     my $orgs = $class->get_org_ancestors($e->requestor->ws_ou);
2315
2316     my $query = {
2317         select  => {vibtf => ['field']},
2318         from    => {vibtf => 'vibtg'},
2319         where   => {'+vibtg' => {owner => $orgs}},
2320         distinct => 1
2321     };
2322
2323     # give me always-apply groups plus any selected groups
2324     if ($grps and @$grps) {
2325         $query->{where}->{'+vibtg'}->{'-or'} = [
2326             {id => $grps},
2327             {always_apply => 't'}
2328         ];
2329
2330     } else {
2331         $query->{where}->{'+vibtg'}->{always_apply} = 't';
2332     }
2333
2334     my $fields = $e->json_query($query);
2335
2336     for my $field (@$fields) {
2337         my $tag = $field->{field};
2338         for my $node ($marcdoc->findnodes('//*[@tag="'.$tag.'"]')) {
2339             $node->parentNode->removeChild($node);
2340         }
2341     }
2342
2343     return $class->entityize($marcdoc->documentElement->toString);
2344 }
2345
2346 # marcdoc is an XML::LibXML document
2347 # updates the document and returns the entityized MARC string.
2348 sub set_marc_905u {
2349     my ($class, $marcdoc, $username) = @_;
2350
2351     # Look for existing 905$u subfields. If any exist, do nothing.
2352     my @nodes = $marcdoc->findnodes('//*[@tag="905"]/*[@code="u"]');
2353     unless (@nodes) {
2354         # We create a new 905 and the subfield u to that.
2355         my $parentNode = $marcdoc->createElement('datafield');
2356         $parentNode->setAttribute('tag', '905');
2357         $parentNode->setAttribute('ind1', '');
2358         $parentNode->setAttribute('ind2', '');
2359         $marcdoc->documentElement->addChild($parentNode);
2360         my $node = $marcdoc->createElement('subfield');
2361         $node->setAttribute('code', 'u');
2362         $node->appendTextNode($username);
2363         $parentNode->addChild($node);
2364
2365     }
2366
2367     return $class->entityize($marcdoc->documentElement->toString);
2368 }
2369
2370 # Given a list of PostgreSQL arrays of numbers,
2371 # unnest the numbers and return a unique set, skipping any list elements
2372 # that are just '{NULL}'.
2373 sub unique_unnested_numbers {
2374     my $class = shift;
2375
2376     no warnings 'numeric';
2377
2378     return undef unless ( scalar @_ );
2379
2380     return uniq(
2381         map(
2382             int,
2383             map { $_ eq 'NULL' ? undef : (split /,/, $_) }
2384                 map { substr($_, 1, -1) } @_
2385         )
2386     );
2387 }
2388
2389 # Given a list of numbers, turn them into a PG array, skipping undef's
2390 sub intarray2pgarray {
2391     my $class = shift;
2392     no warnings 'numeric';
2393
2394     return '{' . join( ',', map(int, grep { defined && /^\d+$/ } @_) ) . '}';
2395 }
2396
2397 # Check if a transaction should be left open or closed. Close the
2398 # transaction if it should be closed or open it otherwise. Returns
2399 # undef on success or a failure event.
2400 sub check_open_xact {
2401     my( $self, $editor, $xactid, $xact ) = @_;
2402
2403     # Grab the transaction
2404     $xact ||= $editor->retrieve_money_billable_transaction($xactid);
2405     return $editor->event unless $xact;
2406     $xactid ||= $xact->id;
2407
2408     # grab the summary and see how much is owed on this transaction
2409     my ($summary) = $self->fetch_mbts($xactid, $editor);
2410
2411     # grab the circulation if it is a circ;
2412     my $circ = $editor->retrieve_action_circulation($xactid);
2413
2414     # If nothing is owed on the transaction but it is still open
2415     # and this transaction is not an open circulation, close it
2416     if(
2417         ( $summary->balance_owed == 0 and ! $xact->xact_finish ) and
2418         ( !$circ or $circ->stop_fines )) {
2419
2420         $logger->info("closing transaction ".$xact->id. ' because balance_owed == 0');
2421         $xact->xact_finish('now');
2422         $editor->update_money_billable_transaction($xact)
2423             or return $editor->event;
2424         return undef;
2425     }
2426
2427     # If money is owed or a refund is due on the xact and xact_finish
2428     # is set, clear it (to reopen the xact) and update
2429     if( $summary->balance_owed != 0 and $xact->xact_finish ) {
2430         $logger->info("re-opening transaction ".$xact->id. ' because balance_owed != 0');
2431         $xact->clear_xact_finish;
2432         $editor->update_money_billable_transaction($xact)
2433             or return $editor->event;
2434         return undef;
2435     }
2436     return undef;
2437 }
2438
2439 # Because floating point math has rounding issues, and Dyrcona gets
2440 # tired of typing out the code to multiply floating point numbers
2441 # before adding and subtracting them and then dividing the result by
2442 # 100 each time, he wrote this little subroutine for subtracting
2443 # floating point values.  It can serve as a model for the other
2444 # operations if you like.
2445 #
2446 # It takes a list of floating point values as arguments.  The rest are
2447 # all subtracted from the first and the result is returned.  The
2448 # values are all multiplied by 100 before being used, and the result
2449 # is divided by 100 in order to avoid decimal rounding errors inherent
2450 # in floating point math.
2451 #
2452 # XXX shifting using multiplication/division *may* still introduce
2453 # rounding errors -- better to implement using string manipulation?
2454 sub fpdiff {
2455     my ($class, @args) = @_;
2456     my $result = shift(@args) * 100;
2457     while (my $arg = shift(@args)) {
2458         $result -= $arg * 100;
2459     }
2460     return $result / 100;
2461 }
2462
2463 sub fpsum {
2464     my ($class, @args) = @_;
2465     my $result = shift(@args) * 100;
2466     while (my $arg = shift(@args)) {
2467         $result += $arg * 100;
2468     }
2469     return $result / 100;
2470 }
2471
2472 # Non-migrated passwords can be verified directly in the DB
2473 # with any extra hashing.
2474 sub verify_user_password {
2475     my ($class, $e, $user_id, $passwd, $pw_type) = @_;
2476
2477     $pw_type ||= 'main'; # primary login password
2478
2479     my $verify = $e->json_query({
2480         from => [
2481             'actor.verify_passwd', 
2482             $user_id, $pw_type, $passwd
2483         ]
2484     })->[0];
2485
2486     return $class->is_true($verify->{'actor.verify_passwd'});
2487 }
2488
2489 # Passwords migrated from the original MD5 scheme are passed through 2
2490 # extra layers of MD5 hashing for backwards compatibility with the
2491 # MD5 passwords of yore and the MD5-based chap-style authentication.  
2492 # Passwords are stored in the DB like this:
2493 # CRYPT( MD5( pw_salt || MD5(real_password) ), pw_salt )
2494 #
2495 # If 'as_md5' is true, the password provided has already been
2496 # MD5 hashed.
2497 sub verify_migrated_user_password {
2498     my ($class, $e, $user_id, $passwd, $as_md5) = @_;
2499
2500     # 'main' is the primary login password. This is the only password 
2501     # type that requires the additional MD5 hashing.
2502     my $pw_type = 'main';
2503
2504     # Sometimes we have the bare password, sometimes the MD5 version.
2505     my $md5_pass = $as_md5 ? $passwd : md5_hex($passwd);
2506
2507     my $salt = $e->json_query({
2508         from => [
2509             'actor.get_salt', 
2510             $user_id, 
2511             $pw_type
2512         ]
2513     })->[0];
2514
2515     $salt = $salt->{'actor.get_salt'};
2516
2517     return $class->verify_user_password(
2518         $e, $user_id, md5_hex($salt . $md5_pass), $pw_type);
2519 }
2520
2521
2522 # generate a MARC XML document from a MARC XML string
2523 sub marc_xml_to_doc {
2524     my ($class, $xml) = @_;
2525     my $marc_doc = XML::LibXML->new->parse_string($xml);
2526     $marc_doc->documentElement->setNamespace(MARC_NAMESPACE, 'marc', 1);
2527     $marc_doc->documentElement->setNamespace(MARC_NAMESPACE);
2528     return $marc_doc;
2529 }
2530
2531
2532
2533 1;
2534