]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/Application/AppUtils.pm
LP1366026: Add Active Date to Record Detail Page
[working/Evergreen.git] / Open-ILS / src / perlmods / lib / OpenILS / Application / AppUtils.pm
1 package OpenILS::Application::AppUtils;
2 # vim:noet:ts=4
3 use strict; use warnings;
4 use OpenILS::Application;
5 use base qw/OpenILS::Application/;
6 use OpenSRF::Utils::Cache;
7 use OpenSRF::Utils::Logger qw/$logger/;
8 use OpenILS::Utils::ModsParser;
9 use OpenSRF::EX qw(:try);
10 use OpenILS::Event;
11 use Data::Dumper;
12 use OpenILS::Utils::CStoreEditor;
13 use OpenILS::Const qw/:const/;
14 use Unicode::Normalize;
15 use OpenSRF::Utils::SettingsClient;
16 use UUID::Tiny;
17 use Encode;
18 use DateTime;
19 use DateTime::Format::ISO8601;
20 use List::MoreUtils qw/uniq/;
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 } );
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 } });
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 } );
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 fetch_non_cat_type_by_name_and_org {
767     my( $self, $name, $orgId ) = @_;
768     $logger->debug("Fetching non cat type $name at org $orgId");
769     my $types = $self->simplereq(
770         'open-ils.cstore',
771         'open-ils.cstore.direct.config.non_cataloged_type.search.atomic',
772         { name => $name, owning_lib => $orgId } );
773     return ($types->[0], undef) if($types and @$types);
774     return (undef, OpenILS::Event->new('CONFIG_NON_CATALOGED_TYPE_NOT_FOUND') );
775 }
776
777 sub fetch_non_cat_type {
778     my( $self, $id ) = @_;
779     $logger->debug("Fetching non cat type $id");
780     my( $type, $evt );
781     $type = $self->simplereq(
782         'open-ils.cstore', 
783         'open-ils.cstore.direct.config.non_cataloged_type.retrieve', $id );
784     $evt = OpenILS::Event->new('CONFIG_NON_CATALOGED_TYPE_NOT_FOUND') unless $type;
785     return ($type, $evt);
786 }
787
788 sub DB_UPDATE_FAILED { 
789     my( $self, $payload ) = @_;
790     return OpenILS::Event->new('DATABASE_UPDATE_FAILED', 
791         payload => ($payload) ? $payload : undef ); 
792 }
793
794 sub fetch_booking_reservation {
795     my( $self, $id ) = @_;
796     my( $res, $evt );
797
798     $res = $self->simplereq(
799         'open-ils.cstore', 
800         'open-ils.cstore.direct.booking.reservation.retrieve', $id
801     );
802
803     # simplereq doesn't know how to flesh so ...
804     if ($res) {
805         $res->usr(
806             $self->simplereq(
807                 'open-ils.cstore', 
808                 'open-ils.cstore.direct.actor.user.retrieve', $res->usr
809             )
810         );
811
812         $res->target_resource_type(
813             $self->simplereq(
814                 'open-ils.cstore', 
815                 'open-ils.cstore.direct.booking.resource_type.retrieve', $res->target_resource_type
816             )
817         );
818
819         if ($res->current_resource) {
820             $res->current_resource(
821                 $self->simplereq(
822                     'open-ils.cstore', 
823                     'open-ils.cstore.direct.booking.resource.retrieve', $res->current_resource
824                 )
825             );
826
827             if ($self->is_true( $res->target_resource_type->catalog_item )) {
828                 $res->current_resource->catalog_item( $self->fetch_copy_by_barcode( $res->current_resource->barcode ) );
829             }
830         }
831
832         if ($res->target_resource) {
833             $res->target_resource(
834                 $self->simplereq(
835                     'open-ils.cstore', 
836                     'open-ils.cstore.direct.booking.resource.retrieve', $res->target_resource
837                 )
838             );
839
840             if ($self->is_true( $res->target_resource_type->catalog_item )) {
841                 $res->target_resource->catalog_item( $self->fetch_copy_by_barcode( $res->target_resource->barcode ) );
842             }
843         }
844
845     } else {
846         $evt = OpenILS::Event->new('RESERVATION_NOT_FOUND');
847     }
848
849     return ($res, $evt);
850 }
851
852 sub fetch_circ_duration_by_name {
853     my( $self, $name ) = @_;
854     my( $dur, $evt );
855     $dur = $self->simplereq(
856         'open-ils.cstore', 
857         'open-ils.cstore.direct.config.rules.circ_duration.search.atomic', { name => $name } );
858     $dur = $dur->[0];
859     $evt = OpenILS::Event->new('CONFIG_RULES_CIRC_DURATION_NOT_FOUND') unless $dur;
860     return ($dur, $evt);
861 }
862
863 sub fetch_recurring_fine_by_name {
864     my( $self, $name ) = @_;
865     my( $obj, $evt );
866     $obj = $self->simplereq(
867         'open-ils.cstore', 
868         'open-ils.cstore.direct.config.rules.recurring_fine.search.atomic', { name => $name } );
869     $obj = $obj->[0];
870     $evt = OpenILS::Event->new('CONFIG_RULES_RECURRING_FINE_NOT_FOUND') unless $obj;
871     return ($obj, $evt);
872 }
873
874 sub fetch_max_fine_by_name {
875     my( $self, $name ) = @_;
876     my( $obj, $evt );
877     $obj = $self->simplereq(
878         'open-ils.cstore', 
879         'open-ils.cstore.direct.config.rules.max_fine.search.atomic', { name => $name } );
880     $obj = $obj->[0];
881     $evt = OpenILS::Event->new('CONFIG_RULES_MAX_FINE_NOT_FOUND') unless $obj;
882     return ($obj, $evt);
883 }
884
885 sub fetch_hard_due_date_by_name {
886     my( $self, $name ) = @_;
887     my( $obj, $evt );
888     $obj = $self->simplereq(
889         'open-ils.cstore', 
890         'open-ils.cstore.direct.config.hard_due_date.search.atomic', { name => $name } );
891     $obj = $obj->[0];
892     $evt = OpenILS::Event->new('CONFIG_RULES_HARD_DUE_DATE_NOT_FOUND') unless $obj;
893     return ($obj, $evt);
894 }
895
896 sub storagereq {
897     my( $self, $method, @params ) = @_;
898     return $self->simplereq(
899         'open-ils.storage', $method, @params );
900 }
901
902 sub storagereq_xact {
903     my($self, $method, @params) = @_;
904     my $ses = $self->start_db_session();
905     my $val = $ses->request($method, @params)->gather(1);
906     $self->rollback_db_session($ses);
907     return $val;
908 }
909
910 sub cstorereq {
911     my( $self, $method, @params ) = @_;
912     return $self->simplereq(
913         'open-ils.cstore', $method, @params );
914 }
915
916 sub event_equals {
917     my( $self, $e, $name ) =  @_;
918     if( $e and ref($e) eq 'HASH' and 
919         defined($e->{textcode}) and $e->{textcode} eq $name ) {
920         return 1 ;
921     }
922     return 0;
923 }
924
925 sub logmark {
926     my( undef, $f, $l ) = caller(0);
927     my( undef, undef, undef, $s ) = caller(1);
928     $s =~ s/.*:://g;
929     $f =~ s/.*\///g;
930     $logger->debug("LOGMARK: $f:$l:$s");
931 }
932
933 # takes a copy id 
934 sub fetch_open_circulation {
935     my( $self, $cid ) = @_;
936     $self->logmark;
937
938     my $e = OpenILS::Utils::CStoreEditor->new;
939     my $circ = $e->search_action_circulation({
940         target_copy => $cid, 
941         stop_fines_time => undef, 
942         checkin_time => undef
943     })->[0];
944     
945     return ($circ, $e->event);
946 }
947
948 my $copy_statuses;
949 sub copy_status_from_name {
950     my( $self, $name ) = @_;
951     $copy_statuses = $self->fetch_copy_statuses unless $copy_statuses;
952     for my $status (@$copy_statuses) { 
953         return $status if( $status->name =~ /$name/i );
954     }
955     return undef;
956 }
957
958 sub copy_status_to_name {
959     my( $self, $sid ) = @_;
960     $copy_statuses = $self->fetch_copy_statuses unless $copy_statuses;
961     for my $status (@$copy_statuses) { 
962         return $status->name if( $status->id == $sid );
963     }
964     return undef;
965 }
966
967
968 sub copy_status {
969     my( $self, $arg ) = @_;
970     return $arg if ref $arg;
971     $copy_statuses = $self->fetch_copy_statuses unless $copy_statuses;
972     my ($stat) = grep { $_->id == $arg } @$copy_statuses;
973     return $stat;
974 }
975
976 sub fetch_open_transit_by_copy {
977     my( $self, $copyid ) = @_;
978     my($transit, $evt);
979     $transit = $self->cstorereq(
980         'open-ils.cstore.direct.action.transit_copy.search',
981         { target_copy => $copyid, dest_recv_time => undef });
982     $evt = OpenILS::Event->new('ACTION_TRANSIT_COPY_NOT_FOUND') unless $transit;
983     return ($transit, $evt);
984 }
985
986 sub unflesh_copy {
987     my( $self, $copy ) = @_;
988     return undef unless $copy;
989     $copy->status( $copy->status->id ) if ref($copy->status);
990     $copy->location( $copy->location->id ) if ref($copy->location);
991     $copy->circ_lib( $copy->circ_lib->id ) if ref($copy->circ_lib);
992     return $copy;
993 }
994
995 sub unflesh_reservation {
996     my( $self, $reservation ) = @_;
997     return undef unless $reservation;
998     $reservation->usr( $reservation->usr->id ) if ref($reservation->usr);
999     $reservation->target_resource_type( $reservation->target_resource_type->id ) if ref($reservation->target_resource_type);
1000     $reservation->target_resource( $reservation->target_resource->id ) if ref($reservation->target_resource);
1001     $reservation->current_resource( $reservation->current_resource->id ) if ref($reservation->current_resource);
1002     return $reservation;
1003 }
1004
1005 # un-fleshes a copy and updates it in the DB
1006 # returns a DB_UPDATE_FAILED event on error
1007 # returns undef on success
1008 sub update_copy {
1009     my( $self, %params ) = @_;
1010
1011     my $copy        = $params{copy} || die "update_copy(): copy required";
1012     my $editor  = $params{editor} || die "update_copy(): copy editor required";
1013     my $session = $params{session};
1014
1015     $logger->debug("Updating copy in the database: " . $copy->id);
1016
1017     $self->unflesh_copy($copy);
1018     $copy->editor( $editor );
1019     $copy->edit_date( 'now' );
1020
1021     my $s;
1022     my $meth = 'open-ils.storage.direct.asset.copy.update';
1023
1024     $s = $session->request( $meth, $copy )->gather(1) if $session;
1025     $s = $self->storagereq( $meth, $copy ) unless $session;
1026
1027     $logger->debug("Update of copy ".$copy->id." returned: $s");
1028
1029     return $self->DB_UPDATE_FAILED($copy) unless $s;
1030     return undef;
1031 }
1032
1033 sub update_reservation {
1034     my( $self, %params ) = @_;
1035
1036     my $reservation = $params{reservation}  || die "update_reservation(): reservation required";
1037     my $editor      = $params{editor} || die "update_reservation(): copy editor required";
1038     my $session     = $params{session};
1039
1040     $logger->debug("Updating copy in the database: " . $reservation->id);
1041
1042     $self->unflesh_reservation($reservation);
1043
1044     my $s;
1045     my $meth = 'open-ils.cstore.direct.booking.reservation.update';
1046
1047     $s = $session->request( $meth, $reservation )->gather(1) if $session;
1048     $s = $self->cstorereq( $meth, $reservation ) unless $session;
1049
1050     $logger->debug("Update of copy ".$reservation->id." returned: $s");
1051
1052     return $self->DB_UPDATE_FAILED($reservation) unless $s;
1053     return undef;
1054 }
1055
1056 sub fetch_billable_xact {
1057     my( $self, $id ) = @_;
1058     my($xact, $evt);
1059     $logger->debug("Fetching billable transaction %id");
1060     $xact = $self->cstorereq(
1061         'open-ils.cstore.direct.money.billable_transaction.retrieve', $id );
1062     $evt = OpenILS::Event->new('MONEY_BILLABLE_TRANSACTION_NOT_FOUND') unless $xact;
1063     return ($xact, $evt);
1064 }
1065
1066 sub fetch_billable_xact_summary {
1067     my( $self, $id ) = @_;
1068     my($xact, $evt);
1069     $logger->debug("Fetching billable transaction summary %id");
1070     $xact = $self->cstorereq(
1071         'open-ils.cstore.direct.money.billable_transaction_summary.retrieve', $id );
1072     $evt = OpenILS::Event->new('MONEY_BILLABLE_TRANSACTION_NOT_FOUND') unless $xact;
1073     return ($xact, $evt);
1074 }
1075
1076 sub fetch_fleshed_copy {
1077     my( $self, $id ) = @_;
1078     my( $copy, $evt );
1079     $logger->info("Fetching fleshed copy $id");
1080     $copy = $self->cstorereq(
1081         "open-ils.cstore.direct.asset.copy.retrieve", $id,
1082         { flesh => 1,
1083           flesh_fields => { acp => [ qw/ circ_lib location status stat_cat_entries / ] }
1084         }
1085     );
1086     $evt = OpenILS::Event->new('ASSET_COPY_NOT_FOUND', id => $id) unless $copy;
1087     return ($copy, $evt);
1088 }
1089
1090
1091 # returns the org that owns the callnumber that the copy
1092 # is attached to
1093 sub fetch_copy_owner {
1094     my( $self, $copyid ) = @_;
1095     my( $copy, $cn, $evt );
1096     $logger->debug("Fetching copy owner $copyid");
1097     ($copy, $evt) = $self->fetch_copy($copyid);
1098     return (undef,$evt) if $evt;
1099     ($cn, $evt) = $self->fetch_callnumber($copy->call_number);
1100     return (undef,$evt) if $evt;
1101     return ($cn->owning_lib);
1102 }
1103
1104 sub fetch_copy_note {
1105     my( $self, $id ) = @_;
1106     my( $note, $evt );
1107     $logger->debug("Fetching copy note $id");
1108     $note = $self->cstorereq(
1109         'open-ils.cstore.direct.asset.copy_note.retrieve', $id );
1110     $evt = OpenILS::Event->new('ASSET_COPY_NOTE_NOT_FOUND', id => $id ) unless $note;
1111     return ($note, $evt);
1112 }
1113
1114 sub fetch_call_numbers_by_title {
1115     my( $self, $titleid ) = @_;
1116     $logger->info("Fetching call numbers by title $titleid");
1117     return $self->cstorereq(
1118         'open-ils.cstore.direct.asset.call_number.search.atomic', 
1119         { record => $titleid, deleted => 'f' });
1120         #'open-ils.storage.direct.asset.call_number.search.record.atomic', $titleid);
1121 }
1122
1123 sub fetch_copies_by_call_number {
1124     my( $self, $cnid ) = @_;
1125     $logger->info("Fetching copies by call number $cnid");
1126     return $self->cstorereq(
1127         'open-ils.cstore.direct.asset.copy.search.atomic', { call_number => $cnid, deleted => 'f' } );
1128         #'open-ils.storage.direct.asset.copy.search.call_number.atomic', $cnid );
1129 }
1130
1131 sub fetch_user_by_barcode {
1132     my( $self, $bc ) = @_;
1133     my $cardid = $self->cstorereq(
1134         'open-ils.cstore.direct.actor.card.id_list', { barcode => $bc } );
1135     return (undef, OpenILS::Event->new('ACTOR_CARD_NOT_FOUND', barcode => $bc)) unless $cardid;
1136     my $user = $self->cstorereq(
1137         'open-ils.cstore.direct.actor.user.search', { card => $cardid } );
1138     return (undef, OpenILS::Event->new('ACTOR_USER_NOT_FOUND', card => $cardid)) unless $user;
1139     return ($user);
1140     
1141 }
1142
1143 sub fetch_bill {
1144     my( $self, $billid ) = @_;
1145     $logger->debug("Fetching billing $billid");
1146     my $bill = $self->cstorereq(
1147         'open-ils.cstore.direct.money.billing.retrieve', $billid );
1148     my $evt = OpenILS::Event->new('MONEY_BILLING_NOT_FOUND') unless $bill;
1149     return($bill, $evt);
1150 }
1151
1152 sub walk_org_tree {
1153     my( $self, $node, $callback ) = @_;
1154     return unless $node;
1155     $callback->($node);
1156     if( $node->children ) {
1157         $self->walk_org_tree($_, $callback) for @{$node->children};
1158     }
1159 }
1160
1161 sub is_true {
1162     my( $self, $item ) = @_;
1163     return 1 if $item and $item !~ /^f$/i;
1164     return 0;
1165 }
1166
1167
1168 sub patientreq {
1169     my ($self, $client, $service, $method, @params) = @_;
1170     my ($response, $err);
1171
1172     my $session = create OpenSRF::AppSession($service);
1173     my $request = $session->request($method, @params);
1174
1175     my $spurt = 10;
1176     my $give_up = time + 1000;
1177
1178     try {
1179         while (time < $give_up) {
1180             $response = $request->recv("timeout" => $spurt);
1181             last if $request->complete;
1182
1183             $client->status(new OpenSRF::DomainObject::oilsContinueStatus);
1184         }
1185     } catch Error with {
1186         $err = shift;
1187     };
1188
1189     if ($err) {
1190         warn "received error : service=$service : method=$method : params=".Dumper(\@params) . "\n $err";
1191         throw $err ("Call to $service for method $method \n failed with exception: $err : " );
1192     }
1193
1194     return $response->content;
1195 }
1196
1197 # This logic now lives in storage
1198 sub __patron_money_owed {
1199     my( $self, $patronid ) = @_;
1200     my $ses = OpenSRF::AppSession->create('open-ils.storage');
1201     my $req = $ses->request(
1202         'open-ils.storage.money.billable_transaction.summary.search',
1203         { usr => $patronid, xact_finish => undef } );
1204
1205     my $total = 0;
1206     my $data;
1207     while( $data = $req->recv ) {
1208         $data = $data->content;
1209         $total += $data->balance_owed;
1210     }
1211     return $total;
1212 }
1213
1214 sub patron_money_owed {
1215     my( $self, $userid ) = @_;
1216     my $ses = $self->start_db_session();
1217     my $val = $ses->request(
1218         'open-ils.storage.actor.user.total_owed', $userid)->gather(1);
1219     $self->rollback_db_session($ses);
1220     return $val;
1221 }
1222
1223 sub patron_total_items_out {
1224     my( $self, $userid ) = @_;
1225     my $ses = $self->start_db_session();
1226     my $val = $ses->request(
1227         'open-ils.storage.actor.user.total_out', $userid)->gather(1);
1228     $self->rollback_db_session($ses);
1229     return $val;
1230 }
1231
1232
1233
1234
1235 #---------------------------------------------------------------------
1236 # Returns  ($summary, $event) 
1237 #---------------------------------------------------------------------
1238 sub fetch_mbts {
1239     my $self = shift;
1240     my $id  = shift;
1241     my $e = shift || OpenILS::Utils::CStoreEditor->new;
1242     $id = $id->id if ref($id);
1243     
1244     my $xact = $e->retrieve_money_billable_transaction_summary($id)
1245         or return (undef, $e->event);
1246
1247     return ($xact);
1248 }
1249
1250
1251 #---------------------------------------------------------------------
1252 # Given a list of money.billable_transaction objects, this creates
1253 # transaction summary objects for each
1254 #--------------------------------------------------------------------
1255 sub make_mbts {
1256     my $self = shift;
1257     my $e = shift;
1258     my @xacts = @_;
1259     return () if (!@xacts);
1260     return @{$e->search_money_billable_transaction_summary({id => [ map { $_->id } @xacts ]})};
1261 }
1262         
1263         
1264 sub ou_ancestor_setting_value {
1265     my($self, $org_id, $name, $e) = @_;
1266     $e = $e || OpenILS::Utils::CStoreEditor->new;
1267     my $set = $self->ou_ancestor_setting($org_id, $name, $e);
1268     return $set->{value} if $set;
1269     return undef;
1270 }
1271
1272
1273 # If an authentication token is provided AND this org unit setting has a
1274 # view_perm, then make sure the user referenced by the auth token has
1275 # that permission.  This means that if you call this method without an
1276 # authtoken param, you can get whatever org unit setting values you want.
1277 # API users beware.
1278 #
1279 # NOTE: If you supply an editor ($e) arg AND an auth token arg, the editor's
1280 # authtoken is checked, but the $auth arg is NOT checked.  To say that another
1281 # way, be sure NOT to pass an editor argument if you want your token checked.
1282 # Otherwise the auth arg is just a flag saying "check the editor".  
1283
1284 sub ou_ancestor_setting {
1285     my( $self, $orgid, $name, $e, $auth ) = @_;
1286     $e = $e || OpenILS::Utils::CStoreEditor->new(
1287         (defined $auth) ? (authtoken => $auth) : ()
1288     );
1289
1290     if ($auth) {
1291         my $coust = $e->retrieve_config_org_unit_setting_type([
1292             $name, {flesh => 1, flesh_fields => {coust => ['view_perm']}}
1293         ]);
1294         if ($coust && $coust->view_perm) {
1295             # And you can't have permission if you don't have a valid session.
1296             return undef if not $e->checkauth;
1297             # And now that we know you MIGHT have permission, we check it.
1298             return undef if not $e->allowed($coust->view_perm->code, $orgid);
1299         }
1300     }
1301
1302     my $query = {from => ['actor.org_unit_ancestor_setting', $name, $orgid]};
1303     my $setting = $e->json_query($query)->[0];
1304     return undef unless $setting;
1305     return {org => $setting->{org_unit}, value => OpenSRF::Utils::JSON->JSON2perl($setting->{value})};
1306 }   
1307         
1308
1309 # returns the ISO8601 string representation of the requested epoch in GMT
1310 sub epoch2ISO8601 {
1311     my( $self, $epoch ) = @_;
1312     my ($sec,$min,$hour,$mday,$mon,$year) = gmtime($epoch);
1313     $year += 1900; $mon += 1;
1314     my $date = sprintf(
1315         '%s-%0.2d-%0.2dT%0.2d:%0.2d:%0.2d-00',
1316         $year, $mon, $mday, $hour, $min, $sec);
1317     return $date;
1318 }
1319             
1320 sub find_highest_perm_org {
1321     my ( $self, $perm, $userid, $start_org, $org_tree ) = @_;
1322     my $org = $self->find_org($org_tree, $start_org );
1323
1324     my $lastid = -1;
1325     while( $org ) {
1326         last if ($self->check_perms( $userid, $org->id, $perm )); # perm failed
1327         $lastid = $org->id;
1328         $org = $self->find_org( $org_tree, $org->parent_ou() );
1329     }
1330
1331     return $lastid;
1332 }
1333
1334
1335 # returns the org_unit ID's 
1336 sub user_has_work_perm_at {
1337     my($self, $e, $perm, $options, $user_id) = @_;
1338     $options ||= {};
1339     $user_id = (defined $user_id) ? $user_id : $e->requestor->id;
1340
1341     my $func = 'permission.usr_has_perm_at';
1342     $func = $func.'_all' if $$options{descendants};
1343
1344     my $orgs = $e->json_query({from => [$func, $user_id, $perm]});
1345     $orgs = [map { $_->{ (keys %$_)[0] } } @$orgs];
1346
1347     return $orgs unless $$options{objects};
1348
1349     return $e->search_actor_org_unit({id => $orgs});
1350 }
1351
1352 sub get_user_work_ou_ids {
1353     my($self, $e, $userid) = @_;
1354     my $work_orgs = $e->json_query({
1355         select => {puwoum => ['work_ou']},
1356         from => 'puwoum',
1357         where => {usr => $e->requestor->id}});
1358
1359     return [] unless @$work_orgs;
1360     my @work_orgs;
1361     push(@work_orgs, $_->{work_ou}) for @$work_orgs;
1362
1363     return \@work_orgs;
1364 }
1365
1366
1367 my $org_types;
1368 sub get_org_types {
1369     my($self, $client) = @_;
1370     return $org_types if $org_types;
1371     return $org_types = OpenILS::Utils::CStoreEditor->new->retrieve_all_actor_org_unit_type();
1372 }
1373
1374 my %ORG_TREE;
1375 sub get_org_tree {
1376     my $self = shift;
1377     my $locale = shift || '';
1378     my $cache = OpenSRF::Utils::Cache->new("global", 0);
1379     my $tree = $ORG_TREE{$locale} || $cache->get_cache("orgtree.$locale");
1380     return $tree if $tree;
1381
1382     my $ses = OpenILS::Utils::CStoreEditor->new;
1383     $ses->session->session_locale($locale);
1384     $tree = $ses->search_actor_org_unit( 
1385         [
1386             {"parent_ou" => undef },
1387             {
1388                 flesh               => -1,
1389                 flesh_fields    => { aou =>  ['children'] },
1390                 order_by            => { aou => 'name'}
1391             }
1392         ]
1393     )->[0];
1394
1395     $ORG_TREE{$locale} = $tree;
1396     $cache->put_cache("orgtree.$locale", $tree);
1397     return $tree;
1398 }
1399
1400 sub get_org_descendants {
1401     my($self, $org_id, $depth) = @_;
1402
1403     my $select = {
1404         transform => 'actor.org_unit_descendants',
1405         column => 'id',
1406         result_field => 'id',
1407     };
1408     $select->{params} = [$depth] if defined $depth;
1409
1410     my $org_list = OpenILS::Utils::CStoreEditor->new->json_query({
1411         select => {aou => [$select]},
1412         from => 'aou',
1413         where => {id => $org_id}
1414     });
1415     my @orgs;
1416     push(@orgs, $_->{id}) for @$org_list;
1417     return \@orgs;
1418 }
1419
1420 sub get_org_ancestors {
1421     my($self, $org_id, $use_cache) = @_;
1422
1423     my ($cache, $orgs);
1424
1425     if ($use_cache) {
1426         $cache = OpenSRF::Utils::Cache->new("global", 0);
1427         $orgs = $cache->get_cache("org.ancestors.$org_id");
1428         return $orgs if $orgs;
1429     }
1430
1431     my $org_list = OpenILS::Utils::CStoreEditor->new->json_query({
1432         select => {
1433             aou => [{
1434                 transform => 'actor.org_unit_ancestors',
1435                 column => 'id',
1436                 result_field => 'id',
1437                 params => []
1438             }],
1439         },
1440         from => 'aou',
1441         where => {id => $org_id}
1442     });
1443
1444     $orgs = [ map { $_->{id} } @$org_list ];
1445
1446     $cache->put_cache("org.ancestors.$org_id", $orgs) if $use_cache;
1447     return $orgs;
1448 }
1449
1450 sub get_org_full_path {
1451     my($self, $org_id, $depth) = @_;
1452
1453     my $query = {
1454         select => {
1455             aou => [{
1456                 transform => 'actor.org_unit_full_path',
1457                 column => 'id',
1458                 result_field => 'id',
1459             }],
1460         },
1461         from => 'aou',
1462         where => {id => $org_id}
1463     };
1464
1465     $query->{select}->{aou}->[0]->{params} = [$depth] if defined $depth;
1466     my $org_list = OpenILS::Utils::CStoreEditor->new->json_query($query);
1467     return [ map {$_->{id}} @$org_list ];
1468 }
1469
1470 # returns the ID of the org unit ancestor at the specified depth
1471 sub org_unit_ancestor_at_depth {
1472     my($class, $org_id, $depth) = @_;
1473     my $resp = OpenILS::Utils::CStoreEditor->new->json_query(
1474         {from => ['actor.org_unit_ancestor_at_depth', $org_id, $depth]})->[0];
1475     return ($resp) ? $resp->{id} : undef;
1476 }
1477
1478 # returns the user's configured locale as a string.  Defaults to en-US if none is configured.
1479 sub get_user_locale {
1480     my($self, $user_id, $e) = @_;
1481     $e ||= OpenILS::Utils::CStoreEditor->new;
1482
1483     # first, see if the user has an explicit locale set
1484     my $setting = $e->search_actor_user_setting(
1485         {usr => $user_id, name => 'global.locale'})->[0];
1486     return OpenSRF::Utils::JSON->JSON2perl($setting->value) if $setting;
1487
1488     my $user = $e->retrieve_actor_user($user_id) or return $e->event;
1489     return $self->get_org_locale($user->home_ou, $e);
1490 }
1491
1492 # returns org locale setting
1493 sub get_org_locale {
1494     my($self, $org_id, $e) = @_;
1495     $e ||= OpenILS::Utils::CStoreEditor->new;
1496
1497     my $locale;
1498     if(defined $org_id) {
1499         $locale = $self->ou_ancestor_setting_value($org_id, 'global.default_locale', $e);
1500         return $locale if $locale;
1501     }
1502
1503     # system-wide default
1504     my $sclient = OpenSRF::Utils::SettingsClient->new;
1505     $locale = $sclient->config_value('default_locale');
1506     return $locale if $locale;
1507
1508     # if nothing else, fallback to locale=cowboy
1509     return 'en-US';
1510 }
1511
1512
1513 # xml-escape non-ascii characters
1514 sub entityize { 
1515     my($self, $string, $form) = @_;
1516     $form ||= "";
1517
1518     if ($form eq 'D') {
1519         $string = NFD($string);
1520     } else {
1521         $string = NFC($string);
1522     }
1523
1524     # Convert raw ampersands to entities
1525     $string =~ s/&(?!\S+;)/&amp;/gso;
1526
1527     # Convert Unicode characters to entities
1528     $string =~ s/([\x{0080}-\x{fffd}])/sprintf('&#x%X;',ord($1))/sgoe;
1529
1530     return $string;
1531 }
1532
1533 # x0000-x0008 isn't legal in XML documents
1534 # XXX Perhaps this should just go into our standard entityize method
1535 sub strip_ctrl_chars {
1536     my ($self, $string) = @_;
1537
1538     $string =~ s/([\x{0000}-\x{0008}])//sgoe; 
1539     return $string;
1540 }
1541
1542 sub get_copy_price {
1543     my($self, $e, $copy, $volume) = @_;
1544
1545     $copy->price(0) if $copy->price and $copy->price < 0;
1546
1547
1548     my $owner;
1549     if(ref $volume) {
1550         if($volume->id == OILS_PRECAT_CALL_NUMBER) {
1551             $owner = $copy->circ_lib;
1552         } else {
1553             $owner = $volume->owning_lib;
1554         }
1555     } else {
1556         if($copy->call_number == OILS_PRECAT_CALL_NUMBER) {
1557             $owner = $copy->circ_lib;
1558         } else {
1559             $owner = $e->retrieve_asset_call_number($copy->call_number)->owning_lib;
1560         }
1561     }
1562
1563     my $min_price = $self->ou_ancestor_setting_value($owner, OILS_SETTING_MIN_ITEM_PRICE);
1564     my $max_price = $self->ou_ancestor_setting_value($owner, OILS_SETTING_MAX_ITEM_PRICE);
1565     my $charge_on_0 = $self->ou_ancestor_setting_value($owner, OILS_SETTING_CHARGE_LOST_ON_ZERO, $e);
1566
1567     my $price = $copy->price;
1568
1569     # set the default price if needed
1570     if (!defined $price or ($price == 0 and $charge_on_0)) {
1571         # set to default price
1572         $price = $self->ou_ancestor_setting_value(
1573             $owner, OILS_SETTING_DEF_ITEM_PRICE, $e) || 0;
1574     }
1575
1576     # adjust to min/max range if needed
1577     if (defined $max_price and $price > $max_price) {
1578         $price = $max_price;
1579     } elsif (defined $min_price and $price < $min_price
1580         and ($price != 0 or $charge_on_0 or !defined $charge_on_0)) {
1581         # default to raising the price to the minimum,
1582         # but let 0 fall through if $charge_on_0 is set and is false
1583         $price = $min_price;
1584     }
1585
1586     return $price;
1587 }
1588
1589 # given a transaction ID, this returns the context org_unit for the transaction
1590 sub xact_org {
1591     my($self, $xact_id, $e) = @_;
1592     $e ||= OpenILS::Utils::CStoreEditor->new;
1593     
1594     my $loc = $e->json_query({
1595         "select" => {circ => ["circ_lib"]},
1596         from     => "circ",
1597         "where"  => {id => $xact_id},
1598     });
1599
1600     return $loc->[0]->{circ_lib} if @$loc;
1601
1602     $loc = $e->json_query({
1603         "select" => {bresv => ["request_lib"]},
1604         from     => "bresv",
1605         "where"  => {id => $xact_id},
1606     });
1607
1608     return $loc->[0]->{request_lib} if @$loc;
1609
1610     $loc = $e->json_query({
1611         "select" => {mg => ["billing_location"]},
1612         from     => "mg",
1613         "where"  => {id => $xact_id},
1614     });
1615
1616     return $loc->[0]->{billing_location};
1617 }
1618
1619
1620 sub find_event_def_by_hook {
1621     my($self, $hook, $context_org, $e) = @_;
1622
1623     $e ||= OpenILS::Utils::CStoreEditor->new;
1624
1625     my $orgs = $self->get_org_ancestors($context_org);
1626
1627     # search from the context org up
1628     for my $org_id (reverse @$orgs) {
1629
1630         my $def = $e->search_action_trigger_event_definition(
1631             {hook => $hook, owner => $org_id})->[0];
1632
1633         return $def if $def;
1634     }
1635
1636     return undef;
1637 }
1638
1639
1640
1641 # If an event_def ID is not provided, use the hook and context org to find the 
1642 # most appropriate event.  create the event, fire it, then return the resulting
1643 # event with fleshed template_output and error_output
1644 sub fire_object_event {
1645     my($self, $event_def, $hook, $object, $context_org, $granularity, $user_data, $client) = @_;
1646
1647     my $e = OpenILS::Utils::CStoreEditor->new;
1648     my $def;
1649
1650     my $auto_method = "open-ils.trigger.event.autocreate.by_definition";
1651
1652     if($event_def) {
1653         $def = $e->retrieve_action_trigger_event_definition($event_def)
1654             or return $e->event;
1655
1656         $auto_method .= '.include_inactive';
1657
1658     } else {
1659
1660         # find the most appropriate event def depending on context org
1661         $def = $self->find_event_def_by_hook($hook, $context_org, $e) 
1662             or return $e->event;
1663     }
1664
1665     my $final_resp;
1666
1667     if($def->group_field) {
1668         # we have a list of objects
1669         $object = [$object] unless ref $object eq 'ARRAY';
1670
1671         my @event_ids;
1672         $user_data ||= [];
1673         for my $i (0..$#$object) {
1674             my $obj = $$object[$i];
1675             my $udata = $$user_data[$i];
1676             my $event_id = $self->simplereq(
1677                 'open-ils.trigger', $auto_method, $def->id, $obj, $context_org, $udata);
1678             push(@event_ids, $event_id);
1679         }
1680
1681         $logger->info("EVENTS = " . OpenSRF::Utils::JSON->perl2JSON(\@event_ids));
1682
1683         my $resp;
1684         if (not defined $client) {
1685             $resp = $self->simplereq(
1686                 'open-ils.trigger',
1687                 'open-ils.trigger.event_group.fire',
1688                 \@event_ids);
1689         } else {
1690             $resp = $self->patientreq(
1691                 $client,
1692                 "open-ils.trigger", "open-ils.trigger.event_group.fire",
1693                 \@event_ids
1694             );
1695         }
1696
1697         if($resp and $resp->{events} and @{$resp->{events}}) {
1698
1699             $e->xact_begin;
1700             $final_resp = $e->retrieve_action_trigger_event([
1701                 $resp->{events}->[0]->id,
1702                 {flesh => 1, flesh_fields => {atev => ['template_output', 'error_output']}}
1703             ]);
1704             $e->rollback;
1705         }
1706
1707     } else {
1708
1709         $object = $$object[0] if ref $object eq 'ARRAY';
1710
1711         my $event_id;
1712         my $resp;
1713
1714         if (not defined $client) {
1715             $event_id = $self->simplereq(
1716                 'open-ils.trigger',
1717                 $auto_method, $def->id, $object, $context_org, $user_data
1718             );
1719
1720             $resp = $self->simplereq(
1721                 'open-ils.trigger',
1722                 'open-ils.trigger.event.fire',
1723                 $event_id
1724             );
1725         } else {
1726             $event_id = $self->patientreq(
1727                 $client,
1728                 'open-ils.trigger',
1729                 $auto_method, $def->id, $object, $context_org, $user_data
1730             );
1731
1732             $resp = $self->patientreq(
1733                 $client,
1734                 'open-ils.trigger',
1735                 'open-ils.trigger.event.fire',
1736                 $event_id
1737             );
1738         }
1739         
1740         if($resp and $resp->{event}) {
1741             $e->xact_begin;
1742             $final_resp = $e->retrieve_action_trigger_event([
1743                 $resp->{event}->id,
1744                 {flesh => 1, flesh_fields => {atev => ['template_output', 'error_output']}}
1745             ]);
1746             $e->rollback;
1747         }
1748     }
1749
1750     return $final_resp;
1751 }
1752
1753
1754 sub create_events_for_hook {
1755     my($self, $hook, $obj, $org_id, $granularity, $user_data, $wait) = @_;
1756     my $ses = OpenSRF::AppSession->create('open-ils.trigger');
1757     my $req = $ses->request('open-ils.trigger.event.autocreate', 
1758         $hook, $obj, $org_id, $granularity, $user_data);
1759     return undef unless $wait;
1760     my $resp = $req->recv;
1761     return $resp->content if $resp;
1762 }
1763
1764 sub create_uuid_string {
1765     return create_UUID_as_string();
1766 }
1767
1768 sub create_circ_chain_summary {
1769     my($class, $e, $circ_id) = @_;
1770     my $sum = $e->json_query({from => ['action.summarize_circ_chain', $circ_id]})->[0];
1771     return undef unless $sum;
1772     my $obj = Fieldmapper::action::circ_chain_summary->new;
1773     $obj->$_($sum->{$_}) for keys %$sum;
1774     return $obj;
1775 }
1776
1777
1778 # Returns "mra" attribute key/value pairs for a set of bre's
1779 # Takes a list of bre IDs, returns a hash of hashes,
1780 # {bre_id1 => {key1 => {code => value1, label => label1}, ...}...}
1781 my $ccvm_cache;
1782 sub get_bre_attrs {
1783     my ($class, $bre_ids, $e) = @_;
1784     $e = $e || OpenILS::Utils::CStoreEditor->new;
1785
1786     my $attrs = {};
1787     return $attrs unless defined $bre_ids;
1788     $bre_ids = [$bre_ids] unless ref $bre_ids;
1789
1790     my $mra = $e->json_query({
1791         select => {
1792             mra => [
1793                 {
1794                     column => 'id',
1795                     alias => 'bre'
1796                 }, {
1797                     column => 'attrs',
1798                     transform => 'each',
1799                     result_field => 'key',
1800                     alias => 'key'
1801                 },{
1802                     column => 'attrs',
1803                     transform => 'each',
1804                     result_field => 'value',
1805                     alias => 'value'
1806                 }
1807             ]
1808         },
1809         from => 'mra',
1810         where => {id => $bre_ids}
1811     });
1812
1813     return $attrs unless $mra;
1814
1815     $ccvm_cache = $ccvm_cache || $e->search_config_coded_value_map({id => {'!=' => undef}});
1816
1817     for my $id (@$bre_ids) {
1818         $attrs->{$id} = {};
1819         for my $mra (grep { $_->{bre} eq $id } @$mra) {
1820             my $ctype = $mra->{key};
1821             my $code = $mra->{value};
1822             $attrs->{$id}->{$ctype} = {code => $code};
1823             if($code) {
1824                 my ($ccvm) = grep { $_->ctype eq $ctype and $_->code eq $code } @$ccvm_cache;
1825                 $attrs->{$id}->{$ctype}->{label} = $ccvm->value if $ccvm;
1826             }
1827         }
1828     }
1829
1830     return $attrs;
1831 }
1832
1833 # Shorter version of bib_container_items_via_search() below, only using
1834 # the queryparser record_list filter instead of the container filter.
1835 sub bib_record_list_via_search {
1836     my ($class, $search_query, $search_args) = @_;
1837
1838     # First, Use search API to get container items sorted in any way that crad
1839     # sorters support.
1840     my $search_result = $class->simplereq(
1841         "open-ils.search", "open-ils.search.biblio.multiclass.query",
1842         $search_args, $search_query
1843     );
1844
1845     unless ($search_result) {
1846         # empty result sets won't cause this, but actual errors should.
1847         $logger->warn("bib_record_list_via_search() got nothing from search");
1848         return;
1849     }
1850
1851     # Throw away other junk from search, keeping only bib IDs.
1852     return [ map { pop @$_ } @{$search_result->{ids}} ];
1853 }
1854
1855 # 'no_flesh' avoids fleshing the target_biblio_record_entry
1856 sub bib_container_items_via_search {
1857     my ($class, $container_id, $search_query, $search_args, $no_flesh) = @_;
1858
1859     # First, Use search API to get container items sorted in any way that crad
1860     # sorters support.
1861     my $search_result = $class->simplereq(
1862         "open-ils.search", "open-ils.search.biblio.multiclass.query",
1863         $search_args, $search_query
1864     );
1865     unless ($search_result) {
1866         # empty result sets won't cause this, but actual errors should.
1867         $logger->warn("bib_container_items_via_search() got nothing from search");
1868         return;
1869     }
1870
1871     # Throw away other junk from search, keeping only bib IDs.
1872     my $id_list = [ map { pop @$_ } @{$search_result->{ids}} ];
1873
1874     return [] unless @$id_list;
1875
1876     # Now get the bib container items themselves...
1877     my $e = new OpenILS::Utils::CStoreEditor;
1878     unless ($e) {
1879         $logger->warn("bib_container_items_via_search() couldn't get cstoreeditor");
1880         return;
1881     }
1882
1883     my @flesh_fields = qw/notes/;
1884     push(@flesh_fields, 'target_biblio_record_entry') unless $no_flesh;
1885
1886     my $items = $e->search_container_biblio_record_entry_bucket_item([
1887         {
1888             "target_biblio_record_entry" => $id_list,
1889             "bucket" => $container_id
1890         }, {
1891             flesh => 1,
1892             flesh_fields => {"cbrebi" => \@flesh_fields}
1893         }
1894     ], {substream => 1});
1895
1896     unless ($items) {
1897         $logger->warn(
1898             "bib_container_items_via_search() couldn't get bucket items: " .
1899             $e->die_event->{textcode}
1900         );
1901         return;
1902     }
1903
1904     # ... and put them in the same order that the search API said they
1905     # should be in.
1906     my %ordering_hash = map { 
1907         ($no_flesh) ? $_->target_biblio_record_entry : $_->target_biblio_record_entry->id, 
1908         $_ 
1909     } @$items;
1910
1911     return [map { $ordering_hash{$_} } @$id_list];
1912 }
1913
1914 # returns undef on success, Event on error
1915 sub log_user_activity {
1916     my ($class, $user_id, $who, $what, $e, $async) = @_;
1917
1918     my $commit = 0;
1919     if (!$e) {
1920         $e = OpenILS::Utils::CStoreEditor->new(xact => 1);
1921         $commit = 1;
1922     }
1923
1924     my $res = $e->json_query({
1925         from => [
1926             'actor.insert_usr_activity', 
1927             $user_id, $who, $what, OpenSRF::AppSession->ingress
1928         ]
1929     });
1930
1931     if ($res) { # call returned OK
1932
1933         $e->commit   if $commit and @$res;
1934         $e->rollback if $commit and !@$res;
1935
1936     } else {
1937         return $e->die_event;
1938     }
1939
1940     return undef;
1941 }
1942
1943 # I hate to put this here exactly, but this code needs to be shared between
1944 # the TPAC's mod_perl module and open-ils.serial.
1945 #
1946 # There is a reason every part of the query *except* those parts dealing
1947 # with scope are moved here from the code's origin in TPAC.  The serials
1948 # use case does *not* want the same scoping logic.
1949 #
1950 # Also, note that for the serials uses case, we may filter in OPAC visible
1951 # status and copy/call_number deletedness, but we don't filter on any
1952 # particular values for serial.item.status or serial.item.date_received.
1953 # Since we're only using this *after* winnowing down the set of issuances
1954 # that copies should be related to, I'm not sure we need any such serial.item
1955 # filters.
1956
1957 sub basic_opac_copy_query {
1958     ######################################################################
1959     # Pass a defined value for either $rec_id OR ($iss_id AND $dist_id), #
1960     # not both.                                                          #
1961     ######################################################################
1962     my ($self,$rec_id,$iss_id,$dist_id,$copy_limit,$copy_offset,$staff) = @_;
1963
1964     return {
1965         select => {
1966             acp => ['id', 'barcode', 'circ_lib', 'create_date', 'active_date',
1967                     'age_protect', 'holdable', 'copy_number'],
1968             acpl => [
1969                 {column => 'name', alias => 'copy_location'},
1970                 {column => 'holdable', alias => 'location_holdable'}
1971             ],
1972             ccs => [
1973                 {column => 'id', alias => 'status_code'},
1974                 {column => 'name', alias => 'copy_status'},
1975                 {column => 'holdable', alias => 'status_holdable'}
1976             ],
1977             acn => [
1978                 {column => 'label', alias => 'call_number_label'},
1979                 {column => 'id', alias => 'call_number'},
1980                 {column => 'owning_lib', alias => 'call_number_owning_lib'}
1981             ],
1982             circ => ['due_date'],
1983             acnp => [
1984                 {column => 'label', alias => 'call_number_prefix_label'},
1985                 {column => 'id', alias => 'call_number_prefix'}
1986             ],
1987             acns => [
1988                 {column => 'label', alias => 'call_number_suffix_label'},
1989                 {column => 'id', alias => 'call_number_suffix'}
1990             ],
1991             bmp => [
1992                 {column => 'label', alias => 'part_label'},
1993             ],
1994             ($iss_id ? (sitem => ["issuance"]) : ())
1995         },
1996
1997         from => {
1998             acp => {
1999                 ($iss_id ? (
2000                     sitem => {
2001                         fkey => 'id',
2002                         field => 'unit',
2003                         filter => {issuance => $iss_id},
2004                         join => {
2005                             sstr => { }
2006                         }
2007                     }
2008                 ) : ()),
2009                 acn => {
2010                     join => {
2011                         acnp => { fkey => 'prefix' },
2012                         acns => { fkey => 'suffix' }
2013                     },
2014                     filter => [
2015                         {deleted => 'f'},
2016                         ($rec_id ? {record => $rec_id} : ())
2017                     ],
2018                 },
2019                 circ => { # If the copy is circulating, retrieve the open circ
2020                     type => 'left',
2021                     filter => {checkin_time => undef}
2022                 },
2023                 acpl => {
2024                     ($staff ? () : (filter => { opac_visible => 't' }))
2025                 },
2026                 ccs => {
2027                     ($staff ? () : (filter => { opac_visible => 't' }))
2028                 },
2029                 aou => {},
2030                 acpm => {
2031                     type => 'left',
2032                     join => {
2033                         bmp => { type => 'left' }
2034                     }
2035                 }
2036             }
2037         },
2038
2039         where => {
2040             '+acp' => {
2041                 deleted => 'f',
2042                 ($staff ? () : (opac_visible => 't'))
2043             },
2044             ($dist_id ? ( '+sstr' => { distribution => $dist_id } ) : ()),
2045             ($staff ? () : ( '+aou' => { opac_visible => 't' } ))
2046         },
2047
2048         order_by => [
2049             {class => 'aou', field => 'name'},
2050             {class => 'acn', field => 'label_sortkey'},
2051             {class => 'acp', field => 'copy_number'},
2052             {class => 'acp', field => 'barcode'}
2053         ],
2054
2055         limit => $copy_limit,
2056         offset => $copy_offset
2057     };
2058 }
2059
2060 # Compare two dates, date1 and date2. If date2 is not defined, then
2061 # DateTime->now will be used. Assumes dates are in ISO8601 format as
2062 # supported by DateTime::Format::ISO8601. (A future enhancement might
2063 # be to support other formats.)
2064 #
2065 # Returns -1 if $date1 < $date2
2066 # Returns 0 if $date1 == $date2
2067 # Returns 1 if $date1 > $date2
2068 sub datecmp {
2069     my $self = shift;
2070     my $date1 = shift;
2071     my $date2 = shift;
2072
2073     # Check for timezone offsets and limit them to 2 digits:
2074     if ($date1 && $date1 =~ /(?:-|\+)\d\d\d\d$/) {
2075         $date1 = substr($date1, 0, length($date1) - 2);
2076     }
2077     if ($date2 && $date2 =~ /(?:-|\+)\d\d\d\d$/) {
2078         $date2 = substr($date2, 0, length($date2) - 2);
2079     }
2080
2081     # check date1:
2082     unless (UNIVERSAL::isa($date1, "DateTime")) {
2083         $date1 = DateTime::Format::ISO8601->parse_datetime($date1);
2084     }
2085
2086     # Check for date2:
2087     unless ($date2) {
2088         $date2 = DateTime->now;
2089     } else {
2090         unless (UNIVERSAL::isa($date2, "DateTime")) {
2091             $date2 = DateTime::Format::ISO8601->parse_datetime($date2);
2092         }
2093     }
2094
2095     return DateTime->compare($date1, $date2);
2096 }
2097
2098
2099 # marcdoc is an XML::LibXML document
2100 # updates the doc and returns the entityized MARC string
2101 sub strip_marc_fields {
2102     my ($class, $e, $marcdoc, $grps) = @_;
2103     
2104     my $orgs = $class->get_org_ancestors($e->requestor->ws_ou);
2105
2106     my $query = {
2107         select  => {vibtf => ['field']},
2108         from    => {vibtf => 'vibtg'},
2109         where   => {'+vibtg' => {owner => $orgs}},
2110         distinct => 1
2111     };
2112
2113     # give me always-apply groups plus any selected groups
2114     if ($grps and @$grps) {
2115         $query->{where}->{'+vibtg'}->{'-or'} = [
2116             {id => $grps},
2117             {always_apply => 't'}
2118         ];
2119
2120     } else {
2121         $query->{where}->{'+vibtg'}->{always_apply} = 't';
2122     }
2123
2124     my $fields = $e->json_query($query);
2125
2126     for my $field (@$fields) {
2127         my $tag = $field->{field};
2128         for my $node ($marcdoc->findnodes('//*[@tag="'.$tag.'"]')) {
2129             $node->parentNode->removeChild($node);
2130         }
2131     }
2132
2133     return $class->entityize($marcdoc->documentElement->toString);
2134 }
2135
2136 # Given a list of PostgreSQL arrays of numbers,
2137 # unnest the numbers and return a unique set, skipping any list elements
2138 # that are just '{NULL}'.
2139 sub unique_unnested_numbers {
2140     my $class = shift;
2141
2142     no warnings 'numeric';
2143
2144     return uniq(
2145         map(
2146             int,
2147             map { $_ eq 'NULL' ? undef : (split /,/, $_) }
2148                 map { substr($_, 1, -1) } @_
2149         )
2150     );
2151 }
2152
2153 # Check if a transaction should be left open or closed. Close the
2154 # transaction if it should be closed or open it otherwise. Returns
2155 # undef on success or a failure event.
2156 sub check_open_xact {
2157     my( $self, $editor, $xactid, $xact ) = @_;
2158
2159     # Grab the transaction
2160     $xact ||= $editor->retrieve_money_billable_transaction($xactid);
2161     return $editor->event unless $xact;
2162     $xactid ||= $xact->id;
2163
2164     # grab the summary and see how much is owed on this transaction
2165     my ($summary) = $self->fetch_mbts($xactid, $editor);
2166
2167     # grab the circulation if it is a circ;
2168     my $circ = $editor->retrieve_action_circulation($xactid);
2169
2170     # If nothing is owed on the transaction but it is still open
2171     # and this transaction is not an open circulation, close it
2172     if(
2173         ( $summary->balance_owed == 0 and ! $xact->xact_finish ) and
2174         ( !$circ or $circ->stop_fines )) {
2175
2176         $logger->info("closing transaction ".$xact->id. ' because balance_owed == 0');
2177         $xact->xact_finish('now');
2178         $editor->update_money_billable_transaction($xact)
2179             or return $editor->event;
2180         return undef;
2181     }
2182
2183     # If money is owed or a refund is due on the xact and xact_finish
2184     # is set, clear it (to reopen the xact) and update
2185     if( $summary->balance_owed != 0 and $xact->xact_finish ) {
2186         $logger->info("re-opening transaction ".$xact->id. ' because balance_owed != 0');
2187         $xact->clear_xact_finish;
2188         $editor->update_money_billable_transaction($xact)
2189             or return $editor->event;
2190         return undef;
2191     }
2192     return undef;
2193 }
2194
2195 1;
2196