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