]> 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         if ($coust && $coust->view_perm) {
1322             # And you can't have permission if you don't have a valid session.
1323             return undef if not $e->checkauth;
1324             # And now that we know you MIGHT have permission, we check it.
1325             return undef if not $e->allowed($coust->view_perm->code, $orgid);
1326         }
1327     }
1328
1329     my $query = {from => ['actor.org_unit_ancestor_setting', $name, $orgid]};
1330     my $setting = $e->json_query($query)->[0];
1331     return undef unless $setting;
1332     return {org => $setting->{org_unit}, value => OpenSRF::Utils::JSON->JSON2perl($setting->{value})};
1333 }   
1334
1335 # This fetches a set of OU settings in one fell swoop,
1336 # which can be significantly faster than invoking
1337 # $U->ou_ancestor_setting() one setting at a time.
1338 # As the "_insecure" implies, however, callers are
1339 # responsible for ensuring that the settings to be
1340 # fetch do not need view permission checks.
1341 sub ou_ancestor_setting_batch_insecure {
1342     my( $self, $orgid, $names ) = @_;
1343
1344     my %result = map { $_ => undef } @$names;
1345     my $query = {
1346         from => [
1347             'actor.org_unit_ancestor_setting_batch',
1348             $orgid,
1349             '{' . join(',', @$names) . '}'
1350         ]
1351     };
1352     my $e = OpenILS::Utils::CStoreEditor->new();
1353     my $settings = $e->json_query($query);
1354     foreach my $setting (@$settings) {
1355         $result{$setting->{name}} = {
1356             org => $setting->{org_unit},
1357             value => OpenSRF::Utils::JSON->JSON2perl($setting->{value})
1358         };
1359     }
1360     return %result;
1361 }
1362
1363 # Returns a hash of hashes like so:
1364 # { 
1365 #   $lookup_org_id => {org => $context_org, value => $setting_value},
1366 #   $lookup_org_id2 => {org => $context_org2, value => $setting_value2},
1367 #   $lookup_org_id3 => {} # example of no setting value exists
1368 #   ...
1369 # }
1370 sub ou_ancestor_setting_batch_by_org_insecure {
1371     my ($self, $org_ids, $name, $e) = @_;
1372
1373     $e ||= OpenILS::Utils::CStoreEditor->new();
1374     my %result = map { $_ => {value => undef} } @$org_ids;
1375
1376     my $query = {
1377         from => [
1378             'actor.org_unit_ancestor_setting_batch_by_org',
1379             $name, '{' . join(',', @$org_ids) . '}'
1380         ]
1381     };
1382
1383     # DB func returns an array of settings matching the order of the
1384     # list of org unit IDs.  If the setting does not contain a valid
1385     # ->id value, then no setting value exists for that org unit.
1386     my $settings = $e->json_query($query);
1387     for my $idx (0 .. $#$org_ids) {
1388         my $setting = $settings->[$idx];
1389         my $org_id = $org_ids->[$idx];
1390
1391         next unless $setting->{id}; # null ID means no value is present.
1392
1393         $result{$org_id}->{org} = $setting->{org_unit};
1394         $result{$org_id}->{value} = 
1395             OpenSRF::Utils::JSON->JSON2perl($setting->{value});
1396     }
1397
1398     return %result;
1399 }
1400
1401 # returns the ISO8601 string representation of the requested epoch in GMT
1402 sub epoch2ISO8601 {
1403     my( $self, $epoch ) = @_;
1404     my ($sec,$min,$hour,$mday,$mon,$year) = gmtime($epoch);
1405     $year += 1900; $mon += 1;
1406     my $date = sprintf(
1407         '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1408         $year, $mon, $mday, $hour, $min, $sec);
1409     return $date;
1410 }
1411             
1412 sub find_highest_perm_org {
1413     my ( $self, $perm, $userid, $start_org, $org_tree ) = @_;
1414     my $org = $self->find_org($org_tree, $start_org );
1415
1416     my $lastid = -1;
1417     while( $org ) {
1418         last if ($self->check_perms( $userid, $org->id, $perm )); # perm failed
1419         $lastid = $org->id;
1420         $org = $self->find_org( $org_tree, $org->parent_ou() );
1421     }
1422
1423     return $lastid;
1424 }
1425
1426
1427 # returns the org_unit ID's 
1428 sub user_has_work_perm_at {
1429     my($self, $e, $perm, $options, $user_id) = @_;
1430     $options ||= {};
1431     $user_id = (defined $user_id) ? $user_id : $e->requestor->id;
1432
1433     my $func = 'permission.usr_has_perm_at';
1434     $func = $func.'_all' if $$options{descendants};
1435
1436     my $orgs = $e->json_query({from => [$func, $user_id, $perm]});
1437     $orgs = [map { $_->{ (keys %$_)[0] } } @$orgs];
1438
1439     return $orgs unless $$options{objects};
1440
1441     return $e->search_actor_org_unit({id => $orgs});
1442 }
1443
1444 sub get_user_work_ou_ids {
1445     my($self, $e, $userid) = @_;
1446     my $work_orgs = $e->json_query({
1447         select => {puwoum => ['work_ou']},
1448         from => 'puwoum',
1449         where => {usr => $e->requestor->id}});
1450
1451     return [] unless @$work_orgs;
1452     my @work_orgs;
1453     push(@work_orgs, $_->{work_ou}) for @$work_orgs;
1454
1455     return \@work_orgs;
1456 }
1457
1458
1459 my $org_types;
1460 sub get_org_types {
1461     my($self, $client) = @_;
1462     return $org_types if $org_types;
1463     return $org_types = OpenILS::Utils::CStoreEditor->new->retrieve_all_actor_org_unit_type();
1464 }
1465
1466 my %ORG_TREE;
1467 sub get_org_tree {
1468     my $self = shift;
1469     my $locale = shift || '';
1470     my $cache = OpenSRF::Utils::Cache->new("global", 0);
1471     my $tree = $ORG_TREE{$locale} || $cache->get_cache("orgtree.$locale");
1472     $ORG_TREE{$locale} = $tree; # make sure to populate the process-local cache
1473     return $tree if $tree;
1474
1475     my $ses = OpenILS::Utils::CStoreEditor->new;
1476     $ses->session->session_locale($locale);
1477     $tree = $ses->search_actor_org_unit( 
1478         [
1479             {"parent_ou" => undef },
1480             {
1481                 flesh               => -1,
1482                 flesh_fields    => { aou =>  ['children'] },
1483                 order_by            => { aou => 'name'}
1484             }
1485         ]
1486     )->[0];
1487
1488     $ORG_TREE{$locale} = $tree;
1489     $cache->put_cache("orgtree.$locale", $tree);
1490     return $tree;
1491 }
1492
1493 sub get_global_flag {
1494     my($self, $flag) = @_;
1495     return undef unless ($flag);
1496     return OpenILS::Utils::CStoreEditor->new->retrieve_config_global_flag($flag);
1497 }
1498
1499 sub get_org_descendants {
1500     my($self, $org_id, $depth) = @_;
1501
1502     my $select = {
1503         transform => 'actor.org_unit_descendants',
1504         column => 'id',
1505         result_field => 'id',
1506     };
1507     $select->{params} = [$depth] if defined $depth;
1508
1509     my $org_list = OpenILS::Utils::CStoreEditor->new->json_query({
1510         select => {aou => [$select]},
1511         from => 'aou',
1512         where => {id => $org_id}
1513     });
1514     my @orgs;
1515     push(@orgs, $_->{id}) for @$org_list;
1516     return \@orgs;
1517 }
1518
1519 sub get_org_ancestors {
1520     my($self, $org_id, $use_cache) = @_;
1521
1522     my ($cache, $orgs);
1523
1524     if ($use_cache) {
1525         $cache = OpenSRF::Utils::Cache->new("global", 0);
1526         $orgs = $cache->get_cache("org.ancestors.$org_id");
1527         return $orgs if $orgs;
1528     }
1529
1530     my $org_list = OpenILS::Utils::CStoreEditor->new->json_query({
1531         select => {
1532             aou => [{
1533                 transform => 'actor.org_unit_ancestors',
1534                 column => 'id',
1535                 result_field => 'id',
1536                 params => []
1537             }],
1538         },
1539         from => 'aou',
1540         where => {id => $org_id}
1541     });
1542
1543     $orgs = [ map { $_->{id} } @$org_list ];
1544
1545     $cache->put_cache("org.ancestors.$org_id", $orgs) if $use_cache;
1546     return $orgs;
1547 }
1548
1549 sub get_org_full_path {
1550     my($self, $org_id, $depth) = @_;
1551
1552     my $query = {
1553         select => {
1554             aou => [{
1555                 transform => 'actor.org_unit_full_path',
1556                 column => 'id',
1557                 result_field => 'id',
1558             }],
1559         },
1560         from => 'aou',
1561         where => {id => $org_id}
1562     };
1563
1564     $query->{select}->{aou}->[0]->{params} = [$depth] if defined $depth;
1565     my $org_list = OpenILS::Utils::CStoreEditor->new->json_query($query);
1566     return [ map {$_->{id}} @$org_list ];
1567 }
1568
1569 # returns the ID of the org unit ancestor at the specified depth
1570 sub org_unit_ancestor_at_depth {
1571     my($class, $org_id, $depth) = @_;
1572     my $resp = OpenILS::Utils::CStoreEditor->new->json_query(
1573         {from => ['actor.org_unit_ancestor_at_depth', $org_id, $depth]})->[0];
1574     return ($resp) ? $resp->{id} : undef;
1575 }
1576
1577 # Returns the proximity value between two org units.
1578 sub get_org_unit_proximity {
1579     my ($class, $e, $from_org, $to_org) = @_;
1580     $e = OpenILS::Utils::CStoreEditor->new unless ($e);
1581     my $r = $e->json_query(
1582         {
1583             select => {aoup => ['prox']},
1584             from => 'aoup',
1585             where => {from_org => $from_org, to_org => $to_org}
1586         }
1587     );
1588     if (ref($r) eq 'ARRAY' && @$r) {
1589         return $r->[0]->{prox};
1590     }
1591     return undef;
1592 }
1593
1594 # returns the user's configured locale as a string.  Defaults to en-US if none is configured.
1595 sub get_user_locale {
1596     my($self, $user_id, $e) = @_;
1597     $e ||= OpenILS::Utils::CStoreEditor->new;
1598
1599     # first, see if the user has an explicit locale set
1600     my $setting = $e->search_actor_user_setting(
1601         {usr => $user_id, name => 'global.locale'})->[0];
1602     return OpenSRF::Utils::JSON->JSON2perl($setting->value) if $setting;
1603
1604     my $user = $e->retrieve_actor_user($user_id) or return $e->event;
1605     return $self->get_org_locale($user->home_ou, $e);
1606 }
1607
1608 # returns org locale setting
1609 sub get_org_locale {
1610     my($self, $org_id, $e) = @_;
1611     $e ||= OpenILS::Utils::CStoreEditor->new;
1612
1613     my $locale;
1614     if(defined $org_id) {
1615         $locale = $self->ou_ancestor_setting_value($org_id, 'global.default_locale', $e);
1616         return $locale if $locale;
1617     }
1618
1619     # system-wide default
1620     my $sclient = OpenSRF::Utils::SettingsClient->new;
1621     $locale = $sclient->config_value('default_locale');
1622     return $locale if $locale;
1623
1624     # if nothing else, fallback to locale=cowboy
1625     return 'en-US';
1626 }
1627
1628
1629 # xml-escape non-ascii characters
1630 sub entityize { 
1631     my($self, $string, $form) = @_;
1632     $form ||= "";
1633
1634     if ($form eq 'D') {
1635         $string = NFD($string);
1636     } else {
1637         $string = NFC($string);
1638     }
1639
1640     # Convert raw ampersands to entities
1641     $string =~ s/&(?!\S+;)/&amp;/gso;
1642
1643     # Convert Unicode characters to entities
1644     $string =~ s/([\x{0080}-\x{fffd}])/sprintf('&#x%X;',ord($1))/sgoe;
1645
1646     return $string;
1647 }
1648
1649 # x0000-x0008 isn't legal in XML documents
1650 # XXX Perhaps this should just go into our standard entityize method
1651 sub strip_ctrl_chars {
1652     my ($self, $string) = @_;
1653
1654     $string =~ s/([\x{0000}-\x{0008}])//sgoe; 
1655     return $string;
1656 }
1657
1658 sub get_copy_price {
1659     my($self, $e, $copy, $volume) = @_;
1660
1661     $copy->price(0) if $copy->price and $copy->price < 0;
1662
1663
1664     my $owner;
1665     if(ref $volume) {
1666         if($volume->id == OILS_PRECAT_CALL_NUMBER) {
1667             $owner = $copy->circ_lib;
1668         } else {
1669             $owner = $volume->owning_lib;
1670         }
1671     } else {
1672         if($copy->call_number == OILS_PRECAT_CALL_NUMBER) {
1673             $owner = $copy->circ_lib;
1674         } else {
1675             $owner = $e->retrieve_asset_call_number($copy->call_number)->owning_lib;
1676         }
1677     }
1678
1679     my $min_price = $self->ou_ancestor_setting_value($owner, OILS_SETTING_MIN_ITEM_PRICE);
1680     my $max_price = $self->ou_ancestor_setting_value($owner, OILS_SETTING_MAX_ITEM_PRICE);
1681     my $charge_on_0 = $self->ou_ancestor_setting_value($owner, OILS_SETTING_CHARGE_LOST_ON_ZERO, $e);
1682     my $primary_field = $self->ou_ancestor_setting_value($owner, OILS_SETTING_PRIMARY_ITEM_VALUE_FIELD, $e);
1683     my $backup_field = $self->ou_ancestor_setting_value($owner, OILS_SETTING_SECONDARY_ITEM_VALUE_FIELD, $e);
1684
1685     my $price = defined $primary_field && $primary_field eq 'cost'
1686         ? $copy->cost
1687         : $copy->price;
1688
1689     # set the default price if needed
1690     if (!defined $price or ($price == 0 and $charge_on_0)) {
1691         if (defined $backup_field && $backup_field eq 'cost') {
1692             $price = $copy->cost;
1693         } elsif (defined $backup_field && $backup_field eq 'price') {
1694             $price = $copy->price;
1695         }
1696     }
1697     # possible fallthrough to original default item price behavior
1698     if (!defined $price or ($price == 0 and $charge_on_0)) {
1699         # set to default price
1700         $price = $self->ou_ancestor_setting_value(
1701             $owner, OILS_SETTING_DEF_ITEM_PRICE, $e) || 0;
1702     }
1703
1704     # adjust to min/max range if needed
1705     if (defined $max_price and $price > $max_price) {
1706         $price = $max_price;
1707     } elsif (defined $min_price and $price < $min_price
1708         and ($price != 0 or $charge_on_0 or !defined $charge_on_0)) {
1709         # default to raising the price to the minimum,
1710         # but let 0 fall through if $charge_on_0 is set and is false
1711         $price = $min_price;
1712     }
1713
1714     return $price;
1715 }
1716
1717 # given a transaction ID, this returns the context org_unit for the transaction
1718 sub xact_org {
1719     my($self, $xact_id, $e) = @_;
1720     $e ||= OpenILS::Utils::CStoreEditor->new;
1721     
1722     my $loc = $e->json_query({
1723         "select" => {circ => ["circ_lib"]},
1724         from     => "circ",
1725         "where"  => {id => $xact_id},
1726     });
1727
1728     return $loc->[0]->{circ_lib} if @$loc;
1729
1730     $loc = $e->json_query({
1731         "select" => {bresv => ["request_lib"]},
1732         from     => "bresv",
1733         "where"  => {id => $xact_id},
1734     });
1735
1736     return $loc->[0]->{request_lib} if @$loc;
1737
1738     $loc = $e->json_query({
1739         "select" => {mg => ["billing_location"]},
1740         from     => "mg",
1741         "where"  => {id => $xact_id},
1742     });
1743
1744     return $loc->[0]->{billing_location};
1745 }
1746
1747
1748 sub find_event_def_by_hook {
1749     my($self, $hook, $context_org, $e) = @_;
1750
1751     $e ||= OpenILS::Utils::CStoreEditor->new;
1752
1753     my $orgs = $self->get_org_ancestors($context_org);
1754
1755     # search from the context org up
1756     for my $org_id (reverse @$orgs) {
1757
1758         my $def = $e->search_action_trigger_event_definition(
1759             {hook => $hook, owner => $org_id, active => 't'})->[0];
1760
1761         return $def if $def;
1762     }
1763
1764     return undef;
1765 }
1766
1767
1768
1769 # If an event_def ID is not provided, use the hook and context org to find the 
1770 # most appropriate event.  create the event, fire it, then return the resulting
1771 # event with fleshed template_output and error_output
1772 sub fire_object_event {
1773     my($self, $event_def, $hook, $object, $context_org, $granularity, $user_data, $client) = @_;
1774
1775     my $e = OpenILS::Utils::CStoreEditor->new;
1776     my $def;
1777
1778     my $auto_method = "open-ils.trigger.event.autocreate.by_definition";
1779
1780     if($event_def) {
1781         $def = $e->retrieve_action_trigger_event_definition($event_def)
1782             or return $e->event;
1783
1784         $auto_method .= '.include_inactive';
1785
1786     } else {
1787
1788         # find the most appropriate event def depending on context org
1789         $def = $self->find_event_def_by_hook($hook, $context_org, $e) 
1790             or return $e->event;
1791     }
1792
1793     my $final_resp;
1794
1795     if($def->group_field) {
1796         # we have a list of objects
1797         $object = [$object] unless ref $object eq 'ARRAY';
1798
1799         my @event_ids;
1800         $user_data ||= [];
1801         for my $i (0..$#$object) {
1802             my $obj = $$object[$i];
1803             my $udata = $$user_data[$i];
1804             my $event_id = $self->simplereq(
1805                 'open-ils.trigger', $auto_method, $def->id, $obj, $context_org, $udata);
1806             push(@event_ids, $event_id);
1807         }
1808
1809         $logger->info("EVENTS = " . OpenSRF::Utils::JSON->perl2JSON(\@event_ids));
1810
1811         my $resp;
1812         if (not defined $client) {
1813             $resp = $self->simplereq(
1814                 'open-ils.trigger',
1815                 'open-ils.trigger.event_group.fire',
1816                 \@event_ids);
1817         } else {
1818             $resp = $self->patientreq(
1819                 $client,
1820                 "open-ils.trigger", "open-ils.trigger.event_group.fire",
1821                 \@event_ids
1822             );
1823         }
1824
1825         if($resp and $resp->{events} and @{$resp->{events}}) {
1826
1827             $e->xact_begin;
1828             $final_resp = $e->retrieve_action_trigger_event([
1829                 $resp->{events}->[0]->id,
1830                 {flesh => 1, flesh_fields => {atev => ['template_output', 'error_output']}}
1831             ]);
1832             $e->rollback;
1833         }
1834
1835     } else {
1836
1837         $object = $$object[0] if ref $object eq 'ARRAY';
1838
1839         my $event_id;
1840         my $resp;
1841
1842         if (not defined $client) {
1843             $event_id = $self->simplereq(
1844                 'open-ils.trigger',
1845                 $auto_method, $def->id, $object, $context_org, $user_data
1846             );
1847
1848             $resp = $self->simplereq(
1849                 'open-ils.trigger',
1850                 'open-ils.trigger.event.fire',
1851                 $event_id
1852             );
1853         } else {
1854             $event_id = $self->patientreq(
1855                 $client,
1856                 'open-ils.trigger',
1857                 $auto_method, $def->id, $object, $context_org, $user_data
1858             );
1859
1860             $resp = $self->patientreq(
1861                 $client,
1862                 'open-ils.trigger',
1863                 'open-ils.trigger.event.fire',
1864                 $event_id
1865             );
1866         }
1867         
1868         if($resp and $resp->{event}) {
1869             $e->xact_begin;
1870             $final_resp = $e->retrieve_action_trigger_event([
1871                 $resp->{event}->id,
1872                 {flesh => 1, flesh_fields => {atev => ['template_output', 'error_output']}}
1873             ]);
1874             $e->rollback;
1875         }
1876     }
1877
1878     return $final_resp;
1879 }
1880
1881
1882 sub create_events_for_hook {
1883     my($self, $hook, $obj, $org_id, $granularity, $user_data, $wait) = @_;
1884     my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1885     my $req = $ses->request('open-ils.trigger.event.autocreate', 
1886         $hook, $obj, $org_id, $granularity, $user_data);
1887     return undef unless $wait;
1888     my $resp = $req->recv;
1889     return $resp->content if $resp;
1890 }
1891
1892 sub create_uuid_string {
1893     return create_UUID_as_string();
1894 }
1895
1896 sub create_circ_chain_summary {
1897     my($class, $e, $circ_id) = @_;
1898     my $sum = $e->json_query({from => ['action.summarize_all_circ_chain', $circ_id]})->[0];
1899     return undef unless $sum;
1900     my $obj = Fieldmapper::action::circ_chain_summary->new;
1901     $obj->$_($sum->{$_}) for keys %$sum;
1902     return $obj;
1903 }
1904
1905
1906 # Returns "mra" attribute key/value pairs for a set of bre's
1907 # Takes a list of bre IDs, returns a hash of hashes,
1908 # {bre_id1 => {key1 => {code => value1, label => label1}, ...}...}
1909 my $ccvm_cache;
1910 sub get_bre_attrs {
1911     my ($class, $bre_ids, $e) = @_;
1912     $e = $e || OpenILS::Utils::CStoreEditor->new;
1913
1914     my $attrs = {};
1915     return $attrs unless defined $bre_ids;
1916     $bre_ids = [$bre_ids] unless ref $bre_ids;
1917
1918     my $mra = $e->json_query({
1919         select => {
1920             mra => [
1921                 {
1922                     column => 'id',
1923                     alias => 'bre'
1924                 }, {
1925                     column => 'attrs',
1926                     transform => 'each',
1927                     result_field => 'key',
1928                     alias => 'key'
1929                 },{
1930                     column => 'attrs',
1931                     transform => 'each',
1932                     result_field => 'value',
1933                     alias => 'value'
1934                 }
1935             ]
1936         },
1937         from => 'mra',
1938         where => {id => $bre_ids}
1939     });
1940
1941     return $attrs unless $mra;
1942
1943     $ccvm_cache = $ccvm_cache || $e->search_config_coded_value_map({id => {'!=' => undef}});
1944
1945     for my $id (@$bre_ids) {
1946         $attrs->{$id} = {};
1947         for my $mra (grep { $_->{bre} eq $id } @$mra) {
1948             my $ctype = $mra->{key};
1949             my $code = $mra->{value};
1950             $attrs->{$id}->{$ctype} = {code => $code};
1951             if($code) {
1952                 my ($ccvm) = grep { $_->ctype eq $ctype and $_->code eq $code } @$ccvm_cache;
1953                 $attrs->{$id}->{$ctype}->{label} = $ccvm->value if $ccvm;
1954             }
1955         }
1956     }
1957
1958     return $attrs;
1959 }
1960
1961 # Shorter version of bib_container_items_via_search() below, only using
1962 # the queryparser record_list filter instead of the container filter.
1963 sub bib_record_list_via_search {
1964     my ($class, $search_query, $search_args) = @_;
1965
1966     # First, Use search API to get container items sorted in any way that crad
1967     # sorters support.
1968     my $search_result = $class->simplereq(
1969         "open-ils.search", "open-ils.search.biblio.multiclass.query",
1970         $search_args, $search_query
1971     );
1972
1973     unless ($search_result) {
1974         # empty result sets won't cause this, but actual errors should.
1975         $logger->warn("bib_record_list_via_search() got nothing from search");
1976         return;
1977     }
1978
1979     # Throw away other junk from search, keeping only bib IDs.
1980     return [ map { shift @$_ } @{$search_result->{ids}} ];
1981 }
1982
1983 # 'no_flesh' avoids fleshing the target_biblio_record_entry
1984 sub bib_container_items_via_search {
1985     my ($class, $container_id, $search_query, $search_args, $no_flesh) = @_;
1986
1987     # First, Use search API to get container items sorted in any way that crad
1988     # sorters support.
1989     my $search_result = $class->simplereq(
1990         "open-ils.search", "open-ils.search.biblio.multiclass.query",
1991         $search_args, $search_query
1992     );
1993     unless ($search_result) {
1994         # empty result sets won't cause this, but actual errors should.
1995         $logger->warn("bib_container_items_via_search() got nothing from search");
1996         return;
1997     }
1998
1999     # Throw away other junk from search, keeping only bib IDs.
2000     my $id_list = [ map { shift @$_ } @{$search_result->{ids}} ];
2001
2002     return [] unless @$id_list;
2003
2004     # Now get the bib container items themselves...
2005     my $e = new OpenILS::Utils::CStoreEditor;
2006     unless ($e) {
2007         $logger->warn("bib_container_items_via_search() couldn't get cstoreeditor");
2008         return;
2009     }
2010
2011     my @flesh_fields = qw/notes/;
2012     push(@flesh_fields, 'target_biblio_record_entry') unless $no_flesh;
2013
2014     my $items = $e->search_container_biblio_record_entry_bucket_item([
2015         {
2016             "target_biblio_record_entry" => $id_list,
2017             "bucket" => $container_id
2018         }, {
2019             flesh => 1,
2020             flesh_fields => {"cbrebi" => \@flesh_fields}
2021         }
2022     ], {substream => 1});
2023
2024     unless ($items) {
2025         $logger->warn(
2026             "bib_container_items_via_search() couldn't get bucket items: " .
2027             $e->die_event->{textcode}
2028         );
2029         return;
2030     }
2031
2032     # ... and put them in the same order that the search API said they
2033     # should be in.
2034     my %ordering_hash = map { 
2035         ($no_flesh) ? $_->target_biblio_record_entry : $_->target_biblio_record_entry->id, 
2036         $_ 
2037     } @$items;
2038
2039     return [map { $ordering_hash{$_} } @$id_list];
2040 }
2041
2042 # returns undef on success, Event on error
2043 sub log_user_activity {
2044     my ($class, $user_id, $who, $what, $e, $async) = @_;
2045
2046     my $commit = 0;
2047     if (!$e) {
2048         $e = OpenILS::Utils::CStoreEditor->new(xact => 1);
2049         $commit = 1;
2050     }
2051
2052     my $res = $e->json_query({
2053         from => [
2054             'actor.insert_usr_activity', 
2055             $user_id, $who, $what, OpenSRF::AppSession->ingress
2056         ]
2057     });
2058
2059     if ($res) { # call returned OK
2060
2061         $e->commit   if $commit and @$res;
2062         $e->rollback if $commit and !@$res;
2063
2064     } else {
2065         return $e->die_event;
2066     }
2067
2068     return undef;
2069 }
2070
2071 # I hate to put this here exactly, but this code needs to be shared between
2072 # the TPAC's mod_perl module and open-ils.serial.
2073 #
2074 # There is a reason every part of the query *except* those parts dealing
2075 # with scope are moved here from the code's origin in TPAC.  The serials
2076 # use case does *not* want the same scoping logic.
2077 #
2078 # Also, note that for the serials uses case, we may filter in OPAC visible
2079 # status and copy/call_number deletedness, but we don't filter on any
2080 # particular values for serial.item.status or serial.item.date_received.
2081 # Since we're only using this *after* winnowing down the set of issuances
2082 # that copies should be related to, I'm not sure we need any such serial.item
2083 # filters.
2084
2085 sub basic_opac_copy_query {
2086     ######################################################################
2087     # Pass a defined value for either $rec_id OR ($iss_id AND $dist_id), #
2088     # not both.                                                          #
2089     ######################################################################
2090     my ($self,$rec_id,$iss_id,$dist_id,$copy_limit,$copy_offset,$staff) = @_;
2091
2092     return {
2093         select => {
2094             acp => ['id', 'barcode', 'circ_lib', 'create_date', 'active_date',
2095                     'age_protect', 'holdable', 'copy_number', 'circ_modifier'],
2096             acpl => [
2097                 {column => 'name', alias => 'copy_location'},
2098                 {column => 'holdable', alias => 'location_holdable'},
2099                 {column => 'url', alias => 'location_url'}
2100             ],
2101             ccs => [
2102                 {column => 'id', alias => 'status_code'},
2103                 {column => 'name', alias => 'copy_status'},
2104                 {column => 'holdable', alias => 'status_holdable'},
2105                 {column => 'is_available', alias => 'is_available'}
2106             ],
2107             acn => [
2108                 {column => 'label', alias => 'call_number_label'},
2109                 {column => 'id', alias => 'call_number'},
2110                 {column => 'owning_lib', alias => 'call_number_owning_lib'}
2111             ],
2112             circ => ['due_date',{column => 'circ_lib', alias => 'circ_circ_lib'}],
2113             acnp => [
2114                 {column => 'label', alias => 'call_number_prefix_label'},
2115                 {column => 'id', alias => 'call_number_prefix'}
2116             ],
2117             acns => [
2118                 {column => 'label', alias => 'call_number_suffix_label'},
2119                 {column => 'id', alias => 'call_number_suffix'}
2120             ],
2121             bmp => [
2122                 {column => 'label', alias => 'part_label'},
2123             ],
2124             ($staff ? (erfcc => ['circ_count']) : ()),
2125             crahp => [
2126                 {column => 'name', alias => 'age_protect_label'}
2127             ],
2128             ($iss_id ? (sitem => ["issuance"]) : ())
2129         },
2130
2131         from => {
2132             acp => [
2133                 {acn => { # 0
2134                     join => {
2135                         acnp => { fkey => 'prefix' },
2136                         acns => { fkey => 'suffix' }
2137                     },
2138                     filter => [
2139                         {deleted => 'f'},
2140                         ($rec_id ? {record => $rec_id} : ())
2141                     ],
2142                 }},
2143                 'aou', # 1
2144                 {circ => { # 2 If the copy is circulating, retrieve the open circ
2145                     type => 'left',
2146                     filter => {checkin_time => undef}
2147                 }},
2148                 {acpl => { # 3
2149                     filter => {
2150                         deleted => 'f',
2151                         ($staff ? () : ( opac_visible => 't' )),
2152                     },
2153                 }},
2154                 {ccs => { # 4
2155                     ($staff ? () : (filter => { opac_visible => 't' }))
2156                 }},
2157                 {acpm => { # 5
2158                     type => 'left',
2159                     join => {
2160                         bmp => { type => 'left', filter => { deleted => 'f' } }
2161                     }
2162                 }},
2163                 {'crahp' => { # 6
2164                     type => 'left'
2165                 }},
2166                 ($iss_id ? { # 7
2167                     sitem => {
2168                         fkey => 'id',
2169                         field => 'unit',
2170                         filter => {issuance => $iss_id},
2171                         join => {
2172                             sstr => { }
2173                         }
2174                     }
2175                 } : ()),
2176                 ($staff ? {
2177                     erfcc => {
2178                         fkey => 'id',
2179                         field => 'id'
2180                     }
2181                 }: ()),
2182             ]
2183         },
2184
2185         where => {
2186             '+acp' => {
2187                 deleted => 'f',
2188                 ($staff ? () : (opac_visible => 't'))
2189             },
2190             ($dist_id ? ( '+sstr' => { distribution => $dist_id } ) : ()),
2191             ($staff ? () : ( '+aou' => { opac_visible => 't' } ))
2192         },
2193
2194         order_by => [
2195             {class => 'aou', field => 'name'},
2196             {class => 'acn', field => 'label_sortkey'},
2197             {class => 'acns', field => 'label_sortkey'},
2198             {class => 'bmp', field => 'label_sortkey'},
2199             {class => 'acp', field => 'copy_number'},
2200             {class => 'acp', field => 'barcode'}
2201         ],
2202
2203         limit => $copy_limit,
2204         offset => $copy_offset
2205     };
2206 }
2207
2208 # Compare two dates, date1 and date2. If date2 is not defined, then
2209 # DateTime->now will be used. Assumes dates are in ISO8601 format as
2210 # supported by DateTime::Format::ISO8601. (A future enhancement might
2211 # be to support other formats.)
2212 #
2213 # Returns -1 if $date1 < $date2
2214 # Returns 0 if $date1 == $date2
2215 # Returns 1 if $date1 > $date2
2216 sub datecmp {
2217     my $self = shift;
2218     my $date1 = shift;
2219     my $date2 = shift;
2220
2221     # Check for timezone offsets and limit them to 2 digits:
2222     if ($date1 && $date1 =~ /(?:-|\+)\d\d\d\d$/) {
2223         $date1 = substr($date1, 0, length($date1) - 2);
2224     }
2225     if ($date2 && $date2 =~ /(?:-|\+)\d\d\d\d$/) {
2226         $date2 = substr($date2, 0, length($date2) - 2);
2227     }
2228
2229     # check date1:
2230     unless (UNIVERSAL::isa($date1, "DateTime")) {
2231         $date1 = DateTime::Format::ISO8601->parse_datetime($date1);
2232     }
2233
2234     # Check for date2:
2235     unless ($date2) {
2236         $date2 = DateTime->now;
2237     } else {
2238         unless (UNIVERSAL::isa($date2, "DateTime")) {
2239             $date2 = DateTime::Format::ISO8601->parse_datetime($date2);
2240         }
2241     }
2242
2243     return DateTime->compare($date1, $date2);
2244 }
2245
2246
2247 # marcdoc is an XML::LibXML document
2248 # updates the doc and returns the entityized MARC string
2249 sub strip_marc_fields {
2250     my ($class, $e, $marcdoc, $grps) = @_;
2251     
2252     my $orgs = $class->get_org_ancestors($e->requestor->ws_ou);
2253
2254     my $query = {
2255         select  => {vibtf => ['field']},
2256         from    => {vibtf => 'vibtg'},
2257         where   => {'+vibtg' => {owner => $orgs}},
2258         distinct => 1
2259     };
2260
2261     # give me always-apply groups plus any selected groups
2262     if ($grps and @$grps) {
2263         $query->{where}->{'+vibtg'}->{'-or'} = [
2264             {id => $grps},
2265             {always_apply => 't'}
2266         ];
2267
2268     } else {
2269         $query->{where}->{'+vibtg'}->{always_apply} = 't';
2270     }
2271
2272     my $fields = $e->json_query($query);
2273
2274     for my $field (@$fields) {
2275         my $tag = $field->{field};
2276         for my $node ($marcdoc->findnodes('//*[@tag="'.$tag.'"]')) {
2277             $node->parentNode->removeChild($node);
2278         }
2279     }
2280
2281     return $class->entityize($marcdoc->documentElement->toString);
2282 }
2283
2284 # marcdoc is an XML::LibXML document
2285 # updates the document and returns the entityized MARC string.
2286 sub set_marc_905u {
2287     my ($class, $marcdoc, $username) = @_;
2288
2289     # Look for existing 905$u subfields. If any exist, do nothing.
2290     my @nodes = $marcdoc->findnodes('//*[@tag="905"]/*[@code="u"]');
2291     unless (@nodes) {
2292         # We create a new 905 and the subfield u to that.
2293         my $parentNode = $marcdoc->createElement('datafield');
2294         $parentNode->setAttribute('tag', '905');
2295         $parentNode->setAttribute('ind1', '');
2296         $parentNode->setAttribute('ind2', '');
2297         $marcdoc->documentElement->addChild($parentNode);
2298         my $node = $marcdoc->createElement('subfield');
2299         $node->setAttribute('code', 'u');
2300         $node->appendTextNode($username);
2301         $parentNode->addChild($node);
2302
2303     }
2304
2305     return $class->entityize($marcdoc->documentElement->toString);
2306 }
2307
2308 # Given a list of PostgreSQL arrays of numbers,
2309 # unnest the numbers and return a unique set, skipping any list elements
2310 # that are just '{NULL}'.
2311 sub unique_unnested_numbers {
2312     my $class = shift;
2313
2314     no warnings 'numeric';
2315
2316     return undef unless ( scalar @_ );
2317
2318     return uniq(
2319         map(
2320             int,
2321             map { $_ eq 'NULL' ? undef : (split /,/, $_) }
2322                 map { substr($_, 1, -1) } @_
2323         )
2324     );
2325 }
2326
2327 # Given a list of numbers, turn them into a PG array, skipping undef's
2328 sub intarray2pgarray {
2329     my $class = shift;
2330     no warnings 'numeric';
2331
2332     return '{' . join( ',', map(int, grep { defined && /^\d+$/ } @_) ) . '}';
2333 }
2334
2335 # Check if a transaction should be left open or closed. Close the
2336 # transaction if it should be closed or open it otherwise. Returns
2337 # undef on success or a failure event.
2338 sub check_open_xact {
2339     my( $self, $editor, $xactid, $xact ) = @_;
2340
2341     # Grab the transaction
2342     $xact ||= $editor->retrieve_money_billable_transaction($xactid);
2343     return $editor->event unless $xact;
2344     $xactid ||= $xact->id;
2345
2346     # grab the summary and see how much is owed on this transaction
2347     my ($summary) = $self->fetch_mbts($xactid, $editor);
2348
2349     # grab the circulation if it is a circ;
2350     my $circ = $editor->retrieve_action_circulation($xactid);
2351
2352     # If nothing is owed on the transaction but it is still open
2353     # and this transaction is not an open circulation, close it
2354     if(
2355         ( $summary->balance_owed == 0 and ! $xact->xact_finish ) and
2356         ( !$circ or $circ->stop_fines )) {
2357
2358         $logger->info("closing transaction ".$xact->id. ' because balance_owed == 0');
2359         $xact->xact_finish('now');
2360         $editor->update_money_billable_transaction($xact)
2361             or return $editor->event;
2362         return undef;
2363     }
2364
2365     # If money is owed or a refund is due on the xact and xact_finish
2366     # is set, clear it (to reopen the xact) and update
2367     if( $summary->balance_owed != 0 and $xact->xact_finish ) {
2368         $logger->info("re-opening transaction ".$xact->id. ' because balance_owed != 0');
2369         $xact->clear_xact_finish;
2370         $editor->update_money_billable_transaction($xact)
2371             or return $editor->event;
2372         return undef;
2373     }
2374     return undef;
2375 }
2376
2377 # Because floating point math has rounding issues, and Dyrcona gets
2378 # tired of typing out the code to multiply floating point numbers
2379 # before adding and subtracting them and then dividing the result by
2380 # 100 each time, he wrote this little subroutine for subtracting
2381 # floating point values.  It can serve as a model for the other
2382 # operations if you like.
2383 #
2384 # It takes a list of floating point values as arguments.  The rest are
2385 # all subtracted from the first and the result is returned.  The
2386 # values are all multiplied by 100 before being used, and the result
2387 # is divided by 100 in order to avoid decimal rounding errors inherent
2388 # in floating point math.
2389 #
2390 # XXX shifting using multiplication/division *may* still introduce
2391 # rounding errors -- better to implement using string manipulation?
2392 sub fpdiff {
2393     my ($class, @args) = @_;
2394     my $result = shift(@args) * 100;
2395     while (my $arg = shift(@args)) {
2396         $result -= $arg * 100;
2397     }
2398     return $result / 100;
2399 }
2400
2401 sub fpsum {
2402     my ($class, @args) = @_;
2403     my $result = shift(@args) * 100;
2404     while (my $arg = shift(@args)) {
2405         $result += $arg * 100;
2406     }
2407     return $result / 100;
2408 }
2409
2410 # Non-migrated passwords can be verified directly in the DB
2411 # with any extra hashing.
2412 sub verify_user_password {
2413     my ($class, $e, $user_id, $passwd, $pw_type) = @_;
2414
2415     $pw_type ||= 'main'; # primary login password
2416
2417     my $verify = $e->json_query({
2418         from => [
2419             'actor.verify_passwd', 
2420             $user_id, $pw_type, $passwd
2421         ]
2422     })->[0];
2423
2424     return $class->is_true($verify->{'actor.verify_passwd'});
2425 }
2426
2427 # Passwords migrated from the original MD5 scheme are passed through 2
2428 # extra layers of MD5 hashing for backwards compatibility with the
2429 # MD5 passwords of yore and the MD5-based chap-style authentication.  
2430 # Passwords are stored in the DB like this:
2431 # CRYPT( MD5( pw_salt || MD5(real_password) ), pw_salt )
2432 #
2433 # If 'as_md5' is true, the password provided has already been
2434 # MD5 hashed.
2435 sub verify_migrated_user_password {
2436     my ($class, $e, $user_id, $passwd, $as_md5) = @_;
2437
2438     # 'main' is the primary login password. This is the only password 
2439     # type that requires the additional MD5 hashing.
2440     my $pw_type = 'main';
2441
2442     # Sometimes we have the bare password, sometimes the MD5 version.
2443     my $md5_pass = $as_md5 ? $passwd : md5_hex($passwd);
2444
2445     my $salt = $e->json_query({
2446         from => [
2447             'actor.get_salt', 
2448             $user_id, 
2449             $pw_type
2450         ]
2451     })->[0];
2452
2453     $salt = $salt->{'actor.get_salt'};
2454
2455     return $class->verify_user_password(
2456         $e, $user_id, md5_hex($salt . $md5_pass), $pw_type);
2457 }
2458
2459
2460 # generate a MARC XML document from a MARC XML string
2461 sub marc_xml_to_doc {
2462     my ($class, $xml) = @_;
2463     my $marc_doc = XML::LibXML->new->parse_string($xml);
2464     $marc_doc->documentElement->setNamespace(MARC_NAMESPACE, 'marc', 1);
2465     $marc_doc->documentElement->setNamespace(MARC_NAMESPACE);
2466     return $marc_doc;
2467 }
2468
2469
2470
2471 1;
2472